123321123 / Onliner Bucks

// ==UserScript==
// @name         Onliner Bucks
// @version      1
// @match        http://ab.onliner.by/**
// @match        http://catalog.onliner.by/**
// @grant        none
// ==/UserScript==

// todo monitor cccontents of .autoba-table.adverts-table

setInterval(function() { updatePrices(); }, 1000);

function updatePrices() {
    var rate = getRate();
    if (!rate) {
        return;
    }

    var elements = $('.cost-i p a strong[bucks!=1], .autoba-hd-details-costs .cost strong[bucks!=1], .b-cell-1 .price .js-currency-primary[bucks!=1]');
    elements.each(function(i) {
        var element = $(this);
        element.attr('bucks', 1);
        var roubles = parseCurrency(element.text());
        if (roubles) {
            element.html(formatCurrency(roubles / rate) + ' $<br><small style="color: grey">' + formatCurrency(roubles) + '</small>');
        }
    });

    elements = $('.pprice.pprice_byr a.black[bucks!=1], .b-offers-desc__info-price .b-offers-desc__info-sub[bucks!=1]');
    elements.each(function(i) {
        var element = $(this);
        element.attr('bucks', 1);
        var text = element.text();
        var match = text.match(/^\s*([0-9 \xA0]+)\s*[–-]?\s*([0-9 \xA0]+)?/); // \xA0 is &nbsp;
        if (match) {
            var r1 = parseCurrency(match[1]) / rate;
            var r2 = parseCurrency(match[2]) / rate;
            if (r1 && r2) {
                element.html(formatCurrency(r1) + ' $ &ndash; ' + formatCurrency(r2) + ' $<br><small style="color: grey">' + match[1] + ' &mdash; ' + match[2] + '</small>');
            } else if (r1) {
                element.html(formatCurrency(r1) + ' $<br><small style="color: grey">' + match[1] + '</small>');
            }
        }
    });
}

function parseCurrency(str) {
    if (!str) return 0;
    str = str.replace(/\s|\xA0|\$/g, ''); // \xA0 is &nbsp;
    return parseInt(str, 10);
}

function formatCurrency(val) {
    var result = '';
    val = val.toFixed(0) + '';
    //return val;
    letters = val.split('');
    for (var i = letters.length - 1, j = 0; i >= 0; i--, j++) {
        var letter = letters[i];
        if (j % 3 == 0 && j > 0) {
            result = ' ' + result;
        }
        result = letter + result;
    }
    return result;
}

function getRate() {
    return parseCurrency($('#currency-informer a span._u').text());
}