window.bslst_init = function(){
    // Set global configuration variables
    var user_cookie = "bslstuid";
    var session_cookie = "bslstsid";
    var cross_cookie_prefix = "x"
    var session_expire_minutes = 30; 
    var cookie_domain = window.location.hostname.split(/\./).slice(-2).join('.');
    var cookie_separator = "-";
    var user_cookie_prefix = "B";
    var user_expire_days = 540;
  
    // Function to get cookie values
    window.bslst_getcookie = function(name) {
        var value = "; " + document.cookie;
        var parts = value.split("; " + name + "=");
        if (parts.length == 2) return parts.pop().split(";").shift();
    }
  
    // Set the session start flag to true.
    window.bslst_session_start = false;
  
    // This function is used to set a cookie that is only used on the current domain.
    window.bslst_set_first_party_cookie = function(cookie_name, cookie_value, expiration_in_days, path, domain) {
      var now = new Date();
      now.setTime(now.getTime() + (expiration_in_days * 24 * 60 * 60 * 1000));
      var cookieValue = cookie_name + '=' + cookie_value;
      var expires = 'expires=' + now.toUTCString();
      var path = 'path=' + path;
      var domain = 'domain=' + domain;
      var secure = 'secure';
      var samesite = 'samesite=lax';
      document.cookie = cookieValue + ';' + expires + ';' + path + ';' + domain + ';' + secure + ';' + samesite;
    }
  
    // This function is used to set a cookie that is used cross domain, so it's shared on third party sites.
    window.bslst_set_cross_site_cookie = function(cookie_name, cookie_value, expiration_in_days, path, domain) {
      var now = new Date();
      now.setTime(now.getTime() + (expiration_in_days * 24 * 60 * 60 * 1000));
      var cookieValue = cookie_name + '=' + cookie_value;
      var expires = 'expires=' + now.toUTCString();
      var path = 'path=' + path;
      var domain = 'domain=' + domain;
      var secure = 'secure';
      var samesite = 'samesite=none';
      document.cookie = cookieValue + ';' + expires + ';' + path + ';' + domain + ';' + secure + ';' + samesite;
    }
  
    //set an bslstsid if none is available
    window.bslst_setbslstsid = function(){
      var session_id = Math.floor(100000000 + Math.random() * 900000000).toString();
      var session_expire = new Date().setTime(new Date().getTime() + (session_expire_minutes*60*1000)).toString();
      var session_cookie_value = session_id + cookie_separator + session_expire;
      var session_expire_days = session_expire_minutes / 60 / 24;
      // Set both a first party cookie and third party cookie counterpart
      window.bslst_set_first_party_cookie(session_cookie, session_cookie_value, session_expire_days, "/", cookie_domain);
      window.bslst_set_cross_site_cookie((cross_cookie_prefix + session_cookie), session_cookie_value, session_expire_days, "/", cookie_domain);  
      window.bslst_session_start = true;
      return session_id;
    }
  
    //check if an bslstuid exists
    window.bslst_checkbslstuid = function(){
        if(window.bslst_getcookie(user_cookie)!==undefined){
            return window.bslst_getcookie(user_cookie);
        }
        else{
            return "na";
        }
    }
    //check if an bslstuid exists
    window.bslst_checkbslstsid = function(){
        if(window.bslst_getcookie(session_cookie)!==undefined){
            var session_input = window.bslst_getcookie(session_cookie);
            var session_id = session_input.split(cookie_separator)[0];
            var session_expire = parseInt(session_input.split(cookie_separator)[1]);
            //session cookie expired, create new session id
            if(session_expire!==undefined && new Date(session_expire) < new Date()){
                return window.bslst_setbslstsid();
            }
            //session not expired, refresh cookie expiration time            
            else if (session_expire!==undefined && new Date(session_expire) > new Date()){
                var updated_session_cookie_value = session_id + cookie_separator + new Date().setTime(new Date().getTime() + (session_expire_minutes*60*1000)).toString();
                 // Set both a first party cookie and third party cookie counterpart
                window.bslst_set_first_party_cookie(session_cookie, updated_session_cookie_value, (session_expire_minutes / 60 / 24), "/", cookie_domain);
                window.bslst_set_cross_site_cookie((cross_cookie_prefix + session_cookie), updated_session_cookie_value, (session_expire_minutes / 60 / 24), "/", cookie_domain);
                return session_id;
            }
            else{
                return window.bslst_setbslstsid();
            }
        }
        else{
            return window.bslst_setbslstsid();
      }
    }
    //this is the event function
    window.bslst_event = function(event_name, context, ecommerce){
      //get core objects
      var bslst_core_context = context || {};
      var bslst_ecommerce = ecommerce || {};
      var _ga = bslst_getcookie("_ga") || "";
      if(_ga.length > 0){
        bslst_core_context["ga_cid"] = _ga
      }
  
      //base object to be send with every event
      var default_event_endpoint = "https://ct.beslist.nl/temp_event";
      var event_data = {
          "bslst_eid":  bslst_checkbslstsid() + cookie_separator + Math.floor(100000000 + Math.random() * 900000000).toString(),
          "bslst_sid": bslst_checkbslstsid(),
          "bslst_uid": bslst_checkbslstuid(),
          "event": event_name || "not_provided",
          "timestamp": new Date().getTime(),
          "screen_height": screen.height || "",
          "screen_width": screen.width || "",
          "user_agent": navigator.userAgent || "",
          "language": navigator.language || "",
          "context": bslst_core_context,
          "location": {
              "referrer": document.referrer,
              "host": window.location.host,
              "path": window.location.pathname,
              "query": window.location.search
          },
          "ecommerce": bslst_ecommerce,
      };
      //adding to location nested object
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("POST", default_event_endpoint, true);
      xmlhttp.setRequestHeader("Content-Type", "application/json");
      xmlhttp.send(JSON.stringify(event_data));
    }
  }
  bslst_init();
  //Set the new session recognition logic in a self executing function
  (function(){
    // check if a session id is already present
    if(window.bslst_session_start === true){
      window.bslst_event("session_start");
      window.bslst_session_start = false;
      console.log("no session id");
    }
  
    // check if referrer is similar to the hostname 
    else if(document.referrer.indexOf(location.protocol + "//" + location.host) > -1 || document.referrer === ""){
      window.bslst_event("session_start");
      console.log("new referrer");
    }
  
    // check if utm_* param is present in the search queries
    else if(window.location.search.indexOf("utm_") > -1){
      window.bslst_event("session_start");
      console.log("utm detected");
    }
  
    // check if trackingparameter is present in search queries
    else if(window.location.search.indexOf("clientUuid") > -1){
      window.bslst_event("session_start");
      console.log("new uuid detected");
    }
    else {
      console.log("no conditions met");
    }
})();