MediaWiki:Common.js

De Ragna4th
Revisão de 03h30min de 16 de janeiro de 2022 por Nameless (discussão | contribs)
Ir para navegação Ir para pesquisar

Nota: Após salvar, você pode ter que limpar o "cache" do seu navegador para ver as alterações.

  • Firefox / Safari: Pressione Shift enquanto clica Recarregar, ou pressione Ctrl-F5 ou Ctrl-R (⌘-R no Mac)
  • Google Chrome: Pressione Ctrl-Shift-R (⌘-Shift-R no Mac)
  • Internet Explorer: PressioneCtrl enquanto clica Recarregar, ou Pressione Ctrl-F5
  • Opera: Vá para Menu → Configurações (Opera → Preferencias no Mac) e depois para Privacidade e Segurança → Limpar dados de navegação → Imagens e arquivos em cache.
/* Códigos JavaScript aqui colocados serão carregados por todos aqueles que acessarem alguma página deste wiki */
if (typeof DP == 'undefined') DP = {};

if (typeof DP.Tooltips == 'undefined') DP.Tooltips = new function () { // Reminder: Keep in sync with the equivalent code in dp.js
    var URL_QUERY_BASE = 'http://{mode}.divine-pride.net/tooltip/';
    var URL_QUERY_BASE_DEBUG = 'http://localhost:4312/tooltip/';

    var TYPES = {
        item: {
            type: 'item',
            url: 'database/item/{key}'
        },
        monster: {
            type: 'monster',
            url: 'database/monster/{key}'
        },
        npc: {
            type: 'npc',
            url: 'database/npc/{key}'
        },
        skill: {
            type: 'skill',
            url: 'database/skill/{key}'
        },
        efst: {
            type: 'efst',
            url: 'database/efst/{key}'
        },
        title: {
            type: 'title',
            url: 'database/title/{key}'
        },
        achievement: {
            type: 'achievement',
            url: 'database/achievement/{key}'
        },
        map: {
            type: 'map',
            url: 'database/map/{key}'
        },
        quest: {
            type: 'quest',
            url: 'database/quest/{key}'
        }
    };

    var URL_PATTERN_BASE_DEBUG = new RegExp('^http://localhost:..../(.+)');
    var URL_PATTERN_BASE = new RegExp('^http://(.*)\\.divine-pride\\.net/(.+)');
    var URL_PATTERN_SELF = new RegExp('www\\.divine-pride\\.net/Scripts/tooltip\\.js'); // Used to get region from the <script> tag
    var URL_PATTERNS = [
		{
		    regex: new RegExp('^database/item/([0-9]+)/?.*$'),
		    params: {
		        type: 'item'
		    }
		},
		{
		    regex: new RegExp('^database/npc/([0-9]+)/?.*$'),
		    params: {
		        type: 'npc'
		    }
		},
		{
		    regex: new RegExp('^database/monster/([0-9]+)/?.*$'),
		    params: {
		        type: 'monster'
		    }
		},
		{
		    regex: new RegExp('^database/skill/([0-9]+)/?.*$'),
		    params: {
		        type: 'skill'
		    }
		},
		{
		    regex: new RegExp('^database/efst/([0-9]+)/?.*$'),
		    params: {
		        type: 'efst'
		    }
		},
		{
		    regex: new RegExp('^database/quest/([0-9]+)/?.*$'),
		    params: {
		        type: 'quest'
		    }
		},
		{
		    regex: new RegExp('^database/title/([0-9]+)/?.*$'),
		    params: {
		        type: 'title'
		    }
		},
		{
		    regex: new RegExp('^database/achievement/([0-9]+)/?.*$'),
		    params: {
		        type: 'achievement'
		    }
		},
		{
		    regex: new RegExp('^database/map/([a-zA-Z0-9\_]+)/?.*$'),
		    params: {
		        type: 'map'
		    }
		}
	];

    var DELAY_LOADING = 500; // ms
    var dataCache = {};

    // State
    var loadingTimer;
    var currentLink;
    var currentParams;

    function construct() {
        $.documentReady(initialize);
    }

    function initialize() {
        setTimeout(getCss, 1);
        setTimeout(bindEvents, 1);
    }

    function getCss() {

        var scripts = document.getElementsByTagName('script');
        var currentScript = scripts[scripts.length - 1];
        var scriptRegion;

        if (currentScript && currentScript.src.match(URL_PATTERN_SELF)) {
            scriptRegion = RegExp.$1;
        }

        $.getStyle('https://www.novaragnarok.com/forum/dp.css');
    }

    function bindEvents() {

        $.bindEvent(document, 'mouseover', function (e) {
            e = $.normalizeEvent(e);
            if (e.target && e.target.nodeName.toUpperCase() == 'A') {
                linkMouseOver(e.target);
            }
        });

        $.bindEvent(document, 'mouseout', function (e) {
            e = $.normalizeEvent(e);
            if (e.target && e.target.nodeName.toUpperCase() == 'A') {
                linkMouseOut(e.target);
            }
        });
    }

    function linkMouseOver(link) {

        var params = {};

        if (!parseUrl(link, params))
        {
            parseUrlDebug(link, params);
        }

        if (!params.key || currentLink == link) {
            return;
        }

        currentLink = link;
        currentParams = params;

        var data = getTooltip(params);
        if (data != null) {
            showTooltip(data);
        }
    }

    function linkMouseOut(link) {

        if (link != currentLink) {
            return;
        }

        Tooltip.hide();

        currentLink = null;
        currentParams = null;
    }

    function parseUrl(link, params) {
        if (!link.href.match(URL_PATTERN_BASE)) {
            return false;
        }
        if (link.href.indexOf("#") !== -1) {
            return false;
        }

        var mode = RegExp.$1;
        var path = RegExp.$2;
        for (var i = 0; i < URL_PATTERNS.length; ++i) {

            var urlPattern = URL_PATTERNS[i];
            if (!path.match(urlPattern.regex)) {
                continue;
            }

            var key = RegExp.$1;
            if (key.indexOf('/') != -1) { // Folder and key shouldn't contain any slashes
                continue;
            }

            params.mode = mode;
            params.key = key;

            // Copy pattern's params
            for (var i in urlPattern.params) {
                params[i] = urlPattern.params[i];
            }

            params.tooltipType = getTooltipType(params.type);
            return true;
        }

        return false;
    }

    function parseUrlDebug(link, params) {
        var urlMatch = link.href.match(URL_PATTERN_BASE_DEBUG);
        if (!urlMatch) {
            return;
        }
        if (link.href.indexOf("#") !== -1) {
            return;
        }

        var path = urlMatch[1];
        for (var i = 0; i < URL_PATTERNS.length; ++i) {

            var urlPattern = URL_PATTERNS[i];
            var keyMatch = path.match(urlPattern.regex);
            if (!keyMatch) {
                continue;
            }

            var key = keyMatch[1];
            if (key.indexOf('/') != -1) { // Folder and key shouldn't contain any slashes
                continue;
            }
            
            params.mode = "www";
            params.key = key;

            // Copy pattern's params
            for (var i in urlPattern.params) {
                params[i] = urlPattern.params[i];
            }

            URL_QUERY_BASE = URL_QUERY_BASE_DEBUG;
            params.tooltipType = getTooltipType(params.type);
            return;
        }
    }

    function requestTooltip(params) {
        var url = (URL_QUERY_BASE + params.tooltipType.url)
			.replace('{mode}', params.mode)
			.replace('{key}', params.key)
			.replace('{server}', params.server);
        $.getScript(url);
    }

    function registerData(data) {
        clearTimeout(loadingTimer);

        var params = data.params;

        saveData(params, data);

        if (currentParams != null && getCacheKeyFromParams(params) == getCacheKeyFromParams(currentParams)) {
            showTooltip(data);
        }
    }

    function getTooltip(params) {

        var data = loadData(params);

        if (data == null) { // Fetch data if not already cached

            clearTimeout(loadingTimer);
            loadingTimer = setTimeout(showLoading, DELAY_LOADING);
            requestTooltip(params);
            return null;
        }

        return data;
    }

    function showLoading() {

        if (currentLink != null) {
            Tooltip.show(currentLink, '<div class="dp-tooltip"><div class="loading"></div></div>');
        }
    }

    function showTooltip(data) {

        if (currentLink != null) {
            Tooltip.show(currentLink, data.tooltipHtml);
        }
    }

    // Utilities
    function getTooltipType(type) {
        return TYPES[type];
    }

    function saveData(params, data) {
        var cacheKey = getCacheKeyFromParams(params);
        dataCache[cacheKey] = data;
    }

    function loadData(params) {

        var cacheKey = getCacheKeyFromParams(params);
        return dataCache[cacheKey];
    }

    function getCacheKeyFromParams(params) {
        return [
			params.region,
			params.locale,
			params.type,
			params.key
		].join('-');
    }

    // Public methods
    this.registerData = registerData;



    // HTML Helpers
    var $ = {

        create: function (nodeName) {
            return document.createElement(nodeName);
        },

        getScript: function (url) {

            var script = $.create('script');
            script.type = 'text/javascript';
            script.src = url;

            document.body.appendChild(script);
        },

        getStyle: function (url) {

            var link = $.create('link');
            link.rel = 'stylesheet';
            link.type = 'text/css';
            link.href = url;

            document.body.appendChild(link);
        },

        documentReady: function (callback) {

            if (document.readyState == 'complete') {
                callback();
                return;
            }

            var occurred = false;

            $.bindEvent(document, 'DOMContentLoaded', function () {

                if (!occurred) {
                    occurred = true;
                    callback();
                }
            });

            $.bindEvent(document, 'readystatechange', function () {

                if (document.readyState == 'complete' && !occurred) {
                    occurred = true;
                    callback();
                }
            });

        },

        bindEvent: function (node, eventType, callback) {
            if (node.addEventListener) {
                node.addEventListener(eventType, callback, true); // Must be true to work in Opera
            } else {
                node.attachEvent('on' + eventType, callback);
            }
        },

        normalizeEvent: function (e) {
            var ev = {};
            ev.target = (e.target ? e.target : e.srcElement);
            ev.which = (e.which ? e.which : e.button);
            return ev;
        },

        getWindowSize: function () {

            var w = 0;
            var h = 0;

            if (document.documentElement && document.documentElement.clientHeight) {
                w = document.documentElement.clientWidth;
                h = document.documentElement.clientHeight;
            } else if (document.body && document.body.clientHeight) {
                w = document.body.clientWidth;
                h = document.body.clientHeight;
            } else if (window.innerHeight) {
                w = window.innerWidth;
                h = window.innerHeight;
            }

            return {
                w: w,
                h: h
            };
        },

        getScrollPosition: function () {

            var x = 0;
            var y = 0;

            if (window.pageXOffset || window.pageYOffset) {
                x = window.pageXOffset;
                y = window.pageYOffset;
            } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
                x = document.body.scrollLeft;
                y = document.body.scrollTop;
            } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                x = document.documentElement.scrollLeft;
                y = document.documentElement.scrollTop;
            }

            return {
                x: x,
                y: y
            };
        },

        getOffset: function (node) {

            var x = 0;
            var y = 0;

            while (node) {
                x += node.offsetLeft;
                y += node.offsetTop;

                var p = node.parentNode;

                while (p && p != node.offsetParent && p.offsetParent) {
                    if (p.scrollLeft || p.scrollTop) {
                        x -= (p.scrollLeft | 0);
                        y -= (p.scrollTop | 0);
                        break;
                    }
                    p = p.parentNode;
                }
                node = node.offsetParent;
            }

            return {
                x: x,
                y: y
            };
        },

        getViewport: function () {
            var windowSize = $.getWindowSize();
            var scroll = $.getScrollPosition();

            return {
                l: scroll.x,
                t: scroll.y,
                r: scroll.x + windowSize.w,
                b: scroll.y + windowSize.h
            };
        }
    };

    $.Browser = {};
    $.Browser.ie = !!(window.attachEvent && !window.opera);
    $.Browser.ie6 = $.Browser.ie && navigator.userAgent.indexOf("MSIE 6.0") != -1;



    // Helper class that handles displaying tooltips
    var Tooltip = new function () {

        var PADDING = 5;

        var tooltipWrapper;
        var tooltipContent;

        function initialize() {

            tooltipWrapper = $.create('div');
            tooltipWrapper.className = 'dp-tooltip-wrapper';

            tooltipContent = $.create('div');
            tooltipContent.className = 'dp-tooltip-wrapper-inner';

            tooltipWrapper.appendChild(tooltipContent);
            document.body.appendChild(tooltipWrapper);

            hide();
        }

        function show(node, html) {

            if (tooltipWrapper == null) {
                initialize();
            }

            tooltipWrapper.style.visibility = 'hidden';
            tooltipWrapper.style.display = 'block';
            tooltipContent.innerHTML = html;

            var viewport = $.getViewport();
            var offset = $.getOffset(node);

            var x = offset.x + node.offsetWidth + PADDING;
            var y = offset.y - tooltipWrapper.offsetHeight - PADDING;

            if (y < viewport.t) {
                y = viewport.t;
            }

            if (x + tooltipWrapper.offsetWidth > viewport.r) {
                x = offset.x - tooltipWrapper.offsetWidth - PADDING;
            }

            reveal(x, y);
        }

        function hide() {

            if (tooltipWrapper == null) {
                return;
            }

            tooltipWrapper.style.display = 'none';
        }

        function reveal(x, y) {

            tooltipWrapper.style.left = x + 'px';
            tooltipWrapper.style.top = y + 'px';

            tooltipWrapper.style.visibility = 'visible';
        }

        // Public methods
        this.show = show;
        this.hide = hide;

    };

    construct();

};

function addCommasToNumber(nStr)
        {
            nStr += '';
            x = nStr.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';
            var rgx = /(\d+)(\d{3})/;
            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ',' + '$2');
            }
            return x1 + x2;
        }

// NovaRO Market grabbing functions
//function novaMarketPrices() {
//    if ($('.nro-whosells').length > 0 ) {
//        $('.nro-whosells').each(function () {
//
//            var whosellsEle = $(this)
//            var itemid=$(this).attr("data-id")
//            var refine=$(this).attr("data-refine") ? $(this).attr("data-refine") : -1
//            var options=$(this).attr("data-options") ? $(this).attr("data-options") : ""
//            var notfound = $(this).attr("data-notfound") ? $(this).attr("data-notfound") : 'N/A'
//
//            $.get('https://www.novaragnarok.com/?module=vending&action=item&id=' + itemid, function(data) {
//                var lowestValue = 1000000001
//                $('#itemtable > tbody > tr', data).each(function(index,elem) {
//                    var cols=$('td', $(this))
//                    if (cols.length === 4) { //weapon/armour
//                        if (refine !== -1 && cols[1].textContent.replace(/\D/g,'') != refine)
//                            return
//                    
//                        if (cols[2].textContent.toLowerCase().includes(options.toLowerCase())) {
//                            if (parseInt(cols[0].textContent.replace(/\D/g,'')) < lowestValue)
//                                lowestValue = parseInt(cols[0].textContent.replace(/\D/g,''))
//                        }
//                    }
//                    else if (cols.length === 5) { //card
//                        // Check if it's standalone card
//                        if ($('img',cols[0]).attr('src').replace(/^.*[\\\/]/, '').replace(/\D/g,'') !== itemid)
//                            return
//                        // Ignore refine and options if given, since card on its own makes more sense.
//                        
//                        if (parseInt(cols[1].textContent.replace(/\D/g,'')) < lowestValue)
//                            lowestValue = parseInt(cols[1].textContent.replace(/\D/g,''))
//                    }
//                    else if (cols.length === 3) { //general
//                        if (parseInt(cols[0].textContent.replace(/\D/g,'')) < lowestValue)
//                            lowestValue = parseInt(cols[0].textContent.replace(/\D/g,''))
//                    }
//                })
//                var output = '<a href="https://www.novaragnarok.com/?module=vending&action=item&id=' + itemid + '">' + notfound + '</a>'
//                if (lowestValue != 1000000001)
//                    output='<a href="https://www.novaragnarok.com/?module=vending&action=item&id=' + itemid + '">' + addCommasToNumber(lowestValue) + 'z</a>'
//                whosellsEle.replaceWith(output)
//            })
//        })
//    }
//
//  if ($('.nro-weeklyaverage').length > 0)
//  {
//    var oneWeekAgo = new Date();
//    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7)
//    $('.nro-weeklyaverage').each(function ()
//    {
//      var weeklyAvgEle = $(this)
//      var itemid = $(this).attr("data-id")
//      var refine = $(this).attr("data-refine") ? $(this).attr("data-refine") : -1
//      var options = $(this).attr("data-options") ? $(this).attr("data-options") : ""
//      $.get('https://www.novaragnarok.com/?module=vending&action=itemhistory&id=' + itemid, function (
//        data)
//      {
//        var weekSum = 0
//        var weekQty = 0
//        $('#itemtable > tbody > tr', data).each(function (index, elem)
//        {
//          var cols = $('td', $(this))
//          // Only one week back
//          var sellDateArray = cols[0].textContent.replace(/[:-]/g, '/').split('/')
//          var sellDate = new Date("20" + sellDateArray[2], sellDateArray[0] - 1, sellDateArray[1],
//            sellDateArray[3], sellDateArray[4])
//          if (sellDate < oneWeekAgo)
//              return
//          if (cols.length === 4)
//          { //weapon/armor
//            // Only look at given refine
//            if (refine != -1 && cols[2].textContent.replace(/\D/g, '') != refine)
//                return
//            // Also only if enchant matches
//            if (!cols[3].textContent.toLowerCase().includes(options.toLowerCase()))
//                return
//            weekSum += parseInt(cols[1].textContent.replace(/\D/g, ''), 10)
//            weekQty += 1
//          }
//          else if (cols.length === 3)
//          { // general
//            qty = parseInt(cols[2].textContent.replace(/\D/g, ''), 10)
//            weekSum += parseInt(cols[1].textContent.replace(/\D/g, ''), 10) * qty
//            weekQty += qty
//          }
//        })
//        var output = '<a href="https://www.novaragnarok.com/?module=vending&action=itemhistory&id=' +
//          itemid + '">'
//        if (weekQty > 0)
//        {
//          var avg = weekSum / weekQty
//          output += addCommasToNumber(Math.round(avg) + "z")
//          weeklyAvgEle.text(addCommasToNumber(Math.round(avg) + "z</a>"))
//        }
//        else output += "0z</a>"
//        weeklyAvgEle.replaceWith(output)
//      })
//    })
//  }
//  if ($('.nro-monthlyaverage').length > 0)
//  {
//    var oneMonthAgo = new Date();
//    oneMonthAgo.setDate(oneMonthAgo.getDate() - 31)
//    $('.nro-monthlyaverage').each(function ()
//    {
//      var monthlyAvgEle = $(this)
//      var itemid = $(this).attr("data-id")
//      var refine = $(this).attr("data-refine") ? $(this).attr("data-refine") : -1
//      var options = $(this).attr("data-options") ? $(this).attr("data-options") : ""
//      $.get('https://www.novaragnarok.com/?module=vending&action=itemhistory&id=' + itemid, function (
//        data)
//      {
//        var monthSum = 0
//        var monthQty = 0
//        $('#itemtable > tbody > tr', data).each(function (index, elem)
//        {
//          var cols = $('td', $(this))
//          // Only one month back
//          var sellDateArray = cols[0].textContent.replace(/[:-]/g, '/').split('/')
//          var sellDate = new Date("20" + sellDateArray[2], sellDateArray[0] - 1, sellDateArray[1],
//            sellDateArray[3], sellDateArray[4])
//          if (sellDate < oneMonthAgo) return
//          if (cols.length === 4)
//          { //weapon/armor
//            // Only look at given refine
//            if (refine != -1 && cols[2].textContent.replace(/\D/g, '') != refine)
//                return
//            // Also only if enchant matches
//            if (!cols[3].textContent.toLowerCase().includes(options.toLowerCase()))
//                return
//            
//            monthSum += parseInt(cols[1].textContent.replace(/\D/g, ''), 10)
//            monthQty += 1
//          }
//          else if (cols.length === 3)
//          { // general
//            qty = parseInt(cols[2].textContent.replace(/\D/g, ''), 10)
//            monthSum += parseInt(cols[1].textContent.replace(/\D/g, ''), 10) * qty
//            monthQty += qty
//          }
//        })
//        var output = '<a href="https://www.novaragnarok.com/?module=vending&action=itemhistory&id=' +
//          itemid + '">'
//        if (monthQty > 0)
//        {
//          var avg = monthSum / monthQty
//          output += addCommasToNumber(Math.round(avg) + "z")
//          monthlyAvgEle.text(addCommasToNumber(Math.round(avg) + "z</a>"))
//        }
//        else output += "0z</a>"
//        monthlyAvgEle.replaceWith(output)
//      })
//    })
//  }
//}


// This function is used to automatically copy the Navi information to the user clipboard.
// The data parameters are received from the Template:NaviLink.
function copyNaviLink() {
    if ($('.naviText').length > 0) {
        $('.naviText').each(function () {
            var naviLink = $(this);
            var copiedMessage = naviLink.next();

            var map = naviLink.attr('data-map');
            var x = naviLink.attr('data-x');
            var y = naviLink.attr('data-y');

            naviLink.click({ map: map, x: x, y: y }, function () {
                // Context is used to keep the right 'this' reference, it's needed for setTimeOut to work properly. 
                var context = $(this);
                var copiedText = "/navi " + map + " " + x + "/" + y;
                // Temporary input used to select the text and copy, it's removed after the copy is done.
                var inputTemp = document.createElement("input");
                inputTemp.setAttribute("value", copiedText);
                document.body.appendChild(inputTemp);
                inputTemp.select();
                document.execCommand("copy");
                inputTemp.remove();
                // Switches the text to indicate that the navi was copied and timesout after 2 seconds getting back to normal.
                context.css("display", "none");
                context.next().css("display", "inline-block");
                setTimeout(function () {
                    context.css("display", "inline-block");
                    context.next().css("display", "none");
                }, 2000);
            }
            );
        });
    }
}

$(document).ready(function() {
    //novaMarketPrices();
    copyNaviLink();
})

// Credits to iRO Wiki for the table of contents
var tocImgHid = 'https://www.novaragnarok.com/wiki/images/a/ad/Arr_r.png';
var tocImgSho = 'https://www.novaragnarok.com/wiki/images/f/f0/Arr_d.png';

function tocTree() {
  mw.util.addCSS('a.toctogHidden img, a.toctogShown img, a.toctogNull img {width:12px;height:12px;} #toc li a {padding-right:3px;} a.toctogNull img {visibility:hidden;}');

  var toc = document.getElementById('toc');
  if(!toc) return
  var li = toc.getElementsByTagName('li');
  for(var i=0;i<li.length;i++) {
    var cul = li[i].getElementsByTagName('ul');
    var a = document.createElement('a');
     if(cul.length == 0) {
       a.setAttribute('class','toctogNull');
     } else {
       a.setAttribute('class','toctogShown');
       a.setAttribute('id','toctog-a-' + i );
       a.setAttribute('href','javascript:tocTreeToggle("' + i + '");');
     }
     var img = document.createElement('img');
      img.setAttribute('src',tocImgHid);
      img.setAttribute('id','toctog-i-' + i );
     a.appendChild(img);
    li[i].insertBefore(a,li[i].firstChild);
    if(cul.length != 0) tocTreeToggle(i)
  }
}
if(wgNamespaceNumber != -1 && wgArticleId != 0) 
    $(tocTree)

function tocTreeToggle(id) {
  var a = document.getElementById('toctog-a-' + id);
  var img = document.getElementById('toctog-i-' + id);
  var cul = a.parentNode.getElementsByTagName('ul');
  var disp;
  if(a.getAttribute('class') == 'toctogShown') {
    disp = 'none';
    a.setAttribute('class','toctogHidden');
    img.setAttribute('src',tocImgHid);
  } else {
    disp = 'block';
    a.setAttribute('class','toctogShown');
    img.setAttribute('src',tocImgSho);
  }
  for(var j=0;j<cul.length;j++) {
    if(cul[j].parentNode == a.parentNode) cul[j].style.display = disp
  }
}