MediaWiki:TPprices.js

Материал из Guild Wars 2 wiki
Перейти к: навигация, поиск
/* Показ цен торгового поста через GW2 API.
*  Оригинальный код взят с "http://wiki.guildwars2.com/wiki/Widget:TP_prices".
*/

$(document).ready(function(){
    var elements = {};
    $('.gw2-tpprice').each(function () {
        var id = +this.getAttribute('data-id');
        if (!id || parseInt(id) != id) {
            return;
        }
        if (!elements[id]) {
            elements[id] = [];
        }
        elements[id].push({ elem: this, info: this.getAttribute('data-info') });
    });

    var ids = $.map(elements, function (o, i) { return i; }).join(',');
    if (!ids) return;
    $.getJSON('https://api.guildwars2.com/v2/commerce/prices?wiki=1&ids=' + ids).done(function (data) {
        $.each(data, function (index, item) {
            var buyText = 'Высочайшая цена на покупку: ' + getCoin(item.buys.unit_price);
            var sellText = 'Нижайшая цена на продажу: ' + getCoin(item.sells.unit_price);
            $.each(elements[item.id], function () {
                if (this.info == 'buy') {
                    this.elem.innerHTML = getCoin(item.buys.unit_price, true);
                    this.elem.title = buyText + ' (' + item.buys.quantity + ' заказано)';
                    this.elem.setAttribute('data-sort-value',item.buys.unit_price);
                }
                else if (this.info == 'sell') {
                    this.elem.innerHTML = getCoin(item.sells.unit_price, true);
                    this.elem.title = sellText + ' (' + item.sells.quantity + ' выставлено)';
                    this.elem.setAttribute('data-sort-value',item.sells.unit_price);
                }
                else {
                    this.elem.innerHTML = getCoin(item.sells.unit_price, true);
                    this.elem.title = sellText + ' (' + item.sells.quantity + ' выставлено)\n' +
                                      buyText + ' (' + item.buys.quantity + ' заказано)';
                    this.elem.setAttribute('data-sort-value',item.sells.unit_price);
                }
                if ((this.info == 'buy' && !item.buys.quantity) || (this.info != 'buy' && !item.sells.quantity)) {
                    this.elem.style.opacity = '.5';
                }
            });
        });
    });
    
    function getCoin(coin, asHtml) {
    var text = (coin % 100) + ' мед.';
    var html = (coin % 100) + '&nbsp;<img src="/images/e/eb/Copper_coin.png" alt="Медь" />';
        if (coin >= 100) {
            var silver = (coin / 100 >> 0) % 100;
            html = silver + '&nbsp;<img src="/images/3/3c/Silver_coin.png" alt="Серебро" />&nbsp;' + html;
            text = silver + ' cер. ' + text;
        }
        if (coin >= 10000) {
            var gold = coin / 10000 >> 0;
            html = gold + '&nbsp;<img src="/images/d/d1/Gold_coin.png" alt="Золото" />&nbsp;' + html;
            text = gold + ' зол. ' + text;
        }
        return asHtml ? html : text;
    }
});