var _SETL_CHAT_BASE_URI = 'https://pn.ru';var SETL_CHAT_BASE_URI = window._SETL_CHAT_BASE_URI || 'https://pn.ru';
var NEWTON_CALLBACK = {
  SHOWED: 'n_clb_sh',
  SHOWED_COUNT: 'n_clb_sh_count',
  INITIAL_TIME: 'n_clb_it',
  FORGET: 'n_clb_fg',
  WRAPPER_POSITION: 'n_clb_wp',
  BUTTON_POSITION: 'n_clb_bp',
};

var newtonLoadCaptcha = function () {
  newtonCallback && newtonCallback.captcha();
};

var maskedPhoneRegex = /\+7\s\(\d{3}\)\s\d{3}-\d{2}-\d{2}/gm;

var phoneInputMask = function (o, s) {
  var e = this;
  var a = [];

  getMask = function (e) {
    var t = 99, n = null;
    for (i = 0; i < o.length; i++) o[i].length >= e && o[i].length - e < t && (n = o[i], t = o[i].length - e);
    return n;
  };
  getMaskByInput = function (e) {
    var t = 99, n = null, a = (e = clearInput(e)).length;
    for (i = 0; i < o.length; i++) _ml = o[i].match(/[\d\_]/g).length, _ml >= a && _ml - a < t && (n = o[i], t = _ml - a);
    return n;
  };
  clearInput = function (e) {
    return e.replace(/[^\d]/g, "");
  };
  applyMask = function (e, t) {
    e = e.replace(/[^\d]/g, "");
    var n = 0, a = "";
    for (i = 0; i < t.length; i++) c = t.charAt(i), "_" == c ? (cc = e.charAt(n++), isNaN(parseInt(cc))
      ? a += c
      : a += cc) : (a += c, isNaN(parseInt(c)) || c != e.charAt(n) || n++);
    return a;
  };
  applyKeyCode = function (e) {
    var t = this.selectionStart, n = 0;
    if (t != this.selectionEnd) return !1;
    if (t == this.value.length || 95 == e && t + 1 == this.value.length) {
      var a = 95 == e ? -1 : 1, o = getMask(t + a);
      if (o && o.length != this.value.length) {
        if (0 < a && o.length <= t) return !1;
        this.value = applyMask(this.value, o), t = this.value.search(/\d[^\d]*$/) + 1;
      }
    }
    if (_cc = this.value.charAt(t), 95 != e || isNaN(parseInt(_cc)) && "_" != _cc) {
      if ("_" != _cc) {
        var l = t;
        for (i = t + 1; i < this.value.length; i++) if (_c = this.value.charAt(i), "_" == _c) {
          l = i;
          break;
        }
        if (l == t) return !1;
        t = l;
      }
    } else n = -1;
    o = getMask(this.value.length);
    return o && isNaN(parseInt(o.charAt(t))) && (this.value = this.value.substr(
      0,
      t
    ) + String.fromCharCode(e) + this.value.substr(t + 1), s && !s.call(this)
      ? this.selectionStart = this.selectionEnd = t + n
      : this.selectionStart = this.selectionEnd = t + 1 + n), !1;
  };
  e.onkeydown = function (e) {
    if (90 == e.keyCode && e.ctrlKey && 0 < a.length) {
      var t = a.pop();
      return this.value = t[0], this.selectionStart = this.selectionEnd = t[1], !1;
    }
    if (86 != e.keyCode && 67 != e.keyCode && 65 != e.keyCode || !e.ctrlKey) {
      var n = this.value, t = this.selectionStart, e = onkeydown_.call(this, e);
      return n != this.value && a.push([n, t]), e;
    }
    return !0;
  };
  clearSelection = function () {
    var e = this.selectionStart, t = this.selectionEnd, n = "", a = getMask(this.value.length);
    for (i = 0; i < a.length; i++) i >= e && i < t ? n += a.charAt(i) : n += this.value.charAt(i);
    t == this.value.length
      ? (this.value = applyMask(
        n,
        getMaskByInput(n)
      ), this.selectionStart = this.selectionEnd = this.value.search(/\d[^\d]*$/) + 1)
      : (this.value = n, this.selectionStart = this.selectionEnd = e);
  };
  onkeydown_ = function (e) {
    var t = e.keyCode;
    this.value;
    switch (t) {
      case 8:
        this.selectionStart == this.selectionEnd && this.selectionStart--, clearSelection.call(this);
        break;
      case 36:
      case 35:
      case 39:
      case 37:
      case 9:
      case 116:
      case 13:
        return !0;
      case 46:
        this.selectionStart == this.selectionEnd && this.selectionEnd++, clearSelection.call(this);
        break;
      case 96:
      case 97:
      case 98:
      case 99:
      case 100:
      case 101:
      case 102:
      case 103:
      case 104:
      case 105:
        t -= 48;
      case 48:
      case 49:
      case 50:
      case 51:
      case 52:
      case 53:
      case 54:
      case 55:
      case 56:
      case 57:
        return this.selectionStart != this.selectionEnd && clearSelection.call(this), applyKeyCode.call(this, t);
    }
    return !1;
  };
  e.onfocus = function (e) {
    this.value || (this.value = getMask(0));
  };
  e.onpaste = function (e) {
    var t = e.clipboardData.getData("text/plain"), n = getMaskByInput(t);
    n && (a.push([this.value, this.selectionStart]), this.value = applyMask(t, n)), e.preventDefault();
  };
  e.onmouseup = function (e) {
    var t;
    getMask(this.value.length) != this.value || -1 != (t = this.value.indexOf(
      "_",
      this.value.search(/\d[^\d]*$/)
    )) && (this.selectionEndnStart = this.selectionEnd = t);
  };
};

var eyenewtonLoader;
var newtonCallback;

function EyenewtonLoader() {
  var t = [];
  var n = 0;

  this.load = function (e) {
    "function" == typeof e && (0 == n ? (n = 1, e()) : 1 == n ? t.push(e) : 2 == n && e());
  };

  this.next = function () {
    if (2 != n) {
      n = 2;
      for (var e = 0; e < t.length; e++) t[e]();
      t = [];
    }
  };
}

function NewtonCallback() {
  // region LIBRARY

  function getCaption(e) {
    return captions[default_settings.lang][e] || '';
  }

  function getMasks() {
    return masks[default_settings.lang];
  }

  function getPrefix() {
    return prefix[default_settings.lang];
  }

  function convertMsecs(e, t) {
    return void 0 === t && (t = !1), hours = Math.floor(e / 36e5), hours < 0 && (hours = 0), rest_msec = e - 60 * hours * 60 * 1e3, minutes = Math.floor(
      rest_msec / 6e4), rest_msec -= 60 * minutes * 1e3, seconds = Math.floor(rest_msec / 1e3), rest_msec -= 1e3 * seconds, 10 < rest_msec && (rest_msec = Math.floor(
      rest_msec / 10)), minutes < 10 && (minutes = "0" + minutes), seconds < 10 && (seconds = "0" + seconds), rest_msec < 10 && (rest_msec = "0" + rest_msec), 0 < hours || t
      ? (hours < 10 && (hours = "0" + hours), hours + ":" + minutes + ":" + seconds)
      : minutes + ":" + seconds + "." + rest_msec;
  }

  function getTimeRemaining(e, t) {
    var n = Date.parse(e) - Date.parse(new Date), a = Math.floor(n / 1e3 % 60), i = Math.floor(n / 1e3 / 60 % 60),
      o = Math.floor(n / 36e5 % 24), e = Math.floor(n / 864e5);
    return t
      ? (a = a < 10 ? "<span><b>0</b></span><span><b>" + a + "</b></span>" : "<span><b>" + a.toString()
        .split("")[0] + "</b></span><span><b>" + a.toString().split("")[1] + "</b></span>", i = i < 10
        ? "<span><b>0</b></span><span><b>" + i + "</b></span>"
        : "<span><b>" + i.toString().split("")[0] + "</b></span><span><b>" + i.toString()
        .split("")[1] + "</b></span>", o = o < 10
        ? "<span><b>0</b></span><span><b>" + o + "</b></span>"
        : "<span><b>" + o.toString().split("")[0] + "</b></span><span><b>" + o.toString()
        .split("")[1] + "</b></span>", e = e < 10
        ? "<span><b>0</b></span><span><b>" + e + "</b></span>"
        : "<span><b>" + e.toString().split("")[0] + "</b></span><span><b>" + e.toString().split("")[1] + "</b></span>")
      : (10 <= a && (a = "<span><b>" + a.toString().split("")[0] + "</b></span><span><b>" + a.toString()
        .split("")[1] + "</b></span>"), 10 <= i && (i = "<span><b>" + i.toString()
        .split("")[0] + "</b></span><span><b>" + i.toString()
        .split("")[1] + "</b></span>"), 10 <= o && (o = "<span><b>" + o.toString()
        .split("")[0] + "</b></span><span><b>" + o.toString()
        .split("")[1] + "</b></span>"), 10 <= e && (e = "<span><b>" + e.toString()
        .split("")[0] + "</b></span><span><b>" + e.toString().split("")[1] + "</b></span>")), {
      total: n,
      days: e,
      hours: o,
      minutes: i,
      seconds: a
    };
  }

  function serialize(e) {
    if (e && "FORM" === e.nodeName) {
      for (var t, n = {}, a = e.elements.length - 1; 0 <= a; --a) if ("" !== e.elements[a].name && !e.elements[a].disabled) switch (e.elements[a].nodeName) {
        case"INPUT":
          switch (e.elements[a].type) {
            case"text":
            case"tel":
            case"hidden":
            case"password":
            case"button":
            case"reset":
            case"submit":
              n[e.elements[a].name] = e.elements[a].value;
              break;
            case"checkbox":
            case"radio":
              e.elements[a].checked && (n[e.elements[a].name] = e.elements[a].value);
          }
          break;
        case"TEXTAREA":
          n[e.elements[a].name] = e.elements[a].value;
          break;
        case"SELECT":
          switch (e.elements[a].type) {
            case"select-one":
              n[e.elements[a].name] = e.elements[a].value;
              break;
            case"select-multiple":
              for (t = e.elements[a].options.length - 1; 0 <= t; --t) e.elements[a].options[t].selected && (n[e.elements[a].name] = e.elements[a].options[t].value);
          }
          break;
        case"BUTTON":
          switch (e.elements[a].type) {
            case"reset":
            case"submit":
            case"button":
              n[e.elements[a].name] = e.elements[a].value;
          }
      }
      return n;
    }
  }

  Date.prototype.timeNow = function (e) {
    return (this.getHours() < 10 ? "0" : "") + this.getHours() + ":" + (this.getMinutes() < 10
      ? "0"
      : "") + this.getMinutes();
  };

  const resetPhoneButton = (resetForce) => {
    const newtonCallbackPhone = document.querySelector('#newton_callback_phone');

    if (checkHide(newtonCallbackPhone) || resetForce) {
      $(newtonCallbackPhone).css('inset', 'auto');
      setButtonCustomPosition({x: newtonCallbackPhone.getBoundingClientRect().left, y: newtonCallbackPhone.getBoundingClientRect().top});
    }
  };

  const resetPhoneForm = () => {
    const newtonCallbackWrap = document.querySelector('#newton_callback_wrap');

    if (checkHide(newtonCallbackWrap)) {
      resetPhoneButton(true);
      $(newtonCallbackWrap).css('inset', 'auto');
    }
  };

  const addResizeListener = function() {
    $(window).resize(() => {
      resetPhoneForm();
      resetPhoneButton();
    });
  };

  if (document.readyState == 'loading') {
    window.addEventListener('DOMContentLoaded', addResizeListener);
  } else {
    addResizeListener();
  }

  const checkHide = function (target) {
    const windowX = window.scrollX;
    const windowY = window.scrollY;

    const targetPosition = {
      top: windowY + target.getBoundingClientRect().top,
      left: windowX + target.getBoundingClientRect().left,
      right: windowX + target.getBoundingClientRect().right,
      bottom: windowY + target.getBoundingClientRect().bottom
    };
    const windowPosition = {
      top: windowY,
      left: windowX,
      right: windowX + document.documentElement.clientWidth,
      bottom: windowY + document.documentElement.clientHeight
    };

    if (!(targetPosition.bottom < windowPosition.bottom && targetPosition.top > windowPosition.top
      && targetPosition.right < windowPosition.right && targetPosition.left > windowPosition.left)
      && ($(target).css('display') !== 'none')) {
      return true;
    } else {
      return false;
    }
  };

  // region CLIENT_VERSION

  function isMobile() {
    return /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i.test(
      navigator.userAgent || navigator.vendor || window.opera) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
      (navigator.userAgent || navigator.vendor || window.opera).substr(0, 4));
  }

  function iOSversion() {
    if (/iP(hone|od|ad)/.test(navigator.platform)) {
      var e = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
      return [parseInt(e[1], 10), parseInt(e[2], 10), parseInt(e[3] || 0, 10)];
    }
  }

  function isChromeAndroid() {
    return -1 < navigator.userAgent.indexOf("Android ") && -1 < navigator.userAgent.indexOf("Chrome");
  }

  function isSafari() {
    return /^((?!chrome|android).)*safari/i.test(navigator.userAgent) && !navigator.userAgent.match("CriOS");
  }

  function isFirefox() {
    return -1 < navigator.userAgent.toLowerCase().indexOf("firefox");
  }

  function isNewIOS() {
    var e = iOSversion();
    return void 0 !== e && 8 <= e[0];
  }

  function isIE() {
    var e = document.all && document.compatMode, t = window.navigator.msPointerEnabled;
    return !(!e && !t);
  }

  // endregion CLIENT_VERSION

  function merge_options(e, t) {
    var n, a = {};
    for (n in e) a[n] = e[n];
    for (n in t) a[n] = t[n];
    return a;
  }

  // region DOM

  function hasClass(e, t) {
    return e.className && e.className.match(new RegExp("(\\s|^)" + t + "(\\s|$)"));
  }

  function addClass(e, t) {
    hasClass(e, t) || (e.className += " " + t);
  }

  function removeClass(e, t) {
    hasClass(e, t) && (t = new RegExp("(\\s|^)" + t + "(\\s|$)"), e.className = e.className.replace(t, " "));
  }

  function isDescendant(e, t) {
    if (t === e) {
      return 1;
    }

    for (var n = t.parentNode; null != n;) {
      if (n === e) {
        return 1;
      }

      n = n.parentNode;
    }
  }

  // endregion DOM

  // region EVENTS

  /**
   * @type {{ target: HTMLElement, type: string, listener: function }[]}
   */
  var eventRegistry = [];

  /**
   * @param {HTMLElement} element
   * @param {string} eventType
   * @param {function} handler
   */
  var registerEvent = function (element, eventType, handler) {
    element != document && element != window || eventRegistry.push({
      target: element,
      type: eventType,
      listener: handler
    });
  };

  /**
   * @param {HTMLElement} element
   * @param {string} eventType
   * @param {function} handler
   */
  var unregisterEvent = function (element, eventType, handler) {
    if (element === document || element === window) {
      for (var a in eventRegistry) {
        if (eventRegistry[a].target === element && eventRegistry[a].type === eventType && eventRegistry[a].listener === handler) {
          eventRegistry.splice(a, 1);
          break;
        }
      }
    }
  };

  /**
   * @param {HTMLElement} element
   * @param {string} eventType
   * @param {function} handler
   */
  var addEvent = function (element, eventType, handler) {
    if (document.addEventListener) {
      element.addEventListener(eventType, handler, !1);
    } else {
      element.attachEvent('on' + eventType, handler);
    }

    registerEvent(element, eventType, handler);
  };

  /**
   * @param {HTMLElement} element
   * @param {string} eventType
   * @param {function} handler
   */
  var removeEvent = function (element, eventType, handler) {
    if (document.addEventListener) {
      element.removeEventListener(eventType, handler, !1);
    } else {
      element.detachEvent('on' + eventType, handler);
    }

    unregisterEvent(element, eventType, handler);
  };

  /**
   * @param {HTMLElement} element
   * @param {string} eventType
   */
  var fireEvent = function (element, eventType) {
    if ("createEvent" in document) {
      var n = document.createEvent('HTMLEvents');
      n.initEvent(eventType, !1, !0);
      element.dispatchEvent(n);
    } else {
      element.fireEvent('on' + eventType);
    }
  };

  var cleanAllEvents = function () {
    for (; 0 < eventRegistry.length;) {
      removeEvent(eventRegistry[0].target, eventRegistry[0].type, eventRegistry[0].listener);
    }
  };

  function cancelEvent(e) {
    return (e = e || window.event).stopPropagation && e.stopPropagation(), e.preventDefault && e.preventDefault(), e.cancelBubble = !0, e.cancel = !0, e.returnValue = !1;
  }

  // endregion EVENTS

  // region AJAX

  var ajax = {};

  function buildParams(e, t, n) {
    var a;
    var i;
    var o = [];

    for (a in t) t.hasOwnProperty(a) && "function" != typeof t[a] && (i = e + (n
      ? "[" + a + "]"
      : a), t[a] instanceof Array || "object" == typeof t[a] ? o = o.concat(buildParams(i, t[a], !0)) : o.push(
      encodeURIComponent(i) + "=" + encodeURIComponent(t[a])));

    return o;
  }

  function addSystemQueryData(e) {
    return cookie_local_storage && (e.cookie = cookie_local_storage), e.referer = window.location.href, e;
  }

  ajax.x = function () {
    if ("undefined" != typeof XMLHttpRequest) {
      return new XMLHttpRequest();
    }

    for (var e, t = [
      "MSXML2.XmlHttp.5.0",
      "MSXML2.XmlHttp.4.0",
      "MSXML2.XmlHttp.3.0",
      "MSXML2.XmlHttp.2.0",
      "Microsoft.XmlHttp"
    ], n = 0; n < t.length; n++) try {
      e = new ActiveXObject(t[n]);
      break;
    } catch (e) {
    }

    return e;
  };

  ajax.send = function (url, onSuccess, method, data, withCredentials) {
    var request = ajax.x();

    request.withCredentials = withCredentials;

    request.open(method, url, !0);

    request.onreadystatechange = function () {
      if (4 === request.readyState && onSuccess && typeof onSuccess === 'function') {
        onSuccess(request.responseText);
      }
    };

    if ('POST' === method) {
      request.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
    }

    request.send(data);
  };

  ajax.get = function (url, t, n, a) {
    void 0 === a && (a = !0);
    t = buildParams("", t = addSystemQueryData(t));
    ajax.send(url + (-1 == url.indexOf("?") ? "?" : "&") + t.join("&"), n, "GET", null, a);
  };

  ajax.post = function (url, t, n) {
    var refererData = buildParams("", addSystemQueryData([]));
    var query = buildParams("", t);

    ajax.send(url + "?" + refererData.join("&"), n, "POST", query.join("&"), !0);
  };

  // endregion AJAX

  function getParam(e) {
    if (e && "object" == typeof newton_params && void 0 !== newton_params[e]) return newton_params[e];
  }

  function init() {
    clearInterval(init_interval);
    try {
      is_mobile && default_settings.enable_mobile_direct_call && default_settings.calltracking_dynamic_hash && "undefined" != typeof newton_auction_lot_id_internal
        ? newtonCallback.isCalltrackingAvailable(function (e) {
          direct_phone_dynamic = e, afterSettings();
        })
        : afterSettings();
    } catch (e) {
      return remoteErrorLog(e, "init"), void (initializing = !1);
    }
  }

  function afterCssApply() {
    0 == default_settings.silent_mode && (showPhoneButton(), handleKeyboard(), evalAdditionalJavascript(), is_mobile && correctWidgetSizeFunc(), manageEvents(
      is_mobile), isVkVerion() && (afterLoad = function () {
      showForm();
    }), null != afterLoad && afterLoad(), checkLocationHash()), onInit(), enableSetingsUpdate(is_mobile), initializing = !1;
  }

  function waitCssApply() {
    var e = setInterval(function () {
      cssLoaded && (clearInterval(e), e = null, afterCssApply());
    }, 50);
  }

  function afterSettings() {
    var e;
    isLocalStorageSupported || remoteLocalStorageLog(), getLandingPageReferrer() && remoteRefererLog(
      getLandingPageReferrer()), default_settings.calltracking && applyCalltracking(), default_settings.callback && (e = checkInit(), !default_settings.show_on_mobile && is_mobile || !e || (0 == default_settings.silent_mode
      ? (initialized = !0, applyCss(), handleCallBooking(), drawButton(), drawDialog(), drawForm(), drawDepartmentSelect(), drawCallTypeSelect(), drawMiniVersion(), applyInputMask(), handleCloseButtonClick(), handleDialogButtonsClick(), handleForm(), handleForget(), handleLocationHashChange(), handleMissedButtonClick(), handlePhoneButton(), handleDepartmentSelect(), handleCallTypeSelect(), handleActiveDelay(), handleMultiwidget(), handleAgreement(), handleMiniVersion(), waitCssApply())
      : afterCssApply())), newton_local_cookie = (m = document.cookie.match(new RegExp("(?:^|; )" + "NWTN".replace(
      /([\.$?*|{}\(\)\[\]\\\/\+^])/g,
      "\\$1"
    ) + "=([^;]*)"))) ? decodeURIComponent(m[1]) : void 0, applyMarquiz();
  }

  function applyCalltracking() {
    if (default_settings.calltracking_targets) for (var e in default_settings.calltracking_targets) {
      var t, n = default_settings.calltracking_targets[e], a = [];
      for (t in n) {
        var i = n[t].type, o = n[t].name, l = n[t].html, c = n[t].number;
        if ("#" == i && exchangeNumber(document.getElementById(o), l, c), "." == i) {
          var s, r = document.getElementsByClassName(o);
          for (s in r) exchangeNumber(r[s], l, c);
        }
        "tel" == i && (n[t].reg = new RegExp(n[t].reg, "g"), a.push(n[t])), calltracking_direct_phone = n[t].number;
      }
      a.length && document.querySelectorAll("body *").forEach(function (e) {
        for (var t = e.firstChild; t;) replaceNumber(t, a), t = t.nextSibling;
        replaceNumber(e, a);
      });
    }
  }

  function replaceNumber(e, t) {
    if ("A" == e.tagName) {
      var n = e.getAttribute("href");
      if (n) for (var a = 0; a < t.length; a++) t[a].reg.exec(n) && e.setAttribute(
        "href",
        n.replace(t[a].reg, t[a].number)
      );
    }
    if (Node.TEXT_NODE === e.nodeType) for (var a in t) e.textContent = e.textContent.replace(t[a].reg, t[a].html);
  }

  function decodeHtml(e) {
    var t = document.createElement("textarea");
    return t.innerHTML = e, t.value;
  }

  function exchangeNumber(e, t, n) {
    var a;
    e && ((a = e.href) && "tel:" == a.trim().substring(0, 4) && (e.href = "tel:" + n), e.innerHTML = t);
  }

  function onInit() {
    var e = getParam("onInit");
    void 0 !== e && e();
  }

  function onClose() {
    var e = getParam("onClose");
    void 0 !== e && e();
  }

  function checkInit() {
    return !0;
  }

  function checkLocationHash() {
    "#newton" == window.location.hash && (showForm(), window.location.hash = "#newton-ok");
  }

  function handleLocationHashChange() {
    addEvent(window, "hashchange", checkLocationHash);
  }

  function evalAdditionalJavascript() {

    /* !!! ВСЕ ПРАВКИ ОТРАЗИТЬ В ФАЙЛЕ NEWTON_ADDITIONAL_HTML ПРОЕКТА SPBREALTY !!! */
    function isTablet() {
      return /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/i.test(
        (navigator.userAgent || navigator.vendor || window.opera));
    }

    if (is_mobile && isTablet()) {
      destroy();
      is_mobile = false;
      init();
    } else {
      var chatScript = document.createElement('script');
      chatScript.src = SETL_CHAT_BASE_URI + '/api/js';
      chatScript.setAttribute('defer', 'defer');
      var phone_button = $('#newton_callback_phone');
      var chat = $('#newton_callback_chat_welcome');
      var dialog_chat_link = $('#newton_callback_dialog_chat');
      var dialog_video_link = $('#newton_callback_dialog_video');
      var chat_link = $('#newton_callback_tab_chat_a');

      phone_button.append(
        '<div class="phone-button-icons">' +
        '<div class="phone-button-icon phone"></div>' +
        '<div class="phone-button-icon chat"></div>' +
        '</div>'
      );

      (function () {
        let chatContainer = document.getElementById('setl-chat-wrap');
        if (chatContainer) {
          chatContainer.setAttribute('data-notificationcolor', default_settings.css_phone_button_color);
        }
      })();

      chatScript.onload = function () {
        if (!is_mobile) {
          chat_link.show();
          dialog_chat_link.show();
          dialog_video_link.show();

          // phone button widget
          phone_button.append('<div class="chat-messages"></div><div class="chat-notifications"></div>');
          phone_button.find('.newton-circle').html('<div class="newton-call-icon newton-handset"></div>');
        }
      };
      chatScript.onerror = function () {
        if (!is_mobile) {
          chat.hide();
          chat_link.hide();
          dialog_chat_link.hide();
          dialog_video_link.hide();
        }
      };
      document.body.appendChild(chatScript);

      // callback or delay
      function getType() {
        var form_toggle_link = $('#newton_callback_toggle_a');
        return form_toggle_link.length ? form_toggle_link.data('type') : 'delay';
      }

      function getCurrentType() {
        var type = getType();
        return type === 'delay' ? 'callback' : 'delay';
      }

      //shows callback form
      showForm = function (params) {
        params = params || {};
        var dialog_text = "dialog_text" in params ? params.dialog_text : false;
        var open_callback = "open_callback" in params ? params.open_callback : false;
        hideMiniVersion();
        if (is_mobile && (!default_settings.enable_mobile_direct_call || params.forceCallback)) {
          callType = 'callback';
        }
        if (is_mobile && default_settings.free_version) {
          callType = 'direct';
        }
        if (is_mobile && !callType) {
          /* !!!! fixed check !!!! */
          if (direct_phone_dynamic == null || direct_phone_dynamic == true) {
            showTypeSelect();
            return;
          } else {
            callType = 'callback';
          }
        }
        var departmentId = "departmentId" in params ? params.departmentId : false;
        var singleDepartmentId = getSingleMobileCallbackDepartment();
        if (is_mobile && default_settings.have_departments && callType == 'callback' && singleDepartmentId) {
          departmentId = singleDepartmentId;
          var input = document.getElementById(form_name + '_department_id');
          if (input) {
            input.value = departmentId;
          }
        }
        if (is_mobile && !departmentId && default_settings.have_departments) {
          if (typeof window.newton_department_id === "number" && callType == 'direct') {
            departmentId = window.newton_department_id;
          } else {
            showDepartmentSelect();
            return;
          }
        }
        if (is_mobile && callType === 'direct') {
          if (!checkActive({departmentId: departmentId})) {
            return;
          }
          reachGoal('direct-call');
          // TODO: Снять какой-либо обработчик с телефонного номера
          var phoneEl = document.querySelector('.newton_callback_type_direct__select-direct-call-region');
          window.location = phoneEl.getAttribute('href');
          callType = false;
          return;
        }
        if (!is_mobile && departmentId && default_settings.have_departments) {
          if (getSingleNonMobileDepartment()) {
            document.getElementById(form_name + '_department_id').value = departmentId;
          } else {
            var link = getDepartmentLink(departmentId);
            if (link) {
              setDepartment(link);
            }
          }
        }
        var wrap = document.getElementById('newton_callback_wrap'),
          wrapParent = wrap.parentNode;
        if (wrap && "css" in params && "top" in params.css && 'left' in params.css) {
          wrap.style.cssText = 'top:' + (params.css.top - 475) + 'px !important; left:' + (params.css.left - 224) + 'px !important;';
        }
        if (!isOpened()) {
          // check current time
          getSettings();
          if (!is_mobile) {
            var link_wrap = $('#newton_callback_toggle_a_wrap');
            if (!link_wrap.length) {
              if (checkActive({departmentId: departmentId}))
                $('#newton_sms_notice')
                  .after(
                    '<div id="newton_callback_toggle_a_wrap"><a id="newton_callback_toggle_a" data-type="delay" href="javascript:void(0);"><span>Выбрать удобное время звонка</span></a></div>');
            } else {
              if ((!(checkActive({departmentId: departmentId}) || laterCall) || !checkLaterCall()))
                link_wrap.remove();
            }
          }
          if (checkActive({departmentId: departmentId})) {
            var link = $('#newton_callback_toggle_a');
            if (link.length) {
              link.data('type', 'delay');
              link.find('span').text('Выбрать удобное время звонка');
            }
            if (params.withoutButton) {
              hidePhoneButton({noAnimation: true});
            } else {
              hidePhoneButton();
            }

            if (is_mobile) {
              var btn = document.querySelector('#newton_callback_phone');
              addEvent(btn, 'click', hideForm);
            }

            removeClass(document.getElementById('newton_callback_form_text'), 'newton_callback_form_text_delay');
            document.getElementById('newton_callback_counter').innerHTML = convertMsecs(default_settings.timer);
            if (!is_mobile) {
              document.getElementById('newton_callback_active_delay_wrap').style.display = 'block';
            }
            if (dialog_text) {
              document.getElementById('newton_callback_form_text').innerHTML = dialog_text;
            } else {
              if (is_mobile) {
                handleFormSize();
                document.getElementById('newton_callback_form_text').innerHTML = default_settings.form_text_mobile;

                const delaySelector = document.querySelector('.call-later-date-select');

                if (delaySelector) {
                  delaySelector.remove();
                }
              } else {
                document.getElementById('newton_callback_form_text').innerHTML = default_settings.form_text;
              }
            }
            setShowed();
            customSelects(document.getElementById('newton_callback_form_text'));
            wrap.style.display = 'block';
            if (is_mobile) {
              setTimeout(function () {
                wrapParent.classList.add('active');
                wrap.classList.add('active');
                addClass(wrap, 'newton_wrap_slide');
              }, 1);
              setTranslateForBtn();
            } else {
              setTimeout(function () {
                addClass(wrap, 'newton_wrap_slide');
              }, 50);
            }
            if (!dialog_text) {
              showBackground();
            }
            if (typeof open_callback === 'function') {
              open_callback();
            }
            if (!is_mobile && typeof SetlChatSetStatusShown === 'function') {
              SetlChatSetStatusShown();
            }
            if (typeof SetlChatScrollToEnd === 'function') {
              SetlChatScrollToEnd();
            }
          } else if (checkLaterCall()) {
            var link = $('#newton_callback_toggle_a');
            if (link.length) {
              link.data('type', 'callback');
              link.find('span').text('Перезвоните сейчас');
            }
            hidePhoneButton();
            addClass(document.getElementById('newton_callback_form_text'), 'newton_callback_form_text_delay');
            if (is_mobile) {
              handleFormSize();
              document.getElementById('newton_callback_form_text').innerHTML = getDelayTextMobile({departmentId: departmentId});
            } else {
              if (laterCall && dialog_text) {
                document.getElementById('newton_callback_form_text').innerHTML = dialog_text;
              } else {
                var delay_tab = document.getElementById('newton_callback_tabs_item_delay');
                if (delay_tab) {
                  delay_tab.style.display = 'none';
                }
                document.getElementById('newton_callback_form_text').innerHTML = getDelayText({departmentId: departmentId});
              }
            }
            handleFormSelect();
            customSelects(document.getElementById('newton_callback_form_text'));
            wrap.style.display = 'block';
            if (is_mobile) {
              drawCallLaterDateHourSelectMobile(departmentId);
              var _btn = document.querySelector('#newton_callback_phone'),
                _closeCurrentForm = function (e) {
                  if (wrap.classList.contains('active')) {
                    closeCallLaterMobile(wrap);
                    destroyCallLaterDateSelectMobile();
                    showPhoneButton();
                    clearForm();
                  }
                  removeEvent(_btn, 'click', _closeCurrentForm);
                };

              addEvent(_btn, 'click', _closeCurrentForm);

              setTimeout(function () {
                wrapParent.classList.add('active');
                wrap.classList.add('active');
              }, 110);
            }
            setTimeout(function () {
              addClass(wrap, 'newton_wrap_slide');
            }, 50);
            addClass(wrap, 'newton_delay');
            if (!dialog_text) {
              showBackground();
            }
            if (typeof open_callback === 'function') {
              open_callback();
            }
            if (!is_mobile && typeof SetlChatSetStatusShown === 'function') {
              SetlChatSetStatusShown();
            }
            if (typeof SetlChatScrollToEnd === 'function') {
              SetlChatScrollToEnd();
            }
          } else if (dialog_text) {
            hideBackground();
          }
        }
      };
      clearForm = function () {
        document.getElementById(form_name + '_phone').value = '';
        document.getElementById(form_name + '_phone').style.visibility = 'visible';
        document.getElementById('newton_callback_input_wrap').style.setProperty('display', 'inline-block', 'important');
        removeClass(document.getElementById(form_name + '_phone'), 'error');
        document.getElementById('newton_callback_submit_button').style.visibility = 'visible';
        document.getElementById('newton_callback_submit_button').style.setProperty('display', 'inline', 'important');
        document.getElementById('newton_callback_missed_wrap').style.setProperty('display', 'none', 'important');
        document.getElementById('newton_callback_missed_result').style.setProperty('display', 'none', 'important');
        removeClass(document.getElementById('newton_callback_wrap'), 'newton_missed');
        removeClass(document.getElementById('newton_callback_phone_error'), 'visible');

        if (!checkActive()) {
          document.getElementById('newton_callback_form_text').style.display = 'block';
        }

        removeClass(document.getElementById('newton_callback_form_text'), 'delay_success');

        document.getElementById('newton_callback_submit_result').innerHTML = '';
        clearInterval(countdown_interval_id);
        countdown_interval_id = null;
        document.getElementById('newton_callback_counter').innerHTML = convertMsecs(default_settings.timer);

        if (default_settings.have_departments) {
          var singleDepartmentId = is_mobile ? false : getSingleNonMobileDepartment();
          document.getElementById(form_name + '_department_id').value = singleDepartmentId ? singleDepartmentId : '';
          if (!is_mobile && !singleDepartmentId) {
            var link = document.getElementById('newton_callback_departments_link');
            link.innerHTML = default_settings.department_link_text;
            var link = document.getElementById('newton_callback_departments_link_dummy');
            link.innerHTML = default_settings.department_link_text;

            var select = document.getElementById('newton_callback_departments_list');
            var list = select.getElementsByTagName('a');
            for (var i = 0; i < list.length; i++) {
              removeClass(list[i], 'newton_selected');
            }
          }
        }

        removeClass(document.getElementById('newton_callback_counter'), 'newton_show');
        removeClass(document.getElementById('newton_callback_counter'), 'newton_hide');

        removeClass(document.getElementById('newton_callback_wrap'), 'newton_delay');
        removeClass(document.getElementById('newton_callback_wrap'), 'delay_countdown');

        if (!is_mobile) {
          document.getElementById('newton_callback_active_delay_wrap').style.display = 'none';
        } else {
          removeClass(document.getElementById('newton_callback_submit_button'), 'countdown');
          removeClass(document.getElementById('newton_callback_wrap'), 'video');
          document.getElementById('newton_callback_submit_button').innerText = getCaption('form_submit_button');
        }

        document.getElementById('newton_callback_missed_options').style.display = 'none';

        var sms_notice = document.getElementById('newton_sms_notice');
        if (sms_notice && !laterCall) {
          sms_notice.style.display = 'none';
        }

        clearTimeout(closeFormTimeout);
        closeFormTimeout = null;

        missed_block = false;

        if (default_settings.is_multiwidget) {
          if (default_settings.free_version) {
            if (default_settings.multiwidget_application) {
              setMultiwidgetTabSelected('newton_callback_tab_application');
            }
          } else {
            setMultiwidgetTabSelected('newton_callback_tab_call');
          }

          var delay_tab = document.getElementById('newton_callback_tabs_item_delay');
          if (delay_tab && !default_settings.free_version) {
            delay_tab.style.display = 'inline-block';
          }
          if (default_settings.multiwidget_application) {
            if (!default_settings.free_version) {
              document.getElementById('newton_callback_form').style.display = 'block';
              var applicationForm = document.getElementById('newton_callback_application_form');
              if (applicationForm) {
                applicationForm.style.display = 'none';
              }
            } else {
              var applicationForm = document.getElementById('newton_callback_application_form');
              if (applicationForm) {
                applicationForm.style.display = 'block';
              }
            }

            var application_success = document.getElementById('newton_callback_application_success');
            if (application_success) {
              application_success.style.display = 'none';
            }
          }
          var chat = document.getElementById('newton_chat');
          if (chat) {
            if (!default_settings.free_version) {
              document.getElementById('newton_callback_form').style.display = 'block';
              chat.style.display = 'none';
            } else {
              if (default_settings.multiwidget_application) {
                chat.style.display = 'none';
              }
            }
            deleteCookie('n_chat_opnd');
          }
        }

        var link = document.getElementById('newton_callback_departments_link');
        if (link) {
          removeClass(link, 'newton_callback_departments_link_disabled');
        }
        if (default_settings.banner_bottom) {
          showBanner();
        } else {
          hideBanner();
        }
        showAgreement();

        callType = false;
        successCall = false;
        formFromDialog = false;

        if (typeof onClearForm === 'function') {
          onClearForm();
        }

        enableSubmitButton();
        enableApplicationSubmitButton();
      };

      //hides callback form
      var slideTimeout = null;
      hideForm = function (hide_background, params) {
        var withoutButton = params && params.withoutButton,
          btn = document.querySelector('#newton_callback_phone');

        if (hide_background == undefined) {
          hide_background = true;
        }
        if (isFormOpened()) {
          if (!successCall && hide_background) {
            reachGoal('NEWTON_CLOSE');
          }
          clearForm();
        }
        showPhoneButton();
        if (is_mobile) {
          unhandleFormSize();
          hideMissedCallMobile();
          removeEvent(btn, 'click', hideForm);
        }

        if (withoutButton) {
          var callbackWrap = document.querySelector('#newton_callback_wrap');
          callbackWrap.classList.contains('active') ? showPhoneButton(is_new_ios) : showPhoneButton(is_new_ios, true);
        }

        var runOnClose = false;
        if (hide_background && isFormOpened()) {
          runOnClose = true;
        }
        var wrap = document.getElementById('newton_callback_wrap');
        if (!is_mobile && default_settings.is_multiwidget && hide_background && isFormOpened()) {
          removeClass(wrap, 'newton_wrap_slide');
          clearTimeout(slideTimeout);
          slideTimeout = setTimeout(function () {
            wrap.style.display = 'none';
          }, 200);
        } else {
          wrap.style.display = 'none';
        }
        if (hide_background) {
          hideBackground();
        }

        var wrap = document.getElementById('newton_callback_wrap');

        if (is_mobile) {
          wrap.classList.remove('active');
          wrap.parentNode.classList.remove('active');
          wrap.style.removeProperty('transition');
          wrap.style.removeProperty('bottom');
        }

        if (runOnClose) {
          onClose();
          if (!is_mobile && typeof SetlChatSetStatusHidden === 'function') {
            SetlChatSetStatusHidden();
          }
        }
      };

      function addVideoBtnsListener() {
        let videoEventListener = function (event) {
          switch (event.data.event) {
            case 'onVideoCallClick':
              showCallback(true);
              window.removeEventListener('message', videoEventListener);
              break;
            case 'onVideoChatClick':
              showChat(true);
              window.removeEventListener('message', videoEventListener);
              break;
          }
        };
        window.addEventListener('message', videoEventListener);
      }

      backgroundClickClose = function (e) {
        var phone = document.getElementById('newton_callback_phone');
        var wrap = document.getElementById('newton_callback_wrap');
        var dialog_wrap = document.getElementById('newton_callback_dialog_wrap');
        var department_select = document.getElementById('newton_callback_department_select');
        var type_select = document.getElementById('newton_callback_type_select');
        var mini_version = document.getElementById('ncw_compact');

        if ((!wrap || !isDescendant(wrap, e.target))
          && (!dialog_wrap || !isDescendant(dialog_wrap, e.target))
          && (!phone || !isDescendant(phone, e.target))
          && (!department_select || !isDescendant(department_select, e.target))
          && (!mini_version || !isDescendant(mini_version, e.target))
          && (!type_select || !isDescendant(type_select, e.target))) {

          if (is_mobile) {
            destroyCallLaterDateSelectMobile();
            removeEvent(phone, 'click', hideForm);
            removeEvent(phone, 'click', showPhoneButton);
            showPhoneButton();
            hideForm();
            e.preventDefault();
          } else {
            hideDialog();
            hideForm();
          }
        }
      };

      showSubmitResult = function (json) {
        for (var i in formErrorElements) {
          removeClass(formErrorElements[i], 'error');
        }

        var result = '';
        var resultField = document.getElementById('newton_callback_submit_result');
        if (json == 1) {
          successCall = true;
          reachGoal(formFromDialog ? 'NEWTON_DIALOG_CALL' : 'NEWTON_CALL');
          var departmentId = false;
          var input = document.getElementById(form_name + '_department_id');
          if (input && input.value && default_settings.have_departments) {
            departmentId = input.value;
          }
          if (!checkActive({departmentId: departmentId}) && checkLaterCall()) {
            if (is_mobile) {
              destroyCallLaterDateSelectMobile();
              let a = '';
              a = '<span>Заявка принята!</span><br>' +
                '<span>Мы перезвоним вам ';
              let o = document.getElementById('App_Modules_Api_Forms_CallbackForm_date');
              if (o) {
                a += getDateCaption(new Date(o.value));
              }
              o = document.getElementById('App_Modules_Api_Forms_CallbackForm_hour');

              const minute = document.getElementById('App_Modules_Api_Forms_CallbackForm_minute');

              if (o && minute) {
                a += ' в ' + o.value + ':' + minute.value;
              }
              document.getElementById('newton_callback_form_text').innerHTML = a;
              document.getElementById('newton_callback_input_wrap').style.setProperty('display', 'none', 'important');
              document.getElementById('newton_callback_submit_button')
                .style
                .setProperty('display', 'none', 'important');
              var captchaWrap = document.getElementById('newton_callback_captcha');
              if (captchaWrap) {
                captchaWrap.style.setProperty('display', 'none', 'important');
              }
              addClass(document.getElementById('newton_callback_form_text'), 'delay_success');

              var wrap = document.getElementById('newton_callback_wrap_mobile');
              correctWidgetSize(wrap);

              enableSubmitButton();
            } else {
              let a = '';
              a = '<span>Заявка принята!</span><br>' +
                '<span>Мы перезвоним вам ';
              let o = document.getElementById('App_Modules_Api_Forms_CallbackForm_date');
              if (o) {
                a += o.options[o.selectedIndex].text;
              }

              const hour = document.getElementById('App_Modules_Api_Forms_CallbackForm_hour');
              const minute = document.getElementById('App_Modules_Api_Forms_CallbackForm_minute');

              if (hour && minute) {
                a += ' в ' + hour.options[hour.selectedIndex].text + ':' + minute.options[minute.selectedIndex].text;
              }
              document.getElementById('newton_callback_form_text').innerHTML = '<b>Обратный звонок</b><br>' + a;
              addClass(document.getElementById('newton_callback_form_text'), 'delay_success');
              document.getElementById(form_name + '_phone').style.visibility = 'hidden';
              document.getElementById('newton_callback_input_wrap').style.setProperty('display', 'none', 'important');
              document.getElementById('newton_callback_submit_button').style.visibility = 'hidden';
              var captchaWrap = document.getElementById('newton_callback_captcha');
              if (captchaWrap) {
                captchaWrap.style.visibility = 'hidden';
              }
              var sms_notice = document.getElementById('newton_sms_notice');
              if (sms_notice) {
                sms_notice.style.display = 'none';
              }
            }
            setTimeout(function () {
              getSettings();
            }, 1000);
          } else {
            if (is_mobile) {
              addClass(document.getElementById('newton_callback_counter'), 'newton_show');
              var captchaWrap = document.getElementById('newton_callback_captcha');
              if (captchaWrap) {
                captchaWrap.style.setProperty('display', 'none', 'important');
              }
              setTranslateForBtn();
            } else {
              document.getElementById(form_name + '_phone').style.visibility = 'hidden';
              document.getElementById('newton_callback_submit_button').style.visibility = 'hidden';
              document.getElementById('newton_callback_active_delay_wrap').style.display = 'none';
              var captchaWrap = document.getElementById('newton_callback_captcha');
              if (captchaWrap) {
                captchaWrap.style.visibility = 'hidden';
              }
            }
            countdown();
          }
        } else {
          result = processJson(json, form_name, formErrorElements);
          if (is_mobile) {
            enableSubmitButton();
          }
          setTranslateForBtn();
        }

        resultField.innerHTML = result;
        if (!is_mobile) {
          enableSubmitButton();
        }
      };

      if (!is_mobile) {
        addEvent(document, 'click', backgroundClickClose);
        $.fn.animateCss = function (animationName, remove, callback, fast) {
          var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
          if (fast === true) animationName += ' fast';
          this.addClass('animated ' + animationName).one(animationEnd, function () {
            if (remove !== false) $(this).removeClass('animated ' + animationName);
            if (typeof callback == 'function') callback();
          });
          return this;
        };

        $('#newton_callback_missed_result').html('Спасибо,<br>ваш отзыв учтен!');

        var consultant = $('#chat-consultant');
        var nform = $('#newton_callback_form');

        var banners = $('#newton_callback_banners');

        var tab = $('#newton_callback_tabs');
        var tab_links = tab.find('li a');

        // var summon_link = $('#newton_callback_tab_summon_a');
        // var summon_content = $('#newton_callback_summon');
        // var summon_form_url = 'https://spbrealty.ru/newton/officeform';

        var video_link = $('#newton_callback_tab_video_a');
        var video_content = $('#newton_callback_video');
        var video_form_url = 'https://spbrealty.ru/newton/videoform';

        var callback_link = $('#newton_callback_tab_call_a');
        var missed_delay_link = $('#newton_callback_missed_active_delay');

        var dialog_callback_link = $('#newton_callback_dialog_callback');
        var dialog_chat_form_selector = '#widget-register-form';

        var dialog_wrap = document.getElementById('newton_callback_dialog_wrap');
        var jq_dialog_wrap = $('#newton_callback_dialog_wrap');
        handleDragObject(dialog_wrap, checkWrapCustomPosition, setWrapCustomPosition, function (internalPosition) {
          return internalPosition.x <= 100 && internalPosition.y <= 100;
        }, function () {
        });

        // показываем автоматически только 1 раз
        var already_showed = false;
        enableShowAtTime = function () {
          if (!already_showed && !(getParam("lk_logged_in") === true)) {
            show_timeout_id = setTimeout(function () {
              if (checkShowed() && !isMiniVersionAttached()) {
                incShowedCount();
                showDialog();
              }
            }, default_settings.appearance_time * 1000);
          }
        };

        var topCorner = null;
        mouseEntringTopCorner = function (event) {
          if (!already_showed) {
            if (topCorner == null) {
              if (checkShowed() && !isMiniVersionAttached()) {
                var w = window.innerWidth - exit_one_w;
                var h = exit_one_h;
                if (event.clientX > w && event.clientY < h) {
                  phoneButton = document.getElementById('newton_callback_phone');
                  if (!phoneButton.isMoving) {
                    showDialog();
                    topCorner = setTimeout(function () {
                      clearTimeout(topCorner);
                      topCorner = null;
                    }, 60 * 60 * 1000);
                  }
                }
              }
            }
          }
        };

        setShowed = function (force) {
          if (typeof newton_callback_no_cookie === 'undefined') {
            // виджет считается показанным, если кол-во показов > переменной, отв. за показ на Nой странице
            if (getShowedCount() >= default_settings.appearance_page_views || force === true) {

              deleteCookie(NEWTON_CALLBACK.SHOWED_COUNT);
              var date = new Date();
              // устанавливаем срок действия куки в зависимости от флага "показывать раз в день"
              if (default_settings.show_once_day) {
                date.setDate(date.getDate() + 1);
              } else {
                var time = date.getTime();
                time += 60 * 60 * 1000;
                date.setTime(time);
              }
              // флаг "виджет показан" checkShowed
              setCookie(NEWTON_CALLBACK.SHOWED, '1', {
                expires: date.toUTCString()
              });
            }
          }
        };

        // отключаем отображение на Nой странице, потому что используем эту переменную для ограничения кол-ва показов виджета
        enableShowAtNthPage = function () {
          return false;
        };

        manageEvents = function (mobile) {
          if (default_settings.appearance_disabled) {
            return;
          }
          if (mobile === undefined) {
            mobile = false;
          }
          if (checkActive() || checkLaterCall()) {
            if (!mobile && !checkForget()) {
              if (default_settings.appearance_init == 1) {
                enableShowAtInit();
              } else if (checkShowed() && default_settings.appearance_page_views && getPageViews() == default_settings.appearance_page_views) {
                enableShowAtNthPage();
                resetPageViews();
              } else {
                disableShowAtInit();
              }
              if (default_settings.appearance_exit == 1) {
                enableShowAtExit();
              } else {
                disableShowAtExit();
              }
              if (default_settings.appearance_time > 0) {
                enableShowAtTime();
              } else {
                disableShowAtTime();
              }
            }
            if (!mobile && checkOpenChatAtInit()) {
              openChatAtInit();
            }
          } else {
            if (isOpened()) {
              hideDialog();
              hideForm();
            }
            disableAll();
          }
        };

        showDialog = function () {
          if (document.domain == 'lk.pn.ru' || jq_dialog_wrap.hasClass('inactive'))
            return;
          already_showed = true;
          if (checkShowed() && (!default_settings.dialog_enabled || default_settings.is_multiwidget)) {
            showForm({
              open_callback: function () {
                reachGoal('NEWTON_DIALOG');
              }
            });
          } else {
            if (!isOpened() && checkShowed()) {
              //check current time
              getSettings();
              if (checkActive() || checkLaterCall()) {
                hidePhoneButton();
                setShowed();
                jq_dialog_wrap.animateCss('slideInUp', false, null, true);
                jq_dialog_wrap.show();
                reachGoal('NEWTON_DIALOG');
              }
            }
          }
        };

        incShowedCount = function (count) {
          if (typeof newton_callback_no_cookie === 'undefined') {
            if (typeof count !== 'Number')
              var count = getShowedCount() * 1 + 1;
            var date = new Date();
            if (default_settings.show_once_day) {
              date.setDate(date.getDate() + 1);
            } else {
              var time = date.getTime();
              time += 3600 * 1000;
              date.setTime(time);
            }
            setCookie(NEWTON_CALLBACK.SHOWED_COUNT, count, {
              expires: date.toUTCString()
            });
          }
        };

        getShowedCount = function () {
          var c = getCookie(NEWTON_CALLBACK.SHOWED_COUNT);
          return c === undefined ? 0 : c;
        };

        phoneButtonClick = function () {
          var params = {};

          if (is_mobile && hasClass(btn, 'opened')) {
            var type_select = document.getElementById('newton_callback_type_select');
            var department_select = document.getElementById('newton_callback_department_select');

            if (type_select && hasClass(type_select, 'active')) {
              hideTypeSelect();
            }

            if (department_select && hasClass(department_select, 'active')) {
              calltype = false;
              hideDepartmentSelect();
            }

            return;
          }

          if (laterCall)
            params = {dialog_text: getActiveDelayText()};
          if (!is_mobile) {
            var phoneButton = document.getElementById('newton_callback_phone');
            if (phoneButton) {
              params.css = {
                top: phoneButton.offsetTop,
                left: phoneButton.offsetLeft,
              };
            }
          }
          SetlChatShow();
          reachGoal('NEWTON_OPEN');
          if (typeof _gaq !== "undefined") {
            _gaq.push(['_trackEvent', 'newtonopenform', 'onClick', 'открыта форма - Ньютон']);
          }
          if (typeof report !== "undefined" && report.send) {
            report.send({'link': 'https://spbrealty.ru/virtPage/newtonopenform'});
          }
          if (typeof yaCounter159439 !== "undefined") {
            yaCounter159439.reachGoal("newtonopenform");
          }
        };

        var ntnWindowResize = function (state) {
          if (!state) {
            banners.hide();
            return false;
          }
          if ($(window).height() < 765) {
            banners.hide();
          } else {
            banners.show();
          }
        };

        $('window').resize(function () {
          ntnWindowResize(true);
        });

        function toggleShowCallbackDelay(type) {
          type = type === undefined ? getType() : type;
          if (type === 'delay') {
            showDelay(false);
          } else {
            showCallback(true);
          }
        }

        // function showSummon() {
        // 	var summon_iframe = summon_content.find('iframe');
        // 	if (summon_iframe.length == 1 && summon_iframe.attr('src') == '')
        // 		summon_iframe.attr('src', summon_form_url);
        // 	summon_content.show();
        // 	nform.hide();
        // 	consultant.hide();
        // 	chat.hide();
        // 	ntnWindowResize(false);
        // 	tab_links.removeClass('newton_active');
        // 	summon_link.addClass('newton_active');
        // }

        // summon_link.click(function(){
        // 	showSummon();
        // 	if (typeof yaCounter159439 !== "undefined") {
        // 		yaCounter159439.reachGoal("office_consult");
        // 	}
        // });

        function showVideo() {
          var video_iframe = video_content.find('iframe');
          if (video_iframe.length == 1 && video_iframe.attr('src') == '')
            video_iframe.attr('src', video_form_url);
          video_content.show();

          addVideoBtnsListener();

          nform.hide();
          consultant.hide();
          chat.hide();
          ntnWindowResize(false);
          tab_links.removeClass('newton_active');
          video_link.addClass('newton_active');

          var agreement = $('#newton_agreement');
          if (agreement.length)
            agreement.hide();

          setShowed(true);
        }

        video_link.click(function () {
          showVideo();
        });

        // callback
        function showCallback(from_dialog) {
          nform.show();
          consultant.hide();
          chat.hide();
          // summon_content.hide();
          video_content.hide();
          ntnWindowResize(true);
          laterCall = false;
          setDirectCall();
          if (from_dialog === true) {
            hideDialog(false);
            if (!is_mobile) {
              var phoneButton = document.getElementById('newton_callback_phone'),
                params = {};
              if (phoneButton) {
                params.css = {
                  top: phoneButton.offsetTop,
                  left: phoneButton.offsetLeft,
                };
              }
            }
            showForm(params);
          }
          tab_links.removeClass('newton_active');
          callback_link.addClass('newton_active');
          setShowed(true);
        }

        function showDelayForm() {
          var type = getCurrentType();
          toggleShowCallbackDelay(type);
        }

        callback_link.click(function () {
          showDelayForm();
        });

        dialog_callback_link.click(function () {
          showDelayForm();
        });

        $(document).on('click', '#chat-newton_callback_tab_call', function () {
          if (default_settings.callback_enabled) {
            showDelayForm();
          }
        });

        // delay
        function showDelay(from_dialog) {
          nform.show();
          consultant.hide();
          chat.hide();
          video_content.hide();
          ntnWindowResize(true);
          laterCall = true;
          setActiveLaterCall();
          if (from_dialog === true) {
            hideDialog(false);
            showForm({dialog_text: getActiveDelayText()});
          }
          tab_links.removeClass('newton_active');
          callback_link.addClass('newton_active');
        }

        $(document).on('click', '#newton_callback_toggle_a', function () {
          toggleShowCallbackDelay();
        });

        missed_delay_link.click(function () {
          showDelay(false);
        });

        //chat
        function showChat(from_dialog) {
          if ("setlchat" in window && window.setlchat.settings && window.setlchat.settings.username && window.setlchat.settings.islk) {
            window.setlchat.startChat();
          }
          nform.hide();
          chat.show();
          if (typeof SetlChatScrollToEnd === 'function') {
            SetlChatScrollToEnd();
          }
          // summon_content.hide();
          video_content.hide();
          consultant.css('display', 'flex');
          ntnWindowResize(false);
          if (from_dialog === true) {
            hideDialog(false);
            showForm();
          }
          tab_links.removeClass('newton_active');
          chat_link.addClass('newton_active');

          var agreement = $('#newton_agreement');
          if (agreement.length)
            agreement.hide();

          setShowed(true);
        }

        $(document).on('setlchat_show_trigger', function () {
          showChat(true);
        });

        chat_link.click(function () {
          showChat(false);
        });

        dialog_chat_link.click(function () {
          showChat(true);
        });

        dialog_video_link.click(function () {
          showChat(true);
          showVideo();
        });

        $(document).on('submit', dialog_chat_form_selector, function () {
          showChat(true);
        });

        showBackground = function () {
        };

        disableSubmitButton = function () {
          var e = document.getElementById('newton_callback_submit_button');
          if (e) {
            e.disabled = 'disabled';
          }
          e = document.getElementById('newton_callback_input_wrap');
          if (e) {
            e.style.setProperty('display', 'none', 'important');
          }
          e = document.getElementById('newton_callback_submit_button');
          if (e) {
            e.style.setProperty('display', 'none', 'important');
          }
        };

        enableSubmitButton = function () {
          var e = document.getElementById('newton_callback_submit_button');
          if (e) {
            e.disabled = null;
          }
          e = document.getElementById('newton_callback_input_wrap');
          if (e) {
            e.style.removeProperty('display');
          }
          e = document.getElementById('newton_callback_submit_button');
          if (e) {
            e.style.removeProperty('display');
          }
        };
      } else {
        // is_new_ios =false;
        var mobile_select = $('#newton_callback_type_select_mobile');
        var mobile_select_wrap = $('#newton_callback_type_select');
        var mobile_callback_form = $('#newton_callback_form');
        var mobile_select_ul = mobile_select.find('#newton_callback_type_select > ul');
        var direct_li = mobile_select_ul.find('.newton_callback_type_direct');
        var mobile_callback_wrap = $('#newton_callback_wrap');

        direct_li.text('Позвонить');
        if (!checkActive() || !default_settings.callback_enabled) {
          direct_li.parent().hide();
        } else {
          mobile_callback_form.find('#newton_callback_form_text').hide();
        }

        mobile_select_ul.find('#newton_callback_type_callback').text('Заказать звонок');
        if (!default_settings.callback_enabled) {
          mobile_select_ul.find('#newton_callback_type_callback').parent().hide();
        }

        mobile_select_ul.prepend(
          // '<li><a id="newton_callback_type_summon" href="javascript:void(0);">Вызов консультанта в офис</a></li>' +
          // '<li><a id="newton_callback_type_video" href="javascript:void(0);">Видеозвонок</a></li>' +
          '<li><a id="newton_callback_type_chat" href="javascript:void(0);">Начать чат<span class="chat-messages"></span></a></li>'
        );

        phone_button.append('<div id="newton_callback_links">' +
          '<a href="javascript:void(0);" class="phone" id="newton_callback_phone_link">' +
          '<div class="ico ico-5" data-id="wa"></div>' +
          '<div class="ico ico-4" data-id="vk"></div>' +
          '<div class="ico ico-3" data-id="tg"></div>' +
          '<div class="ico ico-2" data-id="phone"></div>' +
          '<div class="ico ico-1" data-id="chat"></div>' +
          '</a>' +
          '</div>'
        );

        phone_button.append('<div class="chat-messages"></div>');

        // mobile_callback_wrap.find('#newton_callback_content').prepend(
        // 	'<div class="newton_summon_content">' +
        // 	'<iframe frameborder="0" scrolling="no" width="320" height="444" src="https://spbrealty.ru/newton/officeform"></iframe>' +
        // 	'<div class="newton_summon_more">Ознакомьтесь, пожалуйста, с условиями<br> предоставления услуги. <a class="newton_summon_more_btn" href="javascript:void(0);">Подробнее</a></div>' +
        // 	'<div class="newton_summon_more_info">' +
        // 	'<a href="javascript:void(0);" class="newton_summon_more_close"></a>' +
        // 	'<div class="newton_summon_more_title">Условия предоставления услуги<br> «Заявка на консультацию в вашем офисе»</div>' +
        // 	'<div class="newton_summon_more_content">' +
        // 	'<div class="newton_summon_more_text">«Петербургская Недвижимость» ценит ваше время. Назначьте встречу с менеджером компании прямо в вашем офисе в удобный для вас день.</div>' +
        // 	'<ul class="newton_summon_more_stages">' +
        // 	'<li class="newton_summon_more_stage"><span>1</span>Выберите желаемую дату и время для встречи</li>' +
        // 	'<li class="newton_summon_more_stage"><span>2</span>Мы свяжемся с вами для подтверждения</li>' +
        // 	'<li class="newton_summon_more_stage"><span>3</span>Менеджер приедет к вам в офис в назначенный день и поможет выбрать квартиру</li>' +
        // 	'</ul>' +
        // 	'<div class="newton_summon_more_subtitle">Условия предложения:</div>' +
        // 	'<ul class="newton_summon_more_conditions">' +
        // 	'<li class="newton_summon_more_condition">Консультации проводятся только на территории бизнес-центра или в офисе.</li>' +
        // 	'<li class="newton_summon_more_condition">Территориальный охват: Санкт-Петербург и ближайшие пригороды – Мурино и Кудрово.</li>' +
        // 	'<li class="newton_summon_more_condition">Заявки обрабатываются с 9:00 до 18:00. Заявки, отправленные после 18:00, обрабатываются на следующий день.</li>' +
        // 	'<li class="newton_summon_more_condition">Консультации проводятся только в будние дни.</li>' +
        // 	'<li class="newton_summon_more_condition">Консультация не может быть назначена на тот же день, а также на следующий день, если заявка отправлена позднее 15:00.</li>' +
        // 	'<li class="newton_summon_more_condition">Консультация не может быть назначена на выходные или праздничные дни.</li>' +
        // 	'</ul>' +
        // 	'<div class="newton_summon_more_call">Если у вас есть вопросы, вы всегда можете нам позвонить: <a class="newton_summon_more_tel" href="tel:+78123355555">33-55555</a></div>' +
        // 	'<a href="javascript:void(0);" class="newton_summon_more_agree">С условиями ознакомлен</a>' +
        // 	'</div>' +
        // 	'</div>' +
        // 	'</div>'
        // );

        var video_content = mobile_callback_wrap.find('#newton_callback_content');
        video_content.prepend(
          '<div class="newton_video_content">' +
          '<iframe frameborder="0" scrolling="no" width="320" height="250" src="https://spbrealty.ru/newton/videoForm"></iframe>' +
          '</div>'
        );
        setTimeout(function () {
          video_content.find('iframe').contents().on('touchend', '.chat_link', function (event) {
            event.stopPropagation();
            event.preventDefault();
            showChat();
          });
          video_content.find('iframe').contents().on('touchend', '.call_link', function (event) {
            event.stopPropagation();
            event.preventDefault();
            showCallback();
          });
        }, 1000);

        function showChat() {
          hideForm();
          hideTypeSelect();
          if (typeof SetlChatShow === 'function') {
            SetlChatShow();
          }
        }

        function showCallback() {
          hideForm();
          hideTypeSelect();
          callType = 'callback';
          showForm();
        }

        function showVideo() {
          hideTypeSelect();
          mobile_callback_wrap.addClass('video');
          mobile_callback_wrap.addClass('active');
          mobile_callback_wrap.show();
          mobile_callback_wrap.parent().addClass('active');
          showBackground();
          hidePhoneButton();
          correctWidgetSizeFunc();

          addVideoBtnsListener();

          var btn = document.querySelector('#newton_callback_phone');
          addEvent(btn, 'click', hideForm);
        }

        // $(document).on('click touchstart', '#newton_callback_type_summon', function(){
        // 	if (typeof yaCounter159439 !== "undefined") {
        // 		yaCounter159439.reachGoal("office_consult");
        // 	}
        // 	mobile_callback_wrap.addClass('summon');
        // 	mobile_callback_wrap.show();
        // });

        $(document).on('touchend', '#newton_callback_type_video', function () {
          event.stopPropagation();
          event.preventDefault();
          showVideo();
        });

        $(document).on('touchend', '#newton_callback_close', function (event) {
          event.stopPropagation();
          event.preventDefault();
          // mobile_callback_wrap.removeClass('summon');
          mobile_callback_wrap.removeClass('video');
          if (checkActive())
            mobile_callback_form.find('#newton_callback_form_text').hide();
        });

        mobile_select_ul.on('touchend', '#newton_callback_type_chat', function (event) {
          event.stopPropagation();
          event.preventDefault();
          showChat();
        });

        // $(document).on('click', '.newton_summon_more_btn', function(){
        // 	mobile_callback_wrap.find('.newton_summon_content').addClass('show_more');
        // });
        // $(document).on('click', '.newton_summon_more_close', function(){
        // 	mobile_callback_wrap.find('.newton_summon_content').removeClass('show_more');
        // });
        // $(document).on('click', '.newton_summon_more_agree', function(){
        // 	mobile_callback_wrap.find('.newton_summon_content').removeClass('show_more');
        // });

        mobile_callback_form.prepend('<div class="newton_callback_form_title">Заказать звонок</div>');

        correctWidgetSize = function (wrap) {
          setTranslateForBtn();
          clearTimeout(correct_timeout);
          correct_timeout = setTimeout(function (wrap) {
            if (!wrap) return;
            var landscape = (window.innerWidth > window.innerHeight) && wrap.id !== 'newton_callback_wrap_mobile';
            var scale;
            if (landscape) {
              wrap.style.setProperty('width', '1000px', 'important');
              scale = window.innerWidth / 1000;
              if (wrap.id !== 'newton_callback_phone')
                wrap.style.setProperty('height', (window.innerHeight / scale) + 'px', 'important');
            } else {
              var width = 320;
              wrap.style.setProperty('width', width + 'px', 'important');
              scale = window.innerWidth / width;
              if (wrap.id !== 'newton_callback_phone')
                wrap.style.setProperty('height', (window.innerHeight / scale) + 'px', 'impor tant');
            }
            var child = wrap.childNodes[0];
            scale = Math.ceil(scale * 100) / 100;
            var xDiff = (wrap.clientWidth * scale - wrap.clientWidth) / 2;
            setScaleToWrap(child, scale);
            var height = child.clientHeight;

            var bottom = (height * scale - height) / 2;

            var left = window.pageXOffset + xDiff;
            wrap.style.setProperty('left', left + 'px', 'important');
            child.style.setProperty('bottom', bottom + 'px', 'important');
          }, 100, wrap);
        };
        showDepartmentSelect = function () {
          var eventType = 'click';
          if (is_new_ios) {
            eventType = 'touchend';
          }
          addEvent(window, eventType, departmentSelectClickClose);
          hidePhoneButton();
          hideNonDirectDepartments();
          var select = document.getElementById('newton_callback_department_select');
          document.querySelector('.direct-call-region-wrapper__form-title').innerText = callType == 'direct'
            ? 'Позвонить'
            : 'Заказать звонок';
          select.style.setProperty('display', 'flex', 'important');
          select.classList.add('active');
          select.parentNode.classList.add('active');
          handleSelectSize();
        };
        hideDepartmentSelect = function () {
          var eventType = 'click';
          if (is_new_ios) {
            eventType = 'touchend';
          }
          removeEvent(window, eventType, departmentSelectClickClose);
          showPhoneButton();
          showNonDirectDepartments();
          var select = document.getElementById('newton_callback_department_select');
          select.style.setProperty('display', 'none', 'important');
          select.classList.remove('active');
          select.parentNode.classList.remove('active');
          select.style.removeProperty('transition');
          select.style.removeProperty('bottom');
          unhandleSelectSize();
        };
        departmentSelectClickClose = function (e) {
          var phone = document.getElementById('newton_callback_phone');
          var department_select = document.getElementById('newton_callback_department_select');
          var department_select_a = department_select.getElementsByTagName('a');
          var department_select_a_flag = true;
          if (department_select_a.length) {
            for (var i = 0; i < department_select_a.length; i++) {
              var a = department_select_a[i];
              department_select_a_flag = department_select_a_flag && !isDescendant(a, e.target);
              if (!department_select_a_flag)
                break;
            }
          }
          if ((!phone || !isDescendant(phone, e.target)) && department_select_a_flag) {
            hideDepartmentSelect();
            callType = false;
            e.preventDefault();
          }
        };
        showTypeSelect = function () {
          var eventType = 'click';
          if (isNewIOS()) {
            eventType = 'touchend';
          }
          addEvent(window, eventType, typeSelectClickClose);
          hidePhoneButton();
          var select = document.getElementById('newton_callback_type_select');
          select.style.display = 'block';
          handleTypeSize();
          if (is_mobile) {
            setTimeout(function () {
              select.classList.add('active');
            }, 110);
          }
        };
        hideTypeSelect = function () {
          var eventType = 'click';
          if (isNewIOS()) {
            eventType = 'touchend';
          }
          removeEvent(window, eventType, typeSelectClickClose);
          showPhoneButton();
          var select = document.getElementById('newton_callback_type_select');
          select.style.display = 'none';
          select.style.removeProperty('transition');
          select.style.removeProperty('bottom');
          unhandleTypeSize();
        };
        showPhoneButton = function (hidden, params) {
          var btn = document.getElementById('newton_callback_phone');

          if (hidden == undefined) {
            hidden = false;
          }
          removeClass(btn, 'opened');
          if (is_mobile) {
            setTranslateForBtn();
          }
          var phoneButton = document.getElementById('newton_callback_phone');
          if ((checkActive() || checkLaterCall()) && default_settings.show_phone_button) {
            if (hidden && !isAndroid) {
              phoneButton.style.visibility = 'hidden';
            }
            if (isIE()) {
              removeClass(phoneButton, 'newton_ie_hide');
            } else {
              phoneButton.style.display = 'block';
            }
            addClass(phoneButton, 'newton_animation');
          }
        };

        getTranslateValue = function () {
          return new Promise(function (resolve) {
            setTimeout(function () {
              var button = document.querySelector('.newton_callback_phone'),
                buttonHeight = button ? button.getBoundingClientRect().height : 0,
                activeContainerHeight = document.querySelector('.for-phone-icon.active') ? document.querySelector(
                  '.for-phone-icon.active').getBoundingClientRect().height : 0,
                value = Math.round(activeContainerHeight === 0
                  ? activeContainerHeight
                  : activeContainerHeight - buttonHeight / 2);
              resolve(value);
            });
          });
        };

        applyInputMask = function () {
          var checkCorrect = function () {
            var value = this.value;
            var digits = value.replace(/\D+/g, "");
            var preffix = digits.substr(0, 2);
            if (digits.length == 4 && (preffix == '77' || preffix == '78')) {
              if (!isCorrectPhonePrefix(digits)) {
                digits = digits.substr(0, 1) + digits.substr(2);
                this.value = applyMask(digits, getMask(digits.length));
                return false;
              }
            }
            return true;
          };

          var checkCorrectMobile = function (event) {
            event.keyCode && (keyCode = event.keyCode);
            var pos = this.selectionStart;
            if (pos < 3) event.preventDefault();
            var matrix = "+7 (___) ___-__-__",
              i = 0,
              def = matrix.replace(/\D/g, ""),
              val = this.value.replace(/\D/g, ""),
              new_value = matrix.replace(/[_\d]/g, function (a) {
                return i < val.length ? val.charAt(i++) || def.charAt(i) : a;
              });
            i = new_value.indexOf("_");
            if (i != -1) {
              i < 5 && (i = 3);
              new_value = new_value.slice(0, i);
            }
            var reg = matrix.substr(0, this.value.length).replace(
              /_+/g,
              function (a) {
                return "\\d{1," + a.length + "}";
              }
            ).replace(/[+()]/g, "\\$&");
            reg = new RegExp("^" + reg + "$");
            if (!reg.test(this.value) || this.value.length < 5 || keyCode > 47 && keyCode < 58) this.value = new_value;
            if (event.type == "blur" && this.value.length < 5) this.value = "";
          };

          var phone_field = document.getElementById(form_name + '_phone');
          if (is_mobile) {
            var mobileInput = function (e) {
              if (this.value === '') {
                this.value = getPrefix();
              }
            };
            phone_field.addEventListener("input", checkCorrectMobile, false);
            phone_field.addEventListener("focus", checkCorrectMobile, false);
            phone_field.addEventListener("blur", checkCorrectMobile, false);
            phone_field.addEventListener("keydown", checkCorrectMobile, false);

            addEvent(phone_field, 'focus', mobileInput);
          } else {
            phoneInputMask.call(phone_field, getMasks(), checkCorrect);
            phone_field.placeholder = getMasks();
          }

          if (!is_mobile && default_settings.is_multiwidget && default_settings.multiwidget_application) {
            var phone_field = document.getElementById(application_form_name + '_phone');
            phoneInputMask.call(phone_field, getMasks(), checkCorrect);
          }

          if (!is_mobile && default_settings.mini_version_enabled) {
            var input = document.getElementById('ncw_compact_input');
            if (input) {
              phoneInputMask.call(input, getMasks(), checkCorrect);
            }
          }
        };


        applyInputMask();
        setTimeout(function () {
          phone_button.attr(
            'style',
            'opacity: 1 !important; margin-bottom: 0 !important; margin-left: 0 !important; left: auto !important;'
          );
        }, 500);

        var client_phone_field = $('#App_Modules_Api_Forms_CallbackForm_phone');
        client_phone_field.attr("placeholder", "Введите ваш телефон");

        $(document).on('click', '#newton_callback_toggle_a', function () {
          if (laterCall) {
            laterCall = false;
            setDirectCall();
          } else {
            laterCall = true;
            setActiveLaterCall();
          }

          $('#newton_callback_form').show();
        });
      }

      var agreement = document.getElementById('newton_agreement');
      var sms = document.getElementById('newton_sms_notice');
      var form = document.getElementById('newton_callback_form');
      if (sms && typeof sms[0] !== 'undefined') form.insertBefore(agreement, sms[0]);
    }
    if (!default_settings.callback_enabled) {
      showChat();
    }
  }

  function handleForget() {
    var e = document.getElementById("newton_callback_wrap_forget");
    e && addEvent(e, "click", function () {
      hideForm();
      var e = document.getElementById("newton_bottom_wrap");
      e && addClass(e, "newton_forget"), setForget(), disableAll();
    });
  }

  function handleKeyboard() {
    addEvent(document.getElementById(phone_input_id), "focus", function (e) {
      keyboard_opened = !0;
    });
    addEvent(document.getElementById(phone_input_id), "blur", function () {
      keyboard_opened = !1;
    });
  }

  function isCorrectPhonePrefix(e) {
    switch (e) {
      case"7700":
      case"7701":
      case"7702":
      case"7703":
      case"7704":
      case"7705":
      case"7706":
      case"7707":
      case"7708":
      case"7709":
      case"7710":
      case"7711":
      case"7712":
      case"7713":
      case"7714":
      case"7715":
      case"7716":
      case"7717":
      case"7718":
      case"7721":
      case"7722":
      case"7723":
      case"7724":
      case"7725":
      case"7726":
      case"7727":
      case"7728":
      case"7729":
      case"7736":
      case"7747":
      case"7750":
      case"7751":
      case"7760":
      case"7761":
      case"7762":
      case"7763":
      case"7764":
      case"7771":
      case"7775":
      case"7776":
      case"7777":
      case"7778":
      case"7800":
      case"7801":
      case"7802":
      case"7803":
      case"7804":
      case"7805":
      case"7806":
      case"7807":
      case"7808":
      case"7809":
      case"7811":
      case"7812":
      case"7813":
      case"7814":
      case"7815":
      case"7816":
      case"7817":
      case"7818":
      case"7820":
      case"7821":
      case"7831":
      case"7833":
      case"7834":
      case"7835":
      case"7836":
      case"7841":
      case"7842":
      case"7843":
      case"7844":
      case"7845":
      case"7846":
      case"7847":
      case"7848":
      case"7851":
      case"7855":
      case"7861":
      case"7862":
      case"7863":
      case"7865":
      case"7866":
      case"7867":
      case"7869":
      case"7871":
      case"7872":
      case"7873":
      case"7877":
      case"7878":
      case"7879":
        return 1;
    }
  }

  function applyInputMask() {

    function e() {
      var e = this.value.replace(/\D+/g, ""), t = e.substr(0, 2);
      return !!(4 != e.length || "77" != t && "78" != t || isCorrectPhonePrefix(e)) || (e = e.substr(
        0,
        1
      ) + e.substr(2), this.value = applyMask(e, getMask(e.length)), !1);
    }

    function t(e) {
      e.keyCode && (keyCode = e.keyCode), this.selectionStart < 3 && e.preventDefault();
      var t = "+7 (___) ___-__-__", n = 0, a = t.replace(/\D/g, ""), i = this.value.replace(/\D/g, ""),
        o = t.replace(/[_\d]/g, function (e) {
          return n < i.length ? i.charAt(n++) || a.charAt(n) : e;
        });
      -1 != (n = o.indexOf("_")) && (n < 5 && (n = 3), o = o.slice(0, n)), t = t.substr(0, this.value.length)
        .replace(/_+/g, function (e) {
          return "\\d{1," + e.length + "}";
        })
        .replace(
          /[+()]/g,
          "\\$&"
        ), (!(t = new RegExp("^" + t + "$")).test(this.value) || this.value.length < 5 || 47 < keyCode && keyCode < 58) && (this.value = o), "blur" == e.type && this.value.length < 5 && (this.value = "");
    }

    var n = document.getElementById(form_name + "_phone");
    is_mobile ? (n.addEventListener("input", t, !1), n.addEventListener("focus", t, !1), n.addEventListener(
      "blur",
      t,
      !1
    ), n.addEventListener("keydown", t, !1), addEvent(n, "focus", function (e) {
      "" === this.value && (this.value = getPrefix());
    }), addEvent(n, "keypress", t)) : phoneInputMask.call(
      n,
      getMasks(),
      e
    ), !is_mobile && default_settings.is_multiwidget && default_settings.multiwidget_application && (n = document.getElementById(
      application_form_name + "_phone"), phoneInputMask.call(
      n,
      getMasks(),
      e
    )), is_mobile || !default_settings.mini_version_enabled || (n = document.getElementById("ncw_compact_input")) && phoneInputMask.call(
      n,
      getMasks(),
      e
    );
  }

  function hideForm(e, t) {
    var n = t && t.withoutButton, t = document.querySelector("#newton_callback_phone");
    null == e && (e = !0), isFormOpened() && !successCall && e && reachGoal("NEWTON_CLOSE"), clearForm(), showPhoneButton(), is_mobile && (hideMissedCallMobile(), removeEvent(
      t,
      "click",
      hideForm
    )), n && (document.querySelector("#newton_callback_wrap").classList.contains("active")
      ? showPhoneButton(is_new_ios)
      : showPhoneButton(is_new_ios, !0)), is_mobile && (unhandleFormSize(), isNewIOS() && enableScalable());
    t = !1;
    e && isFormOpened() && (t = !0);
    n = document.getElementById("newton_callback_wrap");
    is_mobile && (n.classList.remove("active"), n.parentNode.classList.remove("active"), n.style.removeProperty(
      "transition"), n.style.removeProperty("bottom")), !is_mobile && default_settings.is_multiwidget && e && isFormOpened() && removeClass(
      n,
      "newton_wrap_slide"
    ), n.style.display = "none", e && hideBackground(), t && onClose();
  }

  function clearForm() {
    if (document.getElementById(form_name + "_phone").value = "", document.getElementById(form_name + "_phone").style.visibility = "visible", document.getElementById(
      "newton_callback_input_wrap")
      .style
      .setProperty(
        "display",
        "inline-block",
        "important"
      ), removeClass(document.getElementById(form_name + "_phone"), "error"), document.getElementById(
      "newton_callback_submit_button").style.visibility = "visible", document.getElementById(
      "newton_callback_submit_button").style.setProperty("display", "inline", "important"), document.getElementById(
      "newton_callback_missed_wrap").style.setProperty("display", "none", "important"), document.getElementById(
      "newton_callback_missed_result")
      .style
      .setProperty("display", "none", "important"), removeClass(
      document.getElementById("newton_callback_wrap"),
      "newton_missed"
    ), document.getElementById("newton_callback_form_text").style.display = "block", removeClass(
      document.getElementById("newton_callback_form_text"),
      "delay_success"
    ), document.getElementById("newton_callback_submit_result").innerHTML = "", clearInterval(countdown_interval_id), countdown_interval_id = null, document.getElementById(
      "newton_callback_counter").innerHTML = convertMsecs(default_settings.timer), default_settings.have_departments) {
      var e = !is_mobile && getSingleNonMobileDepartment();
      if (document.getElementById(form_name + "_department_id").value = e || "", !is_mobile && !e) {
        (i = document.getElementById("newton_callback_departments_link")).innerHTML = default_settings.department_link_text, (i = document.getElementById(
          "newton_callback_departments_link_dummy")).innerHTML = default_settings.department_link_text;
        for (var t = document.getElementById("newton_callback_departments_list")
          .getElementsByTagName("a"), n = 0; n < t.length; n++) removeClass(t[n], "newton_selected");
      }
    }
    removeClass(document.getElementById("newton_callback_counter"), "newton_show"), removeClass(document.getElementById(
      "newton_callback_counter"), "newton_hide"), removeClass(
      document.getElementById("newton_callback_wrap"),
      "newton_delay"
    ), removeClass(document.getElementById("newton_callback_wrap"), "delay_countdown"), is_mobile
      ? (removeClass(
        document.getElementById("newton_callback_submit_button"),
        "countdown"
      ), document.getElementById("newton_callback_submit_button").innerText = getCaption("form_submit_button"))
      : document.getElementById("newton_callback_active_delay_wrap").style.display = "none", document.getElementById(
      "newton_callback_missed_options").style.display = "none", laterCall = !1;
    var a, e = document.getElementById("newton_sms_notice");
    e && (e.style.display = "none"), clearTimeout(closeFormTimeout), closeFormTimeout = null, missed_block = !1, default_settings.is_multiwidget && (setMultiwidgetTabSelected(
      "newton_callback_tab_call"), (e = document.getElementById("newton_callback_tabs_item_delay")) && (e.style.display = "inline-block"), default_settings.multiwidget_application && (document.getElementById(
      "newton_callback_form").style.display = "block", (a = document.getElementById("newton_callback_application_form")) && (a.style.display = "none"), (a = document.getElementById(
      "newton_callback_application_success")) && (a.style.display = "none")), (a = document.getElementById("newton_chat")) && (document.getElementById(
      "newton_callback_form").style.display = "block", a.style.display = "none", deleteCookie("n_chat_opnd"))), (i = document.getElementById(
      "newton_callback_departments_link")) && removeClass(
      i,
      "newton_callback_departments_link_disabled"
    ), (default_settings.banner_bottom
      ? showBanner
      : hideBanner)(), showAgreement(), formFromDialog = successCall = callType = !1, "function" == typeof onClearForm && onClearForm(), enableSubmitButton(), enableApplicationSubmitButton();
    var i = document.getElementById("newton_callback_captcha");
    i && (i.style.setProperty(
      "display",
      "block",
      "important"
    ), i.style.visibility = "visible"), void 0 !== captchaId && grecaptcha && grecaptcha.getResponse(captchaId).length && grecaptcha.reset(
      captchaId);
  }

  function hideDialog(e) {
    isDialogOpened() && e && reachGoal("NEWTON_CLOSE"), null == e && (e = !0), is_mobile || showPhoneButton(), document.getElementById(
      "newton_callback_dialog_wrap").style.display = "none", e ? hideBackground() : formFromDialog = !0;
  }

  function hideBackground() {
    if (backgroundShowed) {
      if (!is_mobile) {
        try {
          var e = document.body.childNodes;
          for (i = 0; i < e.length; i++) e[i].nodeType == Node.ELEMENT_NODE && "newton_callback_wrap" != e[i].id && removeClass(
            e[i],
            "newton_blur"
          );
        } catch (e) {
          remoteErrorLog(e, "hideBackground1");
        }
        setTimeout(function () {
          try {
            var e = document.body.childNodes;
            for (i = 0; i < e.length; i++) e[i].nodeType == Node.ELEMENT_NODE && "newton_callback_wrap" != e[i].id && removeClass(
              e[i],
              "newton_blur-t"
            );
          } catch (e) {
            remoteErrorLog(e, "hideBackground2");
          }
        }, 100);
      }
      removeEvent(window, is_mobile ? "touchend" : "click", backgroundClickClose), backgroundShowed = !1;
    }
  }

  function hidePhoneButton(e) {
    var t = document.getElementById("newton_callback_phone");
    removeClass(t, "newton_animation"), addClass(
      t,
      "opened"
    ), is_mobile && (e && e.noAnimation, setTranslateForBtn()), isIE()
      ? addClass(t, "newton_ie_hide")
      : t.style.display = "none";
  }

  function showPhoneButton(e, t) {
    var n = document.getElementById("newton_callback_phone");
    addClass(n, "newton_animation"), removeClass(
      n,
      "opened"
    ), is_mobile && (setTranslateForBtn(), correctButtonSize()), null == e && (e = !1), (checkActive() || checkLaterCall()) && default_settings.show_phone_button && (e && !isAndroid && (n.style.visibility = "hidden"), isIE()
      ? removeClass(n, "newton_ie_hide")
      : n.style.display = "block");
  }

  function getTranslateValue() {
    return new Promise(function (n) {
      setTimeout(function () {
        var e = document.querySelector(".newton_callback_phone"), t = e ? e.getBoundingClientRect().height : 0,
          e = document.querySelector(".for-phone-icon.active") ? document.querySelector(".for-phone-icon.active")
            .getBoundingClientRect().height : 0, t = Math.round(0 === e ? e : e - t / 2 - 150);
        n(t);
      });
    });
  }

  function setTranslateForBtn() {
    var t = document.querySelector(".newton_callback_phone"), n = requestAnimationFrame(setTranslateForBtn);
    getTranslateValue().then(function (e) {
      e = -e, animationFrame < 50
        ? (t && (t.style.transform = "translate(0, " + e + "px)"), animationFrame += 1)
        : (cancelAnimationFrame(n), animationFrame = 0);
    });
  }

  function removeForm() {
    (form = document.getElementById("newton_callback_wrap")).parentNode.removeChild(form);
  }

  function getMetaContent(e) {
    for (var t = document.getElementsByTagName("meta"), n = 0; n < t.length; n++) if (t[n].getAttribute("property") == e) return t[n].getAttribute(
      "content");
  }

  function showForm(e) {
    var t = "dialog_text" in (e = e || {}) && e.dialog_text, n = "open_callback" in e && e.open_callback;
    if (hideMiniVersion(), is_mobile && !default_settings.enable_mobile_direct_call && (callType = "callback"), is_mobile && !callType) {
      if (checkActive() && (null == direct_phone_dynamic || 1 == direct_phone_dynamic)) return void showTypeSelect();
      callType = "callback";
    }
    var a = "departmentId" in e && e.departmentId, i = getSingleMobileCallbackDepartment();
    if (is_mobile && default_settings.have_departments && "callback" == callType && i && (a = i, (o = document.getElementById(
      form_name + "_department_id")) && (o.value = a)), is_mobile && !a && default_settings.have_departments) showDepartmentSelect(); else {
      if (is_mobile && "direct" == callType) {
        if (!checkActive({departmentId: a})) return;
        var o = getDirectPhone({departmentId: a});
        return direct_phone_dynamic ? newtonCallback.getCalltrackingNumber(function (e) {
          e ? window.location = "tel:" + e : direct_phone_dynamic = !1;
        }) : window.location = "tel:" + o, void (callType = !1);
      }
      !is_mobile && a && default_settings.have_departments && (getSingleNonMobileDepartment() ? document.getElementById(
        form_name + "_department_id").value = a : (l = getDepartmentLink(a)) && setDepartment(l));
      var l, c, s, r, d = document.getElementById("newton_callback_wrap"), _ = d.parentNode;
      isOpened() || (l = getParam("dcn"), document.getElementById(form_name + "_landing_page_referrer").value = getLandingPageReferrer(), document.getElementById(
        form_name + "_landing_page_url").value = getLandingPageUrl(), document.getElementById(form_name + "_fingerprint").value = fingerprint, "undefined" != typeof newton_local_cookie && (document.getElementById(
        form_name + "_local_cookie").value = newton_local_cookie), "undefined" != typeof newton_auction_lot_id_internal && (document.getElementById(
        form_name + "_auction_lot_id").value = newton_auction_lot_id_internal, document.getElementById(form_name + "_auction_is_related_page").value = auction_is_related_page
        ? 1
        : 0), document.getElementById(form_name + "_dcn").value = "dcn" in e ? e.dcn : l || "", document.getElementById(
        form_name + "_referrer_keywords").value = getKeywords(e), document.getElementById(form_name + "_metrika_client_id").value = getMetrikaClientId(), document.getElementById(
        form_name + "_ga_client_id").value = getGAClientId(), !is_mobile && default_settings.is_multiwidget && default_settings.multiwidget_application && (document.getElementById(
        application_form_name + "_landing_page_referrer").value = getLandingPageReferrer(), document.getElementById(
        application_form_name + "_landing_page_url").value = getLandingPageUrl(), document.getElementById(
        application_form_name + "_fingerprint").value = fingerprint, "undefined" != typeof newton_local_cookie && (document.getElementById(
        application_form_name + "_local_cookie").value = newton_local_cookie), document.getElementById(
        application_form_name + "_dcn").value = "dcn" in e ? e.dcn : l || "", document.getElementById(
        application_form_name + "_referrer_keywords").value = getKeywords(e), document.getElementById(
        application_form_name + "_metrika_client_id").value = getMetrikaClientId(), document.getElementById(
        application_form_name + "_ga_client_id").value = getGAClientId()), getSettings(), checkActive({departmentId: a})
        ? (e.withoutButton
          ? hidePhoneButton({noAnimation: !0})
          : hidePhoneButton(), is_mobile && (c = document.querySelector("#newton_callback_phone"), addEvent(
          c,
          "click",
          hideForm
        )), removeClass(
          document.getElementById("newton_callback_form_text"),
          "newton_callback_form_text_delay"
        ), document.getElementById("newton_callback_counter").innerHTML = convertMsecs(default_settings.timer), is_mobile || (document.getElementById(
          "newton_callback_active_delay_wrap").style.display = "block"), t ? document.getElementById(
          "newton_callback_form_text").innerHTML = t : is_mobile ? (handleFormSize(), document.getElementById(
          "newton_callback_form_text").innerHTML = default_settings.form_text_mobile) : document.getElementById(
          "newton_callback_form_text").innerHTML = default_settings.auction_lot_usp || default_settings.form_text, setShowed(), customSelects(
          document.getElementById("newton_callback_form_text")), d.style.display = "block", is_mobile
          ? (isNewIOS() && disableScalable(), setTimeout(function () {
            _.classList.add("active"), d.classList.add("active"), addClass(d, "newton_wrap_slide");
          }, 1), setTranslateForBtn())
          : setTimeout(function () {
            addClass(d, "newton_wrap_slide");
          }, 50), t || showBackground(), "function" == typeof n && n())
        : checkLaterCall()
          ? (hidePhoneButton(), addClass(
            document.getElementById("newton_callback_form_text"),
            "newton_callback_form_text_delay"
          ), is_mobile
            ? (handleFormSize(), document.getElementById("newton_callback_form_text").innerHTML = getDelayTextMobile({departmentId: a}))
            : laterCall && t
              ? document.getElementById("newton_callback_form_text").innerHTML = t
              : ((c = document.getElementById("newton_callback_tabs_item_delay")) && (c.style.display = "none"), document.getElementById(
                "newton_callback_form_text").innerHTML = renderAuctionLotUsp() + getDelayText({departmentId: a})), handleFormSelect(), customSelects(
            document.getElementById("newton_callback_form_text")), d.style.display = "block", is_mobile && (drawCallLaterDateHourSelectMobile(
            a), s = document.querySelector("#newton_callback_phone"), addEvent(s, "click", r = function (e) {
            d.classList.contains("active") && (closeCallLaterMobile(d), destroyCallLaterDateSelectMobile(), showPhoneButton()), removeEvent(
              s,
              "click",
              r
            );
          }), isNewIOS() && disableScalable(), setTimeout(function () {
            _.classList.add("active"), d.classList.add("active");
          }, 110)), setTimeout(function () {
            addClass(d, "newton_wrap_slide");
          }, 50), addClass(d, "newton_delay"), t || showBackground(), "function" == typeof n && n())
          : t && hideBackground());
    }
  }

  function disableScalable() {
    var e;
    document.querySelector("head meta[ name=viewport]") || ((e = document.createElement("meta")).setAttribute(
      "name",
      "viewport"
    ), e.setAttribute("for", "newton"), e.setAttribute("content", "user-scalable=0"), document.getElementsByTagName(
      "head")[0].appendChild(e));
  }

  function enableScalable() {
    var e = document.querySelector("head meta[for=newton]");
    e && e.remove();
  }

  function showDialog() {
    !checkShowed() || default_settings.dialog_enabled && !default_settings.is_multiwidget
      ? !isOpened() && checkShowed() && (getSettings(), checkActive() && (hidePhoneButton(), setShowed(), document.getElementById(
      "newton_callback_dialog_wrap").style.display = "block", showBackground(), reachGoal("NEWTON_DIALOG")))
      : showForm({
        open_callback: function () {
          reachGoal("NEWTON_DIALOG");
        }
      });
  }

  function showBackground() {
    if (!is_mobile) try {
      var e = document.body.childNodes;
      for (i = 0; i < e.length; i++) e[i].nodeType == Node.ELEMENT_NODE && "newton_callback_wrap" != e[i].id && "newton_callback_dialog_wrap" != e[i].id && "newton_callback_phone" != e[i].id && (addClass(
        e[i],
        "newton_blur"
      ), addClass(e[i], "newton_blur-t"));
    } catch (e) {
      remoteErrorLog(e, "showBackground");
    }
    addEvent(window, is_mobile ? "touchend" : "click", backgroundClickClose), backgroundShowed = !0;
  }

  function backgroundClickClose(e) {
    var t = document.getElementById("newton_callback_phone"), n = document.getElementById("newton_callback_wrap"),
      a = document.getElementById("newton_callback_dialog_wrap"),
      i = document.getElementById("newton_callback_department_select"),
      o = document.getElementById("newton_callback_type_select"), l = document.getElementById("ncw_compact");
    n && isDescendant(n, e.target) || a && isDescendant(a, e.target) || t && isDescendant(
      t,
      e.target
    ) || i && isDescendant(i, e.target) || l && isDescendant(l, e.target) || o && isDescendant(
      o,
      e.target
    ) || (is_mobile ? (destroyCallLaterDateSelectMobile(), removeEvent(t, "click", hideForm), removeEvent(
      t,
      "click",
      showPhoneButton
    ), showPhoneButton(), hideForm(), e.preventDefault()) : (hideDialog(), hideForm()));
  }

  function departmentSelectClickClose(e) {
    var t = document.getElementById("newton_callback_phone"),
      n = document.getElementById("newton_callback_department_select");
    t && isDescendant(t, e.target) || isDescendant(
      n,
      e.target
    ) || (hideDepartmentSelect(), callType = !1, e.preventDefault());
  }

  function typeSelectClickClose(e) {
    var t = document.getElementById("newton_callback_phone"),
      n = document.querySelector("#newton_callback_type_select ul");
    t && isDescendant(t, e.target) || isDescendant(
      n,
      e.target
    ) || (hideTypeSelect(), callType = !1, e.preventDefault());
  }

  function setShowed() {
    var e, t;
    "undefined" == typeof newton_callback_no_cookie && (e = new Date, default_settings.show_once_day
      ? e.setDate(e.getDate() + 1)
      : (t = e.getTime(), t += 36e5, e.setTime(t)), setCookie(NEWTON_CALLBACK.SHOWED, "1", {expires: e.toUTCString()}));
  }

  function checkShowed() {
    return !getCookie(NEWTON_CALLBACK.SHOWED);
  }

  function setInitTime(e) {
    var t, n = new Date;
    default_settings.show_once_day ? n.setDate(n.getDate() + 1) : (t = n.getTime(), t += 36e5, n.setTime(t)), setCookie(
      NEWTON_CALLBACK.INITIAL_TIME,
      e,
      {expires: n.toUTCString()}
    );
  }

  function getInitTime() {
    var e = getCookie(NEWTON_CALLBACK.INITIAL_TIME);
    return e || null;
  }

  function resetInitTime() {
    "undefined" != typeof newton_callback_no_cookie && deleteCookie(NEWTON_CALLBACK.INITIAL_TIME);
  }

  function setForget() {
    var e;
    "undefined" == typeof newton_callback_no_cookie && ((e = new Date).setDate(e.getDate() + 365), setCookie(
      NEWTON_CALLBACK.FORGET,
      "1",
      {expires: e.toUTCString()}
    ));
  }

  function checkForget() {
    return getCookie(NEWTON_CALLBACK.FORGET);
  }

  function checkActive(e) {
    var e = "departmentId" in (e = e || {}) && e.departmentId, t = 0;
    if (e) t = checkActiveDepartment(e); else for (var n in default_settings.departments) checkShowDepartment(n) && (t = t || checkActiveDepartment(
      n));
    return t;
  }

  function checkActiveDepartment(e) {
    return 1 == default_settings.is_active && 0 == default_settings.departments[e].is_holiday && default_settings.current_time > default_settings.departments[e].time_from && default_settings.current_time < default_settings.departments[e].time_to && !laterCall;
  }

  function checkLaterCall() {
    return 1 == default_settings.is_active && (!default_settings.disable_delayed_calls || laterCall);
  }

  function isOpened() {
    return "block" == document.getElementById("newton_callback_dialog_wrap").style.display || "block" == document.getElementById(
      "newton_callback_wrap").style.display;
  }

  function isDialogOpened() {
    return "block" == document.getElementById("newton_callback_dialog_wrap").style.display;
  }

  function isFormOpened() {
    return "block" == document.getElementById("newton_callback_wrap").style.display;
  }

  function checkShowDepartment(e) {
    return is_mobile || 0 == default_settings.departments[e].only_on_mobile;
  }

  function countdown() {
    var t = !1, e = document.getElementById(form_name + "_department_id"),
      n = document.querySelector("#newton_callback_submit_button"), a = n.innerHTML;
    e && e.value && (t = e.value);
    var i = !1;
    t && default_settings.have_departments && !checkActiveDepartment(t) || !checkActive() && checkLaterCall()
      ? (timer_value = getDelayTimer(), i = !0)
      : timer_value = default_settings.timer, disableSelects();
    e = document.getElementById("newton_callback_departments_link");
    e && addClass(
      e,
      "newton_callback_departments_link_disabled"
    ), "function" == typeof onCountdownStart && onCountdownStart(), is_mobile && disableSubmitButton(), countdown_before = new Date, countdown_interval_id = setInterval(
      function () {
        var e;
        countdown_now = new Date, elapsedTime = countdown_now.getTime() - countdown_before.getTime(), (timer_msecs = timer_value - elapsedTime) <= 0
          ? (clearInterval(countdown_interval_id), countdown_interval_id = null, is_mobile
            ? (removeClass(
              n,
              "countdown"
            ), n.innerHTML = a)
            : document.getElementById("newton_callback_counter").innerHTML = "00:00.00", "function" == typeof onCountdownEnd && onCountdownEnd(), !is_mobile && checkActive() && (!default_settings.have_departments || t && checkActiveDepartment(
            t)) ? (addClass(document.getElementById("newton_callback_wrap"), "newton_missed"), document.getElementById(
            "newton_callback_input_wrap").style.setProperty("display", "none", "important"), document.getElementById(
            "newton_callback_submit_button").style.setProperty("display", "none", "important"), document.getElementById(
            "newton_callback_missed_wrap")
            .style
            .setProperty(
              "display",
              "inline-block",
              "important"
            ), (e = document.getElementById("newton_callback_captcha")) && e.style.setProperty(
            "display",
            "none",
            "important"
          ), missed_block = !0) : is_mobile ? showMissedCallMobile() : closeFormTimeout = setTimeout(function (e) {
            hideForm();
          }, 3e3))
          : is_mobile ? (addClass(n, "countdown"), n.innerHTML = convertMsecs(timer_msecs)) : document.getElementById(
            "newton_callback_counter").innerHTML = convertMsecs(timer_msecs, i);
      },
      countdown_interval
    );
  }

  function disableSelects() {
    var e = document.getElementById("newton_callback_form_text");
    if (e) for (var t = e.getElementsByTagName("select"), n = 0; n < t.length; n++) t[n].disabled = "disabled";
  }

  function drawForm() {
    var e = "";
    is_mobile && (e += renderAuctionLotName(), e += renderAuctionLotUsp()),
    isVkVerion() && (e += '<div id="circle-bg"></div>'),
    !is_mobile && default_settings.is_multiwidget && (
        e += '<div class="newton_callback_wrap_header">' + default_settings.form_header + "</div>"
    ),
    is_mobile || (e += '<a href="javascript:void(0);" id="newton_callback_close" class="newton_callback_close">x</a>'),
      e += '<div id="newton_callback_company_logo" class="newton_callback_company_logo"></div>',
    !is_mobile && default_settings.is_multiwidget && (
      e += '<div class="newton_callback_tabs" id="newton_callback_tabs">',
        e += '<ul class="newton_callback_tabs_list">',
      default_settings.callback_enabled && (
        e += '<li class="newton_callback_tabs_item">',
          e += '<a id="newton_callback_tab_call" class="newton_callback_tab_call newton_active" href="javascript: void(0);">',
          e += '<div class="newton_callback_icon"></div>',
          e += "<span>Обратный<br>звонок</span>",
          e += "</a>",
          e += "</li>",
          e += '<li class="newton_callback_tabs_item" id="newton_callback_tabs_item_delay">',
          e += '<a id="newton_callback_tab_delay" class="newton_callback_tab_delay" href="javascript: void(0);">',
          e += '<div class="newton_callback_icon"></div>',
          e += "<span>Отложенный<br>звонок</span>",
          e += "</a>",
          e += "</li>"
      ),
      default_settings.multiwidget_application && (
        e += '<li class="newton_callback_tabs_item">',
          e += '<a id="newton_callback_tab_application" class="newton_callback_tab_application" href="javascript: void(0);">',
          e += '<div class="newton_callback_icon"></div>',
          e += "<span>Оставить<br>заявку</span>",
          e += "</a>",
          e += "</li>"
      ),
      default_settings.multiwidget_consultant && (
        e += '<li class="newton_callback_tabs_item">',
          e += '<a id="newton_callback_tab_ask" class="newton_callback_tab_ask" href="javascript:void(window.open(\'' + default_settings.multiwidget_consultant_link + "','','width=590,height=760,left=0,top=0,resizable=yes,menubar=no,location=no,status=yes,scrollbars=yes'))\">",
          e += '<div class="newton_callback_icon"></div>',
          e += "<span>Онлайн<br>консультант</span>",
          e += "</a>",
          e += "</li>"
      ),
      default_settings.chat_enabled && checkActive() && (
        e += '<li class="newton_callback_tabs_item">',
          e += '<a id="newton_callback_tab_chat" class="newton_callback_tab_chat" href="javascript: void(0);">',
          e += '<div class="newton_callback_icon"></div>',
          e += "<span>Чат</span>",
          e += "</a>",
          e += "</li>"
      ),
      default_settings.banner_enabled && !default_settings.banner_bottom && (
        e += '<li class="newton_callback_tabs_item">',
          e += '<a id="newton_callback_tab_banner" class="newton_callback_tab_banner" href="javascript: void(0);">',
          e += '<div class="newton_callback_icon"></div>',
          e += "<span>Акции</span>",
          e += "</a>",
          e += "</li>"
      ),
        e += "</ul>",
        e += "</div>"
    );
    e += '<div id="newton_callback_content" class="newton_callback_content">', e += '<form autocomplete="off" id="newton_callback_form" class="newton_callback_form" action="' + form_action + '" method="POST" name="' + form_name + '">';
    var t = default_settings.form_text;
    if (is_mobile && (t = default_settings.form_text_mobile), e += '<div id="newton_callback_form_text" class="newton_callback_form_text">' + t + "</div>", !is_mobile && default_settings.have_departments) if (l = getSingleNonMobileDepartment()) e += '<input type="hidden" name="' + form_name + '[department_id]" id="' + form_name + '_department_id" value="' + l + '" />'; else {
      for (var n in e += '<div class="newton_callback_departments_block">', e += '<div class="newton_callback_departments_wrap">', e += '<div class="newton_callback_departments_link_wrap">', e += '<a href="javascript:void(0);" class="newton_callback_departments_link" id="newton_callback_departments_link_dummy">' + default_settings.department_link_text + "</a>", e += "</div>", e += '<div id="newton_callback_departments" class="newton_callback_departments">', e += '<div class="newton_callback_departments_link_wrap">', e += '<a href="javascript:void(0);" class="newton_callback_departments_link" id="newton_callback_departments_link">' + default_settings.department_link_text + "</a>", e += "</div>", e += '<input type="hidden" name="' + form_name + '[department_id]" id="' + form_name + '_department_id" />', e += '<ul id="newton_callback_departments_list" class="newton_callback_departments_list">', default_settings.departments) !checkShowDepartment(
        n) || !checkActiveDepartment(n) && default_settings.disable_delayed_calls || (e += "<li>", e += '<a href="javascript:void(0);" rel="' + n + '">' + default_settings.departments[n].header + "</a>", e += "</li>");
      e += "</ul>", e += "</div>", e += "</div>", e += "</div>";
    } else is_mobile && default_settings.have_departments && (e += '<input type="hidden" name="' + form_name + '[department_id]" id="' + form_name + '_department_id" />');
    var a = '<label id="newton_sms_notice" class="newton_sms_notice" style="display:none"><input type="checkbox" id="newton_sms_notice_input" name="' + form_name + '[sms_notice]" value="1" /><span></span><label for="newton_sms_notice_input">Отправить мне sms-уведомление за 10 минут';
    a += " до звонка</label></label>";
    var i = '<div id="newton_callback_input_wrap" class="newton_callback_input_wrap">';
    i += '<input type="' + (is_mobile
      ? "tel"
      : "text") + '" placeholder="' + getCaption("form_input_placeholder") + '" name="' + form_name + '[phone]" id="' + phone_input_id + '" />', i += '<div id="newton_callback_phone_error" class="newton_callback_phone_error">Введите корректный телефон</div><div id="newton_callback_submit_result" class="newton_callback_submit_result"></div>', i += "</div>", !is_mobile && default_settings.is_multiwidget && (i += a), i += getFormHiddenFields(
      form_name), i += getCaptcha(), i += '<div class="submit-btn-wrapper">', i += '<button type="submit" id="newton_callback_submit_button">' + getCaption(
      "form_submit_button") + "</button>", i += "</div>", i += '<div id="newton_callback_toggle_a_wrap"><a id="newton_callback_toggle_a" data-type="delay" href="javascript:void(0);"><span>Выбрать удобное время звонка</span></a></div>', i += '<div id="newton_callback_missed_wrap" class="newton_callback_missed_wrap"><a id="newton_callback_missed" class="newton_callback_missed" href="javascript:void(0);">' + getCaption(
      "form_missed_question") + "</a></div>", i += '<div id="newton_callback_missed_options" class="newton_callback_missed_options">', i += '<div class="newton_callback_missed_option newton_retry">', i += '<div class="newton_link_wrap">', i += '<a href="javascript:void(0)" id="newton_callback_missed_retry">Заказать звонок ещё раз</a>', i += "</div>", i += "</div>", i += '<div class="newton_callback_missed_option newton_active_delay">', i += '<div class="newton_link_wrap">', i += '<a href="javascript:void(0)" id="newton_callback_missed_active_delay">Выбрать удобное время</a>', i += "</div>", i += "</div>", i += '<div class="newton_callback_missed_option newton_send">', i += '<div class="newton_link_wrap">', i += '<a href="javascript:void(0)" id="newton_callback_missed_send">Отправить email-жалобу</a>', i += "</div>", i += "</div>", i += "</div>", i += '<div id="newton_callback_missed_result" class="newton_callback_missed_result">' + getCaption(
      "form_missed_result") + "</div>";
    var o,
      t = '<div id="newton_callback_counter" class="newton_callback_counter">' + convertMsecs(default_settings.timer) + "</div>";
    if (is_mobile
      ? (e += t, e += i)
      : (e += i, e += t), is_mobile || default_settings.is_multiwidget || (e += a), is_mobile || (e += '<div class="newton_callback_active_delay_wrap" id="newton_callback_active_delay_wrap" style="display: none;">', e += '<div class="newton_callback_active_delay" id="newton_callback_active_delay">', e += '<a href="javascript:void(0);" id="newton_callback_active_delay_link">Выбрать удобное время для звонка</a>', e += "</div>", e += "</div>"), e += "</form>", !is_mobile && default_settings.is_multiwidget && default_settings.multiwidget_application) {
      if (e += '<form autocomplete="off" id="newton_callback_application_form" class="newton_callback_form" action="' + application_form_action + '" method="POST" name="' + application_form_name + '" style="display: none;">', default_settings.multiwidget_application_header && (e += '<div class="newton_callback_form_text">', e += default_settings.multiwidget_application_header, e += "</div>"), default_settings.have_departments) if (l = getSingleNonMobileDepartment()) e += '<input type="hidden" name="' + application_form_name + '[department_id]" id="' + application_form_name + '_department_id" value="' + l + '" />'; else {
        for (var n in e += '<div class="newton_callback_departments_block">', e += '<div class="newton_callback_departments_wrap">', e += '<div class="newton_callback_departments_link_wrap">', e += '<a href="javascript:void(0);" class="newton_callback_departments_link" id="newton_callback_application_departments_link_dummy">' + default_settings.department_link_text + "</a>", e += "</div>", e += '<div id="newton_callback_application_departments" class="newton_callback_departments">', e += '<div class="newton_callback_departments_link_wrap">', e += '<a href="javascript:void(0);" class="newton_callback_departments_link" id="newton_callback_application_departments_link">' + default_settings.department_link_text + "</a>", e += "</div>", e += '<input type="hidden" name="' + application_form_name + '[department_id]" id="' + application_form_name + '_department_id" />', e += '<ul id="newton_callback_application_departments_list" class="newton_callback_departments_list">', default_settings.departments) checkShowDepartment(
          n) && (e += "<li>", e += '<a href="javascript:void(0);" rel="' + n + '">' + default_settings.departments[n].header + "</a>", e += "</li>");
        e += "</ul>", e += "</div>", e += "</div>", e += "</div>";
      }
      e += '<div class="newton_callback_input_wrap">', e += '<input type="text" placeholder="' + getCaption(
        "form_input_placeholder") + '" name="' + application_form_name + '[phone]" id="' + application_phone_input_id + '" />', e += '<div id="newton_callback_application_submit_result" class="newton_callback_submit_result"></div>', e += "</div>", e += '<div class="newton_callback_input_wrap">', e += '<input id="' + application_form_name + '_name" type="text" placeholder="Представьтесь, пожалуйста" name="' + application_form_name + '[name]" />', e += '<div id="' + application_form_name + '_name_em" class="newton_callback_submit_result"></div>', e += "</div>", e += '<div class="newton_callback_input_wrap">', e += '<input id="' + application_form_name + '_email" type="text" placeholder="Email" name="' + application_form_name + '[email]" />', e += '<div id="' + application_form_name + '_email_em" class="newton_callback_submit_result"></div>', e += "</div>", e += '<div class="newton_callback_textarea_wrapper">', e += '<textarea id="' + application_form_name + '_comment" type="text" placeholder="Комментарий" name="' + application_form_name + '[comment]"></textarea>', e += '<div id="' + application_form_name + '_comment_em" class="newton_callback_submit_result"></div>', e += "</div>", e += getFormHiddenFields(
        application_form_name), e += '<div class="submit-btn-wrapper">', e += '<button type="submit" id="newton_callback_application_submit_button">Отправить</button>', e += "</div>", e += "</form>", e += '<div id="newton_callback_application_success" class="newton_callback_application_success">', e += "Ваша заявка<br />принята!", e += "</div>";
    }
    !is_mobile && default_settings.is_multiwidget && default_settings.chat_enabled && checkActive() && (e += '<iframe id="newton_chat" style="display: none;"></iframe>'), is_mobile || default_settings.is_multiwidget || !default_settings.manager_photo_enabled || (e += '<div class="newton_callback_model_name">' + default_settings.manager_photo_name + "</div>"), null == default_settings.additional_form_html || isVkVerion() || (e += default_settings.additional_form_html), e += "</div>", !is_mobile && default_settings.is_multiwidget && default_settings.banner_enabled && (default_settings.banner_date && (o = setInterval(
      function () {
        var e = getTimeRemaining(default_settings.banner_date, !0),
          t = document.getElementById("newton_callback_banner_timecounter");
        t.innerHTML = '<div class="newton_timecounter__days newton_time-unit" title="дней">' + e.days + '</div><div class="newton_timecounter-delimiter">:</div><div class="newton_imecounter__hours newton_time-unit" title="часов">' + e.hours + '</div><div class="newton_timecounter-delimiter">:</div><div class="newton_timecounter__min newton_time-unit" title="минут">' + e.minutes + '</div><div class="newton_timecounter-delimiter">:</div><div class="newton_timecounter__sec newton_time-unit" title="секунд">' + e.seconds + "</div>", e.total <= 0 && (clearInterval(
          o), t.innerHTML = "Акция завершена");
      },
      1e3
    )), e += '<div id="newton_callback_banner" class="newton_callback_banner" ' + (default_settings.banner_bottom
      ? ""
      : 'style="display: none;"') + ">", e += '<a class="newton_callback_banner-title" href="' + default_settings.banner_url + '" target="_blank"><span>' + default_settings.banner_name + "</span></a>", e += '<div class="newton_callback_banner_descr">' + default_settings.banner_descr + "</div>", e += '<a class="newton_callback_banner-img" href="' + default_settings.banner_url + '" target="_blank"><div class="newton_callback_banner_image" style="background-image: url(' + default_settings.banner_image + ') !important"></div></a>', e += '<div id="newton_callback_banner_timecounter" class="newton_callback_banner_timecounter"></div>', e += "</div>"), is_mobile || default_settings.is_multiwidget || (e += '<div id="newton_bottom_wrap" class="newton_bottom_wrap ' + (default_settings.dialog_enabled || checkForget() || !checkActive()
      ? "newton_forget"
      : "") + '">', e += '<div class="newton_callback_wrap_forget_wrap ' + ("undefined" != typeof newton_auction_lot_id_internal
      ? "newton_callback_wrap_forget_wrap_center"
      : "") + '">', e += '<a class="newton_callback_wrap_forget" id="newton_callback_wrap_forget" href="javascript:void(0);">' + getCaption(
      "form_button_forget") + "</a>", e += "</div>");
    is_mobile || default_settings.is_multiwidget || (e += "</div>", e += "</div>");
    e += '<label id="newton_agreement" class="newton_agreement"><input type="checkbox" id="newton_agreement_input" checked="checked" /><span></span><label for="newton_agreement_input">Я согласен <a href="https://spbrealty.ru/page/zaschita-personalnyh-dannyh" target="_blank">на обработку персональных данных</a></label></label>';
    t = document.createElement("div");
    t.setAttribute("id", "newton_callback_wrap");
    var l, a = "newton_callback_wrap";
    (is_mobile || isVkVerion() && isMobile()) && (a += " mobile for-phone-icon "), is_mobile || default_settings.is_multiwidget || !default_settings.manager_photo_enabled || (a += " newton_callback_with_manager"), a += " newton_callback_wrap_" + newton_callback_id_internal, t.setAttribute(
      "class",
      a
    ), t.style.display = "none", t.innerHTML = e, is_mobile
      ? ((l = document.createElement("div")).setAttribute(
        "id",
        "newton_callback_wrap_mobile"
      ), l.appendChild(t), i = "newton_callback_wrap_mobile", is_new_ios && ((a = document.createElement("div")).setAttribute(
        "id",
        "newton_callback_wrap_mobile_bound"
      ), a.setAttribute(
        "class",
        "newton_callback_wrap_mobile_bound"
      ), document.body.appendChild(a), i += " newton_afix"), l.setAttribute("class", i), document.body.appendChild(l))
      : document.body.appendChild(t);
  }

  function getCaptcha() {
    if (default_settings.recaptcha_site_key && default_settings.is_multiwidget) {
      var e = document.createElement("script");
      return e.setAttribute(
        "src",
        "https://www.google.com/recaptcha/api.js?onload=newtonLoadCaptcha&render=explicit"
      ), document.getElementsByTagName("head")[0].appendChild(e), '<input class="newton_callback_captcha_input" type="hidden" name="' + form_name + '[captcha]" id="' + form_name + '_captcha" /><div class="newton_callback_captcha" id="newton_callback_captcha" data-sitekey="' + default_settings.recaptcha_site_key + '"></div>';
    }
    return "";
  }

  function renderCaptcha() {
    default_settings.recaptcha_site_key && (captchaId = grecaptcha.render(
      "newton_callback_captcha",
      {
        sitekey: default_settings.recaptcha_site_key, size: "normal", callback: function (e) {
          var t = document.getElementById(form_name + "_captcha");
          t && (t.value = e);
        }
      }
    ));
  }

  function renderAuctionLotName() {
    return auction_lot_name ? '<div class="newton_callback_building_name ' + (is_mobile
      ? "mobile"
      : "") + '">' + auction_lot_name + "</div>" : "";
  }

  function renderAuctionLotUsp() {
    return default_settings.auction_lot_usp ? '<div class="newton_callback_main_title ' + (is_mobile
      ? "mobile"
      : "") + '">' + default_settings.auction_lot_usp + "</div>" : "";
  }

  function drawMiniVersion() {
    if (!is_mobile && default_settings.mini_version_enabled && (checkActive() || !default_settings.disable_delayed_calls) && default_settings.show_phone_button) {
      var e, t = checkActive(), n = "";
      if (n += '<div id="ncw_compact_panel">', n += '<div class="ncw_compact_tabs">', t && (n += '<div class="ncw_compact_tab deferred-call" id="ncw_compact_tab_call_switch" rel="Отложенный звонок"></div>'), default_settings.is_multiwidget && (default_settings.multiwidget_application && (n += '<div class="ncw_compact_tab submit-request" id="ncw_compact_tab_application" rel="Оставить заявку"></div>'), default_settings.chat_enabled && checkActive() && (n += '<div class="ncw_compact_tab online-chat" id="ncw_compact_tab_chat" rel="Онлайн чат"></div>'), default_settings.multiwidget_consultant && (n += '<div class="ncw_compact_tab online-consult" id="ncw_compact_tab_consultant" rel="Онлайн консультант"></div>')), n += '<div class="ncw_compact_tabs_tip" id="ncw_compact_tabs_tip"></div>', n += "</div>", n += '<form class="ncw_compact_form" id="ncw_compact_form" autocomplete="off">', n += getFormHiddenFields(
        form_name), default_settings.have_departments) {
        var a = getSingleNonMobileDepartment();
        if (a) n += '<input type="hidden" name="' + form_name + '[department_id]" id="' + form_name + '_department_id_mini" value="' + (e = a) + '" />'; else {
          n += '<div class="ncw_compact_select" id="ncw_compact_select_department">';
          var i = -1;
          for (o in default_settings.departments) if (checkShowDepartment(o) && (checkActiveDepartment(o) || !default_settings.disable_delayed_calls)) {
            n += '<input type="hidden" name="' + form_name + '[department_id]" id="' + form_name + '_department_id_mini" value="' + (i = o) + '" />', n += '<a href="javascript:void(0);" class="ncw_compact_select_current-value">' + default_settings.departments[o].header + "</a>";
            break;
          }
          for (o in n += '<div class="ncw_compact_select_values-list">', default_settings.departments) !checkShowDepartment(
            o) || !checkActiveDepartment(o) && default_settings.disable_delayed_calls || (n += '<a href="javascript:void(0);" rel="' + o + '" class="ncw_compact_select_value" ' + (o == i
            ? 'style="display: none !important"'
            : "") + ">" + default_settings.departments[o].header + "</a>");
          n += "</div>", n += "</div>", e = i;
        }
      } else for (var o in default_settings.departments) {
        e = o;
        break;
      }
      n += '<div class="ncw_compact_extended">', n += '<div class="ncw_compact_select" id="ncw_compact_select_day">';
      a = getMiniVersionDateSelect(e, t);
      n += a.content, n += "</div>", n += '<div class="ncw_compact_select" id="ncw_compact_select_time">', n += getMiniVersionHourSelect(
        e,
        a.selectedDate,
        t
      ), n += "</div>", n += "</div>", n += '<div class="ncw_compact_panel_default">', n += '<input type="text" class="ncw_compact_input" id="ncw_compact_input" name="' + form_name + '[phone]" placeholder="+7 (___) ___-__-__">', n += '<button class="ncw_compact_button" id="ncw_compact_button"><span>Жду звонка!</span></button>', n += '<button class="ncw_compact_counter" id="ncw_compact_counter" disabled="disabled"></button>', n += "</div>", n += "</form>", n += '<div id="ncw_compact_hide"></div>', n += '<div class="ncw_compact_message_container">', n += '<div class="ncw_compact_message" id="ncw_compact_message_info">', n += '<div class="ncw_compact_message_text">' + (t
        ? getMiniVersionDirectCallText()
        : "Рабочий день закончился, укажите удобную дату и время звонка") + "</div>", n += "</div>", n += '<div class="ncw_compact_message ncw_compact_message_error" id="ncw_compact_message_error">', n += "</div>", n += "</div>", n += "</div>";
      a = document.createElement("div");
      a.setAttribute("id", "ncw_compact"), t || a.setAttribute(
        "class",
        "ncw_extended_compact_panel"
      ), a.innerHTML = n, a.style.setProperty("display", "none", "important"), document.body.appendChild(a), setTimeout(
        function () {
          document.getElementById("ncw_compact").style.display = "";
        },
        300
      ), updateMiniVersionCountdownValue();
    }
  }

  function getMiniVersionDateSelect(e, t) {
    t = t || !1;
    var n = "", a = document.createElement("div");
    a.innerHTML = default_settings.departments[e].delay_data.select;
    for (var e = a.getElementsByTagName("select")[0].name, i = [], o = a.getElementsByTagName("option"), l = !1, c = 0; c < o.length; c++) {
      var s = o[c].value, r = o[c].innerHTML;
      i[s] = r, l = l || s;
    }
    for (s in n += '<a href="javascript:void(0);" class="ncw_compact_select_current-value">' + i[l] + "</a>", n += '<input type="hidden" name="' + e + '" id="' + form_name + '_date_mini" value="' + l + '" ' + (t
      ? 'disabled="disabled"'
      : "") + " />", n += '<div class="ncw_compact_select_values-list">', i) n += '<a href="javascript: void(0);" class="ncw_compact_select_value" rel="' + s + '" ' + (s == l
      ? 'style="display: none !important;"'
      : "") + ">" + i[s] + "</a>";
    return {content: n += "</div>", selectedDate: l};
  }

  function getMiniVersionHourSelect(e, t, n) {
    n = n || !1;
    var a = "", i = document.createElement("div");
    i.innerHTML = default_settings.departments[e].delay_data.hours[t];
    for (var o, l, t = i.getElementsByTagName("select")[0].name, c = [], s = i.getElementsByTagName("option"), r = !1, d = 0; d < s.length; d++) s[d].disabled || (l = s[d].value, o = s[d].innerHTML, c[l] = o, r = r || l);
    for (l in a += '<a href="javascript:void(0);" class="ncw_compact_select_current-value">в ' + c[r] + ":00</a>", a += '<input type="hidden" name="' + t + '" id="' + form_name + '_hour_mini" value="' + r + '" ' + (n
      ? 'disabled="disabled"'
      : "") + " />", a += '<div class="ncw_compact_select_values-list">', c) a += '<a href="javascript: void(0);" class="ncw_compact_select_value" rel="' + l + '" ' + (l == r
      ? 'style="display: none !important;"'
      : "") + ">в " + c[l] + ":00</a>";
    return a += "</div>";
  }

  function handleMiniVersion() {
    var e;
    is_mobile || !default_settings.mini_version_enabled || !checkActive() && default_settings.disable_delayed_calls || !default_settings.show_phone_button || (e = document.getElementById(
      "ncw_compact_hide"), addEvent(
      e,
      "click",
      hideMiniVersion
    ), e = document.getElementById("newton_callback_phone"), addEvent(
      e,
      "mouseover",
      mvOver
    ), e = document.getElementById("ncw_compact_panel"), addEvent(e, "mouseover", function () {
      clearTimeout(mvOutTimeout);
    }), handleMiniVersionSelects(), addEvent(e, "click", function (e) {
      isDescendant(document.getElementById("ncw_compact_hide"), e.target) || (e = document.getElementById(
        "ncw_compact_panel"), removeEvent(e, "mouseout", mvOut), addClass(
        document.getElementById("ncw_compact"),
        "ncw_compact_panel_attached"
      ), addEvent(window, "click", backgroundClickCloseMiniVersion));
    }), handleMiniVersionDepartmentSelect(), handleMiniVersionDateSelect(), handleMiniVersionTabs(), enableHandleMiniVersionForm());
  }

  function handleMiniVersionForm(e) {
    disableMiniVersionSubmitButton();
    processForm(e, form_action, showMiniVersionSubmitResult);
  }

  function enableHandleMiniVersionForm() {
    var e = document.getElementById("ncw_compact_form");
    addEvent(e, "submit", handleMiniVersionForm);
  }

  function disableHandleMiniVersionForm() {
    var e = document.getElementById("ncw_compact_form");
    removeEvent(e, "submit", handleMiniVersionForm);
  }

  function handleMiniVersionFormMissed(e) {
    disableMiniVersionSubmitButton();
    processForm(e, missed_action, showMiniVersionMissedSubmitResult);
  }

  function enableHandleMiniVersionFormMissed() {
    var e = document.getElementById("ncw_compact_form");
    addEvent(e, "submit", handleMiniVersionFormMissed);
  }

  function disableHandleMiniVersionFormMissed() {
    var e = document.getElementById("ncw_compact_form");
    removeEvent(e, "submit", handleMiniVersionFormMissed);
  }

  function handleClearMiniVersionForm(e) {
    return e.preventDefault && e.preventDefault(), clearMiniVersionForm(), !1;
  }

  function showMiniVersionMissedSubmitResult() {
    disableHandleMiniVersionFormMissed(), disableMiniVersionSubmitButtonMissedHover();
    var e = document.getElementById("ncw_compact_form");
    addEvent(
      e,
      "submit",
      handleClearMiniVersionForm
    ), setMiniVersionMessageInfo("Жалобу отправили, спасибо!"), setMiniVersionSubmitButtonText("Попробовать ещё раз?"), enableMiniVersionSubmitButton();
  }

  function clearMiniVersionForm() {
    var e = document.getElementById("ncw_compact_form");
    removeEvent(
      e,
      "submit",
      handleClearMiniVersionForm
    ), disableHandleMiniVersionFormMissed(), disableMiniVersionSubmitButtonMissedHover(), clearInterval(
      countdown_interval_id), countdown_interval_id = null;
    e = document.getElementById("ncw_compact_counter");
    e && (e.style.display = "");
    e = document.getElementById("ncw_compact_input");
    e && (e.value = "", e.readOnly = !1, removeClass(e, "ncw_compact_input_error"));
    e = document.getElementById("ncw_compact_message_error");
    e && (e.innerHTML = ""), hasClass(document.getElementById("ncw_compact"), "ncw_extended_compact_panel")
      ? setMiniVersionMessageInfo("Укажите удобную дату и время звонка")
      : setMiniVersionMessageInfo(getMiniVersionDirectCallText()), setMiniVersionSubmitButtonText("Жду звонка!"), enableHandleMiniVersionForm(), enableMiniVersionSubmitButton();
  }

  function showMiniVersionSubmitResult(e) {
    var t, n = document.getElementById("ncw_compact_message_error");
    n.innerHTML = "";
    var a = document.getElementById("ncw_compact_input");
    a && removeClass(a, "ncw_compact_input_error"), 1 == e
      ? (a && (a.readOnly = !0), reachGoal("NEWTON_CALL"), miniVersionCountdown())
      : (a && addClass(a, "ncw_compact_input_error"), t = processJson(
        e,
        form_name,
        void 0,
        void 0,
        !0
      ), enableMiniVersionSubmitButton()), t && n && (n.innerHTML = '<div class="ncw_compact_message_text">' + t + "</div>");
  }

  function getMiniVersionTimerValue() {
    if (hasClass(document.getElementById("ncw_compact"), "ncw_extended_compact_panel")) {
      var e = document.getElementById("App_Modules_Api_Form/s_CallbackForm_department_id_mini").value;
      var t = document.getElementById("App_Modules_Api_Forms_CallbackForm_date_mini").value;
      var n = document.getElementById("App_Modules_Api_Forms_CallbackForm_hour_mini").value;
      var t = default_settings.departments[e].delay_data.delay_date_time[t];

      if (!t) {
        return 0;
      }

      timer_value = 1e3 * (t + 60 * n * 60 - default_settings.current_time) - 1;
    } else {
      timer_value = default_settings.timer;
    }

    return timer_value;
  }

  function setMiniVersionMessageInfo(e) {
    var t = document.getElementById("ncw_compact_message_info");
    t && (t.innerHTML = '<div class="ncw_compact_message_text">' + e + "</div>");
  }

  function getMiniVersionMessageInfo() {
    var e = document.getElementById("ncw_compact_message_info");
    return e ? e.innerText : "";
  }

  function updateMiniVersionCountdownValue() {
    var e = getMiniVersionTimerValue();
    document.getElementById("ncw_compact_counter").innerHTML = convertMsecs(e);
  }

  function miniVersionCountdown() {
    var e = document.getElementById("ncw_compact_counter");
    updateMiniVersionCountdownValue(), e.style.setProperty(
      "display",
      "inline-block",
      "important"
    ), timer_value = getMiniVersionTimerValue(), timer_value != default_settings.timer
      ? setMiniVersionMessageInfo("Спасибо, мы вам обязательно перезвоним")
      : setMiniVersionMessageInfo("Звоним на ваш телефон"), countdown_before = new Date, countdown_interval_id = setInterval(
      function () {
        var e = document.getElementById("ncw_compact_counter");
        countdown_now = new Date, elapsedTime = countdown_now.getTime() - countdown_before.getTime(), (timer_msecs = timer_value - elapsedTime) <= 0
          ? (clearInterval(countdown_interval_id), countdown_interval_id = null, e.innerHTML = "00:00.00", miniVersionCountdownComplete())
          : e.innerHTML = convertMsecs(timer_msecs);
      },
      countdown_interval
    );
  }

  function miniVersionCountdownComplete() {
    var e = document.getElementById("ncw_compact_counter");
    e && (e.style.display = ""), disableHandleMiniVersionForm(), setMiniVersionSubmitButtonText("Не успели перезвонить?"), enableHandleMiniVersionFormMissed(), enableMiniVersionSubmitButton(), enableMiniVersionSubmitButtonMissedHover();
  }

  function miniVersionSubmitButtonMissedMouseover() {
    document.getElementById("ncw_compact_button") && (miniVersionMessageInfoText = getMiniVersionMessageInfo(), setMiniVersionMessageInfo(
      "Отправим жалобу начальнику отдела продаж"));
  }

  function miniVersionSubmitButtonMissedMouseout() {
    document.getElementById("ncw_compact_button") && miniVersionMessageInfoText && setMiniVersionMessageInfo(
      miniVersionMessageInfoText);
  }

  function enableMiniVersionSubmitButtonMissedHover() {
    var e = document.getElementById("ncw_compact_button");
    e && (addEvent(e, "mouseover", miniVersionSubmitButtonMissedMouseover), addEvent(
      e,
      "mouseout",
      miniVersionSubmitButtonMissedMouseout
    ));
  }

  function disableMiniVersionSubmitButtonMissedHover() {
    var e = document.getElementById("ncw_compact_button");
    e && (removeEvent(e, "mouseover", miniVersionSubmitButtonMissedMouseover), removeEvent(
      e,
      "mouseout",
      miniVersionSubmitButtonMissedMouseout
    ));
  }

  function setMiniVersionSubmitButtonText(e) {
    document.getElementById("ncw_compact_button").innerHTML = "<span>" + e + "</span>";
  }

  function disableMiniVersionSubmitButton() {
    var e = document.getElementById("ncw_compact_button");
    e && (e.disabled = !0);
  }

  function enableMiniVersionSubmitButton() {
    var e = document.getElementById("ncw_compact_button");
    e && (e.disabled = !1);
  }

  function handleMiniVersionTabs() {
    var e = document.getElementById("ncw_compact_tab_call_switch");
    e && addEvent(e, "click", function () {
      clearMiniVersionForm(), hasClass(this, "deferred-call") ? (removeClass(this, "deferred-call"), addClass(
        this,
        "direct-call"
      ), this.attributes.rel.value = getMiniVersionDirectCallTextTab(), enableMiniVersionLaterCall()) : (addClass(
        this,
        "deferred-call"
      ), removeClass(
        this,
        "direct-call"
      ), this.attributes.rel.value = "Отложенный звонок", disableMiniVersionLaterCall());
    });
    e = document.getElementById("ncw_compact_tab_application");
    e && addEvent(e, "click", function (e) {
      showForm();
      var t = document.getElementById("newton_callback_tab_application");
      fireEvent(t, "click"), cancelEvent(e);
    });
    e = document.getElementById("ncw_compact_tab_chat");
    e && addEvent(e, "click", function (e) {
      showForm();
      var t = document.getElementById("newton_callback_tab_chat");
      fireEvent(t, "click"), cancelEvent(e);
    });
    e = document.getElementById("ncw_compact_tab_consultant");
    e && addEvent(e, "click", function (e) {
      document.getElementById("newton_callback_tab_ask").click();
      cancelEvent(e);
    });
    for (var t = document.getElementById("ncw_compact")
      .getElementsByClassName("ncw_compact_tab"), n = 0; n < t.length; n++) {
      var a = t[n];
      addEvent(a, "mouseover", function () {
        var e = document.getElementById("ncw_compact_tabs_tip");
        e.innerHTML = this.attributes.rel.value, addClass(
          e,
          "ncw_compact_tabs_tip_hover"
        ), e.style.left = this.offsetLeft - Math.ceil(e.offsetWidth / 2) + 10 + "px";
      }), addEvent(a, "mouseout", function () {
        var e = document.getElementById("ncw_compact_tabs_tip");
        removeClass(e, "ncw_compact_tabs_tip_hover"), e.style.left = this.offsetLeft + "px";
      });
    }
  }

  function enableMiniVersionLaterCall() {
    addClass(document.getElementById("ncw_compact"), "ncw_extended_compact_panel"), document.getElementById(
      "App_Modules_Api_Forms_CallbackForm_date_mini").disabled = !1, document.getElementById(
      "App_Modules_Api_Forms_CallbackForm_hour_mini").disabled = !1, setMiniVersionMessageInfo(
      "Укажите удобную дату и время звонка");
  }

  function disableMiniVersionLaterCall() {
    removeClass(document.getElementById("ncw_compact"), "ncw_extended_compact_panel"), document.getElementById(
      "App_Modules_Api_Forms_CallbackForm_date_mini").disabled = !0, document.getElementById(
      "App_Modules_Api_Forms_CallbackForm_hour_mini").disabled = !0, setMiniVersionMessageInfo(getMiniVersionDirectCallText());
  }

  function pluralForm(e, t, n, a) {
    return e = Math.abs(e), 5 <= (e %= 100) && e <= 20 ? a : 1 == (e %= 10) ? t : 2 <= e && e <= 4 ? n : a;
  }

  function getMiniVersionDirectCallText() {
    var e = default_settings.timer;
    e % 1e3 != 0 && (e += 1), e /= 1e3;
    var t = Math.floor(e / 60), n = e % 60, e = "Мы перезвоним в течение";
    return 0 < t && (e += " " + t + " " + pluralForm(
      t,
      "минуты",
      "минут",
      "минут"
    )), 0 < n && (e += " " + n + " " + pluralForm(n, "секунды", "секунд", "секунд")), e + "!";
  }

  function getMiniVersionDirectCallTextTab() {
    var e = default_settings.timer;
    e % 1e3 != 0 && (e += 1), e /= 1e3;
    var t = Math.floor(e / 60), n = e % 60, e = "Перезвоним за";
    return 0 < t && (e += " " + t + " " + pluralForm(
      t,
      "минуту",
      "минуты",
      "минут"
    )), 0 < n && (e += " " + n + " " + pluralForm(n, "секунду", "секунды", "секунд")), e;
  }

  function handleMiniVersionDepartmentSelect() {
    var e = document.getElementById("ncw_compact_select_department");
    !e || 1 == (e = e.getElementsByTagName("input")).length && (e = e[0], addEvent(e, "change", function () {
      var e = this.value, t = getMiniVersionDateSelect(e), n = document.getElementById("ncw_compact_select_day");
      n.innerHTML = t.content, handleMiniVersionSelect(n), handleMiniVersionDateSelect();
      n = document.getElementById("ncw_compact_select_time");
      n.innerHTML = getMiniVersionHourSelect(e, t.selectedDate), handleMiniVersionSelect(n);
    }));
  }

  function handleMiniVersionDateSelect() {
    var e = document.getElementById("ncw_compact_select_day");
    !e || 1 == (e = e.getElementsByTagName("input")).length && (e = e[0], addEvent(e, "change", function () {
      var e = this.value;
      if (default_settings.have_departments) var t = document.getElementById("App_Modules_Api_Forms_CallbackForm_department_id_mini").value; else for (var n in default_settings.departments) {
        t = n;
        break;
      }
      var a = document.getElementById("ncw_compact_select_time");
      a.innerHTML = getMiniVersionHourSelect(t, e), handleMiniVersionSelect(a);
    }));
  }

  function backgroundClickCloseMiniSelectDepartment(e) {
    var t = document.getElementById("ncw_compact_select_department");
    t && isDescendant(t, e.target) || hideMiniSelect(t);
  }

  function backgroundClickCloseMiniSelectDate(e) {
    var t = document.getElementById("ncw_compact_select_day");
    t && isDescendant(t, e.target) || hideMiniSelect(t);
  }

  function backgroundClickCloseMiniSelectHour(e) {
    var t = document.getElementById("ncw_compact_select_time");
    t && isDescendant(t, e.target) || hideMiniSelect(t);
  }

  function hideMiniSelect(e) {
    removeClass(e, "ncw_compact_select_opened"), "ncw_compact_select_department" == e.id && removeEvent(
      window,
      "click",
      backgroundClickCloseMiniSelectDepartment
    );
  }

  function showMiniSelect(e) {
    addClass(e, "ncw_compact_select_opened"), "ncw_compact_select_department" == e.id && addEvent(
      window,
      "click",
      backgroundClickCloseMiniSelectDepartment
    ), "ncw_compact_select_day" == e.id && addEvent(
      window,
      "click",
      backgroundClickCloseMiniSelectDate
    ), "ncw_compact_select_time" == e.id && addEvent(window, "click", backgroundClickCloseMiniSelectHour);
  }

  function handleMiniVersionSelects() {
    for (var e = document.getElementById("ncw_compact_panel")
      .getElementsByClassName("ncw_compact_select"), t = 0; t < e.length; t++) handleMiniVersionSelect(e[t]);
  }

  function handleMiniVersionSelect(e) {
    var t = e.getElementsByClassName("ncw_compact_select_current-value");
    1 == t.length && (t = t[0], addEvent(t, "click", function () {
      (hasClass(this.parentNode, "ncw_compact_select_opened") ? hideMiniSelect : showMiniSelect)(this.parentNode);
    }));
    e = e.getElementsByClassName("ncw_compact_select_values-list");
    if (1 == e.length) for (var n = (e = e[0]).getElementsByClassName("ncw_compact_select_value"), a = 0; a < n.length; a++) {
      var i = n[a];
      addEvent(i, "click", function () {
        var e = this.parentNode.parentNode, t = e.getElementsByClassName("ncw_compact_select_current-value"),
          n = e.getElementsByTagName("input");
        if (1 == t.length && 1 == n.length) {
          t = t[0], n = n[0], t.innerHTML = this.innerHTML, n.value = this.rel, fireEvent(n, "change");
          for (var a = e.getElementsByClassName("ncw_compact_select_value"), i = 0; i < a.length; i++) a[i].style.display = "";
          this.style.setProperty("display", "none", "important"), hideMiniSelect(e);
        }
      });
    }
  }

  function mvOver() {
    var e = document.getElementById("newton_callback_phone");
    removeEvent(e, "mouseover", mvOver), showMiniVersion();
    e = document.getElementById("ncw_compact_panel");
    addEvent(e, "mouseout", mvOut);
  }

  function mvOut() {
    clearTimeout(mvOutTimeout), mvOutTimeout = setTimeout(function () {
      var e = document.getElementById("ncw_compact_panel");
      removeEvent(e, "mouseout", mvOut), hideMiniVersion();
    }, 100);
  }

  function backgroundClickCloseMiniVersion(e) {
    var t = document.getElementById("ncw_compact_panel");
    t && isDescendant(t, e.target) || (removeEvent(
      window,
      "click",
      backgroundClickCloseMiniVersion
    ), hideMiniVersion());
  }

  function showMiniVersion() {
    addClass(document.getElementById("ncw_compact"), "ncw_compact_panel_active"), hidePhoneButton();
  }

  function hideMiniVersion() {
    var e = document.getElementById("ncw_compact");
    e && hasClass(e, "ncw_compact_panel_active") && (clearMiniVersionForm(), removeClass(
      e,
      "ncw_compact_panel_active"
    ), removeClass(e, "ncw_compact_panel_attached"), showPhoneButton(), e = document.getElementById(
      "newton_callback_phone"), addEvent(e, "mouseover", mvOver));
  }

  function isMiniVersionAttached() {
    var e = document.getElementById("ncw_compact");
    return !(!e || !hasClass(e, "ncw_compact_panel_attached"));
  }

  function getFormHiddenFields(e) {
    var credentials = {
      site_key: '',
      visitor_id: '',
      hit_id: '',
      session_id: '',
    };

    try {
      if (window.Comagic && window.Comagic.getCredentials()) {
        credentials = window.Comagic.getCredentials();
      }
    } catch (e) {
      console.warn(e);
    }

    var content = "";

    content += '<input type="hidden" value="' + window.location + '" name="' + e + '[referer]" id="' + e + '_referer" />';
    content += '<input type="hidden" value="' + credentials.site_key + '" name="' + e + '[site_key]" id="' + e + '_site_key" />';
    content += '<input type="hidden" value="' + credentials.visitor_id + '" name="' + e + '[visitor_id]" id="' + e + '_visitor_id" />';
    content += '<input type="hidden" value="' + credentials.hit_id + '" name="' + e + '[hit_id]" id="' + e + '_hit_id" />';
    content += '<input type="hidden" value="' + credentials.session_id + '" name="' + e + '[session_id]" id="' + e + '_session_id" />';

    return content;
  }

  function drawDepartmentSelect() {
    if (is_mobile && default_settings.have_departments) {
      var e, t = document.createElement("div"), n = "";
      for (e in n += renderAuctionLotName(), n += renderAuctionLotUsp(), n += '<div class="direct-call-region-wrapper__wrap">', n += '<div class="direct-call-region-wrapper__form-title">Позвонить</div>', n += '<div class="direct-call-region-wrapper__buttons">', default_settings.departments) !checkActiveDepartment(
        e) && default_settings.disable_delayed_calls || (n += '<div class="submit-btn-wrapper direct-call-region-wrapper__button"><a href="javascript:void(0);" rel="' + e + '">' + default_settings.departments[e].header + "</a></div>");
      n += "</div>", n += '<div class="direct-call-region-wrapper__form-text">Звонок для регионов бесплатный</div>', n += '<label id="newton_agreement" class="newton_agreement"><input type="checkbox" id="newton_agreement_input" checked="checked"><span></span><label for="newton_agreement_input">Я согласен <a href="https://spbrealty.ru/page/zaschita-personalnyh-dannyh" target="_blank">на обработку персональных данных</a></label></label>', n += "</div>", t.setAttribute(
        "id",
        "newton_callback_department_select"
      ), t.setAttribute(
        "class",
        "newton_callback_department_select newton_callback_wrap  for-phone-icon direct-call-region-wrapper  mobile"
      ), t.style.display = "none", t.innerHTML = n;
      var a = document.createElement("div");
      a.setAttribute("id", "newton_callback_department_select_mobile"), a.setAttribute(
        "class",
        "newton_callback_department_select_mobile " + (is_new_ios ? " newton_afix" : "")
      ), a.appendChild(t), document.body.appendChild(a);
    }
  }

  function drawCallLaterDateHourSelectMobile(n) {
    var e, a = document.querySelector(".newton_callback_form").querySelector(".newton_callback_form_text_delay"),
      i = [], t = document.createElement("div"), o = document.getElementById(form_name + "_date").value,
      l = document.getElementById(form_name + "_hour").value;

    const minute = document.getElementById(form_name + "_minute")?.value;

    if (!n) for (var c in default_settings.departments) {
      n = c;
      break;
    }
    for (e in default_settings.departments[n].delay_data.pure_data) i.push(e);
    var s = '<div class="call-later-date-select-row">';
    s += '<div class="call-later-date-hour-select__item" data-type="date">' + getDateCaption(new Date(o)) + "</div>", s += '<div class="call-later-date-hour-select__item" data-type="hour">' + l + "</div>", s += '<div class="call-later-date-hour-select__item_delimiter">:</div>', s += '<div class="call-later-date-hour-select__item" data-type="minute">' + minute + "</div>", s += "</div>", t.innerHTML = s, t.classList.add(
      "call-later-date-select"), a.parentNode.insertBefore(t, a.nextSibling);
    var r = document.querySelectorAll(".call-later-date-hour-select__item"),
      t = document.querySelector(".newton_callback_input_wrap__text");
    t && t.parentNode.removeChild(t);
    for (c = 0; c < r.length; c++) r[c].addEventListener("click", function () {
      var e = this.getAttribute("data-type"), t = document.getElementById(form_name + "_date").value,
        t = default_settings.departments[n].delay_data.pure_data[t];

      let availableOptions;
      const dateValue = document.querySelector('[name="App_Modules_Api_Forms_CallbackForm[date]"]').value
      const hourValue = document.querySelector('[name="App_Modules_Api_Forms_CallbackForm[hour]"]').value;
      const busySlots = default_settings.departments[5].delay_data.busySlots;
      let minutes = default_settings.departments[n].delay_data.minutes.filter((minute) => !busySlots[dateValue]?.[hourValue]?.[parseInt(minute)]);

      if (isCurrentHour()) {
        minutes = minutes.filter((m) => !isTooLate(m));
      }

      switch (e) {
        case 'date': {
          availableOptions = i;

          break;
        }
        case 'hour': {
          availableOptions = t;

          break;
        }
        case 'minute': {
          availableOptions = minutes;

          break;
        }
      }

      drawCallLaterDateHourOptionsMobile({
        type: e,
        availableOptions,
        insertBeforeElem: a,
        currentValue: document.getElementById(form_name + "_" + e).value
      }), showCallLaterDateSelectOptions(e), setTranslateForBtn(), correctWidgetSizeFunc();
    });
  }

  function getDateCaption(e) {
    var t = new Date, n = new Date;
    return n.setDate(n.getDate() + 1), e.getDate() === t.getDate() ? "Cегодня" : e.getDate() === n.getDate()
      ? "Завтра"
      : e.toLocaleString(default_settings.lang, {month: "long", day: "numeric"});
  }

  function drawCallLaterDateHourOptionsMobile(e) {
    var t = e.availableOptions, n = e.type, a = e.insertBeforeElem, i = e.currentValue,
      o = "date" === n ? "Выберите дату" : "Установите время", e = document.createElement("div"),
      l = '<div class="newton_callback_form_text call-later_title">' + o + "</div>";
    l += '<div class="call-later__selector-items">';
    for (var c = 0; c < t.length; c++) {
      var s = t[c];
      "date" === n
        ? (s = getDateCaption(new Date(t[c])), l += '<div class="call-later__selector-item" data-value="' + t[c] + '">' + s + "</div>")
        : l += '<div class="call-later__selector-item" data-value="' + t[c] + '">' + s + "</div>";
    }
    l += "</div>", l += '<div class="call-later-date-select__selector-borders"></div>', e.classList.add(
      "call-later__selector"), e.setAttribute("data-type", n), e.innerHTML = l, a.parentNode.insertBefore(
      e,
      a.nextSibling
    ), e.querySelector('.call-later__selector-item[data-value="' + i + '"]').classList.add("active");
    var r, d = e.querySelector(".call-later__selector-items"),
      i = e.querySelector('.call-later__selector-item[data-value="' + i + '"]'), _ = i.offsetTop - 2 * i.clientHeight;
    correctWidgetSizeFunc(), new Promise(function (t) {
      setTimeout(function () {
        var e = document.querySelector(".call-later__selector-item").getBoundingClientRect().top - 202;
        d.scrollTo({top: _}), t(e);
      }, 200);
    }).then(function (o) {
      d.addEventListener("touchend", function () {
        var a = d.querySelectorAll(".call-later__selector-item"), i = [];
        clearTimeout(r), r = setTimeout(function () {
          for (var e = 0; e < a.length; e++) a[e].classList.remove("active"), function (e, t, n) {
            e = e.getBoundingClientRect(), n = e.top - n, e = e.bottom;
            return n < t.clientHeight && 0 <= e;
          }(a[e], d, o) && i.push(a[e]);
          var t = i[i.length - 1], n = t.offsetTop - 2 * t.clientHeight;
          t.classList.add("active"), d.scrollTo({top: n, behavior: "smooth"});
        }, 200);
      });
    });
  }

  function closeCallLaterMobile(e) {
    e.classList.remove("active"), e.parentNode.classList.remove("active"), e.style.display = "none", isNewIOS() && enableScalable();
  }

  function showCallLaterDateSelectOptions(t) {
    addClass(document.querySelector(".newton_callback_input_wrap"), "hidden");
    var _ = document.querySelector('.call-later__selector[data-type="' + t + '"]'),
      e = document.querySelector("#newton_callback_submit_button"), m = e.innerText;
    e.innerText = function () {
      var e = t.toUpperCase();
      switch (e) {
        case"DATE":
          return "Выбрать дату";
        case"HOUR":
          return "Выбрать время";
        case"MINUTE":
          return "Выбрать время";
        default:
          throw new Error(e + " is not valid");
      }
    }(), e.setAttribute("type", "button"), _.classList.add("active"), e.addEventListener("click", function e() {
      var t = this, n = document.querySelector(".call-later__selector-item.active"),
        a = document.querySelector(".call-later__selector.active").getAttribute("data-type"),
        i = document.querySelector('.call-later-date-hour-select__item[data-type="' + a + '"]'),
        o = n.getAttribute("data-value");
      if (i.innerText = n.innerText, hideCallLaterDateTimeSelectOptions(_), t.innerText = m, t.removeEventListener(
        "click",
        e
      ), document.getElementById(form_name + "_" + a).value = o, removeClass(document.querySelector(
        ".newton_callback_input_wrap"), "hidden"), "date" == a) {
        var l, c = document.getElementById(form_name + "_hour").value,
          a = document.getElementById(form_name + "_department_id"), s = !1, r = !1;
        if (a && a.value && default_settings.have_departments && (r = a.value), !r) for (var d in default_settings.departments) {
          r = d;
          break;
        }
        for (l in default_settings.departments[r].delay_data.pure_data[o]) if (default_settings.departments[r].delay_data.pure_data[o][l] == c) {
          s = !0;
          break;
        }
        s || (c = default_settings.departments[r].delay_data.pure_data[o][0], document.getElementById(form_name + "_hour").value = c, document.querySelector(
          '.call-later-date-hour-select__item[data-type="hour"]').innerText = c);

        if (isCurrentHour()) {
          const minute = default_settings.departments[r].delay_data.minutes.find((m) => !isTooLate(m));

          document.getElementById(form_name + '_minute').value = minute;
          document.querySelector('.call-later-date-hour-select__item[data-type="minute"]').innerText = minute;
        }
      }
      setTimeout(function () {
        t.setAttribute("type", "submit");
      }, 200);
    });
  }

  function currentTime() {
    return new Date(default_settings.current_time * 1000);
  }

  function isCurrentHour() {
    const current = currentTime();
    const currentWithoutMinutes = new Date(current.getTime());
    const hourValue = parseInt(document.getElementById(form_name + '_hour').value);
    const selectedDate = new Date(document.getElementById(form_name + '_date').value);

    if (currentWithoutMinutes.getMinutes() > 30) {
      currentWithoutMinutes.setHours(currentWithoutMinutes.getHours() + 1);
    }

    currentWithoutMinutes.setMinutes(0, 0, 0);
    selectedDate.setHours(hourValue);

    return currentWithoutMinutes.getTime() === selectedDate.getTime();
  }

  function isTooLate(minute) {
    const current = currentTime();

    return parseInt(minute) < ((current.getMinutes() + 30) % 60 - 15);
  }

  function hideCallLaterDateTimeSelectOptions(e) {
    e.classList.remove("active"), setTranslateForBtn(), setTimeout(function () {
      e.parentNode.removeChild(e), correctWidgetSizeFunc();
    }, 200);
  }

  function destroyCallLaterDateSelectMobile() {
    var e = document.querySelector(".call-later-date-select"), t = document.querySelectorAll(".call-later__selector"),
      n = document.querySelector("#newton_callback_submit_button");
    if (e && e.parentNode.removeChild(e), t.length) for (var a = 0; a < t.length; a++) t[a].parentNode.removeChild(t[a]);
    n && (n.innerText = "Жду звонка!", n.setAttribute("type", "submit"));
  }

  function drawCallTypeSelect() {
    var e, t;
    is_mobile && (t = "", t += renderAuctionLotName(), t += renderAuctionLotUsp(), t += "<ul>", t += "<li" + (default_settings.have_departments && !getSingleMobileCallbackDepartment()
      ? ' class="newton_have_departments"'
      : "") + ">", t += '<a id="newton_callback_type_callback" class="newton_callback_type_callback" href="javascript:void(0);">Заказать звонок</a>', t += "</li>", null != direct_phone_dynamic && 1 != direct_phone_dynamic || (t += "<li" + (default_settings.have_departments
      ? ' class="newton_have_departments"'
      : "") + ">", t += '<a href="tel:+78123355555" class="newton_callback_type_direct newton_callback_type_direct__select-direct-call-region phone">Позвонить</a>', t += "</li>"), t += "</ul>", (e = document.createElement(
      "div")).setAttribute("id", "newton_callback_type_select"), e.setAttribute(
      "class",
      "newton_callback_department_select for-phone-icon"
    ), e.style.display = "none", e.innerHTML = t, (t = document.createElement("div")).setAttribute(
      "id",
      "newton_callback_type_select_mobile"
    ), t.setAttribute(
      "class",
      "newton_callback_department_select_mobile" + (is_new_ios ? " newton_afix" : "")
    ), t.appendChild(e), document.body.appendChild(t));
  }

  function handleFormSize() {
    is_mobile && (correctWidgetSizeFunc(), addEvent(window, "resize", correctWidgetSizeFunc), addEvent(
      document,
      "scroll",
      correctWidgetSizeFunc
    ), addEvent(document, "drag", correctWidgetSizeFunc));
  }

  function unhandleFormSize() {
    is_mobile && (removeEvent(window, "resize", correctWidgetSizeFunc), removeEvent(
      document,
      "scroll",
      correctWidgetSizeFunc
    ), removeEvent(document, "drag", correctWidgetSizeFunc), is_new_ios && document.getElementById(
      "newton_callback_wrap_mobile").setAttribute("style", ""));
  }

  function handleSelectSize() {
    is_mobile && (correctSelectSizeFunc(), addEvent(window, "resize", correctSelectSizeFunc), addEvent(
      document,
      "scroll",
      correctSelectSizeFunc
    ), addEvent(document, "drag", correctSelectSizeFunc));
  }

  function unhandleSelectSize() {
    is_mobile && (removeEvent(window, "resize", correctSelectSizeFunc), removeEvent(
      document,
      "scroll",
      correctSelectSizeFunc
    ), removeEvent(document, "drag", correctSelectSizeFunc), is_new_ios && document.getElementById(
      "newton_callback_department_select_mobile").setAttribute("style", ""));
  }

  function handleTypeSize() {
    is_mobile && (correctTypeSizeFunc(), addEvent(window, "resize", correctTypeSizeFunc), addEvent(
      document,
      "scroll",
      correctTypeSizeFunc
    ), addEvent(document, "drag", correctTypeSizeFunc));
  }

  function unhandleTypeSize() {
    is_mobile && (removeEvent(window, "resize", correctTypeSizeFunc), removeEvent(
      document,
      "scroll",
      correctTypeSizeFunc
    ), removeEvent(document, "drag", correctTypeSizeFunc), is_new_ios && document.getElementById(
      "newton_callback_type_select_mobile").setAttribute("style", ""));
  }

  function correctWidgetSizeFunc(e) {
    correctWidgetSize(document.getElementById("newton_callback_wrap_mobile"));
  }

  function correctSelectSizeFunc(e) {
    correctWidgetSize(document.getElementById("newton_callback_department_select_mobile"));
  }

  function correctTypeSizeFunc(e) {
    correctWidgetSize(document.getElementById("newton_callback_type_select_mobile"));
  }

  function getBodyScrollTop() {
    return (document.scrollingElement || document.documentElement).scrollTop;
  }

  function correctWidgetSize(e) {
    isNewIOS() && isFormOpened() && keyboard_opened || e && (clearTimeout(correct_timeout), correct_timeout = setTimeout(
      function (e) {
        var t = window.innerWidth > window.innerHeight ? (e.style.setProperty(
            "width",
            "1000px",
            "important"
          ), window.innerWidth / 1e3) : (e.style.setProperty("width", "400px", "important"), window.innerWidth / 400),
          n = e.childNodes[0];
        t = Math.ceil(100 * t) / 100;
        var a = (e.clientWidth * t - e.clientWidth) / 2;
        setScaleToWrap(n, t);
        var i = n.clientHeight, i = (i * t - i) / 2, a = window.pageXOffset + a;
        e.style.setProperty("left", a + "px", "important"), n.style.setProperty(
          "bottom",
          i + "px",
          "important"
        ), correctButtonSize(t), setTranslateForBtn();
      },
      100,
      e
    ));
  }

  function setScaleToWrap(e, t) {
    e && (e.style.setProperty("transition", "bottom .2s", "important"), e.style.setProperty(
      "-moz-transform",
      "scale(" + t + "," + t + ")",
      "important"
    ), e.style.setProperty("-ms-transform", "scale(" + t + "," + t + ")", "important"), e.style.setProperty(
      "-webkit-transform",
      "scale(" + t + "," + t + ")",
      "important"
    ), e.style.setProperty("-o-transform", "scale(" + t + "," + t + ")", "important"), e.style.setProperty(
      "transform",
      "scale(" + t + "," + t + ")",
      "important"
    ));
  }

  function correctButtonSize(e) {
    var t = document.querySelector("#newton_callback_phone"),
      n = document.querySelector(".newton_callback_phone__init"),
      a = document.querySelector(".newton_callback_phone__active");
    t && n && a && (e = e || (window.innerWidth > window.innerHeight
      ? window.innerWidth / 1e3
      : window.innerWidth / 400), t.style.setProperty(
      "width",
      60 * e + "px",
      "important"
    ), t.style.setProperty("height", 60 * e + "px", "important"), setScaleToWrap(n, e), setScaleToWrap(a, e));
  }

  function drawDialog() {
    var e = '';

    e += '<a href="javascript:void(0);" id="newton_callback_dialog_close" class="newton_callback_close">x</a>';
    e += '<div id="newton_callback_company_logo" class="newton_callback_company_logo"></div>';
    e += '<div class="newton_callback_content newton_dialog">';
    e += '<div id="newton_callback_dialog_form_text" class="newton_callback_form_text">' + default_settings.dialog_text + '</div>';
    e += '<a href="javascript:void(0);" id="newton_callback_dialog_accept" class="newton_callback_dialog_button">' + getCaption(
      'dialog_button_yes') + '</a>';
    e += '<a href="javascript:void(0);" id="newton_callback_dialog_cancel" class="newton_callback_dialog_button">' + getCaption(
      'dialog_button_no') + '</a>';

    if (is_mobile || default_settings.is_multiwidget || !default_settings.manager_photo_enabled) {
      e += '<div class="newton_callback_model_name">' + default_settings.manager_photo_name + '</div>';
    }

    if (null != default_settings.additional_dialog_html) {
      e += default_settings.additional_dialog_html;
    }

    e += '<div class="newton_callback_dialog_forget_wrap">';
    e += '<a href="javascript:void(0);" id="newton_callback_dialog_forget" class="newton_callback_dialog_forget">' + getCaption(
      'dialog_button_forget') + '</a>';
    e += '</div>';
    e += '</div>';

    var t = document.createElement('div');

    t.setAttribute('id', 'newton_callback_dialog_wrap');

    is_mobile || default_settings.is_multiwidget || !default_settings.manager_photo_enabled || (n += ' newton_callback_with_manager');
    t.setAttribute('class', 'newton_callback_wrap newton_dialog');
    t.style.display = 'none';
    t.innerHTML = e;

    document.body.appendChild(t);
  }

  function drawButton() {
    var e = "";
    is_mobile
      ? (e += '<div class="newton_callback_phone__icon newton_callback_phone__init"></div>', e += '<div class="newton_callback_phone__icon newton_callback_phone__active"></div>')
      : ("spin" == default_settings.animation_type && (e += '<svg id="newton-callback-button" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" height="120px" viewBox="0 0 120 120" width="120px" version="1.1" y="0px" x="0px" xmlns:xlink="http://www.w3.org/1999/xlink">', e += getButtonTextHtml(), e += '<g class="newton-wrapper">', e += '<g class="newton-ring">', e += '<path id="newton-track-right" d="m111.1 30.499c-2.563-4.443-5.644-8.397-9.082-11.89-0.279-0.368-0.709-0.609-1.209-0.609-0.828 0-1.5 0.672-1.5 1.5 0 0.513 0.258 0.965 0.65 1.235-0.014 0.014-0.023 0.026-0.038 0.04 9.937 10.104 16.077 23.938 16.077 39.223 0 15.29-6.146 29.128-16.082 39.23 0.012 0.016 0.025 0.022 0.038 0.041-0.388 0.271-0.644 0.721-0.644 1.229 0 0.828 0.672 1.5 1.5 1.5 0.475 0 0.893-0.227 1.168-0.568 0.004 0.004 0.008 0.01 0.012 0.014 18.21-18.43 22.689-47.415 9.109-70.939v-0.002z" fill="url(' + window.location.pathname + window.location.search + '#newton-track-right-gradient)"/>', e += '<linearGradient id="newton-track-right-gradient" x1="83.227" gradientUnits="userSpaceOnUse" y1="-695.51" gradientTransform="matrix(1 0 0 -1 .1201 -603.36)" x2="119.8" y2="-632.16">', e += '<stop stop-color="#' + default_settings.css_phone_button_color + '" stop-opacity="0" offset="0"/>', e += '<stop stop-color="#' + default_settings.css_phone_button_color + '" offset="1"/>', e += "</linearGradient>", e += '<path id="newton-track-left" d="m20.043 99.271c0.012-0.02 0.026-0.026 0.038-0.041-9.934-10.104-16.081-23.942-16.081-39.232 0-15.285 6.144-29.119 16.074-39.223-0.017-0.019-0.035-0.036-0.051-0.055 0.383-0.271 0.634-0.716 0.634-1.221 0-0.828-0.672-1.5-1.5-1.5-0.545 0-1.018 0.293-1.28 0.728-3.394 3.465-6.435 7.377-8.972 11.771-13.583 23.526-9.109 52.511 9.103 70.943l0.012-0.012c0.275 0.344 0.693 0.563 1.168 0.563 0.828 0 1.5-0.673 1.5-1.5 0-0.511-0.256-0.958-0.645-1.229v0.01z" fill="url(' + window.location.pathname + window.location.search + '#newton-track-left-gradient)"/>', e += '<linearGradient id="newton-track-left-gradient" x1="-.0596" gradientUnits="userSpaceOnUse" y1="-632.15" gradientTransform="matrix(1 0 0 -1 .1201 -603.36)" x2="36.519" y2="-695.51">', e += '<stop stop-color="#' + default_settings.css_phone_button_color + '" stop-opacity="0" offset="0"/>', e += '<stop stop-color="#' + default_settings.css_phone_button_color + '" offset="1"/>', e += "</linearGradient>", e += '<path id="newton-track-background" opacity=".1" d="m60 1c-32.585 0-59 26.415-59 59s26.415 59 59 59 59-26.415 59-59-26.415-59-59-59zm0 115c-30.928 0-56-25.072-56-56s25.072-56 56-56c30.928 0 56 25.072 56 56s-25.072 56-56 56z" fill="#' + default_settings.css_phone_button_color + '"/>', e += "</g>", e += "</g>", e += '<circle class="newton-circle-back" opacity=".2" cy="60" cx="60" r="40" fill="#' + default_settings.css_phone_button_color + '"/>', e += '<g class="newton-circle-front">', e += '<circle cy="60" cx="60" r="' + (default_settings.mini_version_enabled
        ? 28
        : 34) + '" fill="#' + default_settings.css_phone_button_color + '"/>', e += '<path class="newton-icon-handset" d="m59.34 48.038c-0.843 0.181-1.681 0.434-2.504 0.778-6.003 2.52-9.252 8.718-8.221 14.78-0.042 0.26-0.04 0.527 0.072 0.786 0.316 0.733 1.178 1.074 1.923 0.763 0.746-0.313 1.094-1.162 0.778-1.896-0.011-0.024-0.034-0.041-0.046-0.063-0.819-4.893 1.81-9.887 6.652-11.917 0.363-0.152 0.73-0.275 1.099-0.384 0.308 0.082 0.639 0.089 0.956-0.044 0.746-0.313 1.094-1.161 0.778-1.896-0.255-0.589-0.86-0.905-1.476-0.853l-0.011-0.054zm7.877 4.865l0.855-13.908c-2.436 0.489-2.402 2.61-2.402 2.61l-0.473 5.671c-0.814 5.348 2.02 5.627 2.02 5.627zm-21.886 13.454c0.62-0.26 0.932-0.896 0.831-1.523l0.032-0.006c-1.627-7.491 2.303-15.316 9.738-18.437 0.873-0.366 1.76-0.634 2.653-0.845l-0.022-0.118c0.042-0.014 0.085-0.009 0.126-0.025 0.729-0.307 1.071-1.137 0.761-1.854s-1.153-1.052-1.882-0.745c-0.109 0.046-0.191 0.123-0.282 0.19-0.872 0.226-1.74 0.492-2.595 0.851-8.661 3.635-13.241 12.75-11.349 21.478l0.045-0.009c0.019 0.101 0.02 0.201 0.062 0.3 0.31 0.717 1.153 1.05 1.882 0.743zm29.689-26.205c-1.313-1.785-5.783-0.978-5.783-0.978l-0.982 14.23 0.313 0.267 1.793 0.85c0.318 0.267 0.414 0.961 0.414 0.961-1.289 4.879-3.496 7.473-3.496 7.473-3.616 6.393-6.278 8.244-6.278 8.244-0.65 0.539-1.199 0.369-1.199 0.369-0.475-0.002-2.29-1.375-2.29-1.375l-12.773 7.361c1.72 4.612 3.803 4.405 3.803 4.405 16.692-0.466 24.25-14.581 24.25-14.581 9.835-14.467 2.228-27.226 2.228-27.226zm-21.017 28.373s-5.689 2.388-9.379 5.004-0.963 1.07-0.371 2.759l12.28-7.089s-1.356-1.099-2.53-0.674z" fill="#' + default_settings.css_button_icons_color + '"/>', e += '<path class="newton-icon-callback" d="m79 44.986h-38c-2.209 0-4 1.791-4 4v23.028c0 2.209 1.791 4 4 4h38c2.209 0 4-1.791 4-4v-23.028c0-2.209-1.791-4-4-4zm-20.5 23.014h-16c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h16c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm0-7h-16c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h16c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm0-7h-16c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h16c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm20.5 5.005c0 1.656-1.344 3-3 3h-8c-1.657 0-3-1.344-3-3v-5c0-1.657 1.343-3 3-3h8c1.656 0 3 1.343 3 3v5z" fill="#' + default_settings.css_button_icons_color + '"/>', e += '<path class="newton-icon-consultant" d="m75 43.014h-30c-4.418 0-8 3.581-8 8v5.017c0 0.662-0.001 12.629-0.001 12.629 0 5.707 4.819 10.34 11.001 10.34 0-3.535 1.35-6.996 8.786-6.996h18.214c4.418 0 8-3.581 8-8v-12.99c0-4.419-3.582-8-8-8zm-10.5 17.986h-22c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h22c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm0-7h-22c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h22c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5z" fill="#' + default_settings.css_button_icons_color + '"/>', e += '<path class="newton-icon-chat" d="M79.872,43.255L70.616,75.4A2.045,2.045,0,0,1,67.5,76.66L51.259,67.45a0.443,0.443,0,0,1-.085-0.76l18.751-17c1.112-1.008,1.012-1.13-.222-0.275L47.554,64.785a0.946,0.946,0,0,1-.92.042L35.492,58.51c-2.083-1.182-1.925-2.763.351-3.517L77.668,41.159C79.373,40.594,80.366,41.537,79.872,43.255ZM49,69.4a0.35,0.35,0,0,1,.575-0.311L56.752,72.9a0.393,0.393,0,0,1,.12.645l-5,5.415C50.294,80.677,49,80.232,49,77.971h0V69.4Z" fill="#' + default_settings.css_button_icons_color + '"/>', e += "</g>", e += "</svg>"), "pulse" == default_settings.animation_type && (e += '<svg id="newton-callback-button" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" height="120px" viewBox="0 0 120 120" width="120px" version="1.1" y="0px" x="0px" xmlns:xlink="http://www.w3.org/1999/xlink">', e += getButtonTextHtml(), e += '<g class="newton-ring">', e += '<path id="newton-track-background" d="m60 1c-32.585 0-59 26.415-59 59s26.415 59 59 59 59-26.415 59-59-26.415-59-59-59zm0 115c-30.928 0-56-25.072-56-56s25.072-56 56-56c30.928 0 56 25.072 56 56s-25.072 56-56 56z" fill="#' + default_settings.css_phone_button_color + '"/>', e += "</g>", e += '<g class="newton-wrapper">', e += '<circle class="newton-circle-back" cy="60" cx="60" r="34" fill="#' + default_settings.css_phone_button_color + '"/>', e += '<g class="newton-circle-front">', e += '<circle cy="60" cx="60" r="' + (default_settings.mini_version_enabled
        ? 28
        : 34) + '" fill="#' + default_settings.css_phone_button_color + '"/>', e += '<path class="newton-icon-handset" d="m59.34 48.038c-0.843 0.181-1.681 0.434-2.504 0.778-6.003 2.52-9.252 8.718-8.221 14.78-0.042 0.26-0.04 0.527 0.072 0.786 0.316 0.733 1.178 1.074 1.923 0.763 0.746-0.313 1.094-1.162 0.778-1.896-0.011-0.024-0.034-0.041-0.046-0.063-0.819-4.893 1.81-9.887 6.652-11.917 0.363-0.152 0.73-0.275 1.099-0.384 0.308 0.082 0.639 0.089 0.956-0.044 0.746-0.313 1.094-1.161 0.778-1.896-0.255-0.589-0.86-0.905-1.476-0.853l-0.011-0.054zm7.877 4.865l0.855-13.908c-2.436 0.489-2.402 2.61-2.402 2.61l-0.473 5.671c-0.814 5.348 2.02 5.627 2.02 5.627zm-21.886 13.454c0.62-0.26 0.932-0.896 0.831-1.523l0.032-0.006c-1.627-7.491 2.303-15.316 9.738-18.437 0.873-0.366 1.76-0.634 2.653-0.845l-0.022-0.118c0.042-0.014 0.085-0.009 0.126-0.025 0.729-0.307 1.071-1.137 0.761-1.854s-1.153-1.052-1.882-0.745c-0.109 0.046-0.191 0.123-0.282 0.19-0.872 0.226-1.74 0.492-2.595 0.851-8.661 3.635-13.241 12.75-11.349 21.478l0.045-0.009c0.019 0.101 0.02 0.201 0.062 0.3 0.31 0.717 1.153 1.05 1.882 0.743zm29.689-26.205c-1.313-1.785-5.783-0.978-5.783-0.978l-0.982 14.23 0.313 0.267 1.793 0.85c0.318 0.267 0.414 0.961 0.414 0.961-1.289 4.879-3.496 7.473-3.496 7.473-3.616 6.393-6.278 8.244-6.278 8.244-0.65 0.539-1.199 0.369-1.199 0.369-0.475-0.002-2.29-1.375-2.29-1.375l-12.773 7.361c1.72 4.612 3.803 4.405 3.803 4.405 16.692-0.466 24.25-14.581 24.25-14.581 9.835-14.467 2.228-27.226 2.228-27.226zm-21.017 28.373s-5.689 2.388-9.379 5.004-0.963 1.07-0.371 2.759l12.28-7.089s-1.356-1.099-2.53-0.674z" fill="#' + default_settings.css_button_icons_color + '"/>', e += '<path class="newton-icon-callback" d="m79 44.986h-38c-2.209 0-4 1.791-4 4v23.028c0 2.209 1.791 4 4 4h38c2.209 0 4-1.791 4-4v-23.028c0-2.209-1.791-4-4-4zm-20.5 23.014h-16c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h16c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm0-7h-16c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h16c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm0-7h-16c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h16c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm20.5 5.005c0 1.656-1.344 3-3 3h-8c-1.657 0-3-1.344-3-3v-5c0-1.657 1.343-3 3-3h8c1.656 0 3 1.343 3 3v5z" fill="#' + default_settings.css_button_icons_color + '"/>', e += '<path class="newton-icon-consultant" d="m75 43.014h-30c-4.418 0-8 3.581-8 8v5.017c0 0.662-0.001 12.629-0.001 12.629 0 5.707 4.819 10.34 11.001 10.34 0-3.535 1.35-6.996 8.786-6.996h18.214c4.418 0 8-3.581 8-8v-12.99c0-4.419-3.582-8-8-8zm-10.5 17.986h-22c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h22c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5zm0-7h-22c-0.829 0-1.5-0.672-1.5-1.5s0.671-1.5 1.5-1.5h22c0.828 0 1.5 0.672 1.5 1.5s-0.672 1.5-1.5 1.5z" fill="#' + default_settings.css_button_icons_color + '"/>', e += '<path class="newton-icon-chat" d="M79.872,43.255L70.616,75.4A2.045,2.045,0,0,1,67.5,76.66L51.259,67.45a0.443,0.443,0,0,1-.085-0.76l18.751-17c1.112-1.008,1.012-1.13-.222-0.275L47.554,64.785a0.946,0.946,0,0,1-.92.042L35.492,58.51c-2.083-1.182-1.925-2.763.351-3.517L77.668,41.159C79.373,40.594,80.366,41.537,79.872,43.255ZM49,69.4a0.35,0.35,0,0,1,.575-0.311L56.752,72.9a0.393,0.393,0,0,1,.12.645l-5,5.415C50.294,80.677,49,80.232,49,77.971h0V69.4Z" fill="#' + default_settings.css_button_icons_color + '"/>', e += "</g>", e += "</g>", e += "</svg>"), e += default_settings.phone_button_html);
    var t = document.createElement("div");
    t.setAttribute("id", "newton_callback_phone");
    var n = "newton_callback_phone" + (is_mobile ? " mobile" : "");
    isIE() ? n += " newton_ie_hide" : t.style.display = "none", t.setAttribute(
      "class",
      n
    ), t.innerHTML = e, document.body.appendChild(t);
  }

  function getButtonTextHtml() {
    var e = "";
    return default_settings.phone_button_text && (e += '<g class="newton-text">', e += '<path id="newton-text-wrap" d="M0,0h120v120H0V0z" fill="none" />', e += '<path id="newton-text-path" d="M59.99,15.01c24.853,0,45,20.147,45,45c0,24.854-20.147,45-45,45c-24.853,0-45-20.146-45-45 C14.99,35.157,35.137,15.01,59.99,15.01z" fill="none"/>', e += '<text x="0" y="0" text-anchor="middle" fill="#' + default_settings.css_phone_button_text_color + '"><textPath xlink:href="' + window.location.pathname + window.location.search + '#newton-text-path" startOffset="50%">' + default_settings.phone_button_text + "</textPath></text>", e += "</g>"), e;
  }

  function applyCss() {
    cssLoaded = !1, ajax.get(default_settings.css, {}, function (e) {
      var t = document.createElement("style");
      t.setAttribute("type", "text/css"), t.setAttribute(
        "id",
        "newton_callback_css"
      ), t.innerHTML = e, document.getElementsByTagName("head")[0].appendChild(t), cssLoaded = !0;
    }, !1);
  }

  function enableSetingsUpdate(e) {
    null == e && (e = !1), settings_update_interval_id = setInterval(function () {
      getSettings(), manageEvents(e), 0 < calltrackingProlongCount && calltrackingProlongCount--;
    }, settings_update_interval);
  }

  function disableSettingsUpdate() {
    clearInterval(settings_update_interval_id);
  }

  function enableWaitForMetrikaId() {
    wait_for_metrika_interval_id = setInterval(function () {
      wait_for_metrika_attempts--, getMetrikaClientId()
        ? (disableWaitForMetrikaId(), getSettings())
        : wait_for_metrika_attempts <= 0 && disableWaitForMetrikaId();
    }, wait_for_metrika_interval);
  }

  function disableWaitForMetrikaId() {
    wait_for_metrika_attempts = 0, clearInterval(wait_for_metrika_interval_id);
  }

  function enableWaitForGAId() {
    wait_for_ga_interval_id = setInterval(function () {
      wait_for_ga_attempts--, getGAClientId()
        ? (disableWaitForGAId(), getSettings())
        : wait_for_ga_attempts <= 0 && disableWaitForGAId();
    }, wait_for_ga_interval);
  }

  function disableWaitForGAId() {
    wait_for_ga_attempts = 0, clearInterval(wait_for_ga_interval_id);
  }

  function getSettings() {
    var e = {};
    "undefined" != typeof newton_callback_id_internal && (e.hash = newton_callback_id_internal), isVkVerion() && (e.vk = 1), e.landing_page_referrer = getLandingPageReferrer(), e.landing_page_url = getLandingPageUrl(), e.metrika_client_id = getMetrikaClientId(), e.metrika_client_id || wait_for_metrika_interval_id || !wait_for_metrika_attempts || enableWaitForMetrikaId(), e.ga_client_id = getGAClientId(), e.ga_client_id || wait_for_ga_interval_id || !wait_for_ga_attempts || enableWaitForGAId(), 0 < calltrackingProlongCount && "undefined" != typeof newton_calltracking_id_internal && (newton_calltracking_id_internal instanceof Array || (newton_calltracking_id_internal = [newton_calltracking_id_internal]), e.calltracking_hash = newton_calltracking_id_internal, e.fingerprint = fingerprint), "undefined" != typeof newton_auction_lot_id_internal && (e.auction_lot_hash = newton_auction_lot_id_internal), cookies_enabled || (e.cookies_disabled = 1), void 0 === e.hash && void 0 === e.calltracking_hash || eyenewtonLoader.load(
      function () {
        ajax.get(settings_url, e, function (t) {
          if (eyenewtonLoader.next(), !t) return clearInterval(init_interval), !1;
          try {
            var e = JSON.parse(t);
          } catch (e) {
            return remoteErrorLog(e, "getSettings", typeof t + " " + t.length + " " + t), !1;
          }
          var n;
          return 0 == e.length || "undefined" != typeof newton_callback_id_internal && null != e.callback_id && newton_callback_id_internal != e.callback_id
            ? (clearInterval(init_interval), !1)
            : ((default_settings = merge_options(default_settings, e)).callback && (
                default_settings.appearance_disabled = parseInt(default_settings.appearance_disabled),
                  disableAppearanceOnMainPageLot(),
                  default_settings.appearance_init = parseInt(default_settings.appearance_init),
                  default_settings.appearance_exit = parseInt(default_settings.appearance_exit),
                  default_settings.appearance_time = parseInt(default_settings.appearance_time),
                  default_settings.current_time = parseInt(default_settings.current_time),
                  default_settings.show_once_day = parseInt(default_settings.show_once_day),
                  default_settings.hide_after_hours = parseInt(default_settings.hide_after_hours),
                  default_settings.show_on_mobile = parseInt(default_settings.show_on_mobile),
                  default_settings.dialog_enabled = parseInt(default_settings.dialog_enabled),
                  default_settings.disable_delayed_calls = parseInt(default_settings.disable_delayed_calls),
                  default_settings.have_departments = parseInt(default_settings.have_departments),
                  default_settings.silent_mode = 1 == default_settings.silent_mode,
                  default_settings.is_multiwidget = parseInt(default_settings.is_multiwidget),
                  default_settings.multiwidget_application = parseInt(default_settings.multiwidget_application),
                  default_settings.multiwidget_consultant = parseInt(default_settings.multiwidget_consultant),
                  default_settings.enable_mobile_direct_call = parseInt(default_settings.enable_mobile_direct_call),
                  default_settings.enable_log = parseInt(default_settings.enable_log),
                  default_settings.chat_enabled = parseInt(default_settings.chat_enabled),
                  default_settings.chat_active = parseInt(default_settings.chat_active),
                  default_settings.manager_photo_enabled = parseInt(default_settings.manager_photo_enabled),
                  default_settings.banner_enabled = parseInt(default_settings.banner_enabled),
                  default_settings.banner_bottom = parseInt(default_settings.banner_bottom),
                  default_settings.mini_version_enabled = parseInt(default_settings.mini_version_enabled),
                  default_settings.disable_button_drag = parseInt(default_settings.disable_button_drag),
                void 0 !== (n = getParam("show_phone_button")) && (default_settings.show_phone_button = n),
                null == (init_time = getInitTime()) && setInitTime(init_time = default_settings.current_time)),
                void (settingsLoaded = !0)
            );
        });
      });
  }

  function disableAppearanceOnMainPageLot() {
    "undefined" == typeof newton_auction_lot_id || "df69de60-254a-491f-83ce-f161fc571e4d" != newton_auction_lot_id && "3e6df79f-a76e-4560-a3d1-d1228bd5812e" != newton_auction_lot_id || (default_settings.appearance_disabled = 1);
  }

  function manageEvents(e) {
    default_settings.appearance_disabled || (null == e && (e = !1), checkActive()
      ? (e || checkForget() || (1 == default_settings.appearance_init
        ? enableShowAtInit()
        : checkShowed() && default_settings.appearance_page_views && getPageViews() == default_settings.appearance_page_views
          ? (enableShowAtNthPage(), resetPageViews())
          : disableShowAtInit(), (1 == default_settings.appearance_exit
        ? enableShowAtExit
        : disableShowAtExit)(), (0 < default_settings.appearance_time
        ? enableShowAtTime
        : disableShowAtTime)()), !e && checkOpenChatAtInit() && openChatAtInit())
      : (isOpened() && (destroyCallLaterDateSelectMobile(), hideDialog(), hideForm()), disableAll()));
  }

  function checkOpenChatAtInit() {
    return default_settings.is_multiwidget && default_settings.chat_enabled && default_settings.chat_active && getCookie(
      "n_chat_opnd");
  }

  function openChatAtInit() {
    afterLoad = function () {
      showForm(), openChat();
    };
  }

  function handleMissedButtonClick() {
    var e = document.getElementById("newton_callback_missed");
    addEvent(e, "click", showMissedOptions);
    e = document.getElementById("newton_callback_missed_send");
    addEvent(e, "click", processMissed);
    e = document.getElementById("newton_callback_missed_retry");
    addEvent(e, "click", function () {
      setDirectCall();
    });
    e = document.getElementById("newton_callback_missed_active_delay");
    addEvent(e, "click", function () {
      setActiveLaterCall(), default_settings.is_multiwidget && setMultiwidgetTabSelected("newton_callback_tab_delay");
    });
  }

  function showMissedOptions() {
    document.getElementById("newton_callback_missed_options").style.display = "inline-block", document.getElementById(
      "newton_callback_missed_wrap").style.setProperty("display", "none", "important");
  }

  function processMissed() {
    var e = document.getElementById("newton_callback_form");
    data = serialize(e), ajax.post(missed_action, data, missedResult);
  }

  function showMissedCallMobile() {
    var e = document.querySelector("#newton_callback_form_text"),
      t = document.querySelector(".newton_callback_input_wrap"),
      n = document.querySelector("#newton_callback_submit_button"),
      a = document.querySelector(".newton_callback_input_wrap__text"), i = document.createElement("div"),
      o = document.createElement("a");
    a && a.classList.add("hidden"), i && (i.classList.add(
      "newton_callback_input_wrap__text",
      "missed"
    ), i.innerText = "Если вам не перезвонили, мы отправим жалобу начальнику отдела продаж"), n && (o.innerText = "Не успели перезвонить?", addClass(
      o,
      "newton_callback_missed_btn"
    ), n.parentNode.insertBefore(i, n), n.parentNode.insertBefore(o, n), n.style.display = "none", addEvent(
      o,
      "click",
      processMissed
    )), e && (e.innerText = "Перезвоним вам " + default_settings.form_time_text + " бесплатно"), t && t.classList.add(
      "hidden"), correctWidgetSizeFunc(), setTranslateForBtn();
  }

  function hideMissedCallMobile() {
    var e = document.querySelector(".newton_callback_input_wrap__text.missed"),
      t = document.querySelector(".newton_callback_input_wrap__text:not(.missed)"),
      n = document.querySelector(".newton_callback_input_wrap"),
      a = document.querySelector("#newton_callback_submit_button"),
      i = document.querySelector(".newton_callback_missed_btn");
    e && e.parentNode.removeChild(e), n && n.classList.remove("hidden"), t && t.classList.remove("hidden"), a && (a.style.display = "unset"), i && (removeEvent(
      i,
      "click",
      processMissed
    ), i.parentNode.removeChild(i));
  }

  function missedResult() {
    var e;
    is_mobile ? (e = document.querySelector(".newton_callback_missed_btn"), document.querySelector(
      ".newton_callback_input_wrap__text").innerText = getCaption("form_missed_result"), removeEvent(
      e,
      "click",
      processMissed
    ), e.parentNode.removeChild(e), correctWidgetSizeFunc(), setTranslateForBtn()) : (document.getElementById(
      "newton_callback_missed_options").style.display = "none", document.getElementById("newton_callback_missed_result")
      .style
      .setProperty("display", "inline-block", "important"));
  }

  /**
   * @param {Event} event
   * @param {string} url
   * @param {function} callback
   */
  function processForm(event, url, callback) {
    const data = serialize(event.target);
    try {
      event.target.dispatchEvent(new CustomEvent('comagicWidget:beforeSend', {
        bubbles: true,
        detail: {
          phone: data['App_Modules_Api_Forms_CallbackForm[phone]'],
        },
      }));
    } catch (error) {
      //
    }

    submitRequest(url, data, function(result) {
      callback(result);

      if(result === '1') {
        event.target.dispatchEvent(new CustomEvent('comagicWidget:success', { bubbles: true }));
      }
    });
  }

  /**
   * @param {string} method
   * @param {object} data
   * @param {function} callback
   */
  async function submitRequest(method, data, callback) {
    var phone = data['App_Modules_Api_Forms_CallbackForm[phone]'];
    var date = data['App_Modules_Api_Forms_CallbackForm[date]'];
    var hour = data['App_Modules_Api_Forms_CallbackForm[hour]'];
    var minute = parseInt(data['App_Modules_Api_Forms_CallbackForm[minute]']);
    var is_delay = date && hour;
    var group_id = 357027;
    let delayed_call_time;

    if (is_delay) {
      const _date = new Date(date);
      let datetime = Date.UTC(_date.getFullYear(), _date.getMonth(), _date.getDate(), hour - 3, minute, 0);

      delayed_call_time = await Promise.resolve($.get('/api/callback/getFreeSlot', { datetime }));
    } else {
      delayed_call_time = (new Date((new Date()).getTime() + 2 * 60000)).getTime();
    }

    const comagic_params = {
      captcha_key: undefined,
      captcha_value: undefined,
      phone: phone,
      group_id: group_id,
      delayed_call_time,
    };

    window.ComagicWidget.sitePhoneCall(comagic_params, function (response) {
      if (response.result.status !== 0) {
        return;
      }

      if (is_delay) {
        $.post('/api/callback/add', { datetime: comagic_params.delayed_call_time });
      }

      callback('1');
    });
  }

  function showSubmitResult(e) {
    for (var t in formErrorElements) removeClass(formErrorElements[t], "error");
    var n, a, i, o, l = "", c = document.getElementById("newton_callback_submit_result");
    1 == e ? (successCall = !0, reachGoal(formFromDialog
      ? "NEWTON_DIALOG_CALL"
      : "NEWTON_CALL"), n = !1, (a = document.getElementById(form_name + "_department_id")) && a.value && default_settings.have_departments && (n = a.value), !checkActive(
      {departmentId: n}) && checkLaterCall() ? (is_mobile
      ? (o = getDelayTextMobileSuccess({departmentId: n}), i = document.getElementById("newton_callback_wrap_mobile"), destroyCallLaterDateSelectMobile(), document.getElementById(
        "newton_callback_input_wrap").style.setProperty("display", "none", "important"), document.getElementById(
        "newton_callback_submit_button").style.setProperty("display", "none", "important"), document.getElementById(
        "newton_callback_form_text").innerHTML = o, (o = document.getElementById("newton_callback_captcha")) && o.style.setProperty(
        "display",
        "none",
        "important"
      ), addClass(
        document.getElementById("newton_callback_form_text"),
        "delay_success"
      ), correctWidgetSize(i), closeFormTimeout = setTimeout(function () {
        hideForm();
      }, 3e3), enableSubmitButton())
      : (document.getElementById(form_name + "_phone").style.visibility = "hidden", document.getElementById(
        "newton_callback_submit_button").style.visibility = "hidden", (o = document.getElementById(
        "newton_callback_captcha")) && (o.style.visibility = "hidden"), addClass(
        document.getElementById("newton_callback_wrap"),
        "delay_countdown"
      ), (i = document.getElementById("newton_sms_notice")) && (i.style.display = "none"), countdown()), setTimeout(
      function () {
        getSettings();
      },
      1e3
    )) : (is_mobile
      ? (addClass(
        document.getElementById("newton_callback_counter"),
        "newton_show"
      ), (o = document.getElementById("newton_callback_captcha")) && o.style.setProperty(
        "display",
        "none",
        "important"
      ), setTranslateForBtn())
      : (document.getElementById(form_name + "_phone").style.visibility = "hidden", document.getElementById(
        "newton_callback_submit_button").style.visibility = "hidden", document.getElementById(
        "newton_callback_active_delay_wrap").style.display = "none", (o = document.getElementById(
        "newton_callback_captcha")) && (o.style.visibility = "hidden")), countdown())) : (l = processJson(
      e,
      form_name,
      formErrorElements
    ), is_mobile && enableSubmitButton(), setTranslateForBtn()), c.innerHTML = l, is_mobile || enableSubmitButton();
  }

  function showApplicationSubmitResult(e) {
    for (var t in applicationFormErrorElements) removeClass(applicationFormErrorElements[t], "error");
    for (var t in applicationFormErrorMessages) applicationFormErrorMessages[t].innerHTML = "";
    var n, a, i = "", o = document.getElementById("newton_callback_application_submit_result");
    1 == e
      ? ((n = document.getElementById("newton_callback_application_form")) && (n.style.display = "none", (a = document.getElementById(
        application_form_name + "_phone")) && (a.value = ""), (a = document.getElementById(application_form_name + "_name")) && (a.value = ""), (a = document.getElementById(
        application_form_name + "_email")) && (a.value = ""), (a = document.getElementById(application_form_name + "_comment")) && (a.value = "")), (a = document.getElementById(
        "newton_callback_application_success")) && (reachGoal("NEWTON_APPLICATION_SENT"), a.style.display = "block"))
      : i = processJson(
        e,
        application_form_name,
        applicationFormErrorElements,
        applicationFormErrorMessages
      ), o && (o.innerHTML = i);
  }

  function processJson(t, e, n, a, i) {
    i = i || !1;
    var o, l = "";
    try {
      if (data = JSON.parse(t), "object" == typeof data) for (var c in data) i
        ? l += data[c]
        : ((o = document.getElementById(e + "_" + c + "_em"))
          ? (o.innerHTML = data[c], void 0 !== a && a.push(o))
          : l += data[c], (o = document.getElementById(e + "_" + c)) && o.nodeType == Node.ELEMENT_NODE && (addClass(
          o,
          "error"
        ), n.push(o))); else l += data;
    } catch (e) {
      l += e.name + ": " + t;
    }
    return l;
  }

  function mobileTouchStart(e) {
    if (isDescendant(
      document.getElementById("newton_callback_phone"),
      e.target
    )) return phoneButtonClick(), close_button_disabled = !0, setTimeout(function () {
      close_button_disabled = !1;
    }, 400), cancelEvent(e);
  }

  var handleDragObject = function (a, e, i, t, o, n) {

    function l(e, t, n) {
      e.style.setProperty("top", n + "px", "important"), e.style.setProperty(
        "left",
        t + "px",
        "important"
      ), e.style.setProperty("bottom", "auto", "important"), e.style.setProperty(
        "right",
        "auto",
        "important"
      ), e.style.setProperty("margin", "0", "important");
    }

    (customPosition = e()) && (customPosition = JSON.parse(customPosition), l(
      a,
      customPosition.x,
      customPosition.y
    ), n && l(n, customPosition.x, customPosition.y));

    function c(e) {
      return l(a, e.clientX - r.x, e.clientY - r.y), n && l(n, e.clientX - r.x, e.clientY - r.y), cancelEvent(e);
    }

    var s = {}, r = {}, d = function (e) {
      a.isMoving = !1;
      var t = Math.abs(s.x - e.clientX), n = Math.abs(s.y - e.clientY);
      return t < 30 && n < 30 ? o() : i({x: e.clientX - r.x, y: e.clientY - r.y}), removeEvent(
        document,
        "mousemove",
        c
      ), removeEvent(document, "mouseup", d), cancelEvent(e);
    };
    addEvent(a, "mousedown", function (e) {
      if (s.x = e.clientX, s.y = e.clientY, r.x = e.clientX - a.offsetLeft, r.y = e.clientY - a.offsetTop, t(r)) return a.isMoving = !0, addEvent(
        document,
        "mousemove",
        c
      ), addEvent(document, "mouseup", d), cancelEvent(e);
    });
  };

  function handlePhoneButton() {
    var e, t = document.getElementById("newton_callback_phone");
    is_mobile ? is_new_ios ? addEvent(window, "touchstart", mobileTouchStart) : addEvent(t, "click", function () {
      phoneButtonClick();
    }) : default_settings.disable_button_drag
      ? addEvent(t, "click", function () {
        phoneButtonClick();
      })
      : (e = void 0, default_settings.mini_version_enabled && (e = document.getElementById("ncw_compact")), handleDragObject(
        t,
        checkButtonCustomPosition,
        setButtonCustomPosition,
        function () {
          return !0;
        },
        function () {
          phoneButtonClick();
        },
        e
      ));
  }

  var phoneButtonClick = function () {
    var e = document.querySelector("#newton_callback_phone");
    if (hideMiniVersion(), is_mobile && hasClass(e, "opened")) {
      var t = document.getElementById("newton_callback_type_select"),
        e = document.getElementById("newton_callback_department_select");
      return t && hasClass(t, "active") && hideTypeSelect(), void (e && hasClass(
        e,
        "active"
      ) && (callType = !1, hideDepartmentSelect()));
    }
    showForm(), reachGoal("NEWTON_OPEN");
  };

  function checkButtonCustomPosition() {
    return getCookie(NEWTON_CALLBACK.BUTTON_POSITION);
  }

  function checkWrapCustomPosition() {
    return getCookie(NEWTON_CALLBACK.WRAPPER_POSITION);
  }

  function setButtonCustomPosition(e) {
    var t = new Date;
    t.setDate(t.getDate() + 1), setCookie(NEWTON_CALLBACK.BUTTON_POSITION, JSON.stringify(e), {expires: t.toUTCString()});
  }

  function setWrapCustomPosition(e) {
    var t = new Date;
    t.setDate(t.getDate() + 1), setCookie(NEWTON_CALLBACK.WRAPPER_POSITION, JSON.stringify(e), {expires: t.toUTCString()});
  }

  function getPhoneFromForm(form) {
    return serialize(form)['App_Modules_Api_Forms_CallbackForm[phone]'];
  }

  function validateFormMaskedPhone(maskedPhone) {
    var match = maskedPhone.match(maskedPhoneRegex);
    return !!(match && match[0] === maskedPhone);
  }

  function showPhoneError(){
    var errorContainer = document.getElementById('newton_callback_phone_error');
    errorContainer.classList.add('visible');
  }

  function handleForm() {
    var callbackForm = document.getElementById("newton_callback_form");

    addEvent(callbackForm, 'submit', function (event) {
      event.preventDefault && event.preventDefault();

      if (!validateFormMaskedPhone(getPhoneFromForm(event.target))) {
        showPhoneError();
        return;
      }

      disableSubmitButton();
      processForm(event, form_action, showSubmitResult);
    });

    if (default_settings.is_multiwidget && default_settings.multiwidget_application) {
      var applicationForm = document.getElementById('newton_callback_application_form');

      addEvent(applicationForm, 'submit', function (event) {
        processForm(event, application_form_action, showApplicationSubmitResult);
      })
    }
  }

  function handleCloseButtonClick() {
    var e = document.getElementById("newton_callback_close");
    e && (addEvent(e, "click", function () {
      close_button_disabled || hideForm();
    }), e = document.getElementById("newton_callback_dialog_close"), addEvent(e, "click", hideDialog));
  }

  function handleDialogButtonsClick() {
    var e = document.getElementById("newton_callback_dialog_accept");
    addEvent(e, "click", function () {
      hideDialog(!1), showForm({dialog_text: default_settings.dialog_accept_text}), reachGoal("NEWTON_YES");
    });
    e = document.getElementById("newton_callback_dialog_cancel");
    addEvent(e, "click", function () {
      hideDialog(!1), showForm({dialog_text: default_settings.dialog_cancel_text}), reachGoal("NEWTON_NO");
    });
    e = document.getElementById("newton_callback_dialog_forget");
    addEvent(e, "click", function () {
      hideDialog(), setForget(), disableAll();
    });
  }

  function enableShowAtInit() {
    afterLoad = function () {
      checkShowed() && !isMiniVersionAttached() && showForm({
        open_callback: function () {
          reachGoal("NEWTON_DIALOG");
        }
      });
    };
  }

  function enableShowAtNthPage() {
    afterLoad = function () {
      isMiniVersionAttached() || showDialog();
    };
  }

  function disableShowAtInit() {
    afterLoad = null;
  }

  function enableShowAtExit() {
    var e = 1e3 * (10 - (default_settings.current_time - init_time));
    0 < e ? setTimeout(function () {
      addEvent(document, "mousemove", mouseEntringTopCorner);
    }, e) : addEvent(document, "mousemove", mouseEntringTopCorner);
  }

  function mouseEntringTopCorner(e) {
    var t;
    null == topCorner && checkShowed() && !isMiniVersionAttached() && (t = window.innerWidth - exit_one_w, e.clientX > t && e.clientY < exit_one_h && (phoneButton = document.getElementById(
      "newton_callback_phone"), phoneButton.isMoving || (showDialog(), topCorner = setTimeout(function () {
      clearTimeout(topCorner), topCorner = null;
    }, 500))));
  }

  function disableShowAtExit() {
    removeEvent(document.body, "mousemove", mouseEntringTopCorner);
  }

  function enableShowAtTime() {
    var e = 1e3 * (default_settings.appearance_time - (default_settings.current_time - init_time));
    0 < e ? show_timeout_id = setTimeout(function () {
      checkShowed() && !isMiniVersionAttached() && (showDialog(), resetInitTime());
    }, e) : checkShowed() && !isMiniVersionAttached() && (showDialog(), resetInitTime());
  }

  function disableShowAtTime() {
    show_timeout_id = null;
  }

  function disableAll() {
    disableShowAtInit(), disableShowAtExit(), disableShowAtTime();
  }

  function getCookie(e) {
    e = document.cookie.match(new RegExp("(?:^|; )" + e.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, "\\$1") + "=([^;]*)"));
    return e ? decodeURIComponent(e[1]) : void 0;
  }

  function setCookie(e, t, n) {
    var a, i = (n = n || {}).expires;
    "number" == typeof i && i && ((a = new Date).setTime(a.getTime() + 1e3 * i), i = n.expires = a), i && i.toUTCString && (n.expires = i.toUTCString()), n.path = "/";
    var o, l = e + "=" + (t = encodeURIComponent(t));
    for (o in n) {
      l += "; " + o;
      var c = n[o];
      !0 !== c && (l += "=" + c);
    }
    document.cookie = l;
  }

  function deleteCookie(e) {
    setCookie(e, null, {expires: -1});
  }

  function areCookiesEnabled() {
    try {
      document.cookie = "nwtn_cookietest=1";
      var e = -1 !== document.cookie.indexOf("nwtn_cookietest=");
      return document.cookie = "nwtn_cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT", e;
    } catch (e) {
      return !1;
    }
  }

  var reachGoal = function (e) {
    try {
      reachMetrikaGoal(e), reachAnalyticsGoal(e), reachNewtonGoal(e), reachMailGoal(e);
      var t = getParam("onGoal");
      if ("function" == typeof t) try {
        t(e);
      } catch (e) {
        remoteGoalLog(e);
      }
    } catch (e) {
      remoteErrorLog(e, "reachGoal");
    }
  };

  var reachMetrikaGoal = function (e) {
    for (k in e = "NEWTON_DIALOG_CALL" == e ? "NEWTON_CALL" : e, window) if ("yaCounter" == k.substr(
      0,
      9
    ) && window[k].reachGoal) try {
      window[k].reachGoal(e);
    } catch (e) {
      remoteGoalLog(e);
    }
  };

  var reachAnalyticsGoal = function (e) {
    if (e = "NEWTON_DIALOG_CALL" == e ? "NEWTON_CALL" : e, window.hasOwnProperty("pageTracker")) try {
      window.pageTracker._trackEvent(e, "click");
    } catch (e) {
      remoteGoalLog(e);
    } else if (window.hasOwnProperty("ga")) try {
      var t = ga.getAll();
      for (i = 0; i < t.length; i++) t[i].send("event", e, "click");
    } catch (e) {
      remoteGoalLog(e);
    } else if (window.hasOwnProperty("_gaq")) try {
      window._gaq.push(["_trackEvent", e, "click"]);
    } catch (e) {
      remoteGoalLog(e);
    }
  };

  var reachMailGoal = function (e) {
    if (e = "NEWTON_DIALOG_CALL" == e ? "NEWTON_CALL" : e, window.hasOwnProperty("_tmr")) try {
      window._tmr.reachGoal({goal: e});
    } catch (e) {
      remoteGoalLog(e);
    }
  };

  var reachNewtonGoal = function (e) {
    e = goal_url + "?hash=" + newton_callback_id_internal + "&name=" + e + "&x=" + Math.random();
    document.createElement("img").src = e;
  };

  var getPageViews = function () {
    if (!isLocalStorageSupported) return 0;
    var e = window.localStorage.getItem("callback_last_visit"), t = window.localStorage.getItem("callback_pages"),
      n = parseInt(new Date / 1e3);
    e && n - e > default_settings.session_timeout && (t = null), window.localStorage.setItem(
      "callback_last_visit",
      n
    ), t = t ? JSON.parse(t) : [];
    n = location.href.split("/").slice(3).join("/");
    return -1 == t.indexOf(n) && (t.push(n), window.localStorage.setItem(
      "callback_pages",
      JSON.stringify(t)
    )), t.length;
  };

  var resetPageViews = function () {
    isLocalStorageSupported && (window.localStorage.removeItem("callback_last_visit"), window.localStorage.removeItem(
      "callback_pages"));
  };

  function handleFormSelect() {
    var e = document.getElementById(form_name + "_date");
    e && addEvent(e, "change", setHoursSelect), handleFormHoursSelect();
  }

  function handleFormHoursSelect() {
    var e = document.getElementById(form_name + "_hour");
    // e && addEvent(e, "change", setLaterCallTimer), setLaterCallTimer();
    e && addEvent(e, "change", setMinutesSelect), addEvent(e, "change", setLaterCallTimer), handleFormMinutesSelect(), setLaterCallTimer();
  }

  function handleFormMinutesSelect() {
    const element = document.getElementById(form_name + '_minute');

    if (element) {
      addEvent(element, 'change', setLaterCallTimer);
      setLaterCallTimer();
    }
  }

  function setLaterCallTimer() {
    null == countdown_interval_id && (time = getDelayTimer(), document.getElementById("newton_callback_counter").innerHTML = convertMsecs(
      time,
      !0
    ));
  }

  function setActiveCallTimer() {
    null == countdown_interval_id && (document.getElementById("newton_callback_counter").innerHTML = convertMsecs(
      default_settings.timer));
  }

  function getDelayTimer() {
    const hour = document.getElementById(form_name + "_hour");
    const minute = document.getElementById(form_name + "_minute");

    return hour && minute
      ? (getDelayDayTime() + hour.value * 60 * 60 + minute.value * 60 - default_settings.current_time) * 1000 - 1
      : 0;
  }

  function setHoursSelect(e) {
    var t = !1;
    var n = document.getElementById(form_name + "_department_id");

    n && n.value && default_settings.have_departments && (t = n.value);
    t = getHoursSelect({
      departmentId: t,
      value: document.getElementById(form_name + "_date").value,
    });

    document.getElementById(form_name + "_hour").outerHTML = t;

    setMinutesSelect();
    handleFormHoursSelect();
    recreateCustomSelects(document.getElementById("newton_callback_form_text"));
  }

  function setMinutesSelect() {
    const current = new Date(default_settings.current_time * 1000);
    const currentWithoutMinutes = new Date(current.getTime());
    const hourValue = parseInt(document.getElementById(form_name + '_hour').value);
    const selectedDate = new Date(document.getElementById(form_name + '_date').value);

    if (currentWithoutMinutes.getMinutes() > 30) {
      currentWithoutMinutes.setHours(currentWithoutMinutes.getHours() + 1);
    }

    currentWithoutMinutes.setMinutes(0, 0, 0);
    selectedDate.setHours(hourValue);

    const isCurrentHour = currentWithoutMinutes.getTime() === selectedDate.getTime();
    const minute = document.getElementById(form_name + '_minute')
    const formattedDate = selectedDate.toLocaleDateString('en-CA');
    const busySlots = default_settings.departments[5].delay_data.busySlots;

    for (const child of minute.children) {
      child.disabled = (isCurrentHour && parseInt(child.value) < ((current.getMinutes() + 30) % 60 - 15))
        || busySlots[formattedDate]?.[hourValue]?.[child.value];
    }

    const options = Array.from(minute.children);

    if (options.find((item) => item.value === minute.value).disabled) {
      const newActive = options.find((item) => !item.disabled);

      newActive.checked = true;
      minute.value = newActive.value;
    }
  }

  function handleCallBooking() {
    var e = is_new_ios ? "touchend" : "click";
    var t = document.getElementById("newton_callback_type_callback__flat_card");

    if (is_mobile && e && t) {
      addEvent(t, e, function (e) {
        $('.newton_callback_form_title').text('Забронировать');
        callType = "callback";
        showForm();

        return cancelEvent(e);
      });
    }
  }

  function handleCallTypeSelect() {
    var e, t;
    is_mobile && (e = is_new_ios
      ? "touchend"
      : "click", (t = document.getElementById("newton_callback_type_callback")) && addEvent(t, e, function (e) {
      return hideTypeSelect(!0), callType = "callback", showForm(), cancelEvent(e);
    }), (t = document.querySelector(".newton_callback_type_direct__select-direct-call-region")) && addEvent(
      t,
      e,
      function (e) {
        return hideTypeSelect(!0), callType = "direct", showForm(), cancelEvent(e);
      }
    ));
  }

  function handleDepartmentSelect() {
    var e, t;
    if (!default_settings.have_departments || is_mobile || getSingleNonMobileDepartment() || (a = document.getElementById(
      "newton_callback_departments_list"), e = document.getElementById("newton_callback_departments_link"), t = document.getElementById(
      "newton_callback_departments"), handleCustomSelect(
      e,
      t,
      a,
      setDepartment
    )), !is_mobile && default_settings.have_departments && default_settings.is_multiwidget && default_settings.multiwidget_application && !getSingleNonMobileDepartment() && (a = document.getElementById(
      "newton_callback_application_departments_list"), e = document.getElementById(
      "newton_callback_application_departments_link"), t = document.getElementById(
      "newton_callback_application_departments"), handleCustomSelect(e, t, a, function (e) {
      var t = e.rel;
      document.getElementById(application_form_name + "_department_id").value = t;
      t = e.innerHTML;
      document.getElementById("newton_callback_application_departments_link").innerHTML = t, document.getElementById(
        "newton_callback_application_departments_link_dummy").innerHTML = t;
      for (var n = getSelectLinks(document.getElementById("newton_callback_application_departments_list")), a = 0; a < n.length; a++) removeClass(
        n[a],
        "newton_selected"
      );
      addClass(e, "newton_selected");
    })), default_settings.have_departments && is_mobile) {
      var n = "click";
      is_new_ios && (n = "touchend");
      for (var a = document.getElementById("newton_callback_department_select")
        .getElementsByTagName("a"), i = 0; i < a.length; i++) addEvent(a[i], n, function (e) {
        return setDepartment(this), cancelEvent(e);
      });
    }
  }

  function getSingleNonMobileDepartment() {
    var e, t = !1, n = 0;
    for (e in default_settings.departments) !checkShowDepartment(e) || !checkActiveDepartment(e) && default_settings.disable_delayed_calls || (t = e, n++);
    return !(1 < n) && t;
  }

  function getSingleMobileCallbackDepartment() {
    var e, t = !1, n = 0;
    for (e in default_settings.departments) 0 == default_settings.departments[e].only_on_mobile && (t = e, n++);
    return !(1 < n) && t;
  }

  function getDepartmentLinks() {
    return document.getElementById("newton_callback_departments_list").getElementsByTagName("a");
  }

  function setDepartment(e) {
    var t = e.rel, n = document.getElementById(form_name + "_department_id");
    if (n.value = t, is_mobile) hideDepartmentSelect(), showForm({departmentId: t}); else {
      var a = document.getElementById("newton_callback_form_text");
      if (checkActive({departmentId: t})) a.innerHTML = default_settings.form_text, document.getElementById(
        "newton_callback_active_delay_wrap").style.display = "block", setActiveCallTimer(); else {
        if (!checkLaterCall()) return void (n.value = "");
        document.getElementById("newton_callback_active_delay_wrap").style.display = "none", a.innerHTML = (laterCall
          ? getActiveDelayText
          : getDelayText)({departmentId: t}), handleFormSelect();
      }
      customSelects(a);
      a = e.innerHTML;
      document.getElementById("newton_callback_departments_link").innerHTML = a, document.getElementById(
        "newton_callback_departments_link_dummy").innerHTML = a;
      for (var i = getDepartmentLinks(), o = 0; o < i.length; o++) removeClass(i[o], "newton_selected");
      addClass(e, "newton_selected");
    }
  }

  function getDepartmentLink(e) {
    for (var t = getDepartmentLinks(), n = 0; n < t.length; n++) if (t[n].rel == e) return t[n];
    return !1;
  }

  function getDelayTextMobile(e) {
    var t, e = "departmentId" in (e = e || {}) && e.departmentId;
    if (e) return default_settings.departments[e].delay_text_mobile;
    for (t in default_settings.departments) return default_settings.departments[t].delay_text_mobile;
  }

  function getDelayTextMobileSuccess(e) {
    var t = document.querySelectorAll(".call-later-date-hour-select__item"), n = "", a = "";
    return t.forEach(function (e) {
      "date" == e.getAttribute("data-type") && (n = e.innerHTML.toLowerCase()), "hours" == e.getAttribute("data-type") && (a = e.innerHTML);
    }), "Мы перезвоним<br />" + n + " в " + a;
  }

  function getDelayText(e) {
    var t, e = "departmentId" in (e = e || {}) && e.departmentId;
    if (e) return default_settings.departments[e].delay_text;
    for (t in default_settings.departments) if (checkShowDepartment(t)) return default_settings.departments[t].delay_text;
  }

  function getDelayDayTime() {
    var e;
    var t = document.getElementById(form_name + "_department_id");
    var n = document.getElementById(form_name + "_date");

    if (n) {
      if (t && t.value) {
        return default_settings.departments[t.value].delay_data.delay_date_time[n.value];
      }

      for (e in default_settings.departments) {
        if (checkShowDepartment(e)) {
          return default_settings.departments[e].delay_data.delay_date_time[n.value];
        }
      }
    }
  }

  function getActiveDelayText(e) {
    var t, e = "departmentId" in (e = e || {}) && e.departmentId;
    if (e) return default_settings.departments[e].active_delay_text;
    for (t in default_settings.departments) if (checkShowDepartment(t)) return default_settings.departments[t].active_delay_text;
  }

  function getHoursSelect(e) {
    var t, n = "departmentId" in (e = e || {}) && e.departmentId, a = "value" in e && e.value;
    if (n) return default_settings.departments[n].delay_data.hours[a];

    for (t in default_settings.departments) if (checkShowDepartment(t)) return default_settings.departments[t].delay_data.hours[a];
  }

  function showDepartmentSelect() {
    addEvent(window, "touchend", departmentSelectClickClose), hidePhoneButton(), hideNonDirectDepartments();
    var e = document.getElementById("newton_callback_department_select");
    document.querySelector(".direct-call-region-wrapper__form-title").innerText = "direct" == callType
      ? "Позвонить"
      : "Заказать звонок", e.style.setProperty(
      "display",
      "flex",
      "important"
    ), e.classList.add("active"), e.parentNode.classList.add("active"), handleSelectSize();
  }

  function hideDepartmentSelect() {
    removeEvent(window, "touchend", departmentSelectClickClose), showPhoneButton(), showNonDirectDepartments();
    var e = document.getElementById("newton_callback_department_select");
    e.style.setProperty("display", "none", "important"), e.classList.remove("active"), e.parentNode.classList.remove(
      "active"), e.style.removeProperty("transition"), e.style.removeProperty("bottom"), unhandleSelectSize(), onClose();
  }

  function showTypeSelect() {
    addEvent(window, "touchend", typeSelectClickClose), hidePhoneButton();
    var e = document.getElementById("newton_callback_type_select");
    document.getElementById("newton_callback_phone");
    is_mobile ? setTimeout(function () {
      e.classList.add("active");
    }, 110) : e.classList.add("active"), e.style.display = "block", handleTypeSize(), setTranslateForBtn();
  }

  function hideTypeSelect() {
    removeEvent(window, "touchend", typeSelectClickClose), showPhoneButton();
    var e = document.getElementById("newton_callback_type_select");
    e.style.display = "none", e.style.removeProperty("transition"), e.style.removeProperty("bottom"), unhandleTypeSize(), onClose();
  }

  function hideNonDirectDepartments() {
    if ("direct" == callType) for (var e = document.getElementById("newton_callback_department_select")
      .getElementsByTagName("a"), t = 0; t < e.length; t++) e[t].rel && !checkActiveDepartment(e[t].rel) && (e[t].parentNode.style.display = "none");
    if ("callback" == callType) for (e = document.getElementById("newton_callback_department_select")
      .getElementsByTagName("a"), t = 0; t < e.length; t++) e[t].rel && 1 == default_settings.departments[e[t].rel].only_on_mobile && (e[t].parentNode.style.display = "none");
  }

  function getKeywords(e) {
    if (e && "keywords" in e) return e.keywords;
    e = getMetaContent("newton:keywords");
    return e || "";
  }

  function showNonDirectDepartments() {
    if ("direct" == callType || "callback" == callType) for (var e = document.getElementById(
      "newton_callback_department_select")
      .getElementsByTagName("a"), t = 0; t < e.length; t++) e[t].parentNode.style.display = "block";
  }

  function getLandingPageReferrer() {
    return isLocalStorageSupported ? window.localStorage.getItem("callback_landing_page_referrer") : "";
  }

  function getLandingPageUrl() {
    return isLocalStorageSupported ? window.localStorage.getItem("callback_landing_page_url") : "";
  }

  function getMetrikaClientId() {
    if (null == metrika_client_id || !metrika_client_id.length) for (k in window) if ("yaCounter" == k.substr(
      0,
      9
    ) && (window[k].getClientID, 1)) try {
      metrika_client_id = window[k].getClientID();
      break;
    } catch (e) {
    }
    return metrika_client_id;
  }

  function getGAClientId() {
    return null != ga_client_id && ga_client_id.length || !window.hasOwnProperty("ga") || ga(function (e) {
      var t = ga.getAll();
      if (0 < t.length) {
        for (var n = {}, a = 0; a < t.length; a++) n[t[a].get("trackingId")] = t[a].get("clientId");
        ga_client_id = JSON.stringify(n);
      }
    }), ga_client_id;
  }

  function handleActiveDelay() {
    var e;
    is_mobile || (e = document.getElementById("newton_callback_active_delay_link"), addEvent(
      e,
      "click",
      setActiveLaterCall
    ));
  }

  function setDirectCall() {
    var e = document.getElementById(form_name + "_department_id"), t = !(!e || !e.value) && e.value;
    hideForm(!1);
    e = document.getElementById("newton_sms_notice");
    e && (e.style.display = "none"), showForm({ departmentId: t, forceCallback: is_mobile });
  }

  function setActiveLaterCall() {
    var e = document.getElementById(form_name + "_department_id"), t = !(!e || !e.value) && e.value;
    hideForm(!1), laterCall = !0;
    e = document.getElementById("newton_sms_notice");
    e && (e.style.display = "block"), showForm({
      departmentId: t,
      dialog_text: getActiveDelayText({departmentId: t}),
      forceCallback: is_mobile,
    });
  }

  function handleMultiwidget() {
    var e;
    !is_mobile && default_settings.is_multiwidget && ((e = document.getElementById("newton_callback_tab_call")) && addEvent(
      e,
      "click",
      function () {
        setDirectCall(), setMultiwidgetTabSelected("newton_callback_tab_call");
      }
    ), (e = document.getElementById("newton_callback_tab_delay")) && addEvent(e, "click", function () {
      setActiveLaterCall(), setMultiwidgetTabSelected("newton_callback_tab_delay"), reachGoal(
        "NEWTON_DELAYED_CALL_CLICK");
    }), (e = document.getElementById("newton_callback_tab_application")) && addEvent(e, "click", function () {
      document.getElementById("newton_callback_form").style.display = "none", closeChat(), hideBanner(), showAgreement(), enableApplicationSubmitButton(), document.getElementById(
        "newton_callback_application_form").style.display = "block", setMultiwidgetTabSelected(
        "newton_callback_tab_application"), reachGoal("NEWTON_APPLICATION_CLICK");
    }), (e = document.getElementById("newton_callback_tab_chat")) && addEvent(e, "click", function () {
      openChat(), reachGoal("NEWTON_CONS");
    }), (e = document.getElementById("newton_callback_tab_ask")) && addEvent(e, "click", function () {
      reachGoal("NEWTON_CONS");
    }), (e = document.getElementById("newton_callback_tab_banner")) && addEvent(e, "click", function () {
      var e = document.getElementById("newton_callback_form");
      e && (e.style.display = "none"), (e = document.getElementById("newton_callback_application_form")) && (e.style.display = "none"), closeChat(), hideAgreement(), setMultiwidgetTabSelected(
        "newton_callback_tab_banner"), showBanner();
    }));
  }

  function openChat(e) {
    null == e && (e = !0), hideBanner(), hideAgreement(), document.getElementById("newton_callback_form").style.display = "none", default_settings.multiwidget_application && (document.getElementById(
      "newton_callback_application_form").style.display = "none");
    var t, n = document.getElementById("newton_chat");
    n.src || (t = {hash: newton_callback_id_internal}, isVkVerion() && (t.vk = 1), n.src = chat_url + "?" + buildParams(
      "",
      addSystemQueryData(t)
    ).join("&")), document.getElementById("newton_chat").style.display = "inline-block", setMultiwidgetTabSelected(
      "newton_callback_tab_chat"), e && (removeEvent(
      window,
      "click",
      backgroundClickClose
    ), e = (t = new Date).getTime(), e += 36e5, t.setTime(e), setCookie(
      "n_chat_opnd",
      "1",
      {expires: t.toUTCString()}
    ));
  }

  function closeChat() {
    default_settings.chat_enabled && (chat_iframe = document.getElementById("newton_chat"), chat_iframe && ("none" != chat_iframe.style.display && addEvent(
      window,
      "click",
      backgroundClickClose
    ), chat_iframe.style.display = "none"));
  }

  function setMultiwidgetTabSelected(e) {
    var t = document.getElementById("newton_callback_tabs");
    if (t) for (var n = t.getElementsByTagName("a"), a = 0; a < n.length; a++) removeClass(n[a], "newton_active");
    e = document.getElementById(e);
    e && addClass(e, "newton_active");
  }

  function customSelects(e) {
    if (default_settings.is_multiwidget) for (var t = e.getElementsByTagName("select"), n = 0; n < t.length; n++) {
      var a = document.createElement("div");
      addClass(a, "newton_callback_dates_block"), "App_Modules_Api_Forms_CallbackForm_date" == t[n].id && addClass(
        a,
        "select_day"
      ), "App_Modules_Api_Forms_CallbackForm_hour" == t[n].id && addClass(a, "select_time");
      var i = document.createElement("div");
      addClass(i, "newton_callback_dates");
      var o = document.createElement("div");
      addClass(o, "newton_callback_dates_link_wrap");
      var l = document.createElement("a");
      l.href = "javascript:void(0);", addClass(l, "newton_callback_dates_link");
      var c = document.createElement("ul");
      addClass(c, "newton_callback_dates_list");
      for (var s = t[n].id, r = t[n].getElementsByTagName("option"), d = 0; d < r.length; d++) {
        var _ = document.createElement("li"), m = document.createElement("a");
        m.href = "javascript:void(0);", m.rel = r[d].value, m.innerHTML = r[d].innerHTML, m.ncs_link = l, m.ncs_ul = c, m.ncs_selectId = s, m.disabled = r[d].disabled, r[d].disabled && addClass(
          m,
          "newton_callback_dates_list_disabled"
        ), _.appendChild(m), c.appendChild(_), r[d].selected && (l.innerHTML = r[d].innerHTML);
      }
      o.appendChild(l);
      var u = document.createElement("div");
      addClass(u, "newton_callback_dates_link_wrap");
      var p = document.createElement("a");
      p.href = "javascript:void(0);", addClass(
        p,
        "newton_callback_dates_link newton_callback_dates_link_dummy"
      ), p.innerHTML = l.innerHTML, u.appendChild(p), i.appendChild(o), i.appendChild(c), a.appendChild(u), a.appendChild(
        i), t[n].parentNode.insertBefore(a, t[n]), handleCustomSelect(l, i, c, function (e) {
        if (e.disabled) return !1;
        var t = e.ncs_link, n = e.ncs_ul, a = e.ncs_selectId, i = e.rel, a = document.getElementById(a);
        a.value = i;
        i = e.innerHTML;
        t.innerHTML = i;
        for (var o = getSelectLinks(n), l = 0; l < o.length; l++) removeClass(o[l], "newton_selected");
        addClass(e, "newton_selected"), fireEvent(a, "change");
      });
    }
  }

  function openCustomSelect(e, t) {
    e.style.display = "block", addClass(t, "newton_d_opened"), closeCustomSelectEvent(e, t);
  }

  function closeCustomSelectEvent(t, n) {
    addEvent(window, "click", function (e) {
      isDescendant(n, e.target) || (closeCustomSelect(t, n), removeEvent(this, "click", arguments.callee));
    });
  }

  function closeCustomSelect(e, t) {
    e.style.display = "none", removeClass(t, "newton_d_opened");
  }

  function getSelectLinks(e) {
    return e.getElementsByTagName("a");
  }

  function getDirectPhone(e) {
    if (calltracking_direct_phone) return calltracking_direct_phone;
    var t, e = "departmentId" in (e = e || {}) && e.departmentId;
    if (e) return default_settings.departments[e].direct_phone;
    for (t in default_settings.departments) return default_settings.departments[t].direct_phone;
  }

  function disableSubmitButton() {
    var e = document.getElementById("newton_callback_submit_button");
    e && (e.disabled = "disabled");
  }

  function enableSubmitButton() {
    var e = document.getElementById("newton_callback_submit_button");
    e && (e.disabled = !1);
  }

  function disableApplicationSubmitButton() {
    var e = document.getElementById("newton_callback_application_submit_button");
    e && (e.disabled = "disabled");
  }

  function enableApplicationSubmitButton() {
    var e = document.getElementById("newton_callback_application_submit_button");
    e && (e.disabled = !1);
  }

  function showBanner() {
    var e = document.getElementById("newton_callback_banner");
    e && (e.style.display = "block");
  }

  function hideBanner() {
    var e = document.getElementById("newton_callback_banner");
    e && (e.style.display = "none");
  }

  function showAgreement() {
    var e = document.getElementById("newton_agreement_input");
    e && (e.checked = !0);
    e = document.getElementById("newton_agreement");
    e && (e.style.display = "block");
  }

  function hideAgreement() {
    var e = document.getElementById("newton_agreement");
    e && (e.style.display = "none");
  }

  function handleAgreement() {
    var e = document.getElementById("newton_agreement_input");
    e && addEvent(e, "change", function () {
      this.checked
        ? (enableSubmitButton(), enableApplicationSubmitButton())
        : (disableSubmitButton(), disableApplicationSubmitButton());
    });
  }

  function destroy() {
    if (initialized) {
      disableSettingsUpdate(), hideForm(), hideDialog(), cleanAllEvents();
      var e, t = [
        "newton_callback_css",
        "newton_callback_phone",
        "newton_callback_dialog_wrap",
        "newton_callback_wrap",
        "newton_callback_wrap_mobile",
        "newton_callback_department_select_mobile",
        "newton_callback_type_select_mobile"
      ];
      for (e in t) {
        var n = t[e], n = document.getElementById(n);
        n && n.parentNode.removeChild(n);
      }
      settingsLoaded = initialized = !1;
    }
  }

  function remoteRefererLog(e) {
    8 & default_settings.enable_log && remoteLog("referrer", e);
  }

  function remoteLocalStorageLog() {
    4 & default_settings.enable_log && remoteLog("localStorage", "LocalStorage doesn`t supported.");
  }

  function remoteGoalLog(e) {
    2 & default_settings.enable_log && remoteLog("goal", e.name + (e.message ? " : " + e.message : ""));
  }

  function remoteErrorLog(e, t, n) {
    if (!default_settings.enable_log) {
      console.warn(e);
    }
    1 & default_settings.enable_log && remoteLog("error", t + " > " + e.name + (e.message ? " : " + e.message : ""), n);
  }

  function remoteLog(e, t, n) {
    var a = {
      "CallbackLogEntry[hash]": newton_callback_id_internal,
      "CallbackLogEntry[type]": e,
      "CallbackLogEntry[message]": t
    };
    n && (a["CallbackLogEntry[additional]"] = n);
    try {
      ajax.post(log_url, a);
    } catch (e) {
    }
  }

  function isVkVerion() {
    return "undefined" != typeof newton_vk && newton_vk;
  }

  function pullLocalStorageCookie() {
    return isLocalStorageSupported && !!(cookie_local_storage = window.localStorage.getItem(cookie_local_storage_key));
  }

  function setLocalStorageCookie(e) {
    cookie_local_storage = e, isLocalStorageSupported && window.localStorage.setItem(
      cookie_local_storage_key,
      cookie_local_storage
    );
  }

  function checkCookieMissing() {
    is_browser_cookie_blocked && isLocalStorageSupported && !pullLocalStorageCookie() ? ajax.get(
      cookie_url,
      {},
      function (t) {
        try {
          setLocalStorageCookie(JSON.parse(t)), checkEnv();
        } catch (e) {
          remoteErrorLog(e, "checkCookieMissing", typeof t + " " + t.length + " " + t), checkEnv();
        }
      }
    ) : checkEnv();
  }

  function checkEnv() {
    "undefined" != typeof newton_auction_lot_id
      ? (newton_auction_lot_id_internal = newton_auction_lot_id, initJson(initAuction))
      : "undefined" == typeof newton_callback_id && "undefined" == typeof newton_calltracking_id || ("undefined" != typeof newton_callback_id && (newton_callback_id_internal = newton_callback_id), "undefined" != typeof newton_calltracking_id && (newton_calltracking_id_internal = newton_calltracking_id), initJson(
      startWidget));
  }

  function initAuction(e) {
    var t = 1 == getParam("landing_site") ? 1 : 0;
    ajax.post(auction_settings_url, {uuids: newton_auction_lot_id_internal, is_landing_site: t}, function (t) {
      try {
        var e = JSON.parse(t), n = !1;
        "auction_lot_id" in e && (newton_auction_lot_id_internal = e.auction_lot_id), "callback_id" in e && (newton_callback_id_internal = e.callback_id, n = !0), "calltracking_id" in e && (newton_calltracking_id_internal = e.calltracking_id, n = !0), "is_related_page" in e && (auction_is_related_page = e.is_related_page), "callback_srf" in e && 1 == getParam(
          "landing_site") && (n = !1), "auction_lot_name" in e && (auction_lot_name = e.auction_lot_name), n
          ? startWidget()
          : "function" == typeof (n = getParam("onAuctionReject")) && n();
      } catch (e) {
        return remoteErrorLog(e, "initAuction", typeof t + " " + t.length + " " + t), initializing = !1;
      }
    });
  }

  function initJson(e) {
    if ('undefined' === typeof JSON) {
      var t = document.createElement('script');

      t.setAttribute('type', 'text/javascript');
      t.setAttribute('src', '/scripts/json.min.js');
      document.getElementsByTagName('head')[0].appendChild(t);
      t.onload = e;
    } else {
      e();
    }
  }

  function startWidget() {
    getSettings(), init_interval = setInterval(function () {
      "interactive" != document.readyState && "complete" != document.readyState || !settingsLoaded || init();
    }, 100);
  }

  function applyMarquiz() {
    "undefined" != typeof Marquiz && (Marquiz.addParam(
      "newton.landing_page_referrer",
      getLandingPageReferrer()
    ), Marquiz.addParam("newton.landing_page_url", getLandingPageUrl()), Marquiz.addParam(
      "newton.referer",
      window.location.href
    ), Marquiz.addParam("newton.fingerprint", fingerprint), Marquiz.addParam(
      "newton.referrer_keywords",
      getKeywords()
    ), Marquiz.addParam("newton.ga_client_id", getGAClientId()), Marquiz.addParam(
      "newton.metrika_client_id",
      getMetrikaClientId()
    ), "undefined" != typeof newton_local_cookie && Marquiz.addParam(
      "newton.local_cookie",
      newton_local_cookie
    ), Marquiz.addParam("newton.user_agent", navigator.userAgent));
  }

  var recreateCustomSelects = function (e) {
    for (var t = e.getElementsByClassName("newton_callback_dates_block"), n = new Array, a = 0; a < t.length; a++) n.push(
      t[a]);
    for (a = 0; a < n.length; a++) e.removeChild(n[a]);
    customSelects(e);
  };

  var handleCustomSelect = function (e, t, n, a) {
    addEvent(e, "click", function (e) {
      null != countdown_interval_id || missed_block || ("none" == window.getComputedStyle(n).getPropertyValue("display")
        ? openCustomSelect
        : closeCustomSelect)(n, t);
    });
    for (var i = getSelectLinks(n), o = 0; o < i.length; o++) addEvent(i[o], "click", function (e) {
      !1 !== a(this) && closeCustomSelect(n, t), e.preventDefault(), e.stopPropagation();
    });
  };

  var getCalltrackingData = function () {
    var e = {hash: default_settings.calltracking_dynamic_hash};
    return "undefined" != typeof newton_auction_lot_id_internal && (e.newton_auction_lot_id = newton_auction_lot_id_internal, e.auction_is_related_page = auction_is_related_page), e.metrika_client_id = getMetrikaClientId(), e.ga_client_id = getGAClientId(), e.landing_page_referrer = getLandingPageReferrer(), e.landing_page_url = getLandingPageUrl(), e.fingerprint = fingerprint, void 0 !== externalId && (e.external_id = externalId), void 0 !== externalData && (e.external_data = externalData), e;
  };

  // endregion LIBRARY

  // region PARAMS
  var is_mobile = isMobile();
  var captions = {
    ru: {
      form_input_placeholder: 'Введите ваш телефон',
      form_submit_button: 'Жду звонка!',
      form_missed_question: 'Не успели перезвонить?',
      form_missed_result: 'Спасибо, ваш отзыв учтен.',
      form_button_forget: 'Больше не показывать это сообщение',
      dialog_button_yes: 'Да',
      dialog_button_no: 'Нет',
      dialog_button_forget: 'Больше не показывать',
    },
  };
  var masks = {
    ru: ['+7 (___) ___-__-__'],
  };
  var prefix = {ru: '+7'};
  var is_chrome_android = isChromeAndroid();
  var is_browser_cookie_blocked = !0;
  var is_new_ios = !1;
  var afterLoad = null;
  var current_timestamp = (new Date()).getTime();
  var tf = new Date(current_timestamp);
  var tt = new Date(current_timestamp);
  var server_time = null;
  var init_time = null;
  var host = SETL_CHAT_BASE_URI;
  var default_settings = {
    callback: 0,
    appearance_init: 0,
    appearance_exit: 1,
    appearance_time: 0,
    appearance_page_views: 0,
    current_time: current_timestamp,
    css: host + "/css/callback.css",
    form_header: "Профессиональная консультация",
    form_text: "Хотите мы перезвоним вам за 60 секунд <br/>и предложим варианты, недоступные на сайте?",
    form_text_mobile: "",
    form_time_text: "за 60 секунд",
    dialog_text: "Вы нашли то, что искали на сайте?",
    dialog_accept_text: "Давайте мы перезвоним вам за 60 секунд и предложим условия, недоступные на сайте?",
    dialog_cancel_text: "Давайте мы перезвоним вам за 60 секунд и предложим условия, недоступные на сайте?",
    is_active: 0,
    timer: 59999,
    show_phone_button: 1,
    show_once_day: 1,
    session_timeout: 1800,
    lang: "ru",
    css_phone_button_color: "",
    css_button_icons_color: "",
    additional_form_html: null,
    additional_dialog_html: null,
    additional_javascript: null,
    phone_button_html: "",
    show_on_mobile: 0,
    dialog_enabled: 0,
    disable_delayed_calls: 0,
    silent_mode: 0,
    css_phone_button_text_color: "",
    phone_button_text: "",
    calltracking: 0,
    enable_log: 0,
    callback_enabled: 0,
    chat_enabled: 0,
    chat_active: 0
  };
  var settings_url = host + "/api/callback/settings";
  var auction_settings_url = host + "/api/auction/settings";
  var auction_check_url = host + "/api/auction/settings/check";
  var settings_update_interval = 12e4;
  var settings_update_interval_id = null;
  var metrika_client_id = "";
  var wait_for_metrika_interval = 2e3;
  var wait_for_metrika_attempts = 5;
  var wait_for_metrika_interval_id = null;
  var ga_client_id = "";
  var wait_for_ga_interval = 2e3;
  var wait_for_ga_attempts = 5;
  var wait_for_ga_interval_id = null;
  var show_timeout_id = null;
  var countdown_interval = 33;
  var countdown_interval_id = null;
  var exit_one_w = 200;
  var exit_one_h = 100;
  var form_name = "App_Modules_Api_Forms_CallbackForm";
  var form_action = host + "/api/callback/create";
  var overflow = "visible";
  var timer_msecs = default_settings.timer;
  var phone_format = "+7(   )       ";
  var phone_input_id = form_name + "_phone";
  var missed_action = host + "/api/callback/missed";
  var initViewport;
  var keyboard_opened = !1;
  var close_button_disabled = !1;
  var initialized = !1;
  var formErrorElements = [];
  var laterCall = !1;
  var fingerprint = null;
  var closeFormTimeout = null;
  var missed_block = !1;
  var application_form_action = host + "/api/callback/application";
  var application_form_name = "ApplicationForm";
  var application_phone_input_id = application_form_name + "_phone";
  var callType = !1;
  var applicationFormErrorElements = [];
  var applicationFormErrorMessages = [];
  var backgroundShowed = !1;
  var successCall = !1;
  var goal_url = host + "/api/callback/goal";
  var log_url = host + "/api/callback/log";
  var formFromDialog = !1;
  var chat_url = host + "/api/callback/chat";
  var dynamic_url = host + "/api/callback/calltrackingNumber";
  var init_interval = null;
  var auction_is_related_page = !1;
  var direct_phone_dynamic = null;
  var externalId;
  var externalData;
  var calltrackingProlongCount = 4;
  var cookie_url = host + "/api/callback/cookie";
  var cookie_local_storage;
  var cookie_local_storage_key = "nvid";
  var auction_lot_name;
  var calltracking_direct_phone = null;
  var slideTimeout = null;
  var animationFrame = 0;
  var captchaId;
  var mvOutTimeout;
  var miniVersionMessageInfoText;
  var correct_timeout = null;
  var cssLoaded = !1;
  var settingsLoaded = !1;
  var isAndroid = -1 < navigator.userAgent.indexOf("Android "), button_timeout = null;
  var topCorner = null;
  var cookies_enabled = areCookiesEnabled();
  var interval;
  var callRequestProcess = !1;
  var applicationRequestProcess = !1;
  var initializing = !1;
  var isLocalStorageSupported = false;
  // endregion PARAMS

  // region INIT

  if (isVkVerion()) {
    is_mobile = !1;
  }

  tf.setHours('00', '00');
  tt.setHours('23', '00');

  try {
    isLocalStorageSupported = Boolean('localStorage' in window && null !== window.localStorage);
  } catch (e) {
  }

  window.addEventListener('resize', function () {
    setTranslateForBtn();
    correctWidgetSizeFunc();
  });

  setTimeout(checkCookieMissing, 0);

  // endregion INIT

  // region API

  this.externalCall = function (e) {
    var t, n = "delay_call" in (e = e || {}) && e.delay_call;
    initialized && (t = {}, "keywords" in e && (t.keywords = e.keywords), n
      ? (laterCall = !0, t.dialog_text = getActiveDelayText(), showForm(t), default_settings.is_multiwidget && setMultiwidgetTabSelected(
        "newton_callback_tab_delay"))
      : showForm(t));
  };

  this.callDCN = function (e) {
    initialized && showForm({dcn: e});
  };

  this.setExternalId = function (e) {
    externalId = e;
    var t = document.getElementById(form_name + "_external_id");
    t && (t.value = e);
  };

  this.setExternalData = function (e) {
    externalData = e;
    var t = document.getElementById(form_name + "_external_data");
    t && (t.value = e);
  };

  this.sendCallRequest = function (t) {
    if (!callRequestProcess) {
      callRequestProcess = !0, t = t || {};
      var e = {
        "App_Modules_Api_Forms_CallbackForm[landing_page_referrer]": getLandingPageReferrer(),
        "App_Modules_Api_Forms_CallbackForm[landing_page_url]": getLandingPageUrl(),
        "App_Modules_Api_Forms_CallbackForm[fingerprint]": fingerprint,
        "App_Modules_Api_Forms_CallbackForm[referer]": window.location.href,
        "App_Modules_Api_Forms_CallbackForm[hash]": newton_callback_id_internal,
        "App_Modules_Api_Forms_CallbackForm[phone]": t.client_phone,
        "App_Modules_Api_Forms_CallbackForm[referrer_keywords]": getKeywords(t),
        "App_Modules_Api_Forms_CallbackForm[metrika_client_id]": getMetrikaClientId(),
        "App_Modules_Api_Forms_CallbackForm[ga_client_id]": getGAClientId()
      };
      if ("undefined" != typeof newton_local_cookie && (e["App_Modules_Api_Forms_CallbackForm[local_cookie]"] = newton_local_cookie), void 0 !== t.date && (e["App_Modules_Api_Forms_CallbackForm[date]"] = t.date), void 0 !== t.hour && (e["App_Modules_Api_Forms_CallbackForm[hour]"] = t.hour), void 0 !== t.department_id) e["App_Modules_Api_Forms_CallbackForm[department_id]"] = t.department_id; else if (default_settings.have_departments) for (var n in default_settings.departments) {
        e["App_Modules_Api_Forms_CallbackForm[department_id]"] = n;
        break;
      }
      "undefined" != typeof newton_auction_lot_id_internal && (e["App_Modules_Api_Forms_CallbackForm[auction_lot_id]"] = newton_auction_lot_id_internal, e["App_Modules_Api_Forms_CallbackForm[auction_is_related_page]"] = auction_is_related_page
        ? 1
        : 0), void 0 !== externalId && (e["App_Modules_Api_Forms_CallbackForm[external_id]"] = externalId), void 0 !== externalData && (e["App_Modules_Api_Forms_CallbackForm[external_data]"] = externalData), void 0 !== t.tags && (e["App_Modules_Api_Forms_CallbackForm[tags]"] = t.tags), submitRequest(
        form_action,
        e,
        function (e) {
          callRequestProcess = !1, 1 == e && reachGoal("NEWTON_CALL"), void 0 !== t.callback && t.callback(
            1 == e,
            1 != e ? JSON.parse(e) : void 0
          );
        }
      );
    }
  };

  this.sendApplicationRequest = function (t) {
    if (!applicationRequestProcess) {
      applicationRequestProcess = !0, t = t || {};
      var e = {
        "ApplicationForm[landing_page_referrer]": getLandingPageReferrer(),
        "ApplicationForm[landing_page_url]": getLandingPageUrl(),
        "ApplicationForm[fingerprint]": fingerprint,
        "ApplicationForm[referer]": window.location.href,
        "ApplicationForm[hash]": newton_callback_id_internal,
        "ApplicationForm[phone]": t.client_phone,
        "ApplicationForm[metrika_client_id]": getMetrikaClientId(),
        "ApplicationForm[ga_client_id]": getGAClientId()
      };
      if ("undefined" != typeof newton_local_cookie && (e["ApplicationForm[local_cookie]"] = newton_local_cookie), void 0 !== t.department_id) e["ApplicationForm[department_id]"] = t.department_id; else if (default_settings.have_departments) for (var n in default_settings.departments) {
        e["ApplicationForm[department_id]"] = n;
        break;
      }
      void 0 !== t.name && (e["ApplicationForm[name]"] = t.name), void 0 !== t.email && (e["ApplicationForm[email]"] = t.email), void 0 !== t.comment && (e["ApplicationForm[comment]"] = t.comment), void 0 !== t.tags && (e["ApplicationForm[tags]"] = t.tags), submitRequest(
        application_form_action,
        e,
        function (e) {
          applicationRequestProcess = !1, 1 == e && reachGoal("NEWTON_APPLICATION_SENT"), void 0 !== t.callback && t.callback(
            1 == e,
            1 != e ? JSON.parse(e) : void 0
          );
        }
      );
    }
  };

  this.getDelayData = function () {
    var e, t = {};
    for (e in default_settings.departments) t[e] = default_settings.departments[e].delay_data.pure_data;
    return t;
  };

  this.isDirectCall = function () {
    return checkActive();
  };

  this.isCalltrackingAvailable = function (t) {
    var e;
    "function" == typeof t && (default_settings.calltracking_dynamic_hash
      ? ((e = getCalltrackingData()).dummy = !0, ajax.post(dynamic_url, e, function (e) {
        t(!!parseInt(e));
      }))
      : t(!1));
  };

  this.getCalltrackingNumber = function (t) {
    var e;
    "function" == typeof t && default_settings.calltracking_dynamic_hash && (e = getCalltrackingData(), ajax.post(
      dynamic_url,
      e,
      function (e) {
        t(e);
      }
    ));
  };

  this.checkLotIds = function (e, n) {
    "function" == typeof n && ajax.post(auction_check_url, {uuids: e}, function (t) {
      try {
        var e = JSON.parse(t);
        n(e);
      } catch (e) {
        return remoteErrorLog(e, "Check Auction", typeof t + " " + t.length + " " + t), !1;
      }
    });
  };

  this.captcha = function () {
    renderCaptcha();
  };

  this.applyCalltracking = function () {
    applyCalltracking();
  };

  this.init = function (e) {
    e = e || {};
    initializing || (initializing = !0, destroy(), newton_auction_lot_id = "newton_auction_lot_id" in e
      ? e.newton_auction_lot_id
      : void 0, newton_callback_id = "newton_callback_id" in e
      ? e.newton_callback_id
      : void 0, newton_calltracking_id = "newton_calltracking_id" in e ? e.newton_calltracking_id : void 0, checkEnv());
  };

  this.normalizePhone = function (e) {
    return "7" != (e = e.replace(/\D/g, ""))[0] && 10 == e.length ? e = "+7" + e : 11 == e.length && "8" == e[0]
      ? e = "+7" + e.substring(1)
      : 11 == e.length && "7" == e[0] && (e = "+" + e), e;
  };

  // endregion API
}

!function () {
  if (!(!1 in window)) {
    try {
      if (null === window.localStorage) return;
    } catch (e) {
      return;
    }
    var e;
    document.referrer
      ? ((e = document.createElement("a")).href = document.referrer, e.hostname !== location.hostname && (window.localStorage.setItem(
        "callback_landing_page_referrer",
        document.referrer
      ), window.localStorage.setItem("callback_landing_page_url", window.location.href)))
      : (window.localStorage.setItem("callback_landing_page_referrer", "direct"), window.localStorage.setItem(
        "callback_landing_page_url",
        window.location.href
      ));
  }
}(), "eyenewtonLoader" in window && void 0 !== window.eyenewtonLoader || (eyenewtonLoader = new EyenewtonLoader), "newtonCallback" in window && void 0 !== window.newtonCallback || (newtonCallback = new NewtonCallback);
