(function($) {
    'use strict';

    function getQueryArg(url, name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(url);
        return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    function addQueryArg(url, key, value) {
        var re = new RegExp("([?&])" + key + "=.*?(&|$|#)", "i");
        var separator = url.indexOf('?') !== -1 ? "&" : "?";
        if (url.match(re)) {
            return url.replace(re, '$1' + key + "=" + value + '$2');
        }
        var anchor = '';
        if (url.indexOf('#') !== -1) {
            anchor = url.substr(url.indexOf('#'));
            url = url.substr(0, url.indexOf('#'));
        }
        return url + separator + key + "=" + value + anchor;
    }

    function getLocation(href) {
        var a = document.createElement("a");
        a.href = href;
        return a;
    }

    function processUrl(url) {
        var targetLocation = getLocation(url);
        if (url === '#' ||
            targetLocation.host !== location.host
        ) {
            return url;
        }

        if (url[0] === '#') {
            return location.href.split('#')[0] + url;
        }

        var parametersForCheck = ['theme_name'];

        parametersForCheck.forEach(function (attr) {
            var value = getQueryArg(location.href, attr);
            if (value !== null) {
                url = addQueryArg(url, attr, value);
            }
        });
        return url;
    }

    function updatePreviewLinks() {
        $("a[href*=\'#038;\']").each(function () {
            var href = $(this).attr("href");
            href = href.replace("#038;", "&");
            $(this).attr("href", href);
        });

        if (window.isThemlerIframe()) {
            return;
        }

        $('form').each(function () {
            var form = $(this);
            ['action', 'data-url-update'].forEach(function (attr) {
                var value = form.attr(attr);
                if (value) {
                    form.attr(attr, processUrl(value));
                }
            });
        });

        $('[href]').each(function() {
            var link = $(this);
            if (link.prop('tagName').toLowerCase() !== 'link') {
                link.attr('href', processUrl(link.attr('href')));
            }
        });
    }

    $(updatePreviewLinks);

    window.processPreviewUrl = processUrl;
})(jQuery);