
  (function () {
    tp = window["tp"] || [];

    /* Checkout related */
    /**
     * Event properties
     *
     * chargeAmount - amount of purchase
     * chargeCurrency
     * uid
     * email
     * expires
     * rid
     * startedAt
     * termConversionId
     * termId
     * promotionId
     * token_list
     * cookie_domain
     * user_token
     *
     */

    if (typeof (siteRedesign) !== 'undefined') {
      //console.log('redesign') //

      function onCheckoutComplete(data) {
        window.postMessage("REGISTER_NEW_PRO", '*');
        checkoutCompleted = true;
        //analytics tracking for checkout confirmation
        if (__EventBus__){
          const eventObject = document.querySelector('.tp-container-inner');
          const pageNodeId = __EventBus__.getPageNodeId();
          __EventBus__.trigger('PRO Payment Confirmation',
            {
              pageNodeId,
              eventObject
            }
          );
        }
      }

      function onCheckoutExternalEvent(event) {
        switch (event.eventName) {
          case 'sign-in':
            console.log("!!! onCheckoutExternalEvent: event = ", event)
            if (!event.params.source) {
              var params = JSON.parse(event.params.params)
              if (!tp.userRef) {
                if (!tp.util.findCookieByName('__pianoParams')) {
                  var domain = (document.location.host.indexOf('localhost') === 0) ? ';domain=locahost' : ';domain=.cnbc.com';
                  document.cookie = "__pianoParams=" + JSON.stringify(params) + "; path=/" + domain;
                }
                window.postMessage("TOGGLE_LOGIN_POPUP", "*");
              } else {
                tp.offer.startCheckout(params);
              }
            }
            break;
          case 'learn-more':
            window.location.href = 'https://www.cnbc.com/application/pro?__source=pro|in-article|learn-more';
            break;
          case 'get-it-now':
            window.location.href = `${window.top.location.origin}/id/springfield:subscribe:articleid`;
            break;
          case 'already-member':
            window.location.href = `${window.top.location.origin}/id/springfield:subscribe:loggedin:articleid`;
            break;
          case 'webview-learn-more':
            window.location.href = `${window.top.location.origin}/id/springfield:subscribe:learn-more`;
            break;
          case 'mobile-apps-paywall':
            var product = 'none'
            if (event.params.product) {
              product = event.params.product
            }
            window.location.href = `${window.top.location.origin}/mobileapps:subscribe:` + product;
            break;
          case 'mobile-apps-sign-in':
            var product = 'none'
            if (event.params.product) {
              product = event.params.product
            }
            window.location.href = `${window.top.location.origin}/mobileapps:sign-in:` + product;
            break;
          case 'mobile-apps-sign-up':
            var product = 'none'
            if (event.params.product) {
              product = event.params.product
            }
            window.location.href = `${window.top.location.origin}/mobileapps:sign-up:` + product;
            break;
          case 'mobile-apps-learn-more':
            var product = 'none'
            if (event.params.product) {
              product = event.params.product
            }
            window.location.href = `${window.top.location.origin}/mobileapps:learn-more:` + product;
            break;
        }
      }

      function onCheckoutClose(event) {
        /* Default behavior is to refresh the page on successful checkout */
        if (event && event.state == "checkoutCompleted") {
          window.location.reload();
        }
      }

      function onCheckoutClose(event) {
        // Default behavior is to refresh the page on successful checkout
        var isPremiumPage = CNBC_Premium.isPremium;
        // TP is calling this event twice! (Yes, I know....)
        // we need to handle only once.
        if (!closeEventHandled) {
          closeEventHandled = true;
          if (checkoutCompleted) {
            if (isPremiumPage) {
              //refresh the page on default behavior
              window.location.reload();
            } else {
              //if url is a service, call the service; otherwise redirect to home
              var docref = CNBC_Utils.urlParam('service') ? window.decodeURIComponent(CNBC_Utils.urlParam('service')) : CNBC_Settings.baseurls.pub_base_protocol_agnostic;
              window.location.href = docref;
            }
          }
        }
      }

      function onCheckoutCancel() {}

      function onCheckoutError() {}

      /* Meter callback */
      function onMeterExpired() {

      }

      /* Meter callback */
      function onMeterActive() {

      }

      /* Callback executed when a user must login */
      function onLoginRequired(params) {
        // 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
        if (tp.userRef) {
          tp.offer.startCheckout(params);
        } else {
          if (!tp.util.findCookieByName('__pianoParams')) {
            var domain = (document.location.host.indexOf('localhost') === 0) ? ';domain=locahost' : ';domain=.cnbc.com'
            document.cookie = "__pianoParams=" + JSON.stringify(params) + "; path=/;" + domain;
          }
          window.postMessage("TOGGLE_SIGNUP_POPUP", '*')
        }
        // prevents Piano error from displaying
        return false;
      }

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

      /* Callback executed after an experience executed successfully */
      function onExperienceExecute(event) {}

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

      tp.push(["setAid", 'o19WonOrHQ']);
      tp.push(["setCxenseSiteId", "1140838234280700879"]);
      tp.push(["setEndpoint", 'https://buy.tinypass.com/api/v3']);
      tp.push(["setUseTinypassAccounts", false]);

      /* 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]);


      /* 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]);
      tp.push(["init", function () {
        tp.experience.init()
      }]);
    } else {
      console.log('old pub')
      var endpoint = typeof (CNBC_Utils) === 'object' ? CNBC_Utils.searchProp(CNBC_Premium, 'globals->config->endpoint') : '',
        checkoutCompleted = false,
        closeEventHandled = false,
        bedrockSyncErrorMsg = null,
        isMobile = (function () {
          var mobile = false,
            evt;
          try {
            evt = document.createEvent('TouchEvent');
            mobile = true;
          } catch (e) {}

          return mobile;
        }()),
        syncApiUrl = typeof (CNBC_Settings) === 'object' ? CNBC_Settings.baseurls.register_base.split(":")[1] + '/auth/api/' : 'http://wjfkdsj.hdkfjhkjdshkfjdkjsdkfjshd.com/',
        isPremiumPage = typeof (CNBC_Premium) === 'object' ? CNBC_Premium.isPremium : false;

      var displayBedrockSyncErrorMsg = function () {
        if (!bedrockSyncErrorMsg) {
          bedrockSyncErrorMsg = new CNBC_Popup2();
          var errorConfig = {
            closeOnBackgroudClick: false,
            popupId: 'bedrockSyncErrorMsg',
            popupContent: '<div style="clear:both;"></div>' +
              '<div class="popup-body">' +
              '<div class="header">Oops!</div>' +
              '<div class="body">Please call customer service if you encounter any problems accessing Premium content</div>' +
              '</div>' +
              '<hr style="width:85%;margin-top: 20px;margin-bottom: 20px;border: 0;border-top: 1px solid #eee;">' +
              '<div class="popup-footer">' +
              '<button class="button cancel">OK</button>' +
              '</div>',
            initCallback: null,
            autoAlignPopup: true,
            autoHide: true,
            minHeight: '200px',
            minWidth: (CNBC_Premium.globals.product === 'web') ? '400px' : '25%'
          };
          bedrockSyncErrorMsg.init(errorConfig);
          $('#bedrockSyncErrorMsg  .cancel').on('click', function () {
            bedrockSyncErrorMsg.hide();
          });
        };
        bedrockSyncErrorMsg.show();
      }

      function onCheckoutComplete(completeCallback, customEventCallback) {
        console.log('called: onCheckoutComplete');
        //styling refinements to mobile interstitial
        if (isMobile && window.innerWidth <= 450) {
          $('.tp-iframe-wrapper').css('margin', '0px auto');
          $('.tp-iframe-wrapper iframe').height(window.innerHeight).css('position', 'relative');
        }

        //styling refinements to both web + mobile interstitial
        $('.tp-iframe-wrapper iframe').addClass("thank-you-interstitial");
        $('.tp-close.tp-active').addClass("thank-you-interstitial");

        //attach google analytics tag to close button
        $('.tp-modal .tp-close').on('click', function () {
          //_gaq.push(['_trackEvent', 'button', 'click', 'close']);
        })

        //sync with bedrock to process user login
        if (typeof (localStorage) === 'object' && localStorage.getItem('1258')) {
          syncApiUrl = 'http://wjfkdsj.hdkfjhkjdshkfjdkjsdkfjshd.com/';
        }

        if (typeof (CNBC_Bedrock) === 'object') {
          CNBC_Bedrock.syncApi.syncCall({
            uuid: SURF.globals.user._provider.cnbc,
            pid: 152,
            action: 'subscription',
            dataType: 'json',
            url: syncApiUrl,
            success: function (data, text, status) {},
            error: function (data, text, status) {
              displayBedrockSyncErrorMsg();
            }
          });
        }

        //set checkout flag to true
        checkoutCompleted = true;

        //set isPro cookie to true
        CNBC_Utils.createProCookie();

        //place tracking for checkout confirmation
        CNBC_Omniture.genericClickTracking({
          'pageName': 'Registration|Pro|Payment Confirmation',
          'props': {
            '1': 'franchise',
            '10': 'Registration',
            '16': 'registration',
            '31': 'Registration Pages',
            '32': 'Pro',
            '37': 'franchise'
          }
        });

        //fire google analytics call for suscription complete
        //_gaq.push(['_trackEvent', 'button', 'click', 'subscribe']);
      }

      function onCheckoutExternalEvent() {

      }

      function onCheckoutClose(event) {
        // Default behavior is to refresh the page on successful checkout
        var isPremiumPage = CNBC_Premium.isPremium;
        // TP is calling this event twice! (Yes, I know....)
        // we need to handle only once.
        if (!closeEventHandled) {
          closeEventHandled = true;
          if (checkoutCompleted) {
            if (isPremiumPage) {
              //refresh the page on default behavior
              window.location.reload();
            } else {
              //if url is a service, call the service; otherwise redirect to home
              var docref = CNBC_Utils.urlParam('service') ? window.decodeURIComponent(CNBC_Utils.urlParam('service')) : CNBC_Settings.baseurls.pub_base_protocol_agnostic;
              window.location.href = docref;
            }
          }
        }
      }

      function onCheckoutCancel() {
        console.log("called: onCheckoutCancel");
      }

      function onCheckoutError() {
        console.log("called: onCheckoutError");
      }

      /* Meter callback */
      function onMeterExpired() {
        console.log("called: onMeterExpired");

      }

      /* Meter callback */
      function onMeterActive() {
        console.log("called: onMeterActive");

      }

      /* Callback executed when a user must login */
      function onLoginRequired() {
        console.log('called: 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", tp.userRef]); // tp.offer.startCheckout(params); // }
        // this will prevent the tinypass error screen from displaying

        return false;
      }

      /* Callback executed after a tinypassAccounts login */
      function onLoginSuccess() {
        console.log("called: onMetonLoginSuccesserActive");
      }

      tp.push(["setAid", 'o19WonOrHQ']);
      tp.push(["setCxenseSiteId", "1140838234280700879"]);
      tp.push(["setEndpoint", endpoint]);
      tp.push(["setUseTinypassAccounts", false]);

      /* 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", "checkoutCustomEvent", paywallCustomEventCallback ]);


      /* 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]);
    }
  })();


  // do not change this section
  // |BEGIN INCLUDE TINYPASS JS|
  if (typeof (siteRedesign) !== 'undefined') {
    (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.tinypass.com/api/tinypass.min.js");
  }
  // |END   INCLUDE TINYPASS JS|

