//<script>
console.log("-== PRE GTM Consent v1.4 ==-");

//window.pageLang = 'ru';
let cwUserCountry = 'US';
if (typeof window.pageLang == 'undefined') {
  window.pageLang = 'en';
}

if(document.location.href.indexOf('force_country=FR') > -1 ) {
    cwUserCountry = 'FR';
}

if (typeof gtag !== "function") {
  window.dataLayer = window.dataLayer || [];
  window.gtag = function() {
    window.dataLayer.push(arguments);
  };
}

gtag("consent", "default", {
    "ad_storage": "denied",
    "ad_user_data": "denied",
    "ad_personalization": "denied",
    "analytics_storage": "denied"
});

function getCookieSimple(name) {
  const searchName = `${name}=`;
  const cookiesDecoded = decodeURIComponent(document.cookie);
  const cookiesArray = cookiesDecoded.split("; ");
  const find = cookiesArray.find(item => item.indexOf(searchName) === 0);
  if (find) {
    return find.substring(searchName.length);
  }
  return "";
}

function saveGtagDataSimple(data) {
  try {
    gtag("consent", "update", {
      ad_storage: data.advertising ? "granted" : "denied",
      analytics_storage: data.performance ? "granted" : "denied",
      ad_personalization: data.personalizedAdvertising ? "granted" : "denied",
      ad_user_data: data.useDataForAdvertising ? "granted" : "denied"
    });
    console.log("-== Consent was updated from cookie ==-");
  } catch (e) {
    console.log("Google tag manager is not found");
  }
}

const euCountries = [
  "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR",
  "DE", "GR", "HU", "IS", "IE", "IT", "LV", "LI", "LT", "LU",
  "MT", "NL", "NO", "PL", "PT", "RO", "SK", "SI", "ES", "SE",
  "GB"
];

// USER FROM EU 
if (euCountries.indexOf(cwUserCountry) > -1 && document.location.host !== 'www.jforex.net' ) { 

  let cookieName = "yummyCookieWidget_userData";
  const savedData = getCookieSimple(cookieName);

  if (savedData) {
    const parsedSavedData = JSON.parse(savedData);
    console.log("--== Restore consent from cookie ==---");
    saveGtagDataSimple(parsedSavedData);
  } 
  
  // Function for loading main script ater DOM
  function addCookieScript() {
    const openPrivacySettingsElement = document.getElementById("open-privacy-settings");
    if (openPrivacySettingsElement) {
      openPrivacySettingsElement.addEventListener("click", (e) => {
        e.preventDefault();
        if (window.yummyCookieWidget) {
          window.yummyCookieWidget.setWidgetVisibility(true);
          window.yummyCookieWidget.setScreenVisibility(1);
        }
      });
    }
    
    const scriptElement = document.createElement("script");
    scriptElement.src = `https://www.dukascopy.com/api/data/get/yummyCookieWidget?lang=${window.pageLang}&forJs=1&branchId=1&noCache=0&v=2.1.0`;
    document.body.appendChild(scriptElement);
    
    if (document.cookie.indexOf("yummyCookieWidget") === -1) {
      try {
        dataLayer.push({ "event": "cookie_bnr_show_dur" });
      } catch (e) {
      }
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', addCookieScript);
  } else {
    addCookieScript();
  }
  
} else {

  // For non-EU countries, we assume consent is granted by default
  gtag("consent", "update", {
    "ad_storage": "granted",
    "ad_user_data": "granted",
    "ad_personalization": "granted",
    "analytics_storage": "granted"
  });

  const openPrivacySettingsElement = document.getElementById("open-privacy-settings");
  if (openPrivacySettingsElement) {
    openPrivacySettingsElement.parentElement.style.display = "none";
  }
}


/**
 * UTM Params
 */
document.addEventListener('DOMContentLoaded', () => {
  // getting utm_* from current url
  const pageParams = new URLSearchParams(window.location.search);
  const utmEntries = [];
  for (const [k, v] of pageParams) {
    if (k.toLowerCase().startsWith('utm_') && v !== '') utmEntries.push([k, v]);
  }
  const hasUtm = utmEntries.length > 0;

  // 2) Lats find all links (exclude mailto:/tel:/javascript:)
  const anchors = Array.from(document.querySelectorAll('a[href*=".dukascopy.com/rto3"]'))
    .filter(a => {
      const href = a.getAttribute('href') || '';
      return !/^(mailto:|tel:|javascript:)/i.test(href);
    });

  // 3) Update links
  const base = document.baseURI || window.location.href;
  let modified = 0;

  anchors.forEach(a => {
    // Disassamble links
    const url = new URL(a.getAttribute('href'), base);
    if (hasUtm) {
      const sp = url.searchParams;
      for (const [k, v] of utmEntries) sp.set(k, v);
      url.search = sp.toString(); // save other parameters 
      a.setAttribute('href', url.toString()); // save hash/fragment
      modified++;
    }
  });

  // some debug info
  console.log({
    hasUtm,
    utmKeys: utmEntries.map(([k]) => k),
    targetsFound: anchors.length,
    targetsModified: modified
  });
});

/**
 * Dukascopy Pixel
 */
(function() {
    'use strict';
    
    // Config
    const RTO_STATS_CONFIG = {
        endpoint: 'https://www.dukascopy.com/api/rto-stats/track',
        pageIds: {
            'live-login.dukascopy.com': 'RtoSwiss',
            'eu-live.dukascopy.com': 'RtoEu', 
            'eu.site.': 'RtoEuT',
            'kir.dukascopy': 'RtoJpT',
            'rto-page-5': 'RTO5'
        },
        storageKey: 'rto_visitor_id'
    };
    function isLocalStorageSupported() {
        try {
            return ('localStorage' in window && window.localStorage);
        } catch(err) {
            return false;
        }
    }
    function generateVisitorId() {
        return 'v_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
    function getVisitorId() {
        if (!isLocalStorageSupported()) {
            return generateVisitorId();
        }
        
        let visitorId = localStorage.getItem(RTO_STATS_CONFIG.storageKey);
        if (!visitorId) {
            visitorId = generateVisitorId();
            try {
                localStorage.setItem(RTO_STATS_CONFIG.storageKey, visitorId);
            } catch(e) {
                console.warn('RTO Stats: Cannot save visitor ID to localStorage');
            }
        }
        return visitorId;
    }
    function getPageId() {
        // &#1055;&#1088;&#1086;&#1074;&#1077;&#1088;&#1103;&#1077;&#1084; &#1087;&#1086; URL &#1080;&#1083;&#1080; &#1076;&#1088;&#1091;&#1075;&#1080;&#1084; &#1082;&#1088;&#1080;&#1090;&#1077;&#1088;&#1080;&#1103;&#1084;
        const path = window.location.host;
        for (const [key, value] of Object.entries(RTO_STATS_CONFIG.pageIds)) {
            if (path.includes(key)) {
                return value;
            }
        }
        return null;
    }
    function sendStats(pageId, visitorId) {
        const img = new Image();
        img.style.display = 'none';
        
        const params = new URLSearchParams({
            page: pageId,
            visitor: visitorId,
            url: window.location.href,
            ref: document.referrer || '',
            ts: Date.now()
        });
        
        img.src = RTO_STATS_CONFIG.endpoint + '?' + params.toString();
        
        // &#1044;&#1086;&#1073;&#1072;&#1074;&#1083;&#1103;&#1077;&#1084; &#1074; DOM &#1076;&#1083;&#1103; &#1075;&#1072;&#1088;&#1072;&#1085;&#1090;&#1080;&#1080; &#1086;&#1090;&#1087;&#1088;&#1072;&#1074;&#1082;&#1080;
        document.body.appendChild(img);
        
        // &#1059;&#1076;&#1072;&#1083;&#1103;&#1077;&#1084; &#1095;&#1077;&#1088;&#1077;&#1079; &#1085;&#1077;&#1082;&#1086;&#1090;&#1086;&#1088;&#1086;&#1077; &#1074;&#1088;&#1077;&#1084;&#1103;
        setTimeout(() => {
            if (img.parentNode) {
                img.parentNode.removeChild(img);
            }
        }, 3000);
    }
    function trackPageVisit() {
        const pageId = getPageId();
        if (!pageId) {
            return; // &#1053;&#1077; RTO &#1089;&#1090;&#1088;&#1072;&#1085;&#1080;&#1094;&#1072;
        }
        
        const visitorId = getVisitorId();
        sendStats(pageId, visitorId);
    }
    function init() {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', trackPageVisit);
        } else {
            // DOM &#1091;&#1078;&#1077; &#1079;&#1072;&#1075;&#1088;&#1091;&#1078;&#1077;&#1085;, &#1080;&#1089;&#1087;&#1086;&#1083;&#1100;&#1079;&#1091;&#1077;&#1084; setTimeout &#1076;&#1083;&#1103; &#1072;&#1089;&#1080;&#1085;&#1093;&#1088;&#1086;&#1085;&#1085;&#1086;&#1089;&#1090;&#1080;
            setTimeout(trackPageVisit, 100);
        }
    }
    init();
})();

/**
 * End of Dukascopy Pixel
 */
 
 
 /**
  * IB REVERSE BLOCK
  */
 
 (function() {
    'use strict';

    // &#1052;&#1072;&#1089;&#1089;&#1080;&#1074; URL &#1076;&#1083;&#1103; &#1089;&#1086;&#1087;&#1086;&#1089;&#1090;&#1072;&#1074;&#1083;&#1077;&#1085;&#1080;&#1103;
    const urlMappings = [
  {"type":"L","id":176,"url":"https://kir.dukascopy.com/inc/ai/"},

  {"type":"B","id":1,"url":"https://www.dukascopy.com/land/trading/bank/forex/"},
  {"type":"B","id":4,"url":"https://www.dukascopy.com/land/trading/eu/forex/"},
  {"type":"B","id":7,"url":"https://www.dukascopy.com/land/trading/bank/platforms/"},
  {"type":"B","id":10,"url":"https://www.dukascopy.com/land/trading/eu/platforms/"},
  {"type":"B","id":869,"url":"https://www.dukascopy.com/land/trading/bank/crypto/"},
  {"type":"B","id":881,"url":"https://www.dukascopy.com/land/trading/eu/crypto/"},
  {"type":"B","id":1086,"url":"https://www.dukascopy.com/land/trading/bank/home/"},
  {"type":"B","id":1414,"url":"https://www.dukascopy.com/land/trading/bank/home/"},
  {"type":"L","id":190,"url":"https://www.dukascopy.com/land/open-live/eu/"},
  {"type":"L","id":189,"url":"https://www.dukascopy.com/land/try-demo/eu/"},
  {"type":"L","id":188,"url":"https://www.dukascopy.com/europe/english/platforms/mt5/ad-live/"},
  {"type":"L","id":187,"url":"https://www.dukascopy.com/europe/english/platforms/mt4/ad-live/"},
  {"type":"L","id":186,"url":"https://www.dukascopy.com/europe/english/platforms/jforex/"},
  {"type":"L","id":185,"url":"https://www.dukascopy.com/land/try-demo/"},
  {"type":"L","id":184,"url":"https://www.dukascopy.com/swiss/english/platforms/jforex/"},
  {"type":"L","id":183,"url":"https://www.dukascopy.com/land/open-live/"},
  {"type":"L","id":180,"url":"https://www.dukascopy.com/swiss/arabic/home/"},
  {"type":"L","id":179,"url":"https://www.dukascopy.ch/swiss/chinese/home/"},
  {"type":"L","id":178,"url":"https://www.dukascopy.com/swiss/pt/home/"},
  {"type":"L","id":177,"url":"https://www.dukascopy.com/swiss/spanish/home/"},
  {"type":"L","id":176,"url":"https://www.dukascopy.com/swiss/russian/home/"},
  {"type":"L","id":175,"url":"https://www.dukascopy.com/swiss/deutsch/home/"},
  {"type":"L","id":174,"url":"https://www.dukascopy.com/swiss/french/home/"},
  {"type":"L","id":173,"url":"https://www.dukascopy.com/swiss/english/home/"},
  {"type":"L","id":137,"url":"https://www.dukascopy.com/land/trading/eu/crypto/"},
  {"type":"L","id":127,"url":"https://www.dukascopy.com/land/trading/bank/crypto/"},
  {"type":"L","id":80,"url":"https://www.dukascopy.com/land/trading/bank/binaries/"},
  {"type":"L","id":68,"url":"https://www.dukascopy.com/land/trading/eu/platforms/"},
  {"type":"L","id":54,"url":"https://www.dukascopy.com/land/trading/bank/platforms/"},
  {"type":"L","id":41,"url":"https://www.dukascopy.com/land/trading/eu/forex/"}
];
    function getURLParams() {
        const params = {};
        const searchParams = new URLSearchParams(window.location.search);
        for (const [key, value] of searchParams) {
            params[key] = value;
        }
        return params;
    }
    function isInteger(value) {
        return /^\d+$/.test(value);
    }
    function normalizeURL(url) {
        try {
            const urlObj = new URL(url);
            let normalizedHost = urlObj.hostname.replace(/^www\./, '');
            let normalizedPath = urlObj.pathname;
            let normalizedSearch = urlObj.search;

            return normalizedHost + normalizedPath + normalizedSearch;
        } catch (e) {
            return null;
        }
    }

    /**
     * &#1053;&#1072;&#1081;&#1090;&#1080; &#1089;&#1086;&#1086;&#1090;&#1074;&#1077;&#1090;&#1089;&#1090;&#1074;&#1091;&#1102;&#1097;&#1080;&#1081; &#1101;&#1083;&#1077;&#1084;&#1077;&#1085;&#1090; &#1074; &#1084;&#1072;&#1089;&#1089;&#1080;&#1074;&#1077; &#1087;&#1086; URL
     */
    function findMatchingElement(currentURL) {
        const normalizedCurrentURL = normalizeURL(currentURL);
        if (!normalizedCurrentURL) return null;
        for (const element of urlMappings) {
            const normalizedElementURL = normalizeURL(element.url);
            if(normalizedElementURL && normalizedCurrentURL.indexOf(normalizeURL(element.url)) === 0) {
              console.log('Matched URL:', normalizedElementURL);
              return element;
            }
        }
        return null;
    }

    /**
     * &#1057;&#1086;&#1079;&#1076;&#1072;&#1090;&#1100; URL &#1088;&#1077;&#1076;&#1080;&#1088;&#1077;&#1082;&#1090;&#1072;
     */
    function createRedirectURL(ibref, type, linkId, currentParams) {
        const filteredParams = { ...currentParams };
        delete filteredParams.ibref;
        // &#1041;&#1072;&#1079;&#1086;&#1074;&#1099;&#1081; &#1096;&#1072;&#1073;&#1083;&#1086;&#1085; &#1088;&#1077;&#1076;&#1080;&#1088;&#1077;&#1082;&#1090;&#1072; - &#1079;&#1072;&#1084;&#1077;&#1085;&#1080;&#1090;&#1077; &#1085;&#1072; &#1074;&#1072;&#1096; &#1088;&#1077;&#1072;&#1083;&#1100;&#1085;&#1099;&#1081; &#1096;&#1072;&#1073;&#1083;&#1086;&#1085;
        let redirectURL = `https://www.dukascopy.com/api/ib/${ibref}/type-${type}/target-id-${linkId}`;
        if (Object.keys(filteredParams).length > 0) {
            // &#1055;&#1088;&#1086;&#1074;&#1077;&#1088;&#1103;&#1077;&#1084; &#1077;&#1089;&#1090;&#1100; &#1083;&#1080; &#1091;&#1078;&#1077; &#1087;&#1072;&#1088;&#1072;&#1084;&#1077;&#1090;&#1088;&#1099; &#1074; URL
            const separator = redirectURL.includes('?') ? '&' : '?';
            const additionalParams = Object.keys(filteredParams)
                .map(key => `${key}=${encodeURIComponent(filteredParams[key])}`)
                .join('&');
            redirectURL += separator + additionalParams;
        }
        return redirectURL;
    }

    /**
     * &#1054;&#1089;&#1085;&#1086;&#1074;&#1085;&#1072;&#1103; &#1092;&#1091;&#1085;&#1082;&#1094;&#1080;&#1103; &#1087;&#1088;&#1086;&#1074;&#1077;&#1088;&#1082;&#1080; &#1080; &#1088;&#1077;&#1076;&#1080;&#1088;&#1077;&#1082;&#1090;&#1072;
     */
    function checkAndRedirect() {
      console.log('Running redirect script...');
        try {
            const params = getURLParams();
            const ibref = params.ibref;
            const clickid = params.clickid;
            if (!ibref || clickid !== undefined) {
                return;
            }
            if (!isInteger(ibref)) {
                return;
            }
            const currentURL = window.location.href;
            const matchingElement = findMatchingElement(currentURL);
            if (matchingElement) {
                // &#1057;&#1086;&#1079;&#1076;&#1072;&#1077;&#1084; URL &#1088;&#1077;&#1076;&#1080;&#1088;&#1077;&#1082;&#1090;&#1072;
                const redirectURL = createRedirectURL(ibref, matchingElement.type, matchingElement.id, params);

                // &#1042;&#1099;&#1087;&#1086;&#1083;&#1085;&#1103;&#1077;&#1084; &#1088;&#1077;&#1076;&#1080;&#1088;&#1077;&#1082;&#1090;
                console.log('Redirecting to:', redirectURL);
                // alert(redirectURL);
                window.location.href = redirectURL;
            }
            else {
                console.log('No matching URL found for redirection.');
            }

        } catch (error) {
            console.error('Error in redirect script:', error);
        }
    }

    // &#1047;&#1072;&#1087;&#1091;&#1089;&#1082;&#1072;&#1077;&#1084; &#1087;&#1088;&#1086;&#1074;&#1077;&#1088;&#1082;&#1091; &#1087;&#1086;&#1089;&#1083;&#1077; &#1079;&#1072;&#1075;&#1088;&#1091;&#1079;&#1082;&#1080; DOM
    //if (document.readyState === 'loading') {
    //    document.addEventListener('DOMContentLoaded', checkAndRedirect);
    //} else {
        checkAndRedirect();
    //}

})();
 
 
 /**
  * End IB REVERSE BLOCK
  */
 
