
    (function () {
        tp = window["tp"] || [];
        window.PianoESPConfig = {
            id: 90,
        };
        window.tpLoaded = true;
        /* Checkout related */
        /**
         * Event properties
         *
         * chargeAmount - amount of purchase
         * chargeCurrency
         * uid
         * email
         * expires
         * rid
         * startedAt
         * termConversionId
         * termId
         * promotionId
         * token_list
         * cookie_domain
         * user_token
         *
         */
        function onCheckoutComplete(data) {
            // Microsoft UET: prevent duplicate firing per session (recommended)
            var msSend = true;
            try {
                if (sessionStorage.getItem("ms_uet_subscribe_sent") === "1") {
                    msSend = false;
                } else {
                    sessionStorage.setItem("ms_uet_subscribe_sent", "1");
                }
            } catch (e) { }

            sendGA4CustomEvent("checkoutComplete", "G-0JD41JHSX2");
            sendCXEvent("register_premium", "産経ニュース有料会員", null);
            sendGoogleAdEvent('AW-11552239813/5BkHCPCLvccaEMXhxIQr');
            sendFbEvent("vls2504申込完了");

            // Microsoft Advertising conversion (Values ②)
            if (msSend) {
                loadMicrosoftUET(); // ensure base tag is loaded
                sendMicrosoftUETEvent("subscribe", {}); // Values required event
            }


            /* Yahoo!検索 コンバージョン */
            ytag({
                "type": "yss_conversion", "config":
                {
                    "yahoo_conversion_id": "1001369899",
                    "yahoo_conversion_label": "gs2PCOWrydwaEJHDqpFA",
                    "yahoo_conversion_value": "0"
                }
            });
            /* Yahoo!ディスプレイ コンバージョン */
            ytag({
                "type": "yjad_conversion", "config": {
                    "yahoo_ydn_conv_io": "uJbSaAYvZXCsXd-AGrL0wg..",
                    "yahoo_ydn_conv_label": "Q0BHVL84AVOK0T2XYL1249331",
                    "yahoo_ydn_conv_transaction_id": "",
                    "yahoo_ydn_conv_value": "0"
                }
            });
            /* ▼▼▼ START: Yahoo lytag purchase event ▼▼▼ */
            if (typeof lytag === 'function') {
                lytag({
                    type: 'event',
                    eventType: 'purchase',
                    tagId: '9d219f7c-8aff-4c33-a629-9321db5fdd8f',
                    config: {
                        snippetId: '2bb97a0c-9153-416c-bae1-c837937d2e11'
                    }
                });
            }
            /* ▲▲▲ END: Yahoo lytag purchase event ▲▲▲ */
          
  // --- X Ads (via GTM): subscription purchase ---
// Prevent duplicate firing per session (same idea as MS UET guard)
try {
    var xadSend = true;
    if (sessionStorage.getItem("piano_xad_subscription_purchase_sent") === "1") {
        xadSend = false;
    } else {
        sessionStorage.setItem("piano_xad_subscription_purchase_sent", "1");
    }

    if (xadSend) {
        var termId = data && (data.termId || data.termid)
            ? String(data.termId || data.termid)
            : "";

        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push({
            event: "piano_xad_subscription_purchase",
            term_id: termId
        });
    }
} catch (e) {
    // do nothing: must not affect checkout flow
}
// --- /X Ads ---
        
        }

        /* Google ad */
        function sendSegmentsToGoogleAds() {
            window.dataLayer = window.dataLayer ||
                [];
            cX = window.cX || {};
            cX.callQueue = cX.callQueue || [];
            cX.callQueue.push([
                "getSegments",
                {
                    persistedQueryId: "4b0ec19b287c7b8f8c422a414f8ee67eae574cb3", // Pianoから提供されたPersisted Query ID
                    callback: function (segments) {
                        try {
                            const filteredSegmentIds = segments
                                .filter((segment) => segment.type !== "contextual")
                                .map((segment) => segment.shortId); // ← shortId = '3c' など
                            gtag("js", new Date()); // Google広告へ送信
                            gtag("config", "AW-11552239813");
                            gtag("event", "page_view", {
                                'send_to': "AW-11552239813",
                                'customparameter1': filteredSegmentIds, // ← パラメータ名をPIANO側と揃えると安全
                                'aw_remarketing_only': true
                            });
                            console.log(
                                "Google Ad event sent with segments:",
                                filteredSegmentIds
                            );
                        } catch (e) {
                            console.log("Google Ad event send error", e);
                        }
                    }
                }
            ]);
        }
        // 【叶谷】2025/04/21: PIANOの指示。

        function gtag() {
            dataLayer.push(arguments);
        }
        function sendGoogleAdEvent(send_to) {
            window.dataLayer = window.dataLayer || [];
            try {
                gtag('event', 'conversion', {
                    'send_to': send_to,
                    'transaction_id': ''
                });
                //        gtag("js", new Date());
                //        gtag("config", "AW-11552239813");
                //        gtag("event", event, {
                //          send_to: "AW-11552239813/gag1CJjs5YIaEMXhxIQr",
                //        });
                //        console.log("google ad event send");
            } catch (e) {
                console.log(e);
                console.log("google ad event send error");
            }
        }
        // 【叶谷】2025/04/10: Valuesの指示。

        /* Facebook ad */
        function sendFbEvent(event) {
            try {
                fbq("track", event);
                console.log("fb custom conversion event sent:", event);
            } catch (e) {
                console.log("fb ad event send error", e);
            }
        }
        // 【叶谷】2025/04/16: Valuesの指示。

        function sendGACustomEvent(eventName, trackingId, name) {
            try {
                var command = "send";
                if (name != null) {
                    ga("create", trackingId, "auto", name);
                    command = name + ".send";
                } else {
                    ga("create", trackingId, "auto");
                }
                if (eventName === "register_premium") {
                    ga(
                        command,
                        "event",
                        "tools",
                        "move to premium page",
                        "header module"
                    );
                } else if (eventName === "register" || eventName === "offer-register") {
                    ga(
                        command,
                        "event",
                        "tools",
                        "move to userForm page",
                        "header module"
                    );
                } else if (eventName === "login") {
                    ga(command, "event", "tools", "move to login page", "header module");
                } else if (eventName === "plan") {
                    ga(command, "event", "tools", "move to plan page", "header module");
                } else {
                    ga(command, "event", "tools", eventName, "header module");
                }
            } catch (e) {
                console.log(e);
            }
        }
        function sendGA4CustomEvent(
            eventName,
            trackingId,
            termId,
            templateId,
            experienceId
        ) {
            try {
                window.dataLayer = window.dataLayer ||
                    [];
                gtag("js", new Date());
                gtag("config", trackingId);
                if (eventName === "register_premium") {
                    gtag("event", "move to premium page");
                } else if (eventName === "register") {
                    gtag("event", "move to userForm page");
                } else if (eventName === "offer-register") {
                    if (templateId)
                        gtag("event", "move to userForm page", { templateId: templateId });
                    else gtag("event", "move to userForm page");
                } else if (eventName === "login") {
                    gtag("event", "move to login page");
                } else if (eventName.indexOf("offer-subscribe-") == 0) {
                    gtag("event", "payment term selected", {
                        termId: termId,
                        templateId: templateId,
                    });
                    console.log("GA4 event sent");
                } else if (eventName === "plan") {
                    gtag("event", "move to plan page", {
                        templateId: templateId,
                        experienceId: experienceId,
                    });
                    console.log("GA4 event sent");
                } else {
                    gtag("event", eventName);
                }
            } catch (e) {
                console.log(e);
            }
        }

        function sendCXEvent(eventName, termName, template, termId, templateId) {
            try {
                var cxRequestUrl = "https://scomcluster.cxense.com/Repo/rep.gif?";
                var cxParams = {
                    ver: "1",
                    typ: "pgv",
                    sid: "1136337435202690374",
                    ckp: cX.getUserId(),
                    loc: location.href,
                    tzo: "-540",
                    ltm: new Date().getTime(),
                    rnd: cX.library._randomString(),
                };
                cxParams.cp_term_name = termName;
                cxParams.cp_action = "click";
                if (
                    typeof template != "undefined" &&
                    template != null &&
                    template.length > 0
                ) {
                    cxParams.cp_placement = template;
                }
                if (
                    typeof termId != "undefined" &&
                    termId != null &&
                    termId.length > 0
                ) {
                    cxParams.cp_termId = termId;
                }
                if (
                    typeof templateId != "undefined" &&
                    templateId != null &&
                    templateId.length > 0
                ) {
                    cxParams.cp_templateId = templateId;
                }
                cxParams.cp_type = eventName;
                for (var key in cxParams) {
                    cxRequestUrl = cxRequestUrl + key + "=" + cxParams[key] + "&";
                }
                var img = new Image();
                img.src = cxRequestUrl;
            } catch (e) {
                console.log(e);
            }
        }

        function sendSurveyEvent(event) {
            try {
                if (typeof event.params.result != "undefined") {
                    var result = JSON.parse(event.params.result);
                    if (result) {
                        cX.setEventAttributes({
                            origin: "skd-web",
                            persistedQueryId: "403d37ccb64cd5c0378f8ecff5c5ae177794173c",
                        });
                        cX.sendEvent("survey", result);
                    }
                }
            } catch (e) {
                console.log(e);
            }
        }

        function onCheckoutExternalEvent(event) {
            try {
                var params = null;
                if ('params' in event.params) { params = JSON.parse(event.params.params); }
                switch (event.eventName) {
                    case "register":
                    case "register_premium":
                    case "login":
                    case "offer-register":
                        sendCXEvent(
                            event.eventName,
                            "アトリビューション",
                            event.params.template
                        );
                        if (event.params && params.templateId)
                            sendGA4CustomEvent(
                                event.eventName,
                                "G-0JD41JHSX2",
                                "",
                                params.templateId,
                                ""
                            );
                        else sendGA4CustomEvent(event.eventName, "G-0JD41JHSX2");
                        break;
                    case "plan":
                        sendGA4CustomEvent(
                            event.eventName,
                            "G-0JD41JHSX2",
                            "",
                            params.templateId,
                            params.experienceId
                        );
                        break;
                    case (event.eventName.match(/^offer-subscribe-/) || {}).input:
                        sendGA4CustomEvent(
                            event.eventName,
                            "G-0JD41JHSX2",
                            event.params.termid,
                            params.templateId,
                            ""
                        );
                        sendCXEvent(
                            "register_premium",
                            "アトリビューション",
                            "offer",
                            event.params.termid,
                            params.templateId
                        );
                        break;
                    case "survey":
                        sendSurveyEvent(event);
                }
            } catch (e) {
                console.log(e);
            }
        }

        function onCheckoutClose(event) {
            /* Default behavior is to refresh the page on successful checkout */
            if (event && event.state == "checkoutCompleted") {
                //location.reload();
                // 2023/05/11: 以下の処理は「チェックアウト」エクスペリエンス内に移行
                //if (window.location.href.indexOf('/info/help') !== -1) {
                //  document.location.href = 'https://special.sankei.com/verify?return_to=' + encodeURIComponent('https://www.sankei.com/premium/');
                //} else {
                //  document.location.href = 'https://special.sankei.com/verify?return_to=' + encodeURIComponent(window.location.href);
                //}
            }
        }

        function onCheckoutCancel() { }

        function onCheckoutError() { }

        function onCheckoutSubmitPayment() { }

        function onStartCheckout() {
            // 決済方法選択画面を開いた
            sendGA4CustomEvent("startCheckout", "G-0JD41JHSX2");
            sendGoogleAdEvent('AW-11552239813/oTMLCI7XsccaEMXhxIQr');
            sendFbEvent('startCheckout');
        }

        function onCheckoutStateChange(event) {
            if (event.stateName == "confirmation") {
                // 決済確認画面を開いた
                sendGA4CustomEvent("checkoutConfirmation", "G-0JD41JHSX2");
                sendGoogleAdEvent('AW-11552239813/MfRVCJHXsccaEMXhxIQr');
                sendFbEvent('checkoutConfirmation');
            }
        }

        /* Meter callback */
        function onMeterExpired() { }

        /* Meter callback */
        function onMeterActive() { }

        /* Callback executed when a user must login */
        function onLoginRequired() {
            // this is a reference implementation only
            // your own custom login/registration implementation would
            // need to return the tinypass-compatible userRef inside the callback

            // mysite.showLoginRegistration(function (tinypassUserRef)
            //    // tp.push(["setUserRef", tinypassUserRef]); // tp.offer.startCheckout(params); // }
            // this will prevent the tinypass error screen from displaying

            return false;
        }

        /* Callback executed after a tinypassAccounts login */
        function onLoginSuccess() { }

        /* ▼▼▼ START: Microsoft Advertising (Bing) UET loader ▼▼▼ */
        function loadMicrosoftUET() {
            try {
                if (window.__msUetLoaded) return;

                (function (w, d, t, r, u) {
                    var f, n, i;
                    w[u] = w[u] || [], f = function () {
                        var o = { ti: "97220093", enableAutoSpaTracking: true };
                        o.q = w[u], w[u] = new UET(o), w[u].push("pageLoad")
                    },
                        n = d.createElement(t), n.src = r, n.async = 1, n.onload = n.onreadystatechange = function () {
                            var s = this.readyState;
                            s && s !== "loaded" && s !== "complete" || (f(), n.onload = n.onreadystatechange = null)
                        },
                        i = d.getElementsByTagName(t)[0], i.parentNode.insertBefore(n, i)
                })(window, document, "script", "//bat.bing.com/bat.js", "uetq");

                window.__msUetLoaded = true;
            } catch (e) {
                console.log("Microsoft UET load error", e);
            }
        }

        function sendMicrosoftUETEvent(eventName, params) {
            try {
                window.uetq = window.uetq || [];
                window.uetq.push("event", eventName, params || {});
            } catch (e) {
                console.log("Microsoft UET event send error", e);
            }
        }
        /* ▲▲▲ END: Microsoft Advertising (Bing) UET loader ▲▲▲ */

        /* ▼▼▼ START: Yahoo lytag global snippet loader ▼▼▼ */
        function loadYahooLytag() {
            if (window.lytagLoaded) {
                return;
            }
            var a = document.createElement("script");
            a.async = true;
            a.src = "https://tag.flvcdn.net/lytag.js";
            a.onload = function () {
                window.lyDataLayer = window.lyDataLayer || [];
                function lytag() { lyDataLayer.push(arguments); }
                window.lytag = lytag; // Make it globally accessible

                lytag({
                    type: 'init',
                    tagId: '9d219f7c-8aff-4c33-a629-9321db5fdd8f',
                    config: {
                        useCookie: true,
                        useLocalStorage: true
                    }
                });
                lytag({
                    type: 'event',
                    eventType: 'page_view',
                    tagId: '9d219f7c-8aff-4c33-a629-9321db5fdd8f'
                });
            };
            var b = document.getElementsByTagName("script")[0];
            b.parentNode.insertBefore(a, b);
            window.lytagLoaded = true;
        }
        /* ▲▲▲ END: Yahoo lytag global snippet loader ▲▲▲ */

        /* Callback executed after an experience executed successfully */
        function onExperienceExecute(event) {
            if (
                typeof localStorage === "object" &&
                typeof localStorage.setItem === "function"
            ) {
                if (
                    typeof event === "object" &&
                    "user" in event &&
                    "uid" in event.user &&
                    event.user.uid &&
                    event.user.uid != "anon"
                ) {
                    localStorage.setItem("piano-uid", event.user.uid);
                }
            }
            sendSegmentsToGoogleAds();
            loadYahooLytag(); // Fire Yahoo page_view tag
            loadMicrosoftUET(); // Microsoft UET base tag
        }

        /* Callback executed if experience execution has been failed */
        function onExperienceExecutionFailed(event) { }

        /* Callback executed if external checkout has been completed successfully */
        function onExternalCheckoutComplete(event) {
            /* Default behavior is to refresh the page on successful checkout */
            var userToken = tp.pianoIdLite.getToken();
            checkToken(userToken);
        }
        function checkMetaTag(tagName) {
            try {
                const tag = document.querySelector('meta[name="' + tagName + '"]');
                if (tag) {
                    return tag.content;
                } else {
                    return null;
                }
            } catch (e) {
                console.log(e);
                return null;
            }
        }
        function addPubDate() {
            const pubDate = checkMetaTag("article:published_time");
            if (pubDate) {
                tp.push(["setContentCreated", pubDate]);
            }
        }
        addPubDate();

        tp.push(["setAid", "ZDyOAW1spj"]);
        tp.push(["setEndpoint", "https://buy-ap.piano.io/api/v3"]);
        tp.push(["setUseTinypassAccounts", false]);
        tp.push(["setPianoIdUrl", "https://id-ap.piano.io"]);
        tp.push(["setEspEndpoint", "https://api-esp-ap.piano.io"]);
        tp.push(["setUsePianoIdUserProvider", false]);
        tp.push(["setUsePianoIdLiteUserProvider", true]);

        /* checkout related events */
        tp.push(["addHandler", "checkoutComplete", onCheckoutComplete]);
        tp.push(["addHandler", "checkoutClose", onCheckoutClose]);
        tp.push(["addHandler", "checkoutCustomEvent", onCheckoutExternalEvent]);
        tp.push(["addHandler", "checkoutCancel", onCheckoutCancel]);
        tp.push(["addHandler", "checkoutError", onCheckoutError]);
        tp.push(["addHandler", "checkoutSubmitPayment", onCheckoutSubmitPayment]);
        tp.push(["addHandler", "startCheckout", onStartCheckout]);
        tp.push(["addHandler", "checkoutStateChange", onCheckoutStateChange]);
        /* user login events */
        tp.push(["addHandler", "loginRequired", onLoginRequired]);
        tp.push(["addHandler", "loginSuccess", onLoginSuccess]);
        /* meter related */
        tp.push(["addHandler", "meterExpired", onMeterExpired]);
        tp.push(["addHandler", "meterActive", onMeterActive]);

        tp.push(["addHandler", "experienceExecute", onExperienceExecute]);
        tp.push([
            "addHandler",
            "experienceExecutionFailed",
            onExperienceExecutionFailed,
        ]);
        /* external checkout related events */
        tp.push([
            "addHandler",
            "externalCheckoutComplete",
            onExternalCheckoutComplete,
        ]);
        /* Piano Content */
        tp.push(["setCxenseSiteId", "1144143704823992673"]);

        tp.push([
            "init",
            function () {
                tp.setLocale("ja_JP");
                /* tp.experience.init(); */
            },
        ]);
    })();
    var httpRequest = function (url, options, success, error) {
        var request = new XMLHttpRequest();
        if (!request) {
            error();
        }

        request.onreadystatechange = function () {
            try {
                if (
                    request.readyState === XMLHttpRequest.DONE &&
                    request.status === 200
                ) {
                    success(request);
                } else if (
                    request.readyState === XMLHttpRequest.DONE &&
                    request.status === 0
                ) {
                    error();
                }
            } catch (e) {
                error();
            }
        };

        request.onabort = function (e) {
            error();
        };

        request.timeout = 60000;
        request.ontimeout = function (e) {
            error();
        };

        request.open("GET", url);
        Object.keys(options).forEach(function (key) {
            request[key] = options[key];
        });
        request.send();
    };
    function checkToken(userToken) {
        var head = document.querySelector("head");
        var script = document.createElement("script");
        script.setAttribute("src", "https://code.jquery.com/jquery-3.6.0.js");
        script.setAttribute("type", "text/javascript");
        const url = new URL(window.location.href);
        let ecd = encodeURIComponent(url.href);
        const pattern = /\/article\//;
        if (
            url.pathname === "/plans/" &&
            pattern.test(document.referrer) === true
        ) {
            ecd = document.referrer;
        } else if (url.pathname === "/plans/") {
            ecd = url.origin;
        }
        script.addEventListener("load", function () {
            $(function () {
                // トークンを取得する
                // postする
                const apiUrl = "https://special.sankei.com/gns/prov";
                $.post(apiUrl, { token: userToken }, function (data) {
                    httpRequest(
                        "https://special.sankei.com/saml/sp/sankeinews-sp/u",
                        { responseType: "json", withCredentials: true },
                        function (res) {
                            if (res.response.lg === 0) {
                                document.location.href =
                                    "https://special.sankei.com/login?return_to=" + ecd;
                            } else if (res.response.lg === 1) {
                                document.location.href =
                                    "https://special.sankei.com/verify?return_to=" + ecd;
                            } else {
                                console.log(res.response);
                            }
                        }
                    );
                });
            });
        });
        document.head.appendChild(script);
    }



    !(function (f, b, e, v, n, t, s) {
        if (f.fbq) return;
        n = f.fbq = function () {
            n.callMethod
                ? n.callMethod.apply(n, arguments)
                : n.queue.push(arguments);
        };
        if (!f._fbq) f._fbq = n;
        n.push = n;
        n.loaded = !0;
        n.version = "2.0";
        n.queue = [];
        t = b.createElement(e);
        t.async = !0;
        t.src = v;
        s = b.getElementsByTagName(e)[0];
        s.parentNode.insertBefore(t, s);
    })(
        window,
        document,
        "script",
        "https://connect.facebook.net/en_US/fbevents.js"
    );
    fbq("init", "1164983951646668");
    fbq("track", "PageView");


    (function (src) {
        var a = document.createElement("script");
        a.type = "text/javascript";
        a.async = true;
        a.src = src;
        var b = document.getElementsByTagName("script")[0];
        b.parentNode.insertBefore(a, b);
    })("https://s.yimg.jp/images/listing/tool/cv/ytag.js")


    window.yjDataLayer = window.yjDataLayer ||
        [];
    function ytag() { yjDataLayer.push(arguments); }
    // Yahoo! サイトジェネラルタグ
    ytag({ "type": "ycl_cookie", "config": { "ycl_use_non_cookie_storage": true } });
    // Yahoo!ディスプレイ リマーケティング
    ytag({
        "type": "yjad_retargeting", "config": {
            "yahoo_retargeting_id": "C3Y13V7TGD",
            "yahoo_retargeting_label": "",
            "yahoo_retargeting_page_type": "",
            "yahoo_retargeting_items": [{ item_id: '', category_id: '', price: '', quantity: '' }]
        }
    });


    // Click tracking (2026-01-14)
    function cxSendEvent(eventName,obj) {
      cX.setEventAttributes({
        origin: "skd-web",
        persistedQueryId: "403d37ccb64cd5c0378f8ecff5c5ae177794173c",
      });
      cX.sendEvent(eventName, obj);
    }
    function onClickEvent(event) {
      var ev = event || window.event;
      var obj;
      if (ev) { 
        var el = ev.target || ev.srcElement;
        for (var i=0; (i<20) && (el) && el.nodeName.toLowerCase() !== 'body'; i++) {
          if(el.nodeType===1 && el.nodeName.toLowerCase() === 'a') {
            if (el.classList.contains('gtm-click')) {
              if (el.attributes['data-gtm-label'].value.toLowerCase().includes('sponsored')) {
                    obj = {
                      "href": el.attributes['href'].value,
                      "category": el.attributes['data-gtm-category'].value,
                      "action": el.attributes['data-gtm-action'].value,
                      "label": el.attributes['data-gtm-label'].value,
                      "wrapper": el.attributes['data-gtm-wrapper'].value,
                      "unit": el.attributes['data-gtm-unit'].value
                    };
                    cxSendEvent('click', obj);
              } else if (el.attributes['data-gtm-category'].value === 'tools') {
                  obj = {
                    "category": el.attributes['data-gtm-category'].value,
                    "action": el.attributes['data-gtm-action'].value,
                    "label": el.attributes['data-gtm-label'].value
                  };
                  cxSendEvent('click', obj);
              } else {
                  obj = {
                    "href": el.attributes['href'].value,
                    "category": el.attributes['data-gtm-category'].value,
                    "action": el.attributes['data-gtm-action'].value,
                    "label": el.attributes['data-gtm-label'].value
                  };
                  cxSendEvent('click', obj);
              }
            }
            break;
          }
          el = el.parentNode; 
        } 
      }
    }
    window.addEventListener('click', onClickEvent, false);


    // do not change this section
    // |BEGIN INCLUDE TINYPASS JS|
    (function (src) {
        var a = document.createElement("script");
        a.type = "text/javascript";
        a.async = true;
        a.src = src;
        var b = document.getElementsByTagName("script")[0];
        b.parentNode.insertBefore(a, b);
    })("//cdn-ap.piano.io/api/tinypass.min.js");
    // |END   INCLUDE TINYPASS JS|
