if (!("thrive_pv" in window)) {

window.thrive_pv = function() {
  window.thrive = {}

  window.thrive.frontend_pv_msec = (new Date).getTime()
  window.thrive.performance = {}
  window.thrive.performance.uieRun = window.thrive.frontend_pv_msec;

  ( function () {
    var b64_digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'
    this.i_to_b64 = function(i) {
      var b64 = ''
      while (i>0) {
        b64 = b64_digits[i%64]+b64
        i = Math.floor(i/64)
      }
      return b64
    }
    this.b64_to_i = function(b64) {
      var i = 0
      for (var j=0; j<b64.length; j++) {
        i = i * 64 + b64_digits.indexOf( b64[j] )
      }
      return i
    }
    this.urlsafe_b64_encode = function(object) {
      return btoa( unescape( encodeURIComponent( JSON.stringify(object) ) ) ).replace(/\+/g,'-').replace(/\//g,'_').replace(/\=+$/,'')
    }
    this.trim_attributes = function(object) {
      Object.keys(object).forEach(function(a){ if (typeof(object[a]) == "string") { object[a] = object[a].substring(0, 255) } })
      return object
    }
    this.generate_uuid = function(msec) {
      var b = ''
      for (var i=0; i<44; i++) { b += b64_digits[ Math.floor((Math.random()) * 64) ] }
      return ('AAAAAAAAAAAA'+this.i_to_b64(msec)).slice(-12) +
        ('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'+b).slice(-44)
    }
    this.get_query_param = function(key) {
      var vars = window.location.search.substring(1).split('&')
      for (var i=0; i<vars.length; i++) {
        var pair = vars[i].split('=')
        if (decodeURIComponent(pair[0]) == key) {
          return decodeURIComponent(pair[1])
        }
      }
    }
    this.get_fragment_param = function(key) {
      var vars = window.location.hash.substring(2).split('&')
      for (var i=0; i<vars.length; i++) {
        var pair = vars[i].split('=')
        if (decodeURIComponent(pair[0]) == key) {
          return decodeURIComponent(pair[1])
        }
      }
    }
    this.get_cookie = function(key) {
      var match
      if ( match = ( new RegExp('(?:^|; )'+encodeURIComponent(key)+'=([^;]*)') ).exec(document.cookie) ) {
        return decodeURIComponent(match[1])
      }
    }
    this.set_cookie = function(key, value, domain, expiration) {
      document.cookie = encodeURIComponent(key)+'='+encodeURIComponent(value)+'; path=/;' +
        (domain ? (' domain='+encodeURIComponent(domain)+';') : '') +
        (expiration ? (' expires='+expiration+';') : '') +
        'Secure; SameSite=Lax;'
      return this.get_cookie(key)
    }
    this.get_top_cookieable_domain = function () {
      var key = [...Array(8)].map(() => Math.floor(Math.random() * 16).toString(16)).join('')
      var top_cookieable_domain = null
      var try_domain = '..' + document.domain
      while ( try_domain.match(/^\.[^\.]*\./) ) {
        try_domain = try_domain.replace(/^\.[^\.]*/, '')
        if ( this.set_cookie(key, '1', try_domain) ) {
          top_cookieable_domain = try_domain
        }
        document.cookie = encodeURIComponent(key)+'=; path=/;'+
          ' domain='+encodeURIComponent(try_domain)+';'+
          ' expires=Thu, 01 Jan 1970 00:00:00 GMT;' +
          'Secure; SameSite=Lax;'
      }
      return top_cookieable_domain
    }

    this.add_script = function(src, async) {
      var new_node = document.createElement('script')
      new_node.src = src
      new_node.async = async
      document.querySelector('head').appendChild(new_node)
    }

    // if no valid fp_uuid, set a new one
    if (!( this.get_cookie('thrive_fp_uuid') &&  this.get_cookie('thrive_fp_uuid').length == 56 )) {
      this.set_cookie(
        'thrive_fp_uuid',
        this.generate_uuid( this.frontend_pv_msec ),
        this.get_top_cookieable_domain(),
        'Wed, 01 Jan 2070 00:00:00 GMT'
      )
    }

    this.pv_uuid = this.generate_uuid( this.frontend_pv_msec )
    var effective_url_b64 = this.urlsafe_b64_encode( this.effective_url = window.location.href )

    // 30m thrive "session" & landing page
    if ( !this.get_cookie( 'thrive_lp_msec' ) || parseInt( this.get_cookie( 'thrive_lp_msec' ) ) < this.frontend_pv_msec - 30*60*1000 ) {
      this.set_cookie( 'thrive_lp_msec', this.frontend_pv_msec.toString(), this.get_top_cookieable_domain(), 'Wed, 01 Jan 2070 00:00:00 GMT' )
      this.set_cookie( 'thrive_lp'     , this.effective_url              , this.get_top_cookieable_domain(), 'Wed, 01 Jan 2070 00:00:00 GMT' )
    }

    // 60m thrive "session"
    if ( !this.get_cookie( 'thrive_60m_msec' ) || parseInt( this.get_cookie( 'thrive_60m_msec' ) ) < this.frontend_pv_msec - 60*60*1000 ) {
      this.set_cookie( 'thrive_60m_msec', this.frontend_pv_msec.toString(), this.get_top_cookieable_domain(), 'Wed, 01 Jan 2070 00:00:00 GMT' )
    }

    this.new_nodes = {}
    this.observers = {}
    this.functions = {}
    this.gte_queue = []

    this.ga4_ids = []
    this.ga4_queue = []

    this.ga4_send = function( name, attributes ) {
      this.ga4_ids.forEach( t => {
        var attributes_with_send_to = attributes
        attributes_with_send_to["send_to"] = t
        window.gtag( 'event', name, attributes_with_send_to )
      } )
    }

    this.ga4 = function( name, attributes ) {
      if ( this.ga4_ids.length > 0 ) {
        this.ga4_send( name, attributes )
      } else {
        this.ga4_queue.push( { name: name, attributes: attributes } )
      }
    }

    this.periodic_check_ga4_ready = function( next_wait ) {
      this.ga4_ids = Object.keys( window.google_tag_manager || [] ).filter( e => { return e.substring(0,2) == 'G-' } )
      if ( this.ga4_ids.length > 0 ) {
        if ( typeof window.gtag != 'function' ) {
          window.gtag = function() { dataLayer.push(arguments) }
        }
        while ( this.ga4_queue.length > 0 ) {
          e = this.ga4_queue.shift()
          this.ga4_send( e['name'], e['attributes'] )
        }
      } else if ( next_wait < 20000 ) {
        setTimeout( function() { window.thrive.periodic_check_ga4_ready( next_wait*1.5 ) }, next_wait )
      }
    }
    this.periodic_check_ga4_ready( 100 )

    this.trigger_ga4 = function( gte_object ) {
      var attributes = {
        'thrive_uuid':  gte_object['uuid'],
        'thrive_token': gte_object[ gte_object['gte_class_name'] == 'pageview' ? 'tsc_available' : 'token' ]
      }
      switch ( gte_object['tsckind'] ) {
        case 'dbtsc': attributes['thrive_promotions_center_type'] = 'Smart Bar';    break
        case 'cctsc': attributes['thrive_promotions_center_type'] = 'Smart Button'; break
        case 'tsc':   attributes['thrive_promotions_center_type'] = 'Smart Pages';  break
      }

      if ( gte_object["gte_class_name"]=='pageview' && gte_object['ab'] != '' ) {
        this.ga4( 'thrive_experiment_view', { 'thrive_uuid': gte_object['uuid'], 'thrive_variant': gte_object['ab'] } )
      }

      if ( gte_object["gte_class_name"]=='pageview' && ( /^(db|cc)tsc$/.exec( gte_object["tsckind"] ) ) ) {
        this.ga4( 'thrive_available', attributes )

      } else if ( gte_object["gte_class_name"]=='tsc' ) {
        attributes['thrive_category'       ] = gte_object['category']
        attributes['thrive_engagement_type'] = ( gte_object['caveat'] == 'auto' ? 'Auto' : 'Manual' )
        this.ga4( 'thrive_view_offers', attributes )

      } else if ( gte_object["gte_class_name"]=='offer_engagement' && ( !/_(engage|pass)$/.exec( gte_object["kind"] ) ) ) {
        attributes['thrive_offer_title'    ] = gte_object['name'    ]
        attributes['thrive_offer_id'       ] = gte_object['offer_id']
        if ( /_code$/.exec( gte_object["kind"] ) ) { attributes['thrive_code'] = gte_object['code'] }

        switch ( gte_object["kind"] ) {
            case 'apply_code':   attributes['thrive_engagement_type'] = 'Apply Code';       break
            case 'copy_code':    attributes['thrive_engagement_type'] = 'Copy Code';        break
            case 'click_code':   attributes['thrive_engagement_type'] = 'Manual Code Copy'; break
            case 'navigate':     attributes['thrive_engagement_type'] = 'CTA Click';        break
            case 'details':      attributes['thrive_engagement_type'] = 'Details Click';    break
        }
        if ( gte_object["kind"] == 'instore_execute' ) {
          switch ( gte_object['instore_type'] ) {
            case 'apple_wallet': attributes['thrive_engagement_type'] = 'Save to Apple Wallet';      break
            case 'email':        attributes['thrive_engagement_type'] = 'Email Share';               break
            case 'sms':          attributes['thrive_engagement_type'] = 'SMS Share';                 break
            case 'print':        attributes['thrive_engagement_type'] = 'In-Store Print Click';      break
            case 'view':         attributes['thrive_engagement_type'] = 'In-Store View Offer Click'; break
          }
        }
        if ( gte_object["kind"] == 'social_execute' ) {
          switch ( gte_object['social_type'] ) {
            case 'apple_wallet': attributes['thrive_engagement_type'] = 'Save to Apple Wallet'; break
            case 'email':        attributes['thrive_engagement_type'] = 'Email Share';          break
            case 'sms':          attributes['thrive_engagement_type'] = 'SMS Share';            break
          }
        }

        if ( gte_object['in_store'] == '1' ) {
          attributes['thrive_offer_type'] = 'In-Store'
        } else {
          switch ( gte_object['offer_type'] ) {
            case 'rebate': attributes['thrive_offer_type'] = 'Rebate';         break
            case 'coupon': attributes['thrive_offer_type'] = 'Code-Based';     break
            case 'other':  attributes['thrive_offer_type'] = 'Non-Code Based'; break
          }
        }

        this.ga4( 'thrive_select_offer', attributes )
      }
    }

    this.gte = function( gte_class_name, gte_object ) {
      gte_object = this.trim_attributes(gte_object)
      if ( gte_class_name != 'pageview' ) {
        gte_object["uuid"]                   = this.generate_uuid( gte_object["msec"] = (new Date).getTime() )
        gte_object["pv_uuid"]                = this.pv_uuid
      }

      gte_object["fp_uuid"]                  = this.get_cookie('thrive_fp_uuid')

      if ( ["txn", "checkout", "cart"].indexOf(gte_class_name) >= 0 ) { //superclass
        gte_object["gte_class_name"]         = "cart"
        gte_object["status"]                 = gte_class_name
        gte_object["txn_id"]                 = gte_object["id"]
      } else if ( gte_class_name == 'product' ) {
        gte_object["gte_class_name"]         = gte_class_name
        gte_object["txn_id"]                 = gte_object["id"]
      } else {
        gte_object["gte_class_name"]         = gte_class_name
      }
      delete gte_object["id"]
      this.gte_queue.push( gte_object )
      if ( gte_class_name=='tsc' ) {
        this.tsc_uuid = gte_object["uuid"]
      }
    }
    this.gte_send = function() {
      if ('site' in this) {
        this.gte_queue.forEach(function(gte_object) {
          (function(){
            gte_object["site"] = this.site
            this.add_script( ( "//gte.thrive.today/" + this.urlsafe_b64_encode( gte_object ) + '/gte.js' ), 1 )
            this.trigger_ga4( gte_object )
          }).call( window.thrive )
        } )
        this.gte_queue = []
      }
    }

    if ( !['shop.advanceautoparts.com'].includes( document.domain ) ) {
      this.add_script(
        "//dtam.thrive.today/" + this.pv_uuid + '/' + effective_url_b64 + '/dtam.js?' +
        'fp_uuid=' + this.get_cookie('thrive_fp_uuid') +
        '&lp='  + encodeURIComponent( this.get_cookie( 'thrive_lp' ) ) +
        '&mbo=' + encodeURIComponent( this.get_cookie( 'thrive_60m_msec' ) )
      , 0 )
    }
  } ).call( window.thrive )
}

window.thrive_pv()
}
