/*\
|*|
|*| :: cookies.js ::
|*|
|*| A complete cookies reader/writer framework with full unicode support.
|*|
|*| https://developer.mozilla.org/en-US/docs/DOM/document.cookie
|*|
|*| This framework is released under the GNU Public License, version 3 or later.
|*| http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*| Syntaxes:
|*|
|*| * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*| * docCookies.getItem(name)
|*| * docCookies.removeItem(name[, path])
|*| * docCookies.hasItem(name)
|*| * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    return unescape(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toGMTString();
          break;
      }
    }
    document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath) {
      if (!sKey || !this.hasItem(sKey)) { return false; }
      document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
      return (new RegExp("(?:^|;\\s*)" + escape(sKey).toLowerCase().replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie.toLowerCase());
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = unescape(aKeys[nIdx]); }
    return aKeys;
  },

    simple: {
        getCookie: function (cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1);
                }
                if (c.indexOf(name) == 0) {
                    return c.substring(name.length, c.length);
                }
            }
            return "";
        },
        hasItem: function (sKey) {
            return (new RegExp("(?:^|;\\s*)" + sKey.toLowerCase() + "\\s*\\=")).test(document.cookie.toLowerCase());
        },
        removeItem: function (sKey, sPath, sDomain) {
            if (!sKey || !this.hasItem(sKey)) { return false; }
            document.cookie = sKey + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sPath ? "; path=" + sPath : "") + (sDomain ? "; Domain=" + sDomain : "");
            return true;
        }
    }
};

class BifrostCors{constructor(e,t=!1,s){var o;(this.bifrostResponse,this.address=e,this.socketListner,this.bifrostBridge=bifrostBridge.bind(this),this.promiseConstructor=promiseConstructor.bind(this),this.postbackLocalstorage=postbackLocalstorage.bind(this),this.postbackSetLocalstorage=postbackSetLocalstorage.bind(this),this.postbackDeleteLocalstorage=postbackDeleteLocalstorage.bind(this),this.postbackGetCookie=postbackGetCookie.bind(this),this.postbackSetCookie=postbackSetCookie.bind(this),this.postbackRunEval=postbackRunEval.bind(this),this.postbackDomManipulationId=postbackDomManipulationId.bind(this),this.postbackDomManipulationClass=postbackDomManipulationClass.bind(this),this.startMessageThread=startMessageThread.bind(this),this.handleSocketMessage=handleSocketMessage.bind(this),t&&(this.midgard=document.getElementById(s)),!1===t)&&((o=document.createElement("iframe")).setAttribute("id","bifrost-cors"),o.setAttribute("width","0px"),o.setAttribute("height","0px"),o.setAttribute("style","position:absolute; top: -999px; display: none"),o.setAttribute("src",this.address),document.body.appendChild(o),this.midgard=document.getElementById("bifrost-cors"));window.addEventListener("message",e=>{if(e.origin===this.address){if(e.data.type?.includes("request")){let t=e.data.type.replace("request","postback").replace(/-/g,"_");this.heimdall(t,e.data.value)}"bifrost-socket-message"===e.data.type&&(this.socketListner?(this.bifrostBridge("bifrost-response",!0,!0),this.socketListner(e.data.value)):(console.group("Error - Bifrost-Cors"),console.error("Message Thread not init -- Bifrost-Cors"),console.log("You.developer ? dig into lib at line 37 : Raise a issue"),console.groupEnd()))}})}async getLocalStorage(e){return this.heimdall("get_localstorage",e),this.heimdall("get_response"),await this.bifrostResponse}async setLocalStorage(e){return this.heimdall("set_localstorage",e),this.heimdall("get_response"),await this.bifrostResponse}async deleteLocalStorage(e){return this.heimdall("delete_localstorage",e),this.heimdall("get_response"),await this.bifrostResponse}async getCookie(e){return this.heimdall("get_cookie",e),this.heimdall("get_response"),await this.bifrostResponse}async setCookie(e,t,s){let o=[e,t,s];return this.heimdall("set_cookie",o),this.heimdall("get_response"),await this.bifrostResponse}async runExpression(e){return this.heimdall("run_eval",e),this.heimdall("get_response"),await this.bifrostResponse}async domManipulationById(e,t){let s=[e,t];return this.heimdall("dom_manipulation_id",s),this.heimdall("get_response"),await this.bifrostResponse}async domManipulationByClass(e,t,s){let o=[e,t,s];return this.heimdall("dom_manipulation_class",o),this.heimdall("get_response"),await this.bifrostResponse}async requestMessageThread(e){return this.heimdall("start_message_thread",e),!!this.socketListner}async send(e){return this.heimdall("bifrost_socket_send_message",e),this.heimdall("get_response"),await this.bifrostResponse}heimdall(e,t){switch(e){case"get_response":this.promiseConstructor("bifrost-response");break;case"get_localstorage":this.bifrostBridge("request-get-localstorage",t);break;case"set_localstorage":this.bifrostBridge("request-set-localstorage",t);break;case"delete_localstorage":this.bifrostBridge("request-delete-localstorage",t);break;case"get_cookie":this.bifrostBridge("request-get-cookie",t);break;case"set_cookie":this.bifrostBridge("request-set-cookie",t);break;case"run_eval":this.bifrostBridge("request-run-eval",t);break;case"dom_manipulation_id":this.bifrostBridge("request-dom-manipulation-id",t);break;case"dom_manipulation_class":this.bifrostBridge("request-dom-manipulation-class",t);break;case"postback_get_localstorage":this.postbackLocalstorage(t);break;case"postback_set_localstorage":this.postbackSetLocalstorage(t);break;case"postback_delete_localstorage":this.postbackDeleteLocalstorage(t);break;case"postback_get_cookie":this.postbackGetCookie(t);break;case"postback_set_cookie":this.postbackSetCookie(t);break;case"postback_run_eval":this.postbackRunEval(t);break;case"postback_dom_manipulation_id":this.postbackDomManipulationId(t);break;case"postback_dom_manipulation_class":this.postbackDomManipulationClass(t);break;case"start_message_thread":this.startMessageThread(t);break;case"bifrost_socket_send_message":this.handleSocketMessage(t)}}}function bifrostBridge(e,t,s=!1){let o={type:e,value:t};s?window.parent.postMessage(o,"*"):this.midgard&&this.midgard.contentWindow.postMessage(o,"*")}function promiseConstructor(e){return this.bifrostResponse=new Promise((t,s)=>{window.addEventListener("message",s=>{s.origin===this.address&&s.data.type&&s.data.type===e&&t(s.data.value)})}),this.bifrostResponse}function postbackLocalstorage(e){if("object"==typeof e){let t=[];e.map(e=>{t.push(localStorage.getItem(e))}),this.bifrostBridge("bifrost-response",t,!0)}else{let t=localStorage.getItem(e);this.bifrostBridge("bifrost-response",t,!0)}}function postbackSetLocalstorage(e){localStorage.setItem(e.key,e.value),localStorage.getItem(e.key),this.bifrostBridge("bifrost-response",!0,!0)}function postbackDeleteLocalstorage(e){"object"==typeof e?(e.map(e=>{localStorage.removeItem(e)}),this.bifrostBridge("bifrost-response",!0,!0)):(localStorage.removeItem(e),this.bifrostBridge("bifrost-response",!0,!0))}function postbackGetCookie(e){let t=document.cookie.split(";"),s={};for(var o=0;o<t.length;o++){let e=t[o].split("=");s[(e[0]+"").trim()]=unescape(e[1])}if(e){let t=s[e];this.bifrostBridge("bifrost-response",t,!0)}else{let e=s;this.bifrostBridge("bifrost-response",e,!0)}}function postbackSetCookie(e){let t=e[0],s=e[1],o=e[2],i="";if(o){let e=new Date;e.setTime(e.getTime()+24*o*60*60*1e3),i="; expires="+e.toUTCString()}document.cookie=t+"="+(s||"")+i+"; path=/",this.bifrostBridge("bifrost-response",!0,!0)}function postbackRunEval(payload){let data=eval(payload);this.bifrostBridge("bifrost-response",data,!0)}function postbackDomManipulationId(e){let t=e[0],s=e[1],o=document.getElementById(t).style;Object.keys(s).map(e=>{o[e]=s[e]}),this.bifrostBridge("bifrost-response",!0,!0)}function postbackDomManipulationClass(e){let t=e[0],s=e[1],o=e[2],i=document.getElementsByClassName(t)[s].style;Object.keys(o).map(e=>{i[e]=o[e]}),this.bifrostBridge("bifrost-response",!0,!0)}function startMessageThread(e){this.socketListner=e,this.bifrostBridge("bifrost-response",!0,!0)}function handleSocketMessage(e){this.bifrostBridge("bifrost-socket-message",e,Boolean(!this.midgard))}
//to enable listen events of the closing frame while the frame running in ssl and the page is not

// const { settings } = require("cluster");

//http://madskristensen.net/post/iframe-cross-domain-javascript-calls
(function () {
  if (typeof window.CustomEvent === "function") return false;

  function CustomEvent(event, params) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent("CustomEvent");
    evt.initCustomEvent(
      event,
      params.bubbles,
      params.cancelable,
      params.detail
    );
    return evt;
  }

  CustomEvent.prototype = window.Event.prototype;

  window.CustomEvent = CustomEvent;
})();
var cookieLoginlname = "zpbwxsSyX4h0fGZQICW5pQ%3d%3d";
//check if this script didn't been called earlier
//test code
let host = document.location.host;
var domain = host.includes("yeshiva.org.il")
  ? "https://www.yeshiva.co"
  : "https://www.yeshiva.org.il";
if (host.includes(".local")) {
  domain = host.includes("he.local") ? "http://en.local" : "http://he.local";
} else if (host.includes(".staging")) {
  domain = host.includes("he.staging")
    ? "http://en.staging"
    : "http://he.staging";
} else if (host.includes("local.yeshiva")) {
  domain = host.includes("local.yeshiva.org.il")
    ? "https://local.yeshiva.co:8043"
    : "https://local.yeshiva.org.il:8043";
}
//console.log("domain: local: " + host + " dest: " + domain);
var bifrostCors = new BifrostCors(domain + "/users/transferdata", false);
if (user == undefined) {
  // Callbacks to support Angular's users
  var callbacks = [];

  // Domain ovveride won't work on modern browsers
  //try {
  //  document.domain = document.domain.substring(
  //    document.domain.indexOf(".") + 1
  //  ); //'local.org';//'yeshiva.org.il';
  //} catch (e) {
  //  /*Do nothing*/
  //}

  var separateLogins = false;
  separateLogins = true;
  var ssldomain = document.location.protocol + "//" + document.location.host;
  var localDomainHeb = "he.local";
  var localDomainEng = "en.local";
  var heb = true;
  try {
    heb = !lang || lang.startsWith("he");
  } catch (ex) {
    //??
  }

  document.addEventListener(
    "DOMContentLoaded",
    function () {
      //(function ($) {

      settings = {
        Greeting: heb ? "שלום, " : "Hello, ",
        ActionLog: heb ? "התחבר" : "Sign in",
        ActionLogHref: "/Users/Login/",
        ActionReg: heb ? "הרשם" : "Register",
        ActionRegHref: "/Users/Register/",
        Username: heb ? "אורח" : "guest",
        IsInternal: null,
        CmsBaseLink: null,
        CmsApiLink: null,
        CmsDisconnectLink: null,
        RepliesLink: null,
        CmsContentLink: null,
        AskHebRavId: null,
        AskEngRavId: null,
        MidrashRavId: null,
      };

      getIsInternal = function () {
        return settings.IsInternal;
      };
      getAskHebRavId = function () {
        return settings.AskHebRavId;
      };
      getAskEngRavId = function () {
        return settings.AskEngRavId;
      };
      getMidrashRavId = function () {
        return settings.MidrashRavId;
      };
      getCmsBaseLink = function () {
        return settings.CmsBaseLink;
      };
      getCmsApiLink = function () {
        return settings.CmsApiLink;
      };
      getCmsDisconnectLink = function () {
        return settings.CmsDisconnectLink;
      };
      getRepliesLink = function () {
        return settings.RepliesLink;
      };

      getCmsContentLink = function () {
        return settings.CmsContentLink;
      };

      updateSettings = function (data, addToOtherDomain = true) {
        if (data !== undefined && data !== "" && data.Id !== 0) {
          if (
            data.ck !== undefined &&
            data.ck.name !== undefined &&
            data.ck.name !== ""
          ) {
            var cookie = docCookies.simple.getCookie(data.ck.name);
            if (cookie === null || cookie === "") {
              //console.log("setting cookie " + JSON.stringify(data.ck));
              //this sets the cookie with an expiration date of 1 year from now
              //the cookie has a built in expiration so it's just to keep it from being deleted early
              // docCookies.setItem(
              //   data.ck.name,
              //   data.ck.key + "=" + data.ck.value,
              //   new Date().getTime() + 1000 * 60 * 60 * 24 * 365,
              //   "/"
              // );
              document.cookie =
                data.ck.name +
                "=" +
                data.ck.key +
                "=" +
                data.ck.value +
                "; path=/;" +
                "expires=" +
                new Date(
                  new Date().getTime() + 1000 * 60 * 60 * 24 * 365
                ).toUTCString() +
                ";";
            }
            if (data.ck && data.ck.name && addToOtherDomain) {
              //console.log("setting bifrostcors ck: " + JSON.stringify(data.ck));
              bifrostCors
                .setLocalStorage({
                  key: "ckYesh",
                  value: JSON.stringify(data),
                })
                .then();
            }
          }
          settings.Username =
            "<a id='userIdLink' href='/Users/'>" + data.firstName + "</a>";
          settings.ActionLog = "";
          settings.CmsBaseLink = data.cmsBaseLink;
          settings.CmsApiLink = data.cmsApiLink;
          settings.CmsDisconnectLink = data.cmsDisconnectLink;
          settings.RepliesLink = data.repliesLink;
          settings.CmsContentLink = data.cmsContentLink;
          settings.IsInternal = data.isInternal;
          settings.AskEngRavId = data.AskEngRavId;
          settings.AskHebRavId = data.AskHebRavId;
          settings.MidrashRavId = data.MidrashRavId;
          //$("#HidelinksIcons").hide();
          if (document.getElementById("HidelinksIcons"))
            document.getElementById("HidelinksIcons").style.display = "none";

          var opts = {
            method: "POST",
            headers: {},
          };
          fetch("/Users/UserAlerts/", opts).then(function (body) {
            if (typeof alertsData !== "undefined") {
              if (alertsData.alerts) $(".userAlert").toggle();
              if (alertsData.answers > 0) $(".userAnswers").toggle();
            }
          });

          //  $.ajax({
          //    url: "/Users/UserAlerts/",
          //    method: "post",
          //  }).done(function (alertsData) {
          //    if (alertsData.alerts) $(".userAlert").toggle();
          //    if (alertsData.answers > 0) $(".userAnswers").toggle();
          //  });
        }

        // Greeting not in use since Angular header is live
        //$("#regUpBar").html(
        //  settings.Greeting +
        //  settings.Username +
        //  (settings.ActionLog !== ""
        //    ? " <span onclick=\"user.login()\" style='cursor: pointer;'>" +
        //    settings.ActionLog +
        //    "</span> | <a href='" +
        //    settings.ActionRegHref +
        //    "'>" +
        //    settings.ActionReg +
        //    "</a>"
        //    : "")
        //);
        for (var i = 0; i < callbacks.length; i++) {
          if (data !== undefined) {
            callbacks[i](data.user !== undefined ? data.user : data);
          } else {
            callbacks[i]({});
          }
        }
      };

      isUserConnected = function () {
        var cookieLoginlname = "zpbwxsSyX4h0fGZQICW5pQ%3d%3d";
        var cookie = docCookies.simple.getCookie(cookieLoginlname);
        if (cookie !== null && cookie !== "") {
          return true;
        } else {
          return settings.IsInternal;
        }
      };

      let alreadyInit = false;
      let whenReadyPromiseInstance = null;
      whenReadyPromise = function (forceCheck) {
        if (!whenReadyPromiseInstance) {
          whenReadyPromiseInstance = new Promise((resolve, reject) => {
            if (alreadyInit) {
              //console.log("alreadyInit");
              resolve(true);
            } else {
              var cookieLoginlname = "zpbwxsSyX4h0fGZQICW5pQ%3d%3d";
              var cookie = docCookies.simple.getCookie(cookieLoginlname);
              if ((cookie !== null && cookie !== "") || forceCheck) {
                // || document.location.host.indexOf('yeshiva.org.il') < 0) {
                //console.log("cookie found: " + JSON.stringify(cookie));
                var opts = {
                  method: "POST",
                  credentials: "include",
                };
                fetch(ssldomain + "/Users/UserName/", opts)
                  .then(function (response) {
                    alreadyInit = true;
                    // console.log("respond");
                    return response.json();
                  })
                  .then(function (data) {
                    if (data && data.Id !== 0) {
                      //console.log("user found");
                      //docCookies.setItem("YeshivaUser", JSON.stringify(data), 365, "", "", true);

                      if (
                        localStorage.getItem("ckYesh") === "delete" ||
                        docCookies.simple.getCookie("transferLogout") === "1"
                      ) {
                        //console.log("deleting cookie");
                        if (localStorage.getItem("ckYesh")) {
                          localStorage.removeItem("ckYesh");
                        }
                        if (docCookies.hasItem("userYeshiva")) {
                          docCookies.removeItem("userYeshiva", "/");
                        }
                        if (docCookies.hasItem("transferLogout")) {
                          docCookies.removeItem("transferLogout", "/");
                        }
                        window.location = "/users/LogOff/";
                      } else if (docCookies.simple.getCookie("transferLogin")) {
                        updateSettings(
                          JSON.parse(
                            docCookies.simple.getCookie("transferLogin")
                          )
                        );
                        docCookies.removeItem("transferLogin", "/");
                        if (
                          /(article|category|rabbi)management/i.test(
                            window.location.pathname
                          )
                        ) {
                          //we do this on any page with the pictures system which opens up a new window and doesn't work well with this script
                          self.location.reload();
                        }
                      }
                      updateSettings(data);
                    } else {
                      if (data) {
                        //console.log("data: " + JSON.stringify(data));
                      } else {
                        //console.log("no data");
                      }
                      let stgStr = localStorage.getItem("ckYesh");
                      let stg = null;
                      if (stgStr) {
                        stg = JSON.parse(stgStr);
                      }
                      if (stg && stg != "delete") {
                        //console.log("stg found");
                        updateSettings(stg, false);
                        localStorage.removeItem("ckYesh");
                        self.location.reload();
                      } else {
                        //console.log("delete cookie 1");
                        if (localStorage.getItem("deleteOtherDomains")) {
                          bifrostCors
                            .setLocalStorage({
                              key: "ckYesh",
                              value: "delete",
                            })
                            .then();
                          localStorage.removeItem("deleteOtherDomains");
                        }
                        docCookies.simple.removeItem(cookieLoginlname);
                        // document.cookie =
                        //   cookieLoginlname +
                        //   "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
                      }
                    }
                    resolve(data);
                  });
              } else {
                //console.log("cookie not found");
                //console.log("delete cookie 2");
                if (localStorage.getItem("deleteOtherDomains")) {
                  bifrostCors
                    .setLocalStorage({
                      key: "ckYesh",
                      value: "delete",
                    })
                    .then();
                  localStorage.removeItem("deleteOtherDomains");
                }
                resolve(false);
              }
            }
          });
        }
        return whenReadyPromiseInstance;
      };
      whenReadyPromise(!heb).then();
    },
    false
  );
  //})(jQuery);

  var receiveMessage = function (event) {
    if (
      typeof event.data.detail !== "undefined" &&
      event.data.detail &&
      typeof event.data.detail.message !== "undefined" &&
      event.data.detail.message === "redirect" &&
      event.data.detail.location
    ) {
      event.stopPropagation();
      event.preventDefault();
      window.location = event.data.detail.location;
      return;
    }
    var origin = event.origin || event.originalEvent.origin; // For Chrome, the origin property is in the event.originalEvent object.
    //console.log(event);
    if (
      origin !== ssldomain &&
      origin.indexOf("localhost") === -1 &&
      origin.indexOf(localDomainEng) === -1 &&
      origin.indexOf(localDomainHeb) === -1 &&
      origin.indexOf("staging") === -1
    )
      return;
    if (!event.data) return;
    if (event.data.type === "registerPhase1") {
      //we need to log them in on the client
      document.dispatchEvent(
        new CustomEvent("loggedIn", { detail: event.data.detail })
      );
      updateSettings({
        Id: event.data.detail.id,
        firstName: event.data.detail.firstName,
        user: ev.detail.user,
        ck: event.data.detail.ck,
      });
      return;
    } else if (event.data.type !== "modalClosed") {
      return;
    }
    //console.log("correct");
    user.iframe_closed(event.data);
  };

  window.addEventListener("message", receiveMessage, false);

  // This class is exported
  var _user = function () {
    var activeUser;
    this.redirectUrl;

    this.iframe_loaded = function () {
      var self = this;
      fr = document.getElementById("loginiframe");
      fr.contentWindow.document.addEventListener(
        "modalClosed",
        this.iframe_closed,
        false
      );
    };
    this.iframe_closed = function (ev) {
      var loginframe = document.getElementById("loginFrameCont");
      if (loginframe?.offsetWidth > 0 || loginframe?.offsetHeight > 0) {
        //if ($("#loginFrameCont").is(":visible")) {
        //$("#loginFrameCont").hide();
        loginframe.style.display = "none"; // hide
        //console.log(ev);
        if (ev?.detail && ev.detail.allow) {
          document.dispatchEvent(
            new CustomEvent("loggedIn", { detail: ev.detail })
          );
          updateSettings({
            Id: ev.detail.id,
            firstName: ev.detail.firstName,
            user: ev.detail.user,
            ck: ev.detail.ck,
          });
          if (this.redirectUrl && this.redirectUrl.trim().length > 0) {
            location = this.redirectUrl;
          } else if (
            self.location.href.toLowerCase().indexOf("/users") !== -1
          ) {
            // Will hopefully refresh the page so it will auto show the user page.
            // Remy's a bit confused why this code is should hopefully do what it supposed to do.
            // But anyway deleted since no longer needed since in Angular
            //self.location.reload(true);
          }
        }
      }
    };

    //ex: 1 = extra registeration phase, 2 = both edditon details phase (use when the system sent the password to the user
    //register pass '1' in the register param and it will open the iframe directly in the registration section
    this.login = function (rUrl, ex, email, register) {
      var secur = true;
      if (window.location.host.indexOf("local") >= 0) {
        secur = false;
      }

      var eng =
        document.body.classList.contains("LangEN") ||
        window.location.host.indexOf("yeshiva.co") >= 0 ||
        window.location.host.split(".")[0] === "en";
      var src = (secur === true ? ssldomain : "") + "/users/loginframe";
      if (eng === true) src += "?lang=eng";
      this.redirectUrl = rUrl;
      fr = document.getElementById("loginiframe");
      if (!fr) fr = this.createLoginIframe();
      var continueParm = "?";
      if (src !== undefined && src !== null && src.indexOf("?") > -1)
        continueParm = "&";

      fr.src = src; //ssldomain + '/users/loginframe';

      if (ex !== undefined && ex !== null) {
        fr.src += continueParm + "ex=" + ex;
        continueParm = "&";
      }
      if (register !== undefined && register !== null) {
        fr.src += continueParm + "register=" + register;
        continueParm = "&";
      }
      if (email !== undefined && email !== null)
        fr.src += continueParm + "email=" + email;

      document.getElementById("loginFrameCont").style.display = "block";

      //$("#loginFrameCont").show();
    };

    this.logout = function () {
      let address = host;
      // We need to keep the adress prefix adress
      if (
        !document.location.host.startsWith("he.") &&
        !document.location.host.startsWith("en.") &&
        document.location.host.indexOf("test") === -1
      ) {
        address = host.slice(document.location.host.indexOf(".") + 1);
      } else {
        // In develop serve we need to cut the port
        address = location.hostname;
      }
      try {
        docCookies.simple.removeItem(
          "zpbwxsSyX4h0fGZQICW5pQ%3d%3d",
          "/",
          address
        );
      } catch (error) {
        /*Do nothing*/
      }

      updateSettings();
    };

    this.createLoginIframe = function () {
      var cont = document.createElement("div");
      cont.id = "loginFrameCont";
      cont.style.display = "none";
      cont.style.backgroundColor = "rgba(10, 10, 10, 0.43)";
      cont.style.position = "fixed";
      cont.style.top = "0";
      cont.style.right = "0";
      cont.style.zIndex = "2000";
      cont.style.width = "100%";
      cont.style.height = "100%";
      cont.style.textAlign = "center";
      cont.innerHTML =
        '<iframe id="loginiframe" frameborder="0" allowTransparency="true"  style="width: 100%;height: 100%;"></iframe>';
      document.body.appendChild(cont);
      var iframe = document.getElementById("loginiframe");
      //iframe.onload = function () {
      //    user.iframe_loaded()
      //};
      return iframe;
    };
    this.addCallback = function (callback) {
      if (activeUser) {
        callback(activeUser);
      }
      callbacks.push(callback);
    };

    /** Not garantee to initiate activeUser in mobile
     * @return {boolean} Is the user connected
     * */
    this.isConnected = function () {
      return typeof isUserConnected !== "undefined" ? isUserConnected() : false;
    };

    this.isInternal = function () {
      return getIsInternal();
    };
    this.askEngRavId = function () {
      return getAskEngRavId();
    };
    this.askHebRavId = function () {
      return getAskHebRavId();
    };
    this.midrashRavId = function () {
      return getMidrashRavId();
    };
    this.cmsBaseLink = function () {
      return getCmsBaseLink();
    };
    this.cmsApiLink = function () {
      return getCmsApiLink();
    };
    this.cmsDisconnectLink = function () {
      return getCmsDisconnectLink();
    };
    this.repliesLink = function () {
      return getRepliesLink();
    };
    this.cmsContentLink = function () {
      return getCmsContentLink();
    };
    this.whenReadyPromise = function (forceCheck) {
      return whenReadyPromise(forceCheck);
    };

    // Register ourself so we can determine if we have connected user
    this.addCallback(function (usr) {
      activeUser = usr;
    });
  };
  var user = new _user();
}

