<script 
  src="https://cdn.cookielaw.org/scripttemplates/otSDKStub.js" 
  type="text/javascript" 
  charset="UTF-8"
  data-domain-language="true" 
  data-domain-script="c938af5b-8612-421f-8d15-740c329a09bc{% if current_school.properties.sandbox %}-test{% endif %}"></script>
<script type="text/javascript">
  !function(){var i="analytics",analytics=window[i]=window[i]||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","debug","page","screen","once","off","on","addSourceMiddleware","addIntegrationMiddleware","setAnonymousId","addDestinationMiddleware","register"];analytics.factory=function(e){return function(){if(window[i].initialized)return window[i][e].apply(window[i],arguments);var n=Array.prototype.slice.call(arguments);if(["track","screen","alias","group","page","identify"].indexOf(e)>-1){var c=document.querySelector("link[rel='canonical']");n.push({__t:"bpc",c:c&&c.getAttribute("href")||void 0,p:location.pathname,u:location.href,s:location.search,t:document.title,r:document.referrer})}n.unshift(e);analytics.push(n);return analytics}};for(var n=0;n<analytics.methods.length;n++){var key=analytics.methods[n];analytics[key]=analytics.factory(key)}analytics.load=function(key,n){var t=document.createElement("script");t.type="text/javascript";t.async=!0;t.setAttribute("data-global-segment-analytics-key",i);t.src="https://cdn-segment.pipedrive.com/analytics.js/v1/" + key + "/analytics.min.js";var r=document.getElementsByTagName("script")[0];r.parentNode.insertBefore(t,r);analytics._loadOptions=n};analytics._writeKey={% if current_school.properties.sandbox %}"cmgpJlGksHfgGGINH2nFMKIrkLzUrHEk"{% else %}"Toe2jCBJvPgwWBT0GvOylUgge4ZHeEyc"{% endif %};;analytics.SNIPPET_VERSION="5.2.0";
  analytics._writeKey = {% if current_school.properties.sandbox %}"cmgpJlGksHfgGGINH2nFMKIrkLzUrHEk"{% else %}"Toe2jCBJvPgwWBT0GvOylUgge4ZHeEyc"{% endif %};;
    }}();
  

  const consent_middleware = function({payload, next, integration}) {
  const payloadObject = payload.obj.properties || payload.obj.traits;
  if (payloadObject) {
      payloadObject.consent_id = OneTrust.getDataSubjectId();
      payloadObject.cookie_policy_v2 = OnetrustActiveGroups
  }

  next(payload);
  };

  var gtm_middleware = function({payload, next, integration}) {
    if (payload.obj.messageId) {
      payload.obj.properties.messageId = payload.obj.messageId;
    }
    next(payload);
  };
  window.analytics.addSourceMiddleware(consent_middleware);
  window.analytics.addDestinationMiddleware('Google Tag Manager',[gtm_middleware]);
</script>

<script type="text/javascript">
  // Read Google Analytics cookie values and format them
  function getCookie(name) {
    const match = document.cookie.match(new RegExp(`(^| )${name}=([^;]+)`));
    return Array.isArray(match) && match.length > 1 ? match[2] : "";
  }
  ("use strict");
  function _slicedToArray(t, e) {
    return (
      _arrayWithHoles(t) || _iterableToArrayLimit(t, e) || _nonIterableRest()
    );
  }
  function _nonIterableRest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
  }
  function _iterableToArrayLimit(t, e) {
    var r = [],
      n = !0,
      i = !1,
      o = void 0;
    try {
      for (
        var a, l = t[Symbol.iterator]();
        !(n = (a = l.next()).done) && (r.push(a.value), !e || r.length !== e);
        n = !0
      );
    } catch (t) {
      (i = !0), (o = t);
    } finally {
      try {
        n || null == l.return || l.return();
      } finally {
        if (i) throw o;
      }
    }
    return r;
  }
  function _arrayWithHoles(t) {
    if (Array.isArray(t)) return t;
  }
  function getGoogleAnalyticsClients() {
    try {
      return ga && "function" == typeof ga.getAll ? ga.getAll() : [];
    } catch (t) {
      return [];
    }
  }
  function formatGACookieValue(t) {
    if (!t) return "";
    var e = _slicedToArray("".concat(t).split("."), 4),
      r = e[2],
      n = e[3];
    return r && n ? "".concat(r, ".").concat(n) : "";
  }
  function getAnalyticsValues() {
    var t = getGoogleAnalyticsClients(),
      e = "",
      r = "";
    return (
      (r = t.length
        ? ((e = t[0].get("clientId")), t[0].get("_gid"))
        : ((e = formatGACookieValue(getCookie("_ga"))),
          formatGACookieValue(getCookie("_gid")))),
        { ga_client_id: e, gid: r }
    );
  }
</script>

<script type="text/javascript">
  function createPdReferrerCookie() {
    !function() {
        function e(e) {
            var c = document.cookie.match(new RegExp("(^| )".concat(e, "=([^;]+)")));
            return Array.isArray(c) && 1 < c.length ? c[2] : ""
        }
        var c = "pd_referrer_session";
        if ("" === e(c)) {
            var t;
            try {
                t = window.location.hostname.split(".").slice(-2).join(".")
            } catch (e) {
                t = "pipedrive.com"
            }
            var n, o = "pd_referrer";
            try {
                n = JSON.parse(decodeURIComponent(e(o))),
                Array.isArray(n) || (n = [])
            } catch (e) {
                n = []
            }
            7 < n.length && (n.length = 7);
            var a = null;
            try {
                document.referrer.split("/")[2].split(":")[0].split(".").slice(-2).join(".").slice(-t.length) !== t && (a = document.referrer)
            } catch (e) {
                a = null
            }
            var r, i, s, l, u, d, h, p = document.location.href;
            "1" === e("has_account") && (p = "".concat(p).concat(-1 === document.location.href.indexOf("?") ? "?" : "&", "hasaccount=1")),
            n.push({
                referrer_url: a,
                landing_url: p,
                ts: (r = new Date,
                i = r.getUTCFullYear(),
                s = "00".concat(r.getUTCMonth() + 1).slice(-2),
                l = "00".concat(r.getUTCDate()).slice(-2),
                u = "00".concat(r.getUTCHours()).slice(-2),
                d = "00".concat(r.getUTCMinutes()).slice(-2),
                h = "00".concat(r.getUTCSeconds()).slice(-2),
                "".concat(i, "-").concat(s, "-").concat(l, " ").concat(u, ":").concat(d, ":").concat(h))
            });
            var g = new Date
              , m = new Date;
            g.setDate(g.getDate() + 365),
            m.setMinutes(m.getMinutes() + 30);
            var f = "".concat(o, "=").concat(encodeURIComponent(JSON.stringify(n)), "; ") + "path=/; domain=".concat(t, "; max-age=31536000; expires=").concat(g)
              , v = "".concat(c, "=1; path=/; domain=").concat(t, "; max-age=31536000; expires=").concat(m);
            document.cookie = f,
            document.cookie = v
        }
    }
}
</script>

<script type="text/javascript">
  function loadSegmentTemplate() {
      if (typeof window.analytics.load !== "function") {
        return;
      }
      var groups = window.OnetrustActiveGroups || "C0001";
      if (!groups.includes("C0002")) {
        return;
      }
      //write key within load call also would need updated.
      window.analytics.load({% if current_school.properties.sandbox %}"cmgpJlGksHfgGGINH2nFMKIrkLzUrHEk"{% else %}"Toe2jCBJvPgwWBT0GvOylUgge4ZHeEyc"{% endif %}, 
        {
        obfuscate:true,
        integrations: {
            "Segment.io": {
              deliveryStrategy: {
                strategy: "batching",
                config: {
                  size: 10,
                  timeout: 5000
                }
              }
            }
          },
          "Google Tag Manager": groups.includes("C0002")
    });
{% if current_person.signed_in? %}
  {% if current_school.sso_active? %}
    var email = '{{ current_person.email }}' || null
    var user_id = '{{ current_person.id }}' || null
    var sso_uid = '{{ current_person.sso_uid }}' || null
  {% else %}
    var email = '{{ current_person.email }}' || null
    var user_id = '{{ current_person.id }}' || null
    var sso_uid = null
  {% endif %}
  analytics.identify({
    "northpass_email": email ,
    "northpass_identifier": user_id,
    {% if current_school.sso_active? %}
      "pd_sso": sso_uid
    {% endif %}
});
{% endif %}
      
analytics.page(document.title, getAnalyticsValues());
}
</script>

<script type="text/javascript">
  function OptanonWrapper() {
   loadSegmentTemplate();
   createPdReferrerCookie();
  }
</script>

{% if current_person.signed_in? and current_school.properties.sandbox == false %}
  <script type="text/javascript">
    let permissionCookie = ''
    function validateCookieProperty() {
      getCookie('OptanonConsent').split('&').forEach(x => {
        if (x.startsWith('groups='))
          permissionCookie = decodeURIComponent(x.split('=')[1])
      })
      if (permissionCookie !== '{{ current_person.properties.cookie_permissions }}') {
        const xhr = new XMLHttpRequest();
        {% if current_school.sso_active? %}
          var url = 'https://webhooks.workato.com/webhooks/rest/997192d2-6726-4f22-afbc-8cf021019896/pipedrive-sso-change-cookie-value'
        {% else %}
          var url = 'https://webhooks.workato.com/webhooks/rest/4a75076f-e7be-472b-b661-319f34ee9d24/pipedrive-open-change-cookie-value'
        {% endif %}
        xhr.open('POST', url);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify({
          "personUUID": '{{ current_person.id }}',
          "newCookie": permissionCookie
        }));
      }
    }
    validateCookieProperty();
  </script>
{% endif %}
