/**
 * Rewrite Velzon theme relative "assets/..." URLs to absolute theme asset base.
 */
(function () {
    'use strict';

    var base = document.documentElement.getAttribute('data-theme-assets-base') || '';
    if (!base) {
        return;
    }
    if (base.charAt(base.length - 1) !== '/') {
        base += '/';
    }

    function resolveThemeUrl(url) {
        if (typeof url !== 'string' || url.indexOf('assets/') !== 0) {
            return url;
        }
        return base + url.slice(7);
    }

    var xhrOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (method, url) {
        var args = Array.prototype.slice.call(arguments);
        args[1] = resolveThemeUrl(url);
        return xhrOpen.apply(this, args);
    };

    var imgSrc = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, 'src');
    if (imgSrc && imgSrc.set) {
        Object.defineProperty(HTMLImageElement.prototype, 'src', {
            configurable: true,
            enumerable: imgSrc.enumerable,
            get: imgSrc.get,
            set: function (value) {
                imgSrc.set.call(this, resolveThemeUrl(value));
            },
        });
    }
})();
