document.addEventListener('DOMContentLoaded', function () {
    function getParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(location.search);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }
    var origen = getParameter('utm_source') || 'organico';
    var inputOrigen = document.querySelector('#form-field-origen');
    if (inputOrigen) inputOrigen.value = origen;

    var currentSearch = location.search;
    if (currentSearch) {
        var urlParams = new URLSearchParams(currentSearch);
        var utmParams = [];
        urlParams.forEach(function (value, key) {
            if (key.indexOf('utm_') === 0 && key !== 'gclid') { utmParams.push(key + '=' + value); }
        });
        if (utmParams.length > 0) {
            var queryString = utmParams.join('&');
            document.querySelectorAll('a').forEach(function (link) {
                if (link.href && link.hostname === location.hostname && link.href.indexOf('javascript:') === -1 && link.getAttribute('href') !== '#') {
                    var separator = link.href.indexOf('?') > -1 ? '&' : '?';
                    link.href += separator + queryString;
                }
            });
        }
    }
    var currentPath = window.location.pathname || '/';
    var history = JSON.parse(sessionStorage.getItem('user_nav_history') || '[]');
    if (history.length > 0 && history[0].indexOf('http') === 0) { history = []; }
    if (history.length === 0 || history[history.length - 1] !== currentPath) {
        history.push(currentPath);
        sessionStorage.setItem('user_nav_history', JSON.stringify(history));
    }
    var entryPage = history[0];
    var pageLead = currentPath;
    var prevPage = history.length > 1 ? history[history.length - 2] : 'Entrada directa';

    var inputEntry = document.querySelector('#form-field-landing_url');
    if (inputEntry) inputEntry.value = entryPage;
    var inputPrev = document.querySelector('#form-field-prev_url');
    if (inputPrev) inputPrev.value = prevPage;
    var inputCurrent = document.querySelector('#form-field-current_url');
    if (inputCurrent) inputCurrent.value = pageLead;
});
