PageSourceSearch

https://fibot-widget.fibabanka.com.tr/js/widget/cbot-fiballm-generator.js

js fibabanka.com.tr collected 2026-09-24 22:51:23 UTC 403,418 bytes, 10,597 lines download raw bytes

1
2        var answerisnotdefined_message = 'Beklenmeyen bir hata ile karşılaştım. Daha sonra tekrar dener misiniz?'
3        var botlanguage = "tr"
4        var clients = {};
5        var CLIENT = "fiballm"; 
6        var CBOT_CUSTOM_CSS_IS_ACTIVE = true;
7        setTimeout(() => {
8            var cssFileName = !minify_css ? 'cbot-' + CLIENT + "-custom" : 'cbot-' + CLIENT + "-custom.min";
9            addCssFile(cssFileName /* , Math.random() */);
10            var interval = setInterval(function () {
11                    const isCssLoaded = Array.from(document.styleSheets).some(
12                    (styleSheet) =>
13                        styleSheet.href && styleSheet.href.includes(cssFileName)
14                    );
15                    if (window.jQuery && isCssLoaded) {
16                        clearInterval(interval);
17                        clients = {
18 "opening_delay": 0,
19 "theme": "flat",
20 "title": "Fi’bot’a Sor ",
21 "color": "#00008b",
22 "title_font_color": "#FFFFFF",
23 "welcome_message": "Merhaba, ben yenilenen Fi&rsquo;bot🐰🤖<br />Yapay zeka desteğiyle artık daha hızlı ve akıllıyım. Size nasıl yardımcı olabilirim?<br /><br />İşlenen kişisel verilerinize ilişkin Aydınlatma Metni&rsquo;ni incelemek için <a href=\"https://www.fibabanka.com.tr/docs/default-source/aydinlatma-metni/chatbot-aydinlatma-metni.pdf?sfvrsn=66abc41f_4\" target=\"_blank\"><strong>tıklayınız</strong></a>.",
24 "link_list": {},
25 "widget_urls": [
26  {
27   "url": "",
28   "delay": 0
29  }
30 ],
31 "disable_user_chat_input_button_component": false,
32 "file_upload_mimetypes": [],
33 "clear_after_close_page": {
34  "DEFAULT": false,
35  "MOBILE": false,
36  "FACEBOOK": false
37 },
38 "clear_after_close_bot": {
39  "DEFAULT": false,
40  "MOBILE": false,
41  "FACEBOOK": false
42 },
43 "dont_clear_after_another_page": {
44  "DEFAULT": false,
45  "MOBILE": false,
46  "FACEBOOK": false
47 },
48 "messages_sending_time": {
49  "DEFAULT": false,
50  "MOBILE": false,
51  "FACEBOOK": false
52 },
53 "leave_livechat_after_close_bot": {
54  "DEFAULT": false,
55  "MOBILE": false,
56  "FACEBOOK": false
57 },
58 "close_widget_after_leave_livechat": {
59  "DEFAULT": false,
60  "MOBILE": false,
61  "FACEBOOK": false
62 },
63 "avatar": "https://fibot-widget.fibabanka.com.tr/firm-fiba/assets/img/fibot.png",
64 "icon": "https://fibot-widget.fibabanka.com.tr/firm-fiba/assets/img/fibot.png",
65 "help_text": "<div class=\"chatbot__sidebar-header\"><div class=\"cbot-help-back-icon\" style=\"background:url(https://fibot-widget.fibabanka.com.tr/firm-fiba/assets/img/cbot-fiba-back-mark.svg);background-size:15px;background-position:center;background-repeat:no-repeat;width:23px;height:23px;background-size:22px 22px;position: absolute;left: 21px;top: 20px;\">&nbsp;</div><div class=\"chatbot__sidebar-logo\"><img src=\"https://fibot-widget.fibabanka.com.tr/firm-fiba/assets/img/fibot.png\" /><br />&nbsp;</div></div><div class=\"chatbot__sidebar-content\"><div class=\"chatbot__sidebar-text-with-icon\"><div class=\"chatbot__sidebar-text\"><p>Fi&#39;bot, yapay zekâ desteğiyle <a href=\"https://fibabanka.com.tr\" style=\"color: #006cb7; text-decoration: underline;\" target=\"_blank\">fibabanka.com.tr</a>&#39;de bilgileri ve raporları analiz edilerek sorularınıza cevap arar ve bu bilgileri özetleyerek yanıt oluşturur. Fi&#39;bot tarafından oluşturulan yanıtlar herhangi bir tavsiye ya da yönlendirme niteliğinde olmadığından <a href=\"https://fibabanka.com.tr\" style=\"color: #006cb7; text-decoration: underline;\" target=\"_blank\">fibabanka.com.tr</a>&#39;yi ziyaret ederek dilediğiniz zaman detaylara ulaşabilirsiniz.</p></div></div></div>",
66 "custom_css_is_active": true,
67 "trigger_messages": "",
68 "feedback": {},
69 "user_timeout": {
70  "DEFAULT": {}
71 },
72 "livechat_timeout": {
73  "DEFAULT": {}
74 },
75 "close_bot_toggle": false,
76 "close_bot_message": "Size daha iyi hizmet verebilmek için kısa bir çalışma yapıyoruz.",
77 "chat_avatar": "",
78 "chat_agent_avatar": "",
79 "custom_css_url": "https://fibot-widget.fibabanka.com.tr/css/cbot-fiballm-custom.css",
80 "bot_name": "fiballm"
81};
82                        var head = document.getElementsByTagName('head')[0];
83                        var s = document.createElement("script");
84                        s.type = "text/javascript";
85                        var i = 0;
86                        cbot_init(clients.icon, clients.icon, clients.color + '', clients.title, clients.color + ' !important', 'fiballm', undefined, clients.opening_delay, clients.welcome_message, clients.help_text, (clients.trigger_messages || []), true, 100, 1500);
87                }
88            }, 100);
89        }, 400);
90
91/**
92 * CBot Widget
93 * */
94
95var LIVE_CHAT = "undefined";
96LIVE_CHAT = LIVE_CHAT == "true";
97
98var USER_CONTROL_IS_ACTIVE = "true";
99var SEND_ENDCHAT = "false" == "true";
100
101var CSP_BLOCK_UNSAFE_INLINE = "false" == "true";
102var cbot_voice_bot_is_active=false
103var tts_is_active=false
104var mute_tts = false;
105var chartjs_is_active=false
106var is_interactive_response_active=false
107var interactive_actions=undefined
108var with_credentials = "false" == "true";
109var powered_by_cbot = "undefined" == "true";
110var animated_button = "undefined" == "true";
111var minify_css = "false" == "true";
112var dark_mode_is_active = "undefined" == "true";
113var stream_response = null;
114
115USER_CONTROL_IS_ACTIVE = USER_CONTROL_IS_ACTIVE == "true";
116var SOCKET_CONNECT_ON_START = "false" == "true";
117
118var rootAddress = "https://fibot-widget.fibabanka.com.tr";
119var staticAddress = "https://fibot-widget.fibabanka.com.tr";
120var soc_connect = "https://socketservisadresi";
121var vc_url = "";
122
123var WIDGET_TIMEOUT_MESSAGE = "Beklenmeyen bir hata ile karşılaştım. Sorunu biraz daha farklılaştırıp tekrar dener misin?"
124var WIDGET_NETWORK_ERROR_MESSAGE = "Beklenmeyen bir hata ile karşılaştım. Sorunu biraz daha farklılaştırıp tekrar dener misin?"
125
126var user_chat_input_states = {
127  "DISABLED": "DISABLED",
128  "ENABLED": "ENABLED"
129}
130
131var user_chat_input_state = user_chat_input_states.ENABLED;
132
133var conversations = [];
134var kvkk_is_active = "false" == "true";
135var kvkk_status = null;
136var KVKK_STATUS_ENUM = {
137  TOBEASKED: "TOBEASKED",
138  ASKED: "ASKED",
139  DECLINED: "DECLINED",
140  ACCEPTED: "ACCEPTED",
141  UNHANDLED: "UNHANDLED",
142  NOT_SET: "NOT_SET"
143}
144if (kvkk_is_active) {
145  kvkk_status = KVKK_STATUS_ENUM.TOBEASKED;
146} else {
147  kvkk_status = KVKK_STATUS_ENUM.NOT_SET;
148}
149var is_kvkk_progress_done = false;
150var sendMessage = () => { }
151
152
153var emojies = [":)", ":-)", ":D", ":-D", ":-(", ":()", ":(", "<3", ":>", "0_0", "0_o", "o_o", "o_0", ":p", ";)"];
154var emojiIcons = ["😊", "😊", "😂", "😂", "😞", "😮", "😞", "❤️", "😊", "👀", "👀", "👀", "👀", "😋", "😉"];
155
156var dialogCloseSurveyShowed = false; // Popup yönetmek için
157var isWidgetOpen = false;
158var refresh_button_clicked = false;
159
160var ratingSelector = 0;
161var ratingGroup = 0;
162
163var firstLoad = false;
164var newMsgCount = 0;
165var hasSurveyShowAsPopUp = false;
166var closing_popup_is_showing = false;
167var hasSurveyFeedback = false;
168var sentSurveyFeedback = false;
169var cbotInputKeyboardClicked = false;
170var cbotKeyboardScrollInitialized = false;
171var cbotShowMessageArea = "show";
172var version;
173var agent_name;
174var lang_vars;
175var show_agent_name = "false" == "true";
176var before_agent_name = " ";
177
178var timeoutNotifySecPeriod = 0;
179
180var data_jquery = (getParameterFromScript("data-jquery") || "true") == "true";
181var data_owl = getParameterFromScript("data-owl");
182var data_owl_margin = getParameterFromScript("data-owl-margin");
183var widget_lang = getParameterFromScript("widget-lang") || "tr";
184var scriptVars = getQueryVariable(getParameterFromScript("src"));
185var data_clear_session = getParameterFromScript("data-clear-session");
186
187if (scriptVars.v) {
188  version = scriptVars.v;
189}
190
191
192/* ATTACHMENTS */
193var bool_attachments = false;
194
195var welcomeMessage = ""
196var welcomeMessageSent = false;
197var data_full_page;
198var elCbotDialogRegularButton;
199var elCbotDialog;
200var previousURL = localStorage.getItem(getDynamicLSName("currentURL"));
201var currentURL = window.location.href;
202localStorage.setItem(getDynamicLSName("currentURL"), currentURL);
203var cbot_messages_sending_time = false;
204var currentTime;
205var hours;
206var minutes;
207var user_timeout;
208var data_owl_variable = "false"
209var minimize_icon_is_active = "false"
210var cbot_lottie_icon_activation = false
211var cbot_lottie;
212var handlePopupTimeouts = [];
213var is_schedule;
214var visitor_countable;
215var IS_TYPING = false;
216var stopped_by_customer = false;
217var agent_display_name = "";
218
219var data_static_url = getParameterFromScript("data-static-url");
220if (data_static_url) {
221  staticAddress = data_static_url;
222}
223
224/* THEMEING */
225
226let default_messages;
227
228function setDefaultMessages() {
229  lang_vars = {
230    "LIVECHAT_CLOSE_MESSAGE": lang_vars?.LIVECHAT_CLOSE_MESSAGE || "Görüşme sonlandırıldı.",
231    "LIVECHAT_CUSTOMER_CLOSE_MESSAGE": lang_vars?.LIVECHAT_CUSTOMER_CLOSE_MESSAGE || "Görüşme sonlandırdınız.",
232    "LANGVARS_LCHAT_CLOSE_BTN_TEXT": "Görüşmeyi sonlandır",
233    "LANGVARS_CLOSE_TEXT_MESSAGE": clients.close_text_message,
234    "LANGVARS_MINIMIZE_TEXT_MESSAGE": clients.minimize_text_message,
235    "LANGVARS_TTS_MUTE_MESSAGE": clients.tts_mute_message,
236    "LANGVARS_REFRESH_BUTTON_TOOLTIP_MESSAGE": clients.refresh_button_tooltip_message,
237    "LANGVARS_HELP_TEXT_MESSAGE": clients.help_text_message,
238    "LANGVARS_HELP_TEXT_CONTENT": null,
239    "LANGVARS_PLACEHOLDER_MESSAGE": clients.placeholder_message,
240    "LANGVARS_TYPING_MESSAGE": null,
241    "LANGVARS_USER_TIMEOUT_MESSAGE": null,
242    "LANGVARS_WIDGET_TITLE": null,
243    "LANGVARS_USER_TIMEOUT_BANNER_MESSAGE": null,
244    "LANGVARS_HELP_TEXT_TITLE": null,
245  };
246  default_messages = {
247    "tr": {
248      TYPING: lang_vars.LANGVARS_TYPING_MESSAGE || "Yazıyor"
249    },
250    "en": {
251      TYPING: lang_vars.LANGVARS_TYPING_MESSAGE || "Typing"
252    },
253    "ar": {
254      TYPING: lang_vars.LANGVARS_TYPING_MESSAGE || "الكتابة"
255    }
256  }
257}
258
259setDefaultMessages();
260
261var user_message_bubble_color = "";
262var user_message_text_color = "";
263var bot_message_text_title_color = "";
264var bot_message_text_color = "";
265var bot_message_bubble_color = "";
266var bot_button_background_color = "";
267var bot_button_text_color = "";
268var cbotRightBeforeFocused = false;
269var voiceRecordingEnabled = false;
270var recognition;
271var recorder;
272var login_user_display_name;
273var voice_bot_button_option=false;
274var voice_bot_button_push_to_talk=false;
275var voice_assistant=false;
276var voice_button_tooltip="";
277var welcomeDoc;
278let audioElement = undefined;
279
280const lang_map = {
281  "en": "en-EN",
282  "tr": "tr-TR",
283  "ar": "ar-AR",
284  "es": "es-ES"
285}
286
287var triple_button_css = "";
288var triple_button_class = "";
289var suggestion_button_style = "";
290var text_button_class = "";
291var button_payload;
292const browser_engine = detectBrowser();
293
294/* do not comment it */
295window.dataLayer = window.dataLayer || [];
296
297if (!String.prototype.includes) {
298  String.prototype.includes = function (val) {
299    return this.indexOf(val) > -1;
300  }
301}
302
303if (!Array.prototype.find) {
304  Array.prototype.find = function (predicate) {
305    if (this == null) {
306      throw new TypeError('Array.prototype.find called on null or undefined');
307    }
308    if (typeof predicate !== 'function') {
309      throw new TypeError('predicate must be a function');
310    }
311    var list = Object(this);
312    var length = list.length >>> 0;
313    var thisArg = arguments[1];
314    var value;
315
316    for (var i = 0; i < length; i++) {
317      value = list[i];
318      if (predicate.call(thisArg, value, i, list)) {
319        return value;
320      }
321    }
322    return undefined;
323  };
324}
325
326setTimeout(function () {
327  if (data_jquery && !window.jQuery) {
328    var jqueryScript = document.createElement('script');
329    jqueryScript.type = "text/javascript";
330    jqueryScript.src = staticAddress + "/js/jquery-3.7.1.min.js" + "?client=" + CLIENT;
331    jqueryScript.async = true;
332    document.getElementsByTagName('head')[0].insertBefore(jqueryScript, document.getElementsByTagName('head')[0].firstChild);
333  }
334
335
336
337  if (data_owl && data_owl_variable == "false") {
338    var interval = null;
339
340    interval = setInterval(function () {
341      if (window.$) {
342        clearInterval(interval)
343        loadDataOwl()
344      }
345    }, 200)
346  }
347}, 500);
348
349window.addEventListener("CBOT_LOAD", function () {
350  if (data_jquery && !window.jQuery) {
351    var jqueryScript = document.createElement('script');
352    jqueryScript.type = "text/javascript";
353    jqueryScript.src = staticAddress + "/js/jquery-3.7.1.min.js" + "?client=" + CLIENT;
354    jqueryScript.async = true;
355    document.getElementsByTagName('head')[0].insertBefore(jqueryScript, document.getElementsByTagName('head')[0].firstChild);
356  }
357  if (data_owl && data_owl_variable == "CBOT_LOAD") {
358    loadDataOwl()
359    addCssFile("owl.carousel.min", version)
360  }
361});
362
363window.addEventListener('storage', (event) => {
364  // console.log('event_key:', event.key, 'oldVal:', event.oldValue, 'newVal:', event.newValue);
365  switch (event.key) {
366    case getDynamicLSName("isLive"):
367      isLive = getisLiveFLS();
368      break;
369    case getDynamicLSName("isLiveAgentTyped"):
370      is_liveagent_typed = getIsLiveAgentTypedFLS();
371      break;
372    case getDynamicLSName("firstmessagesent"):
373      firstMessageSent = (getFromLocalStorage(getDynamicLSName("firstmessagesent")) === "true" || getFromLocalStorage(getDynamicLSName("firstmessagesent")) === "false") ? JSON.parse(getFromLocalStorage(getDynamicLSName("firstmessagesent"))) : firstMessageSent;
374      break;
375    case getDynamicLSName("userid"):
376      cbotUserId = getFromLocalStorage(getDynamicLSName("userid"));
377      break;
378    case getDynamicLSName("sessionId"):
379      cbotSessionId = getFromLocalStorage(getDynamicLSName("sessionId"));
380      break;
381    default:
382      break;
383  }
384});
385
386function getFromLocalStorage(key, currentValue) {
387  if (key === getDynamicLSName("userid") || key === getDynamicLSName("sessionId")) {
388    if (
389      isLive &&
390      socket &&
391      localStorage[getDynamicLSName("userid")] !== 'null' &&
392      localStorage[getDynamicLSName("sessionId")] !== 'null' &&
393      (localStorage[getDynamicLSName("userid")] !== cbotUserId || (localStorage[getDynamicLSName("userid")] === cbotUserId && !cbotSessionId))
394    ) {
395      socket.emit('new_client', { userId: localStorage[getDynamicLSName("userid")], sessionId: localStorage[getDynamicLSName("sessionId")] });
396    }
397  }
398  try {
399    return localStorage[key];
400  } catch (err) {
401    // console.log("[getFromLocalStorage] ERR", err.message);
402    return currentValue;
403  }
404}
405
406function toggleJitsiMeet() {
407  if ($('#cbot-meet iframe').length == 0 && $('.cbot-start-meeting').text() != 'Görüntülü görüşme talebi iletildi. Yanıt bekleniyor... ⏱️') {
408    // Agent'a görüntülü görüşme talebi ilet.
409    socket_widget('Sizinle görüntülü görüşmek istiyorum.');
410    appendMessageToDialogBox('Sizinle görüntülü görüşmek istiyorum.', 'cbot-self');
411    // Buton stilini değiştir.
412    $('.cbot-start-meeting').text('Görüntülü görüşme talebi iletildi. Yanıt bekleniyor... ⏱️');
413    $('.cbot-start-meeting').css('background', '#32a1b4');
414  } else if ($('.cbot-start-meeting').text() == 'Görüntülü görüşme talebi iletildi. Yanıt bekleniyor... ⏱️') {
415    // do nothing
416  } else {
417    closeMiniWeb();
418    $('#cbot-meet iframe').remove();
419    // Buton stilini değiştir.
420    $('.cbot-start-meeting').text('Görüntülü Görüşme Talep Et 🖥️');
421    $('.cbot-start-meeting').css('background', '#18bc39');
422  }
423}
424
425function forceCloseJitsiMeet() {
426  if ($('#cbot-meet iframe').length == 1) {
427    closeMiniWeb();
428    $('#cbot-meet iframe').remove();
429    // Buton stilini değiştir.
430    $('.cbot-start-meeting').text('Görüntülü Görüşme Talep Et 🖥️');
431    $('.cbot-start-meeting').css('background', '#18bc39');
432  }
433}
434
435function addAvatarLetters(username) {
436  let nameSplit = username.toUpperCase().split(' ');
437  if (nameSplit.length == 1) {
438    initials = nameSplit[0] ? nameSplit[0].charAt(0) : '?';
439  } else {
440    initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
441  }
442  $('#cbot-chat').append('<style nonce="8IBTHwOdqNKAWeKl7plt8g==">.cbot-self::after{content:"' + initials + '"}</style>')
443}
444
445
446function runGAScript(UAId) {
447  var gaScript = document.createElement('script');
448  gaScript.type = "text/javascript";
449  gaScript.async = true;
450  gaScript.src = "https://www.googletagmanager.com/gtag/js?id=" + UAId;
451  document.getElementsByTagName('head')[0].insertBefore(gaScript, document.getElementsByTagName('head')[0].firstChild);
452  window.dataLayer = window.dataLayer || [];
453  cbotgtag('js', new Date());
454
455  cbotgtag('config', UAId);
456}
457
458
459function cbotgtag() { window.dataLayer.push(arguments); }
460
461function numberToString(data) {
462  if (data && typeof data == "number") {
463    return data.toString();
464  }
465  if (!data || data == null || data == undefined) {
466    return "";
467  }
468  return data;
469}
470
471function sendUrlsToGA(text) {
472  text = numberToString(text)
473  var urls = (text || "").match(/(http[^\s'"]*)/g);
474  for (var j = 0; urls && j < urls.length; j++) {
475    cbotgtag('event', 'cbot', {
476      'event_category': 'cbot-link',
477      'event_action': urls[j],
478      'event_label': urls[j]
479    });
480  }
481}
482
483function sendSurveyViewToGA(surveyGtaViewData) {
484  cbotgtag('event', 'cbot', {
485    'event_category': 'cbot-survey-view',
486    'event_action': surveyGtaViewData.survey_type, // Anket tipi
487    'event_label': surveyGtaViewData.survey_name // Anket adı
488  });
489}
490
491function sendSurveyResultToGA(surveyGtaResultData) {
492  cbotgtag('event', 'cbot', {
493    'event_category': 'cbot-survey-result',
494    'event_action': surveyGtaResultData.survey_result, // Anket sonucu
495    'event_label': surveyGtaResultData.survey_name // Anket adı
496  });
497}
498
499function clickTheURLs(el) {
500  var url = el.getAttribute('href');
501  // console.log("clickTheURLs", url);
502  cbotgtag('event', 'cbot', {
503    'event_category': 'cbot-link',
504    'event_action': "click",
505    'event_label': url
506  })
507}
508
509var FIRST_LIVE_MESSAGE = false;
510var livechatStopSendMessageFired = false;
511
512/* if (LIVE_CHAT) {
513    var socketIO = document.createElement('script');
514    socketIO.type = "text/javascript";
515    socketIO.src = staticAddress + "/js/socket.io.js";
516    document.getElementsByTagName('head')[0].insertBefore(socketIO, document.getElementsByTagName('head')[0].firstChild);
517} */
518
519var cbotUserId;
520var CHANNEL = "WIDGET";
521
522var cbotSessionId;
523var trigger_messages_count = 0;
524var trigger_messages;
525var lastMessageReceiveDate = null;
526var firstMessageSent = false;
527var surveyTimeout, sentSurvey = false,
528  showedSurvey = null
529var surveyInterval, lastRequestTime, isSurveyShowed = false;
530var exitSurvey = null;
531
532var cbot_config = {};
533var intents = [];
534var isOpen = false;
535var interval;
536var ua = navigator.userAgent;
537var iOS = /iPad|iPhone|iPod/.test(ua);
538var iOS11 = /OS 11(_[0-3])*/.test(ua);
539var isIE = /MSIE|Trident/.test(ua);
540var loginId;
541var focookie;
542var socket;
543var $;
544var data_vip;
545var data_livechat;
546var data_user;
547var data_do_not_preload_load_font;
548var data_script_qs = {};
549var queryStringVars = {};
550var data_user_fls;
551var data_cdn_url;
552var data_function;
553var storageCount = 0;
554var cbot_custom_positioning = {}
555var interactive_recommends;
556var ia_display_popup_state;
557var ia_open_widget_state;
558var ia_take_attention_state;
559var ia_take_attention_state_timer;
560var cbot_dynamic_id;
561var sendCategory = ''
562var cbotIsMobile = {
563  Android: function () {
564    return navigator.userAgent.match(/Android/i);
565  },
566  BlackBerry: function () {
567    return navigator.userAgent.match(/BlackBerry/i);
568  },
569  iOS: function () {
570    return navigator.userAgent.match(/iPhone|iPad|iPod/i);
571  },
572  Opera: function () {
573    return navigator.userAgent.match(/Opera Mini/i);
574  },
575  Windows: function () {
576    return navigator.userAgent.match(/IEMobile/i) || navigator.userAgent.match(/WPDesktop/i);
577  },
578  any: function () {
579    return (cbotIsMobile.Android() || cbotIsMobile.BlackBerry() || cbotIsMobile.iOS() || cbotIsMobile.Opera() || cbotIsMobile.Windows());
580  }
581};
582
583function cbotFocus(element) {
584  if (!cbotIsMobile.Android()) {
585    element.focus();
586  }
587}
588
589CHANNEL = getParameterFromScript("data-channel");
590if (!CHANNEL && cbotIsMobile.any()) // kanal ayarı set edilmemiş ise mobil olabilir
591  CHANNEL = "MOBILE"
592
593if (!CHANNEL)
594  CHANNEL = "WIDGET";
595
596
597function cbot_init(robotImageURL, dialogImageURL, dialogButtonColor, dialogTitle, chooseButtonColor, client, justLink, time, welcomeMessageParam, helpText, trigger_messages, scrollProp, scrollTop, inputMaxLen, dataOpen) {
598  setDefaultMessages()
599  if (isIE) return;
600  welcomeMessage = welcomeMessageParam;
601  // let scrollTopForScroll = $(window).scrollTop();
602  // $(window).scroll(function () {
603  //     if (scrollTopForScroll != $(window).scrollTop() && cbotIsMobile.any()) {
604  //         scrollTopForScroll = $(window).scrollTop();
605  //         if (cbotKeyboardScrollInitialized) {
606  //             cbotKeyboardScrollInitialized = false;
607  //             $("#cbot-form-message").blur();
608  //         }
609  //     }
610  // });
611
612
613
614  // $(window).scroll(function(e){ e.preventDefault()});
615
616  stream_response = clients.stream_response || false;
617  dialogTitle = dialogTitle /*  || "Cbot" */;
618  user_message_bubble_color = clients.user_message_bubble_color ? "background-color: " + clients.user_message_bubble_color + ";" : "";
619  user_message_text_color = clients.user_message_text_color ? "color: " + clients.user_message_text_color + ";" : "";
620  bot_message_bubble_color = clients.bot_message_bubble_color ? "background-color: " + clients.bot_message_bubble_color + ";" : "";
621  bot_message_text_title_color = clients.bot_message_text_title_color ? "color: " + clients.bot_message_text_title_color + ";" : "";
622  bot_message_text_color = clients.bot_message_text_color ? "color: " + clients.bot_message_text_color + ";" : "";
623  bot_button_background_color = clients.bot_button_background_color ? "background-color: " + clients.bot_button_background_color + ";" : "";
624  bot_button_text_color = clients.bot_button_text_color ? "color: " + clients.bot_button_text_color + ";" : "";
625  clients.remotestorage_is_active = clients.remotestorage_is_active && !isIE;
626  if (clients.remotestorage_is_active) {
627    appendLocalStorageIFrame(rootAddress + "/localstorage" + "?client=" + CLIENT, function () {
628      getVarsFromLocalStorageIFrame(client);
629    });
630  }
631  if (clients.lottie_icon_activation) {
632    loadLottieLibrary(clients.lottie_icon_url);
633  }
634  chatEndNotifier();
635  interval = setInterval(function () {
636    if ((!clients.remotestorage_is_active || !xdLocalStorage.checkIFrameLocalStorage() || storageCount >= 5) && window.jQuery) {
637      if (typeof $ !== "function") $ = window.jQuery;
638      var openWidget = true;
639      var dataOpen = checkLastMessageDate(client) && getFirstMessageSentFLS(client);
640      if (clients.widget_url_activation) {
641        var activeUrl = checkURLs(clients.widget_urls);
642        if (activeUrl && activeUrl.url && activeUrl.url.length && !dataOpen) {
643          time = activeUrl.delay || time;
644        } else if (!dataOpen) {
645          openWidget = false; // URL'ler arasında yok, widget çıkmayacak.
646        }
647      }
648      if (clients.chat_avatar_activation) {
649        var cbot_other_icon = $('<style nonce="8IBTHwOdqNKAWeKl7plt8g==">.cbot-other:before { content: "";width: 35px;height: 35px;position: absolute;left: 16px;border: 1px solid #DCDCDC;border-radius: 24px;background-image: url(../img/cbot-chat-icon.svg?client=' + CLIENT + ');background-repeat: no-repeat;background-size: 100% 100%;background-position-x: center;background-position-y: center;} .cbot-chat li {display:flex; padding: 0 20px; position: relative;} .cbot-other .cbot-msg {margin-left: 44px;margin-top: 2px;}</style>');
650        $('head').append(cbot_other_icon);
651
652        if (clients.chat_avatar) {
653          let custom_cbot_other_icon = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">.cbot-other:before { content: "";width: 35px;height: 35px;position: absolute;left: 16px;top: 0;border: 1px solid #DCDCDC;border-radius: 24px;display: flex;justify-content: center;align-items: center;background-image: url(${clients.chat_avatar});background-repeat: no-repeat;background-position-x: center;background-position-y: center;}</style>`);
654          $('head').append(custom_cbot_other_icon);
655        }
656
657      }
658      if (openWidget) {
659        init(robotImageURL, dialogImageURL, dialogButtonColor, dialogTitle, chooseButtonColor, client, justLink, time, welcomeMessage, helpText, trigger_messages, scrollProp, scrollTop, inputMaxLen, dataOpen);
660      }
661      clearInterval(interval);
662      interval = null;
663    } else { }
664  }, 100);
665
666}
667
668function loadParticles() {
669  var jqueryScript = document.createElement('script');
670  jqueryScript.type = "text/javascript";
671  jqueryScript.src = staticAddress + "/js/particles.min.js";
672  jqueryScript.async = true;
673  document.getElementsByTagName('head')[0].insertBefore(jqueryScript, document.getElementsByTagName('head')[0].firstChild);
674}
675
676async function loadOrt() {
677  return new Promise((resolve, reject) => {
678    var ortScript = document.createElement('script');
679    ortScript.type = "text/javascript";
680    ortScript.src = staticAddress + "/js/ort.js";
681    ortScript.onload = () => {
682      // Wait a bit for the library to initialize and configure ONNX Runtime v1.14.0
683      setTimeout(() => {
684        try {
685          if (typeof window.ort !== 'undefined') {
686            // Configure ONNX Runtime v1.14.0 to use local WASM files instead of CDN
687            if (window.ort.env && window.ort.env.wasm) {
688              window.ort.env.wasm.wasmPaths = staticAddress + "/js/";
689              window.ort.env.wasm.simd = true;
690              if (window.ort.env.logLevel !== undefined) {
691                window.ort.env.logLevel = 'error';
692              }
693            }
694            // console.log('ONNX Runtime v1.14.0 configured with local paths');
695            resolve();
696          } else {
697            reject(new Error('ONNX Runtime failed to load'));
698          }
699        } catch (error) {
700          reject(error);
701        }
702      }, 100);
703    };
704    ortScript.onerror = (error) => reject(new Error('Failed to load ONNX Runtime script'));
705    document.getElementsByTagName('head')[0].appendChild(ortScript);
706  });
707}
708
709async function loadVad() {
710  return new Promise((resolve, reject) => {
711    var vadScript = document.createElement('script');
712    vadScript.type = "text/javascript";
713    vadScript.src = staticAddress + "/js/vad-bundle.min.js";
714    vadScript.onload = resolve;
715    vadScript.onerror = (error) => reject(new Error('Failed to load VAD script'));
716    document.getElementsByTagName('head')[0].appendChild(vadScript);
717  });
718}
719
720// Helper function to check if speech features are enabled
721function isSpeechEnabled() {
722  return (cbot_voice_bot_is_active == "true" || cbot_voice_bot_is_active === true) &&
723    (tts_is_active == "true" || tts_is_active === true) || voice_assistant;
724}
725
726// Load scripts in the correct order - only when TTS and STT are both active
727async function loadScripts() {
728  if (isSpeechEnabled()) {
729    try {
730      loadParticles(); // This can load independently
731      // console.log('Loading ONNX Runtime...');
732      await loadOrt();    // Wait for ONNX Runtime to load and configure first
733      // console.log('ONNX Runtime loaded, loading VAD...');
734      await loadVad();    // Then load VAD
735      // console.log('All scripts loaded successfully');
736    } catch (error) {
737      console.error('Failed to load scripts:', error);
738    }
739  }
740}
741
742// Only call loadScripts if both TTS and STT are active
743if (isSpeechEnabled()) {
744  loadScripts();
745}
746
747
748function waitForVAD() {
749  if (!isSpeechEnabled()) {
750    return Promise.resolve();
751  }
752
753  return new Promise((resolve) => {
754    const loaderInterval = setInterval(() => {
755      if (typeof vad !== 'undefined') {
756        clearInterval(loaderInterval);
757        resolve();
758      }
759    }, 100);
760  });
761}
762
763let isUserSpeaking = false;
764let SILENCE_DURATION = 1000; // ms
765let PRE_BUFFER_ARRAY = [];
766let PRE_BUFFER_CHUNK_COUNT = 5;
767let USERS_SPEECH_ARRAY = [];
768let showMicEnergyAnimation = true;
769let isPlayingAudio = false;
770let VAD;
771let speechEndTimeout;
772
773// Push-to-talk için yeni değişkenler
774let isPushToTalkActive = false;
775let pushToTalkStarted = false;
776let pushToTalkMediaRecorder = null;
777let pushToTalkAudioChunks = [];
778let pushToTalkAnimationInterval = null;
779
780async function startVoiceDetection() {
781  if (!isSpeechEnabled()) {
782    return;
783  }
784
785  try {
786    await waitForVAD();
787    if (!VAD) {
788      VAD = await vad.MicVAD.new({
789        workletURL: staticAddress + "/js/vad.worklet.bundle.min.js",
790        onSpeechStart: async () => {
791          // console.log("speech started");
792          isUserSpeaking = true;
793          clearTimeout(speechEndTimeout);
794        },
795        onSpeechEnd: () => {
796          // console.log("speech ended");
797          speechEndTimeout = setTimeout(() => {
798            userMicrophoneVolumeEnergy(0);
799            isUserSpeaking = false;
800            if (!isPlayingAudio && isSpeechViewMicButtonOpen) {
801              sendBase64EncodedAudioAsMessage();
802            }
803          }, SILENCE_DURATION);
804        },
805        onVADMisfire: () => {
806          // console.log("vad misfire - starting silence timeout");
807        },
808        onFrameProcessed: (frame) => {
809          // console.log("VAD frame:", frame);
810        },
811      });
812
813      VAD.start();
814
815      // Update sample rate from VAD's audio context
816      if (VAD.audioContext) {
817        currentSampleRate = VAD.audioContext.sampleRate;
818        // console.log("VAD Audio Context Sample Rate:", currentSampleRate);
819      }
820
821      // VAD'ın internal audio stream'ine erişim için
822      if (VAD.audioNodeVAD && VAD.audioNodeVAD.audioWorkletNode) {
823        // AudioWorkletNode'dan audio verilerini almak için
824        VAD.audioNodeVAD.audioWorkletNode.port.onmessage = (event) => {
825          if (event.data.type === 'audio') {
826            // Raw audio chunks buradan gelir
827            console.log("Raw audio chunk from VAD:", event.data.audio);
828            handleRawAudioFromVAD(event.data.audio);
829          }
830        };
831      }
832
833      // Alternatif: VAD'ın source node'undan audio almak
834      if (VAD.stream) {
835        connectToVADStream(VAD.stream);
836      }
837    }
838  } catch (error) {
839    console.error("VAD error:", error);
840  }
841}
842
843
844function connectToVADStream(stream) {
845  // console.log("Connecting to VAD stream for audio chunks");
846
847  try {
848    const audioContext = VAD.audioContext;
849
850    // Update sample rate from VAD's audio context
851    currentSampleRate = audioContext.sampleRate;
852    // console.log("VAD Audio Context Sample Rate:", currentSampleRate);
853
854    const source = audioContext.createMediaStreamSource(stream);
855
856    // AudioWorkletProcessor kullanarak audio chunk'larını al
857    const processorNode = audioContext.createScriptProcessor(4096, 1, 1);
858
859    processorNode.onaudioprocess = (event) => {
860      const inputBuffer = event.inputBuffer;
861      const inputData = inputBuffer.getChannelData(0); // Mono channel
862
863      // Float32Array olarak audio chunk'ı al
864      const audioChunk = new Float32Array(inputData);
865      handleRawAudioFromVAD(audioChunk);
866    };
867
868    // Audio pipeline'ı kur
869    source.connect(processorNode);
870    processorNode.connect(audioContext.destination);
871
872    // console.log("VAD stream connection established");
873  } catch (error) {
874    console.error("Error connecting to VAD stream:", error);
875  }
876}
877
878function handleRawAudioFromVAD(data) {
879  if (!isUserSpeaking) {
880    PRE_BUFFER_ARRAY.push(data);
881    if (PRE_BUFFER_ARRAY.length > PRE_BUFFER_CHUNK_COUNT) {
882      PRE_BUFFER_ARRAY.shift();
883    }
884  }
885
886  if (isUserSpeaking && !isPlayingAudio && isSpeechViewMicButtonOpen) {
887    USERS_SPEECH_ARRAY.push(data);
888
889    // Calculate audio energy from the raw audio data
890    let energy = 0;
891    for (let i = 0; i < data.length; i++) {
892      energy += Math.abs(data[i]);
893    }
894    energy = energy / data.length;
895
896    // Update microphone animation
897    userMicrophoneVolumeEnergy(energy);
898  }
899}
900
901function userMicrophoneVolumeEnergy(energy) {
902  if (!isSpeechEnabled() || !showMicEnergyAnimation) {
903    return;
904  }
905  if (energy < 0) {
906    energy = 0;
907  }
908
909  // Normalize energy to 0-30 range
910  // Based on observed values, typical energy is between 0-0.08
911  const normalizedEnergy = Math.min(30, Math.floor(energy * 375)); // 0.08 * 375 = 30
912
913  if (normalizedEnergy === 0) {
914    // Sessizlik - gray
915    $(".cbot-dialog-speech-content-bottom-mic-button-open").css({
916      "background-color": "rgba(128, 128, 128, 0.2)",
917      "box-shadow": "0 1px 3px rgba(0, 0, 0, 0.3)",
918      "transform": "scale(1)"
919    });
920  } else {
921    // Güçlü kırmızı geçiş + glow + scale efekti
922    const intensity = normalizedEnergy / 30; // 0-1 range
923    const red = Math.floor(60 + (intensity * 195)); // 60-255 arası
924    const green = Math.floor(60 * Math.pow(1 - intensity, 3)); // Hızla azalan
925    const blue = Math.floor(60 * Math.pow(1 - intensity, 4)); // Çok hızla azalan
926    const alpha = 0.4 + (intensity * 0.6); // 0.4-1.0
927
928    // Glow efekti
929    const glowSize = intensity * 15; // 0-15px glow
930
931    $(".cbot-dialog-speech-content-bottom-mic-button-open").css({
932      "background-color": `rgba(${red}, ${green}, ${blue}, ${alpha})`,
933      "box-shadow": `0 0 ${glowSize}px rgba(${red}, ${green / 2}, ${blue / 2}, ${alpha}), 0 1px 3px rgba(0, 0, 0, 0.3)`,
934      "transition": "all 0.1s ease-out"
935    });
936  }
937}
938
939// Audio conversion variables
940let currentSampleRate = 16000; // VAD uses 16kHz
941
942function float32ToWav(float32Array, sampleRate) {
943  // Convert Float32Array to 16-bit PCM with improved quality
944  const length = float32Array.length;
945  const buffer = new ArrayBuffer(44 + length * 2);
946  const view = new DataView(buffer);
947
948  // WAV header
949  const writeString = (offset, string) => {
950    for (let i = 0; i < string.length; i++) {
951      view.setUint8(offset + i, string.charCodeAt(i));
952    }
953  };
954
955  writeString(0, 'RIFF'); // ChunkID
956  view.setUint32(4, 36 + length * 2, true); // ChunkSize
957  writeString(8, 'WAVE'); // Format
958  writeString(12, 'fmt '); // Subchunk1ID
959  view.setUint32(16, 16, true); // Subchunk1Size
960  view.setUint16(20, 1, true); // AudioFormat (PCM)
961  view.setUint16(22, 1, true); // NumChannels
962  view.setUint32(24, sampleRate, true); // SampleRate
963  view.setUint32(28, sampleRate * 2, true); // ByteRate
964  view.setUint16(32, 2, true); // BlockAlign
965  view.setUint16(34, 16, true); // BitsPerSample
966  writeString(36, 'data'); // Subchunk2ID
967  view.setUint32(40, length * 2, true); // Subchunk2Size
968
969  // Analyze audio levels for better conversion
970  let maxLevel = 0;
971  for (let i = 0; i < length; i++) {
972    maxLevel = Math.max(maxLevel, Math.abs(float32Array[i]));
973  }
974
975  // console.log("Audio max level before conversion:", maxLevel);
976
977  // Apply soft limiting if needed
978  const softLimit = 0.95;
979  let scaleFactor = 1.0;
980  if (maxLevel > softLimit) {
981    scaleFactor = softLimit / maxLevel;
982    // console.log("Applying scale factor:", scaleFactor);
983  }
984
985  // Convert float samples to 16-bit PCM with dithering
986  let offset = 44;
987  for (let i = 0; i < length; i++) {
988    let sample = float32Array[i] * scaleFactor;
989
990    // Add subtle dithering to reduce quantization noise
991    const dither = (Math.random() - 0.5) * (1 / 32768);
992    sample += dither;
993
994    // Clamp and convert to 16-bit signed integer
995    sample = Math.max(-1, Math.min(1, sample));
996    const intSample = Math.round(sample * 32767);
997
998    view.setInt16(offset, intSample, true);
999    offset += 2;
1000  }
1001
1002  return buffer;
1003}
1004
1005async function convertUserSpeechToBase64EncodedAudio() {
1006  try {
1007    // console.log("Converting speech to base64.");
1008    // console.log("PRE_BUFFER_ARRAY chunks:", PRE_BUFFER_ARRAY.length);
1009    // console.log("USERS_SPEECH_ARRAY chunks:", USERS_SPEECH_ARRAY.length);
1010    // console.log("Using sample rate:", currentSampleRate);
1011
1012    // Combine PRE_BUFFER_ARRAY and USERS_SPEECH_ARRAY
1013    const allChunks = [...PRE_BUFFER_ARRAY, ...USERS_SPEECH_ARRAY];
1014
1015    if (allChunks.length === 0) {
1016      console.warn("No audio data available for conversion");
1017      return null;
1018    }
1019
1020    // Calculate total samples
1021    let totalSamples = 0;
1022    for (const chunk of allChunks) {
1023      totalSamples += chunk.length;
1024    }
1025
1026    // console.log("Total audio samples:", totalSamples);
1027
1028    // Combine all audio chunks into a single Float32Array
1029    const combinedAudio = new Float32Array(totalSamples);
1030    let offset = 0;
1031
1032    for (const chunk of allChunks) {
1033      combinedAudio.set(chunk, offset);
1034      offset += chunk.length;
1035    }
1036
1037    // Clear speech arrays immediately to free memory
1038    USERS_SPEECH_ARRAY = [];
1039    // PRE_BUFFER_ARRAY'i temizlemiyoruz çünkü sürekli kullanılıyor
1040
1041    // Convert to WAV format
1042    const wavBuffer = float32ToWav(combinedAudio, currentSampleRate);
1043
1044    // Clear combined audio from memory after conversion
1045    combinedAudio.fill(0);
1046
1047    const audioBlob = new Blob([wavBuffer], { type: 'audio/wav' });
1048
1049    if (audioBlob.size === 0) {
1050      console.warn("Audio blob is empty! Audio data might not be captured properly.");
1051      return null;
1052    }
1053
1054    // Convert to base64 using FileReader API (güvenli yöntem)
1055    const base64EncodedAudio = await new Promise((resolve, reject) => {
1056      const reader = new FileReader();
1057      reader.onload = () => {
1058        // Data URL formatından base64 kısmını al (data:audio/wav;base64, prefixi olmadan)
1059        const result = reader.result.split(',')[1];
1060        resolve(result);
1061      };
1062      reader.onerror = reject;
1063      reader.readAsDataURL(audioBlob);
1064    });
1065
1066    // console.log("Base64 encoding completed. Length:", base64EncodedAudio.length);
1067    // console.log("First 100 chars:", base64EncodedAudio.substring(0, 100));
1068
1069    // Force garbage collection hint (not guaranteed but might help)
1070    if (window.gc) {
1071      window.gc();
1072      console.log("Garbage collection triggered");
1073    }
1074
1075    return base64EncodedAudio;
1076
1077  } catch (error) {
1078    console.error("Error processing audio recording:", error);
1079    // Clear memory on error too
1080    USERS_SPEECH_ARRAY = [];
1081    return null;
1082  }
1083}
1084
1085async function sendBase64EncodedAudioAsMessage() {
1086  showMicEnergyAnimation = false;
1087
1088  // Convert audio chunks to base64
1089  const base64EncodedAudio = await convertUserSpeechToBase64EncodedAudio();
1090
1091  if (base64EncodedAudio) {
1092    sendMessage(base64EncodedAudio, "audio");
1093    isPlayingAudio = true;
1094  } else {
1095    console.error("Failed to convert audio to base64");
1096  }
1097  USERS_SPEECH_ARRAY = [];
1098}
1099
1100async function playBase64Audio(base64AudioData) {
1101  try {
1102    // console.log("Playing base64 audio from backend");
1103
1104    // Base64 data URL'sini direkt kullan (data:audio/mpeg;base64,... formatında geliyor)
1105    const audio = new Audio(base64AudioData);
1106    currentPlayingAudio = audio; // Global referansı sakla
1107
1108    // Create audio context and analyser for volume monitoring
1109    const audioContext = new AudioContext();
1110    const analyser = audioContext.createAnalyser();
1111    const source = audioContext.createMediaElementSource(audio);
1112
1113    source.connect(analyser);
1114    analyser.connect(audioContext.destination);
1115
1116    analyser.fftSize = 256;
1117    const bufferLength = analyser.frequencyBinCount;
1118    const dataArray = new Uint8Array(bufferLength);
1119
1120    // Monitor volume while playing
1121    const checkVolume = () => {
1122      if (audio.paused) return;
1123
1124      analyser.getByteFrequencyData(dataArray);
1125
1126      // Calculate average volume
1127      const average = dataArray.reduce((acc, val) => acc + val, 0) / bufferLength;
1128      // Convert to 0-100 range
1129      const volume = Math.round((average / 255) * 100);
1130
1131      ttsFileVolumeEnergy(volume);
1132
1133      requestAnimationFrame(checkVolume);
1134    };
1135
1136    audio.onplay = () => {
1137      checkVolume();
1138      isPlayingAudio = true;
1139    };
1140
1141    audio.onended = () => {
1142      isPlayingAudio = false;
1143      currentPlayingAudio = null; // Referansı temizle
1144      source.disconnect();
1145      analyser.disconnect();
1146      audioContext.close();
1147
1148      // Push-to-talk modunda VAD başlatma
1149      if (!voice_bot_button_push_to_talk) {
1150        startVoiceDetection();
1151      }
1152      if (isSpeechEnabled()) {
1153        $("#particles-container").css("border", "1px solid rgba(0, 0, 0, 0.5)")
1154      }
1155
1156      // Parçacıkları başlangıç seviyesine döndür
1157      particlesUpdateByEnergy(0);
1158      showMicEnergyAnimation = true;
1159    };
1160    if (showSpeechView) {
1161      await audio.play();
1162    }
1163
1164  } catch (error) {
1165    console.error("Error playing base64 audio:", error);
1166
1167    // Hata durumunda referansı temizle
1168    currentPlayingAudio = null;
1169    isPlayingAudio = false;
1170
1171    // Hata durumunda parçacıkları başlangıç seviyesine döndür
1172    particlesUpdateByEnergy(0);
1173    if (isSpeechEnabled()) {
1174      $("#particles-container").css("border", "1px solid rgba(0, 0, 0, 0.5)")
1175    }
1176
1177    // Push-to-talk modunda VAD başlatma
1178    if (!voice_bot_button_push_to_talk) {
1179      startVoiceDetection();
1180    }
1181  }
1182}
1183
1184function cancelOngoingPlayback() {
1185  // console.log("cancelOngoingPlayback");
1186
1187  // Önce global olarak saklanan audio'yu durdur
1188  if (currentPlayingAudio) {
1189    currentPlayingAudio.pause();
1190    currentPlayingAudio.currentTime = 0;
1191    currentPlayingAudio = null;
1192  }
1193
1194  // Ek güvenlik için DOM'daki tüm audio elementlerini de durdur
1195  const audioElements = document.getElementsByTagName('audio');
1196  for (let audio of audioElements) {
1197    audio.pause();
1198    audio.currentTime = 0;
1199  }
1200
1201  isPlayingAudio = false;
1202  showMicEnergyAnimation = true;
1203
1204  // Push-to-talk modunda VAD başlatma
1205  if (!voice_bot_button_push_to_talk) {
1206    startVoiceDetection();
1207  }
1208
1209  // Reset particles and border
1210  particlesUpdateByEnergy(0);
1211  if (isSpeechEnabled()) {
1212    $("#particles-container").css("border", "1px solid rgba(0, 0, 0, 0.5)");
1213  }
1214}
1215
1216
1217function ttsFileVolumeEnergy(energy) {
1218  if (!isSpeechEnabled()) {
1219    return;
1220  }
1221
1222  if (energy > 30) {
1223    energy = 30;
1224  }
1225  // console.log("TTS file volume energy:", energy);
1226
1227  // Border efekti için (opsiyonel)
1228  $("#particles-container").css("border", `${energy}px solid rgba(0, 0, 0, 0.5)`)
1229
1230  // Parçacıkları enerji seviyesine göre güncelle
1231  particlesUpdateByEnergy(energy);
1232}
1233
1234
1235let showSpeechView = false;
1236let isParticlesInitialized = false;
1237let currentPlayingAudio = null;
1238
1239function toggleSpeechView() {
1240  if (!isParticlesInitialized) {
1241    setTimeout(() => {
1242      initParticlesAnimation();
1243      isParticlesInitialized = true;
1244    }, 500);
1245  }
1246  showSpeechView = !showSpeechView;
1247
1248  if (showSpeechView) {
1249    // * speech view açılıyor..
1250    // Speech view'ı göster
1251    $(".cbot-dialog-speech").css("display", "block");
1252
1253    // Ana dialog'u fade out yap
1254    $(".cbot-dialog").removeClass("fade-in").addClass("fade-out");
1255
1256    // Kısa bir delay sonra speech dialog'u fade in yap
1257    setTimeout(() => {
1258      $(".cbot-dialog-speech").removeClass("fade-out").addClass("fade-in");
1259    }, 250);
1260
1261  } else {
1262    // * speech view kapatılıyor..
1263    // Speech dialog'u fade out yap
1264    $(".cbot-dialog-speech").removeClass("fade-in").addClass("fade-out");
1265
1266    // Animasyon bitince display:none yap ve ana dialog'u fade in yap
1267    setTimeout(() => {
1268      $(".cbot-dialog-speech").css("display", "none");
1269      $(".cbot-dialog").removeClass("fade-out").addClass("fade-in");
1270    }, 500);
1271
1272    if (isSpeechViewMicButtonOpen) {
1273      toggleSpeechViewMicButton();
1274    }
1275  }
1276  particlesUpdateByEnergy(0);
1277}
1278
1279let isSpeechViewMicButtonOpen = false;
1280function toggleSpeechViewMicButton() {
1281  if (voice_bot_button_push_to_talk) {
1282    // Push-to-talk mode
1283    if (!isSpeechViewMicButtonOpen) {
1284      // İlk basış - ses izinlerini al ve UI'ı güncelle
1285      $(".cbot-dialog-speech-content-bottom-mic-button-open").css("display", "flex");
1286      $(".cbot-dialog-speech-content-bottom-mic-button-muted").css("display", "none");
1287      isSpeechViewMicButtonOpen = true;
1288
1289      // Sadece mikrofon erişim izni al, VAD kullanma
1290      navigator.mediaDevices.getUserMedia({ audio: true })
1291        .then(stream => {
1292          // Stream'i sakla, push-to-talk için kullanacağız
1293          window.pushToTalkStream = stream;
1294        })
1295        .catch(err => {
1296          console.error('Mikrofon erişimi reddedildi:', err);
1297        });
1298    } else {
1299      // İkinci basış - kapatma
1300      $(".cbot-dialog-speech-content-bottom-mic-button-open").css("display", "none");
1301      $(".cbot-dialog-speech-content-bottom-mic-button-muted").css("display", "flex");
1302      isSpeechViewMicButtonOpen = false;
1303      isPushToTalkActive = false;
1304      pushToTalkStarted = false;
1305
1306      // Stream'i kapat
1307      if (window.pushToTalkStream) {
1308        window.pushToTalkStream.getTracks().forEach(track => track.stop());
1309        window.pushToTalkStream = null;
1310      }
1311
1312      // Eğer kayıt aktifse durdur ve gönder
1313      if (pushToTalkMediaRecorder && pushToTalkMediaRecorder.state === 'recording') {
1314        stopPushToTalkRecording();
1315      }
1316
1317      userMicrophoneVolumeEnergy(0);
1318    }
1319  } else {
1320    // Mevcut normal mode (değişiklik yok)
1321    if (isSpeechViewMicButtonOpen) {
1322      $(".cbot-dialog-speech-content-bottom-mic-button-open").css("display", "none");
1323      $(".cbot-dialog-speech-content-bottom-mic-button-muted").css("display", "flex");
1324      isSpeechViewMicButtonOpen = false;
1325    } else {
1326      $(".cbot-dialog-speech-content-bottom-mic-button-open").css("display", "flex");
1327      $(".cbot-dialog-speech-content-bottom-mic-button-muted").css("display", "none");
1328      isSpeechViewMicButtonOpen = true;
1329      startVoiceDetection();
1330    }
1331  }
1332}
1333
1334// Push-to-talk için yeni fonksiyonlar
1335function startPushToTalkRecording() {
1336  if (voice_bot_button_push_to_talk && isSpeechViewMicButtonOpen && !isPushToTalkActive && window.pushToTalkStream) {
1337    isPushToTalkActive = true;
1338    pushToTalkStarted = true;
1339
1340    // USERS_SPEECH_ARRAY'i temizle
1341    USERS_SPEECH_ARRAY = [];
1342
1343    // VAD benzeri ses işleme için AudioContext oluştur
1344    setupPushToTalkAudioProcessing(window.pushToTalkStream);
1345
1346    // Kayıt başladığını belirt
1347    isUserSpeaking = true;
1348    showMicEnergyAnimation = true;
1349
1350    // Push-to-talk animasyonu başlat
1351    startPushToTalkAnimation();
1352  }
1353}
1354
1355function stopPushToTalkRecording() {
1356  if (voice_bot_button_push_to_talk && isPushToTalkActive) {
1357    isPushToTalkActive = false;
1358    isUserSpeaking = false;
1359    showMicEnergyAnimation = false;
1360
1361    // Audio processing'i durdur
1362    if (window.pushToTalkAudioContext) {
1363      window.pushToTalkAudioContext.close();
1364      window.pushToTalkAudioContext = null;
1365    }
1366
1367    userMicrophoneVolumeEnergy(0);
1368
1369    // Push-to-talk animasyonu durdur
1370    stopPushToTalkAnimation();
1371
1372    // VAD benzeri ses gönderme sistemi kullan
1373    if (USERS_SPEECH_ARRAY.length > 0) {
1374      sendBase64EncodedAudioAsMessage();
1375    }
1376  }
1377}
1378
1379// Push-to-talk için VAD benzeri ses işleme
1380function setupPushToTalkAudioProcessing(stream) {
1381  try {
1382    // AudioContext oluştur
1383    window.pushToTalkAudioContext = new (window.AudioContext || window.webkitAudioContext)();
1384    const audioContext = window.pushToTalkAudioContext;
1385
1386    // Sample rate'i güncelle
1387    currentSampleRate = audioContext.sampleRate;
1388
1389    const source = audioContext.createMediaStreamSource(stream);
1390
1391    // VAD'daki gibi ScriptProcessor kullan
1392    const processorNode = audioContext.createScriptProcessor(4096, 1, 1);
1393
1394    processorNode.onaudioprocess = (event) => {
1395      if (!isPushToTalkActive) return; // Sadece aktifken işle
1396
1397      const inputBuffer = event.inputBuffer;
1398      const inputData = inputBuffer.getChannelData(0); // Mono channel
1399
1400      // Float32Array olarak audio chunk'ı al
1401      const audioChunk = new Float32Array(inputData);
1402
1403      // VAD'daki gibi USERS_SPEECH_ARRAY'e ekle
1404      USERS_SPEECH_ARRAY.push(audioChunk);
1405
1406      // Ses enerjisini hesapla (animasyon için)
1407      let energy = 0;
1408      for (let i = 0; i < audioChunk.length; i++) {
1409        energy += Math.abs(audioChunk[i]);
1410      }
1411      energy = energy / audioChunk.length;
1412
1413      if (showMicEnergyAnimation) {
1414        userMicrophoneVolumeEnergy(energy);
1415      }
1416    };
1417
1418    // Bağlantıları yap
1419    source.connect(processorNode);
1420    processorNode.connect(audioContext.destination);
1421
1422  } catch (error) {
1423    console.error("Push-to-talk audio processing error:", error);
1424  }
1425}
1426
1427// Blob'u base64'e çevirip gönder (artık kullanılmıyor ama bırakıyoruz)
1428function convertBlobToBase64AndSend(audioBlob) {
1429  const reader = new FileReader();
1430  reader.onloadend = function () {
1431    const base64Audio = reader.result;
1432    sendMessage(base64Audio, "audio");
1433    isPlayingAudio = true;
1434  };
1435  reader.readAsDataURL(audioBlob);
1436}
1437
1438// Push-to-talk animasyon fonksiyonları
1439function startPushToTalkAnimation() {
1440  let animationStep = 0;
1441  const baseColor = 'rgba(255, 59, 48, 0.8)'; // Tek kırmızı renk
1442
1443  pushToTalkAnimationInterval = setInterval(() => {
1444    const scale = 1 + (Math.sin(animationStep * 0.3) * 0.08); // 1.0 - 1.08 arası salınım
1445    const glowSize = 12 + (Math.sin(animationStep * 0.5) * 6); // 6-18px glow
1446    const opacity = 0.7 + (Math.sin(animationStep * 0.4) * 0.2); // 0.5-0.9 opacity
1447
1448    const currentColor = `rgba(255, 59, 48, ${opacity})`;
1449
1450    $(".cbot-dialog-speech-content-bottom-mic-button-open").css({
1451      "background-color": currentColor,
1452      "box-shadow": `0 0 ${glowSize}px ${currentColor}, 0 1px 3px rgba(0, 0, 0, 0.3)`,
1453      "transform": `scale(${scale})`,
1454      "transition": "all 0.2s ease-out",
1455      "border": `2px solid ${currentColor}`
1456    });
1457
1458    animationStep++;
1459  }, 150);
1460
1461  // İlk efekti hemen uygula
1462  $(".cbot-dialog-speech-content-bottom-mic-button-open").css({
1463    "background-color": baseColor,
1464    "box-shadow": `0 0 15px ${baseColor}, 0 1px 3px rgba(0, 0, 0, 0.3)`,
1465    "transform": "scale(1.05)",
1466    "transition": "all 0.2s ease-out",
1467    "border": `2px solid ${baseColor}`
1468  });
1469}
1470
1471function stopPushToTalkAnimation() {
1472  if (pushToTalkAnimationInterval) {
1473    clearInterval(pushToTalkAnimationInterval);
1474    pushToTalkAnimationInterval = null;
1475  }
1476
1477  // Normal görünümü geri yükle
1478  $(".cbot-dialog-speech-content-bottom-mic-button-open").css({
1479    "background-color": "rgba(128, 128, 128, 0.2)",
1480    "box-shadow": "0 1px 3px rgba(0, 0, 0, 0.3)",
1481    "transform": "scale(1)",
1482    "transition": "all 0.3s ease-out",
1483    "border": "none"
1484  });
1485}
1486
1487function initParticlesAnimation() {
1488  if (!isSpeechEnabled()) {
1489    return;
1490  }
1491
1492  // particles js loading interval
1493  let particlesJsLoadingInterval = setInterval(() => {
1494    if (particlesJS) {
1495      clearInterval(particlesJsLoadingInterval);
1496      particlesJS("particles-js", particlesConfig);
1497      setTimeout(() => {
1498        particlesChangeIntensity(particles_intensity_levels_enums.low)
1499      }, 100);
1500    }
1501  }, 100);
1502}
1503
1504function init(robotImageURL, dialogImageURL, dialogButtonColor, dialogTitle, chooseButtonColor, client, justLink, time, welcomeMessage, helpText, param_trigger_messages, scrollProp, scrollTop, inputMaxLen, dataOpen) {
1505  trigger_messages = param_trigger_messages;
1506  if (!time) time = 0;
1507
1508
1509  if (client) CLIENT = client;
1510
1511  firstMessageSent = getFirstMessageSentFLS(client);
1512
1513  var open = getParameterByName("open"); // URL - widget instantly opens after loaded
1514  var data_open = getParameterFromScript("data-open") || getIsWidgetOpenedTLS();/*  || dataOpen; */ // widget instantly opens after loaded
1515  data_full_page = getParameterFromScript("data-full-page"); // optional hide help when mobile app is on
1516  var data_not_set_cookie_redirect_url = getParameterFromScript("data-not-set-cookie-redirect-url");
1517  var data_cookie_name = getParameterFromScript("data-cookie-name");
1518  var data_banner_img = getParameterFromScript("data-banner-img");
1519  var data_banner_url = getParameterFromScript("data-banner-url");
1520  data_function = getParameterFromScript("data-function");
1521  data_vip = getParameterFromScript("data-vip");
1522  data_livechat = getParameterFromScript("data-livechat");
1523  data_user = getParameterFromScript("data-user");
1524  data_clear_session = getParameterFromScript("data-clear-session");
1525  if (data_clear_session == "true") {
1526    setSessionIdTLS(null);
1527    setUserIdTLS(null);
1528    isLive = setIsLive(false);
1529    setisLiveTLS(isLive);
1530  }
1531  data_do_not_preload_load_font = getParameterFromScript("data-do-not-preload-font");
1532  data_script_qs = getQueryVariable(window.location.href);
1533  queryStringVars = getQueryVariable(window.location.href);
1534  if (clients.notification_sound) {
1535    audioElement = new Audio(rootAddress + "/sounds/cbot_notification.mp3");
1536  }
1537  // INTERACTIVE START
1538  if (is_interactive_response_active) {
1539    interactive_recommends = interactive_class.recommend();
1540    interactive_class.setStats();
1541  }
1542  ia_open_widget_state = interactive_actions_executer.checkOpenWidget();
1543  if (ia_open_widget_state) data_open = true;
1544  ia_display_popup_state = interactive_actions_executer.checkDisplayPopup();
1545  ia_take_attention_state = interactive_actions_executer.checkTakeAttention();
1546  if (ia_take_attention_state.status) {
1547    ia_take_attention_state.is_executed = false;
1548    ia_take_attention_state_timer = setTimeout(() => {
1549      ia_take_attention_state.is_executed = true;
1550      dialogButtonRegular((userId, message) => {
1551        dialog(userId, message, () => { }, undefined, false, undefined, () => { }, true);
1552      })
1553    }, ia_take_attention_state.delay * 1000);
1554  }
1555  // INTERACTIVE END
1556
1557  if (window.dataLayer["cbot_repeat"] && !isIE) {
1558    queryStringVars.cbot_repeat = window.dataLayer["cbot_repeat"];
1559    window.dataLayer["cbot_repeat"] = false;
1560  }
1561
1562  if (window.dataLayer["cbot_message"]) {
1563    queryStringVars.cbot_message = decodeURIComponent(window.dataLayer["cbot_message"]);
1564    window.dataLayer["cbot_message"] = null;
1565  }
1566
1567  if (queryStringVars.cbot_dynamic_id) {
1568    cbot_dynamic_id = queryStringVars.cbot_dynamic_id;
1569  } else {
1570    cbot_dynamic_id = getParameterFromScript("dynamic-id");
1571  }
1572
1573  if (queryStringVars["data-user"]) {
1574    data_user = queryStringVars["data-user"];
1575  } else {
1576    data_user = getParameterFromScript("data-user");
1577  }
1578
1579  if (!data_open && queryStringVars.widget_open == "true") {
1580    data_open = queryStringVars.widget_open;
1581  }
1582  getCustomHeaders(!data_function);
1583
1584  if (hasAttributeOnScript("data-user")) {
1585    var dataUserInterval = setInterval(function () {
1586      if (!!getParameterFromScript("data-user")) {
1587        data_user = getParameterFromScript("data-user");
1588        clearInterval(dataUserInterval);
1589        data_user_fls = getUserInfoFLS();
1590
1591
1592        // if ((!data_user.trim() && data_user_fls) || (!data_user_fls && data_user.trim())) { // olurda boşluklu gönderilirse
1593        //   // session ataması aşağıda yapılacak
1594        //   setSessionIdTLS(null);
1595
1596        // }
1597
1598        setUserInfoTLS("successful")
1599      }
1600    }, 100);
1601  } else {
1602    data_user_fls = getUserInfoFLS();
1603
1604
1605    // if ((!data_user.trim() && data_user_fls) || (!data_user_fls && data_user.trim())) { // olurda boşluklu gönderilirse
1606    //   // session ataması aşağıda yapılacak
1607    //   setSessionIdTLS(null);
1608
1609    // }
1610
1611    setUserInfoTLS("successful")
1612  }
1613
1614
1615
1616  data_cdn_url = getParameterFromScript("data-cdn-url");
1617
1618  var data_mobileapp = getParameterFromScript("data-mobileapp"); // for mobile apps
1619
1620
1621  robotImageURL = (robotImageURL || "").replace(/staticAddress/g, staticAddress);
1622  dialogImageURL = (dialogImageURL || "").replace(/staticAddress/g, staticAddress);
1623
1624  // addCssFile('cbot-' + CLIENT + "-custom", Math.random());
1625
1626  // if (!(data_do_not_preload_load_font == "true")) {
1627  //     addFontFile("Proxima4");
1628  //     addFontFile("Proxima5");
1629  // }
1630
1631  if (chartjs_is_active) addChartJs();
1632
1633  cbot_custom_positioning = getCustomPositionings();
1634
1635  if (data_full_page == "true") {
1636    data_full_page = true;
1637    addCssFile('cbot-fullpage-flat-style', version);
1638  }
1639
1640
1641  isLive = getisLiveFLS();
1642  if (data_open == "true" || open == "true" || data_open || queryStringVars.cbot_repeat == "true" || (!cbotIsMobile.any() && isLive)) {
1643    isWidgetOpen = true;
1644    data_open = true;
1645  }
1646  else data_open = false;
1647
1648  if (queryStringVars.cbot_repeat != "true") {
1649    setLastMessageTLS([]);
1650  }
1651
1652  if (data_vip == "true") {
1653    data_vip = true;
1654  } else {
1655    data_vip = false;
1656  }
1657
1658  if (data_livechat == "true") {
1659    data_livechat = true;
1660  } else {
1661    data_livechat = false;
1662  }
1663
1664  if (clients.attachments_is_active)
1665    bool_attachments = true;
1666
1667  loginId = getParameterFromScript("data-session");
1668
1669
1670  if (data_cookie_name)
1671    focookie = cbotGetCookie(data_cookie_name); //FOSecurity
1672
1673  if (data_cookie_name && !focookie && data_not_set_cookie_redirect_url) {
1674    window.location.replace(data_not_set_cookie_redirect_url);
1675  }
1676
1677  if (!isLive) {
1678    isLive = setIsLive(data_vip || data_livechat);
1679  }
1680
1681  //CSS dosyası ekleniyor
1682  // if (CUSTOM_CSS)
1683  //     addCssFile('cbot-style-' + CLIENT, Math.random());
1684
1685  if (data_owl && data_owl_variable == "false")
1686    addCssFile("owl.carousel.min", version)
1687
1688  if (data_mobileapp == "true") {
1689    data_open = true;
1690    data_mobileapp = true;
1691  }
1692  else data_mobileapp = false;
1693
1694  // if (data_mobileapp)
1695  // addCssFile("cbot-mobileapp-flat-style-" + CLIENT, Math.random());
1696
1697  if (data_vip)
1698    addCssFile('cbot-vip-flat-' + CLIENT, version);
1699
1700  var helpContent = (helpText || "")
1701
1702  cbotUserId = getUserIDFLS();
1703  // isLive = getisLiveFLS();
1704
1705
1706  cbotSessionId = getSessionIdFLS();
1707  if (!cbotSessionId) {
1708    isLive = setIsLive(false);
1709    setisLiveTLS(isLive);
1710  }
1711
1712  if (!checkLastMessageDate()) {
1713    cbotSessionId = null;
1714    isLive = setIsLive(false);
1715    setisLiveTLS(isLive);
1716    setSessionIdTLS(cbotSessionId);
1717    clearLastMessageSentDateTLS();
1718  }
1719
1720  let is_close_icon_pressed = getCloseIconPressed();
1721  if (getChannelValue(clients.clear_after_close_bot, CHANNEL) && is_close_icon_pressed == "true") {
1722    removeCloseIconPressed();
1723    reset(true);
1724  }
1725
1726  if (getChannelValue(clients.dont_clear_after_another_page, CHANNEL)) {
1727    if (getChannelValue(clients.clear_after_close_page, CHANNEL) && !isLive && checkPageTransition()) {
1728      cbotClearUserDialog(true);
1729    }
1730  } else {
1731    if (getChannelValue(clients.clear_after_close_page, CHANNEL) && !isLive) {
1732      sendToEndChat();
1733      cbotClearUserDialog(true);
1734    }
1735  }
1736
1737  if (getChannelValue(clients.messages_sending_time, CHANNEL)) {
1738    cbot_messages_sending_time = true
1739  }
1740
1741
1742  // getConversations();
1743
1744
1745
1746  setTimeout(function () {
1747
1748    cbot_config = {
1749      robotImageURL: robotImageURL,
1750      dialogImageURL: dialogImageURL,
1751      dialogButtonColor: dialogButtonColor,
1752      chooseButtonColor: chooseButtonColor,
1753      dialogTitle: dialogTitle,
1754      client: CLIENT
1755    };
1756    clients.placeholder_message = clients.placeholder_message || "Mesajınızı buraya yazınız!"
1757    clients.send_survey_button_is_active = clients.send_survey_button_is_active || false
1758    clients.disable_user_chat_input_button_component = clients.disable_user_chat_input_button_component || false
1759
1760    if (clients.send_survey_button_is_active) {
1761      clients.send_survey_placeholder_message = clients.send_survey_placeholder_message || "Görüşlerinizi bizimle paylaşın..."
1762    }
1763
1764    var display_none = "display: none;"
1765    var display_block = "display: block;";
1766    //Dialog elementleri sayfaya ekleniyor!
1767
1768
1769    /* WIDGET SIZING */
1770    var custom_width_height = "";
1771    if (clients.custom_width && clients.custom_height)
1772      custom_width_height = "; width: " + clients.custom_width + "; height: " + clients.custom_height;
1773
1774    if (cbot_custom_positioning.height && cbot_custom_positioning.width) { // overriding
1775      custom_width_height = "; width: " + cbot_custom_positioning.width + "; height: " + cbot_custom_positioning.height;
1776    }
1777
1778
1779    /* WIDGET ICON POSITIONING */
1780    var custom_positioning = "";
1781
1782
1783    if (clients.custom_top) custom_positioning = "; top: " + clients.custom_top;
1784
1785    if (cbot_custom_positioning.right) { // parametrik gelenler öncelikli
1786      custom_positioning += "; right: " + cbot_custom_positioning.right;
1787    }
1788    else {
1789      if (clients.custom_right && !clients.slide_from_right && !clients.slide_from_left) custom_positioning += "; right: " + clients.custom_right;
1790    }
1791
1792    if (cbot_custom_positioning.bottom) { // parametrik gelenler öncelikli
1793      custom_positioning += "; bottom: " + cbot_custom_positioning.bottom;
1794    }
1795    else {
1796      if (clients.custom_bottom) custom_positioning += "; bottom: " + clients.custom_bottom;
1797    }
1798
1799    if (cbot_custom_positioning.left) { // parametrik gelenler öncelikli
1800      custom_positioning += "; left: " + cbot_custom_positioning.left
1801    }
1802    else {
1803
1804      if (clients.custom_left && !clients.slide_from_right && !clients.slide_from_left) custom_positioning += "; left: " + clients.custom_left;
1805    }
1806
1807    /* WIDGET DIALOG POSITIONING AUTOMATICALLY */
1808    var custom_positioning_dialog = ""
1809    if (custom_positioning.indexOf("left") > -1) custom_positioning_dialog = "; left: 20px";
1810    if (custom_positioning.indexOf("right") > -1) custom_positioning_dialog = "; right: 20px";
1811
1812    if (clients.slide_from_left) {
1813
1814      custom_positioning_dialog += "; left: 20px";
1815      // custom_positioning += "; left: 20px";
1816    }
1817
1818    var custom_popup_positioning = "";
1819    var custom_width_int = parseInt((clients.custom_width || "61px").replace(/[^0-9]/g, ""));
1820
1821
1822
1823    var custom_height_int = parseInt((clients.custom_height || "61px").replace(/[^0-9]/g, ""));
1824    if (cbot_custom_positioning.height)
1825      custom_height_int = parseInt((cbot_custom_positioning.height || "61px").replace(/[^0-9]/g, ""));
1826
1827
1828    var custom_top_int = parseInt((clients.custom_top || "").replace(/[0-9]/g, "")) || 0;
1829    var custom_right_int = parseInt((clients.custom_right || "").replace(/[^0-9]/g, "")) || 0;
1830    var custom_bottom_int = parseInt((clients.custom_bottom || "20px").replace(/[^0-9]/g, "")) || 0;
1831    var custom_left_int = parseInt((clients.custom_left || "").replace(/[^0-9]/g, "")) || 0;
1832
1833    custom_popup_positioning = "; bottom: " + (10 + custom_height_int) + "px; "
1834    if (custom_left_int > 0 && !clients.slide_from_right && !clients.slide_from_left)
1835      custom_popup_positioning += "; left: 0px; "
1836    if (custom_right_int > 0 && !clients.slide_from_right && !clients.slide_from_left)
1837      custom_popup_positioning += "; right: 0px; "
1838
1839    var custom_animation = ""
1840    if (clients.bounce)
1841      custom_animation = "cbot-bounce";
1842    if (clients.slide_from_right)
1843      custom_animation = "cbot-slide-right";
1844    if (clients.slide_from_left)
1845      custom_animation = "cbot-slide-left";
1846
1847    cbot_lottie_icon_activation = clients.lottie_icon_activation || false;
1848    var lottie_icon_url = clients.lottie_icon_url || "";
1849
1850    if (CSP_BLOCK_UNSAFE_INLINE) {
1851      $.htmlPrefilter = function (html) {
1852        // Really it have to be more complicated for replacing a tag's attributes only,
1853        // not just plain text replacement:
1854        return (html + '').replace(/ style=/gi, ' data-style=');
1855      };
1856    }
1857    var appendHtmL = "";
1858    appendHtmL += `
1859        <div id="cbot-overlay-background"></div>
1860        <div class="cbot-spinner-overlay" id="spinnerContainer">
1861            <div class="cbot-spinner"></div>
1862        </div>`
1863    appendHtmL +=
1864      '<div class="cbot-survey-fadebg"></div>' +
1865      // '<div id="close-scroll" class="cbot-dialog-button-close" style="' + ((data_open && !data_mobileapp) ? display_block : display_none) + '; background-color:' + cbot_config.dialogButtonColor + custom_positioning_dialog + '"></div>' +
1866      '<div id="close-scroll" class="cbot-dialog-button-close"></div>' + // bu alan hiç gözükmeyecek
1867      '<div class="cbot-animation-holder ' + custom_animation + '" style="' + custom_positioning + '">' +
1868      '<div class="cbot-count-badge" id="cbot-count-badge">' + newMsgCount + '</div>' +
1869      '<div class="cbot-dialog-button-regular cbot-channel-' + CHANNEL.toLowerCase() + '" style="' + (data_open ? display_none : display_block) +
1870      'background-size: 100% 100%; ' +
1871      // 'margin-top:10px; background-image: url(' + cbot_config.dialogImageURL + ');' +
1872      custom_width_height +
1873      '">'
1874      + (clients.hide_bot_button ?
1875        '<div class="cbot-dialog-button-hide-icon"><span style="font-size: 14px; font-weight: bold;">×</span></div>'
1876        : '')
1877      + (!cbot_lottie_icon_activation ? '<img class="cbot-dialog-button-image" src="' + cbot_config.dialogImageURL + '" aria-label= "' + (clients.icon_voice_over || 'chatbot icon') + '" alt="cbot_icon"/>' : '<div id="lottie-animation">' + '</div>') +
1878
1879      '<div class="cbot-dialog-end-survey" style="' + custom_positioning_dialog + '"><span>Anketimize katılmak ister misiniz?</span> <a href="#" class="cbot-survey-yes">Evet</a> <a href="#" class="cbot-survey-no">Hayır</a></div>' +
1880
1881      '</div>';
1882
1883
1884
1885
1886    if (clients.popup_is_active) {
1887      var popup_message = clients.popup_text || 'Ben kişisel asistanınız ' + clients.bot_name + ',  size nasıl yardımcı olabilirim?';
1888      var popup_background_color = clients.popup_background_color || cbot_config.dialogButtonColor || "#000";
1889      var popup_text_color = clients.popup_text_color || cbot_config.title_font_color || "#FFF";
1890      var colors = "background: " + popup_background_color + "; color: " + popup_text_color + ";";
1891      var slidefromleftselected = ""
1892      if (clients.slide_from_left)
1893        slidefromleftselected += "; left: 20px";
1894      appendHtmL += '' +
1895        '<div class="cbot-proactive-rule cbot-dialog-button-help-message popup"' +
1896        'style="' + colors + display_none + custom_popup_positioning + slidefromleftselected + '">' + popup_message + '</div>';
1897
1898      var opening_delay = parseInt((clients.popup_initial_delay || 1) * 1000)
1899      var popup_duration = parseInt((clients.popup_show_time || 4) * 1000);
1900      setTimeout(() => {
1901        if (!isWidgetOpen) {
1902          $('.cbot-proactive-rule').not(".popup").css('display', 'none');
1903          $(".cbot-dialog-button-help-message.popup").fadeIn();
1904          if (!clients.popup_infinite_hold)
1905            setTimeout(() => {
1906              $(".cbot-dialog-button-help-message.popup").fadeOut();
1907            }, popup_duration);
1908        }
1909      }, opening_delay);
1910    }
1911    if (ia_display_popup_state && ia_display_popup_state.res) {
1912      let popupContent = handlePopup(ia_display_popup_state, clients, cbot_config);
1913      appendHtmL += popupContent
1914    }
1915    appendHtmL += "</div>"
1916
1917
1918    // cbot_config.robotImageURL 
1919    appendHtmL +=
1920      '<div class="cbot-survey-fadebg"></div>' +
1921      '<div id="cbot-modal" class="cbot-modal">' +
1922      '<span class="cbot-modal-close">&times;</span>' +
1923      '<img class="cbot-modal-content" id="cbot-modal-image">' +
1924      '</div >' +
1925      '<div class="notranslate cbot-main-container">' +
1926      (isSpeechEnabled() ?
1927        '<div class="notranslate cbot-dialog-speech">' +
1928        '<div class="cbot-dialog-speech-content-top">' +
1929        '<div id="particles-container">' +
1930        '<div id="particles-js"></div>' +
1931        '</div>' +
1932        '<div id="particles-thinking"><img class="cbot-thinking-image" src="' + staticAddress + '/img/cbot-thinking.gif?client=' + CLIENT + '" /></div>' +
1933        '</div>' +
1934        '<div class="cbot-dialog-speech-content-bottom">' +
1935        '<div class="cbot-dialog-speech-content-bottom-mic-button-open"><img src="' + staticAddress + '/img/cbot-speech-microphone-open.svg?client=' + CLIENT + '" style="width: 45%; height: 45%;" /></div>' +
1936        '<div class="cbot-dialog-speech-content-bottom-mic-button-muted"><img src="' + staticAddress + '/img/cbot-speech-microphone-muted.svg?client=' + CLIENT + '" style="width: 45%; height: 45%;" /></div>' +
1937        '<div class="cbot-dialog-speech-content-bottom-close-button"><img src="' + staticAddress + '/img/cbot-speech-close-icon.svg?client=' + CLIENT + '" style="width: 50%; height: 50%;" /></div>' +
1938        '</div>' +
1939        '</div>'
1940        : '') +
1941      '<div class="notranslate cbot-dialog" style="' + (data_open ? display_block : display_none) + custom_positioning_dialog + '">' +
1942      '<div id="cbot-web-area" style="display: none; opacity: 0;">' +
1943      '<div class="cbot-web-area-header" style="background: ' + dialogButtonColor + '">' +
1944      '<div class="cbot-web-reload"></div>' +
1945      '<div class="cbot-web-close"></div>' +
1946      '</div>' +
1947      '<div class="cbot-web-area-content" id="cbot-meet" ></div>' +
1948      '</div>' +
1949      '<div class="cbot-overlay" style="' + (data_open ? display_block : display_none) + 'display:none;transition:.5s;position:relative;width:100%;height:calc(100% - 67px);position: absolute;z-index: 999;background: rgba(0,0,0,0.5);border-radius:5px;">'
1950      +
1951
1952      '<div id="cbot-overlay-text" class="cbot-overlay-text cbot-overlay-help-collapse-on" style="' +
1953      'overflow: auto;' +
1954      'background: rgb(255, 255, 255);' +
1955      'bottom: 0px;' +
1956      'position: absolute;' +
1957      'border-radius: 5px;' +
1958      'padding: 20px 20px 10px;' +
1959      'width: calc(100% - 40px);' +
1960      'margin-top: 0px;' +
1961      'margin-bottom: 0px;' +
1962      'overflow: hidden;' +
1963      '">' +
1964
1965      '</div>' +
1966
1967
1968      '</div>' +
1969
1970
1971      '<div class="cbot-head-cover" style="' + (data_mobileapp ? display_none : display_block) + '">' +
1972      '<div class="cbot-dialog-sozlesme">' +
1973      '<div id="help-back-icon" style="background: url(' + staticAddress + '/img/flat/cbot-back.svg?client=' + CLIENT + ');' +
1974      'background-size: 15px;' +
1975      // 'background-color: lightgray;' +
1976      'background-position: center;' +
1977      'background-repeat: no-repeat;">' +
1978      // 'height: 55px;' +
1979      // 'background-position: 12px;' +
1980      // 'cursor: pointer;">' +
1981      '</div><span class="cbot-help-text-title" style="font-size: 16px;' +
1982      'line-height: 55px;' +
1983      '/* padding-left: 49px; */' +
1984      'user-select: none;' +
1985      'color: ' + clients.title_font_color + ';' +
1986      'text-align: center;' +
1987      'width: 100%;' +
1988      'display: block;">
1988' + (clients.help_text_title || "Yardım") + '</span>' +
1989      '</div><div class="cbot-dialog-head" style="background: ' + dialogButtonColor + ';">';
1990    // if (!data_full_page) {
1991    //     appendHtmL += '<div class="cbot-triple-dot" cbot-tooltip="Web"></div>';
1992    // }
1993
1994
1995    if (!data_full_page) {
1996      appendHtmL += '<div class="cbot-close-icon-new"  cbot-tooltip="' + (lang_vars.LANGVARS_CLOSE_TEXT_MESSAGE || "Kapat") + '" id="cbot-close-icon-new"></div>';
1997      if (clients.refresh_button) {
1998        appendHtmL += '<div class="cbot-refresh-icon"  cbot-tooltip="' + (lang_vars.LANGVARS_REFRESH_BUTTON_TOOLTIP_MESSAGE || "Yenile") + '" id="cbot-refresh-icon"></div>';
1999      }
2000      if (minimize_icon_is_active != "false") {
2001        appendHtmL += '<div class="cbot-minimize-icon"  cbot-tooltip="' + (lang_vars.LANGVARS_MINIMIZE_TEXT_MESSAGE || "Küçült") + '" id="cbot-minimize-icon"></div>';
2002      }
2003      if (tts_is_active) {
2004        appendHtmL += '<div class="cbot-mute-icon"  cbot-tooltip="' + (lang_vars.LANGVARS_TTS_MUTE_MESSAGE || "Ses") + '" id="cbot-mute-icon"></div>';
2005      }
2006    }
2007    appendHtmL += '<div class="cbot-cog-icon" id="cbot-cog-icon" cbot-tooltip="' + (lang_vars.LANGVARS_HELP_TEXT_MESSAGE || "Yardım") + '"></div>' +
2008      '<div class="cbot-avatar">
2008<img alt="cbot logo" src="' + "https://fibot-widget.fibabanka.com.tr/firm-fiba/assets/img/fibot.png" + '" draggable="false"/><span class="cbot-avatar-title-span" style="color: ' + (clients.title_font_color || "white") + '">' +
2009      (cbot_config.dialogTitle || "") + '</span></div></div></div>' +
2010      '' +
2011      '' +
2012      '<div class="cbot-help"  style="height: 100%;display:none;" id="cbot-help">' +
2013      '<div class="cbot-help-text">' +
2014      helpContent +
2015      '</div>' +
2016      '</div>' +
2017      '<div class="cbot-livechat-close">' + lang_vars.LANGVARS_LCHAT_CLOSE_BTN_TEXT +
2018      '<img src="' + staticAddress + '/img/cbot-livechat-close-icon.png?client=' + CLIENT + '" style="width:16px; box-shadow:none;"></div>' +
2019      '<div class="cbot-start-meeting">Görüntülü Görüşme Talep Et 🖥️</div>' +
2020      '<div class="cbot-alert-welcome-message"></div>' +
2021      '<ul class="notranslate cbot-chat" id="cbot-chat" ' + (data_mobileapp ? 'style="height: calc(100% - 116px);"' : '') + '>' +
2022      '<div class="cbot-survey"><div class="cbot-survey-text">Yapmış olduğunuz görüşmeyi değerlendirebilir misiniz?</div></div>' +
2023      '</ul> ' +
2024      '<div class="cbot-dialog-end-timer" style="display:none;"></div>' +
2025      '<div class="cbot-livechat-end-timer" style="display:none;"></div>' +
2026      '<div class="ripple_effect" style="display:none;">' +
2027      '<div class="cbot-boxContainer"><div class="cbot-box cbot-box1"></div><div class="cbot-box cbot-box2"></div><div class="cbot-box cbot-box3"></div><div class="cbot-box cbot-box4"></div><div class="cbot-box cbot-box5"></div></div>' +
2028      '</div>' +
2029      '<form id="cbot-form" action="" onsubmit="return false;">' +
2030      '<div class="cbot-form-message-area" id="cbot-form-message-area">' +
2031      '<span id="cbot-illusion-placeholder" class="cbot-illusion-placeholder">' + (lang_vars.LANGVARS_PLACEHOLDER_MESSAGE || clients.placeholder_message) + '</span>' +
2032      '<input type="button" class="cbot-send-button-info" style="display:none;" />' +
2033      '<textarea class="textarea" autocomplete="off" id="cbot-form-message" type="text" placeholder="' + (lang_vars.LANGVARS_PLACEHOLDER_MESSAGE) + '"></textarea> ';
2034
2035    if (!(iOS && iOS11)) {
2036      appendHtmL += '<button id="cbot-send-button" class="cbot-send-button" aria-label="Gönder"></button>';
2037    }
2038    /* ATTACHMENT AREA */
2039
2040    appendHtmL += "<input id='cbot-attachment-file-input' type='file' accept='' hidden/>";
2041    appendHtmL += '<div id="cbot-attachment-area" class="cbot-attachment-area" style="display: ' + (bool_attachments && isLive ? "block" : "none") + '">' +
2042      '<div class="cbot-attachment-container">' +
2043      // '<div class="cbot-attachment-block cbot-attachment-location"><img src="' + staticAddress + '/img/cbot-location-image.png" /> <span>Konum</span></div>' +
2044      // '<div class="cbot-attachment-block cbot-attachment-image"><img src="' + staticAddress + '/img/cbot-gallery.png" /> <span>Resim</span></div>' +
2045      // '<div class="cbot-attachment-block cbot-attachment-video"><img src="' + staticAddress + '/img/cbot-gallery.png" /> <span>Video</span></div>' +
2046      '<div class="cbot-attachment-block cbot-attachment-file"><img alt="file icon" title="file icon" src="' + staticAddress + '/img/cbot-file-icon.png?client=' + CLIENT + '" /> <span>Dosya</span></div>' +
2047      '</div>' +
2048      '</div>';
2049    setTimeout(() => {
2050      if (cbot_voice_bot_is_active) {
2051        $("#cbot-attachment-area").css("right", "77px");
2052      }
2053    }, 50);
2054    /* ATTACHMENT AREA */
2055
2056    /* VOICE AREA */
2057    var voiceAreaTooltip = (voice_bot_button_push_to_talk && voice_button_tooltip) ? ' cbot-voice-tooltip="' + voice_button_tooltip + '"' : '';
2058    appendHtmL += '<div id="cbot-voice-area" class="cbot-voice-area" style="' + (cbot_voice_bot_is_active || voice_assistant ? 'display: block;' : 'display: none;') + '"' + voiceAreaTooltip + '></div>';
2059    if (cbot_voice_bot_is_active && typeof initRecorder === "function" && (window.SpeechRecognition || window.webkitSpeechRecognition)) {
2060      initRecorder()
2061    }
2062    /* VOICE AREA */
2063
2064
2065    appendHtmL += '</div>';
2066
2067    if (powered_by_cbot) {
2068      appendHtmL += `<a href="https://cbot.ai" target="_blank"><img src="` + staticAddress + `/img/cbot-powered-by-cbot-black.png?client=` + CLIENT + `" style="
2069    position: absolute;
2070    bottom: 2px;
2071    width: 140px;
2072    left: 28%;
2073        "></a>`;
2074    }
2075
2076    appendHtmL += '</form>' +
2077      '</div>';
2078    appendHtmL += '</div>';
2079
2080    $('body').append(appendHtmL);
2081    afterAppend();
2082    initializeLottieAnimation("lottie-animation", lottie_icon_url);
2083
2084
2085    setInterval(function () {
2086      cbotRightBeforeFocused = $("#cbot-form-message").is(":focus")
2087    }, 100)
2088
2089    // $("#cbot-chat").scroll(function () {
2090    //     if (cbotKeyboardScrollInitialized) {
2091    //         cbotKeyboardScrollInitialized = false;
2092    //         $("#cbot-form-message").blur();
2093    //     }
2094    // });
2095
2096
2097
2098    if (data_open) {
2099      dialogOpenFunctions()
2100    }
2101
2102    $("#cbot-attachment-area")
2103      .on("click", function (event) {
2104        /* event.stopPropagation(); */
2105        sendCustomPostMessage("CBOT_FILE_UPLOAD_BUTTON_CLICKED", {});
2106      }).children()
2107      .on('click', 'div', function (e) {
2108        e.stopPropagation();
2109      });
2110
2111
2112
2113    fileUploadListener();
2114
2115
2116
2117    $(".cbot-dialog-end-survey").css("background-color", clients.popup_background_color || cbot_config.dialogButtonColor || "#000")
2118    $(".cbot-dialog-end-survey *").css("color", clients.popup_text_color || cbot_config.title_font_color || "#FFF")
2119    $(".cbot-dialog-end-survey").css("border-color", clients.popup_text_color || cbot_config.title_font_color || "#FFF")
2120
2121
2122
2123
2124    $(".cbot-dialog-sozlesme").css("background", dialogButtonColor || "rgb(21, 0, 143)");
2125
2126    $(".cbot-secondary-button").click(function () {
2127      cbotHideHelpTextMenu();
2128      cbotFocus($(".cbot-form-message"));
2129    })
2130    $(".cbot-primary-button").click(function () {
2131
2132      cbotHideHelpTextMenu();
2133      fadeIn(elCbotDialogRegularButton);
2134      fadeOut(elCbotDialog);
2135    })
2136    $(".cbot-dialog-button").animate({
2137      right: "+=270"
2138    }, 1000, function () {
2139      //console.log("cbot-dialog-button animate completed");
2140    });
2141
2142    $(".cbot-okudum-anladim-trigger").on("click", function () {
2143
2144      $(".cbot-okudum-anladim-checkbox").attr("checked", !$(".cbot-okudum-anladim-checkbox").attr("checked"))
2145
2146    })
2147
2148    $(".cbot-close-icon-new").on("click", cbotCloseIcon)
2149    $(".cbot-refresh-icon").on("click", cbotRefreshIcon)
2150    $(".cbot-minimize-icon").on("click", function () {
2151      sendCustomPostMessage("CBOT_WIDGET_MINIMIZED", {});
2152      isWidgetOpen = false;
2153
2154      if (!data_full_page) {
2155        fadeIn(elCbotDialogRegularButton);
2156        fadeOut(elCbotDialog);
2157      }
2158
2159      $(".cbot-dialog-button-regular").removeClass("cbot-slide-right")
2160      $(".cbot-dialog-button-regular").removeClass("cbot-slide-left")
2161
2162      if (clients.slide_from_left) {
2163        $(".cbot-dialog-button-regular").css("left", "20px");
2164      }
2165    })
2166    $("#cbot-mute-icon").on("click", function () {
2167      cancelTTS();
2168      tts_is_active = !tts_is_active;
2169      if (!tts_is_active) {
2170        $(".cbot-mute-icon").css('background', 'url(../img/flat/cbot-volume-mute.svg?client=' + CLIENT + ') no-repeat')
2171        $(".cbot-mute-icon").css('background-size', '15px')
2172        $(".cbot-mute-icon").css('background-position', 'center')
2173      } else {
2174        $(".cbot-mute-icon").css('background', 'url(../img/flat/cbot-volume-unmute.svg?client=' + CLIENT + ') no-repeat')
2175        $(".cbot-mute-icon").css('background-size', '15px')
2176        $(".cbot-mute-icon").css('background-position', 'center')
2177      }
2178    });
2179    $(document).on("click", "#cbot-close-button", function () {
2180      isWidgetOpen = false;
2181      $(".cbot-dialog-button").animate({
2182        right: "-=270"
2183      }, 1000, function () {
2184        fadeIn(elCbotDialogRegularButton);
2185      });
2186    });
2187
2188    $(document).on("click", ".cbot-dropdown-input", function (element) {
2189      var dropdown = $(this).next();
2190
2191      $(dropdown).css("display", "block");
2192      $(".cbot-msg").css("max-height", "60px")
2193
2194      scrollChatScreen()
2195    });
2196
2197    $(document).on("keyup", ".cbot-dropdown-input", function (event) {
2198      var input, filter, ul, li, a, i;
2199      input = document.getElementsByClassName("cbot-dropdown-input")[document.getElementsByClassName("cbot-dropdown-input").length - 1];
2200      input = event.target;
2201      filter = input.value.toLocaleUpperCase("tr");
2202      div = $(event.target).next();
2203      a = $(div).find("button");
2204      for (i = 0; i < a.length; i++) {
2205        txtValue = a[i].textContent || a[i].innerText;
2206        if (txtValue.toLocaleUpperCase("tr").indexOf(filter) > -1) {
2207          a[i].style.display = "";
2208        } else {
2209          a[i].style.display = "none";
2210        }
2211      }
2212    })
2213    $(document).on("click", ".cbot-combobox", function (element) {
2214      // console.log(element)
2215      var payload = element.target.getAttribute('data-payload');
2216      // clickButton("postback", null, payload);
2217      // console.log("PAYLOAD: ", payload, element.target);
2218      cbotgtag('event', 'cbot', {
2219        'event_category': 'cbot-button',
2220        'event_action': "click",
2221        'event_label': payload
2222      });
2223      $(".cbot-dropdown-input").attr("disabled", "disabled")
2224      $(".cbot-dropdown-input:last").val(payload)
2225      dialog(cbotUserId, payload, null, payload);
2226
2227    });
2228    $(document).click(function (e) {
2229      if (e.target.className != "cbot-dropdown-input" && e.target.className != "cbot-dropdown-input") {
2230        $(".cbot-dropdown-content").css("display", "none");
2231      }
2232    });
2233
2234    $(document).on("click", ".cbot-web-close", function () {
2235      setTimeout(function () {
2236        forceCloseJitsiMeet();
2237        $('.cbot-web-area-content').html("");
2238      }, 500);
2239
2240      $("#cbot-web-area").fadeOut();
2241    });
2242
2243    $(document).on("click", ".cbot-web-reload", function () {
2244      // $('#cbot-web-iframe').attr('src', $('#cbot-web-iframe').attr('src'));
2245      $('.cbot-web-area-content').html($('.cbot-web-area-content').html());
2246    });
2247
2248    $(document).on("click", ".cbot-join-chat-container-close", function () {
2249      $(".cbot-join-chat-container").css("display", "none");
2250    });
2251
2252    $(document).on("click", ".cbot-dialog-button-regular", function () {
2253      dialogButtonRegular();
2254    });
2255    $(document).on("click", ".cbot-dialog-button-hide-icon", function (e) {
2256      e.stopPropagation();
2257      $(".cbot-animation-holder").hide();
2258    });
2259
2260    $(document).on("click", ".cbot-livechat-close", function () {
2261      clickToCloseLivechatButton();
2262    });
2263    $(document).on("click", ".cbot-start-meeting", toggleJitsiMeet);
2264    $(document).on("click", "#cbot-mini-web-toggle", toggleMiniWebForMobile);
2265
2266
2267
2268    $(".cbot-dialog-end-survey").click(function (event) { event.stopPropagation(); });
2269
2270    $(".cbot-survey-yes").on("click", function () {
2271      dialogCloseSurveyShowed = false;
2272      // dialogCloseSurveyAsked = true;
2273      // surveyTrigger(clients.dialog_end_survey_object, cbotUserId, 1)
2274      // dialog(cbotUserId, clients.dialog_end_survey_keyword || "CLOSE_DIALOG_SURVEY", null, null, false);
2275      dialogButtonRegular();
2276      $(".cbot-dialog-end-survey").fadeOut();
2277      $(".cbot-survey-fadebg").css("display", "none")
2278    })
2279
2280    $(".cbot-survey-no").on("click", function () {
2281      dialogCloseSurveyShowed = false;
2282      // dialogCloseSurveyAsked = true;
2283      $(".cbot-dialog-end-survey").fadeOut();
2284      $(".cbot-survey-fadebg").css("display", "none")
2285    })
2286
2287    $(".display-popup").on("click", function () {
2288      ia_take_attention_state.is_executed = true;
2289    })
2290
2291    var elCbotDialogButton = document.getElementsByClassName('cbot-dialog-button')[0];
2292    elCbotDialogRegularButton = document.getElementsByClassName('cbot-dialog-button-regular')[0];
2293    elCbotDialog = document.getElementsByClassName('cbot-dialog')[0];
2294    // var elCbotDialogButtonClose = document.getElementsByClassName('cbot-dialog-button-close')[0];
2295    var elCbotDialogHead = document.getElementsByClassName('cbot-dialog-head')[0];
2296    var elCbotRemove = document.getElementsByClassName('cbot-remove')[0];
2297    var elCbotForm = document.getElementById('cbot-form');
2298    var elCbotFormMessage = document.getElementById('cbot-form-message');
2299    var elCbotChat = document.getElementsByClassName('cbot-chat')[0];
2300    var elCbotHelpIcon = document.getElementById('cbot-help-icon');
2301    var elCbotTripleDot = document.getElementsByClassName('cbot-triple-dot')[0];
2302    var elCbotHelp = document.getElementById('cbot-help');
2303    var elCbotWebArea = document.getElementById('cbot-web-area');
2304    var elCbotAttachmentArea = document.getElementById("cbot-attachment-area");
2305    var elCbotMessageArea = document.getElementById('cbot-form-message-area');
2306
2307
2308    cbotModal = document.getElementById("cbot-modal");
2309    if (!queryStringVars.cbot_message) queryStringVars.cbot_message = getParameterFromScript("message");
2310    welcomeMessage = welcomeMessage;
2311    welcomeMessageSent = !!queryStringVars.cbot_message;
2312    if (!queryStringVars.cbot_message && welcomeMessage) {
2313      appendMessageToDialogBox(welcomeMessage, "cbot-other", null, {}, function () {
2314      });
2315    }
2316    welcomeMessageSent = true;
2317
2318    // getConversations(function() {
2319    //     writeConversations();
2320    // });
2321    // var open = getParameterByName("open");
2322    // var data_open = getParameterFromScript("data-open");
2323    // try {
2324    //     if (open == "true" || data_open == "true" || IS_OPENED) {
2325    //         elCbotDialogRegularButton.click();
2326    //     }
2327    // } catch (err) {
2328
2329    // }
2330
2331
2332
2333
2334    elCbotAttachmentArea.onclick = function (e) {
2335      $("#cbot-attachment-file-input").click();
2336      // console.log("Attachment icon is clicked");
2337
2338    }
2339
2340    // $(document).click(function (e) {
2341    //     if (e.target.className != "cbot-attachment-container" && e.target.className != "cbot-attachment-area") {
2342    //         // console.log("dışarıya bastın", e.target.className);
2343    //         hideAttachmentMenu();
2344    //     }
2345    // })
2346
2347
2348
2349    // Get the image and insert it inside the modal - use its "alt" text as a caption
2350    cbotModalImg = document.getElementById("cbot-modal-image");
2351
2352
2353    var span = document.getElementsByClassName("cbot-modal-close")[0];
2354
2355    // When the user clicks on <span> (x), close the modal
2356    span.onclick = function () {
2357      cbotModal.style.display = "none";
2358    }
2359
2360    $(elCbotFormMessage).bind('input', function () {
2361      $(this).val() // get the current value of the input field.
2362      var word = $(this).val();
2363      if (word && word.length > 0 && word != " ") {
2364        hideHelperMenu();
2365        $(".cbot-send-button").addClass("active");
2366        // $(".cbot-send-button").css("background-image", "url(" + staticAddress + "/img/flat/send-active.png)")
2367      } else {
2368        $(".cbot-send-button").removeClass("active");
2369        // $(".cbot-send-button").css("background-image", "url(" + staticAddress + "/img/flat/send-disabled.png)")
2370
2371      }
2372    });
2373
2374    var cbotSendButtonInfoToggle = true;
2375    $(".cbot-send-button-info").on("click", function () {
2376
2377      // $(".cbot-overlay").toggle();
2378      // $(".cbot-overlay").animate({ backgroundColor: "#FFF" }, 1000, function() { });
2379      $(".cbot-dialog-help-menu-help").fadeOut();
2380      $(".cbot-dialog-help-menu-help").css("display", "none");
2381      toggleHelperMenu();
2382
2383
2384    })
2385    $(".cbot-send-button-info").hover(function () {
2386      $(".cbot-dialog-help-menu-help").css("opacity", "0");
2387      $(".cbot-dialog-help-menu-help").css("display", "block");
2388      $(".cbot-dialog-help-menu-help").stop().animate({ opacity: 1 }, 400, function () {
2389
2390      });
2391
2392
2393    }, function () {
2394
2395      $(".cbot-dialog-help-menu-help").stop().animate({ opacity: 0 }, 400, function () {
2396        $(".cbot-dialog-help-menu-help").css("display", "none");
2397      });
2398    })
2399    function toggleHelperMenu() {
2400
2401      if (cbotSendButtonInfoToggle) {
2402        hideHelperMenu();
2403      }
2404      else {
2405        showHelperMenu();
2406      }
2407    }
2408    hideHelperMenu()
2409    $(".cbot-overlay").click(function (e) {
2410      if (e.target.className == "cbot-overlay") {
2411        hideHelperMenu();
2412      }
2413    })
2414    // $(document).click(function (e) {
2415    //     //if clicked element is not your element and parents aren't your div
2416    //     if (e.target.id != 'cbot-overlay-text' && $(e.target).parents('#cbot-overlay-text').length == 0 && e.target.id != 'cbot-form-message-area' && $(e.target).parents('#cbot-form-message-area').length == 0) {
2417    //         //do stuff
2418    //         hideHelperMenu();
2419    //     }
2420    // });
2421
2422    if (voice_bot_button_option) {
2423
2424      $('.cbot-dialog-button-regular').on('click', function () {
2425        viewVoiceButton()
2426      });
2427
2428      $('#cbot-form-message').on('keypress', function (event) {
2429        if (event.which === 13) {
2430          // $(".cbot-send-button").css("display", "none");
2431          $(".cbot-voice-area").css("display", "block");
2432        }
2433      });
2434
2435      $('#cbot-send-button').on('click', function () {
2436        $("#cbot-voice-area").css("display", "block");
2437        $("#cbot-send-button").css("display", "none");
2438      });
2439
2440
2441      $("#cbot-form-message").on("input", function () {
2442        var currentValue = $(this).val().trim();
2443        var placeholderValue = $(this).attr('placeholder').trim();
2444        if (currentValue.length > 0) {
2445          $(".cbot-send-button").css("display", "block");
2446          $(".cbot-voice-area").css("display", "none");
2447          var currentValue = $(this).val().trim();
2448          if (currentValue === "" && $(this).val() !== $(this).attr('placeholder')) {
2449            $(this).val($(this).attr('currentValue'));
2450          }
2451        } else {
2452          if (currentValue === placeholderValue) {
2453            currentValue = '';
2454          }
2455          if (currentValue.length === 0) {
2456            // $(".cbot-send-button").css("display", "none");
2457            $(".cbot-voice-area").css("display", "block");
2458          }
2459        }
2460        if (bool_attachments && isLive) {
2461          var currentValue = $(this).val().trim();
2462          var placeholderValue = $(this).attr('placeholder').trim();
2463
2464          if (currentValue === placeholderValue) {
2465            currentValue = '';
2466          }
2467
2468          if (currentValue.length === 0) {
2469            toggleAttachmentIcon("block");
2470          } else {
2471            toggleAttachmentIcon("none");
2472          }
2473        }
2474      });
2475    }
2476
2477    var sozlesmeToggler = true;
2478    $(".cbot-cog-icon").on("click", function () {
2479      cbotShowHelpTextMenu()
2480      sendCustomPostMessage("CBOT_INFO_ICON_CLICKED", {});
2481      // sendTriggerMessages(trigger_messages)
2482      // cbotShowHelpTextMenu();
2483
2484    })
2485    $(".cbot-dialog-sozlesme").on("click", function () {
2486      cbotHideHelpTextMenu();
2487      sendCustomPostMessage("CBOT_INFO_BACK_ICON_CLICKED", {});
2488    })
2489    $(".cbot-help-back-icon").on("click", function () {
2490
2491      cbotHideHelpTextMenu();
2492      sendCustomPostMessage("CBOT_INFO_BACK_ICON_CLICKED", {});
2493
2494    })
2495    function showHelperMenu() {
2496
2497      // $(".cbot-overlay-text").css("transform", "scaleY(0)")
2498      // $(".cbot-overlay").animate({ "bottom": "-9999px" });
2499      $(".cbot-overlay").css("display", "block");
2500      $(".cbot-overlay").css("transition", "transform 0.3s ease-out");
2501      setTimeout(function () { // bug !!
2502        $(".cbot-overlay").css("background-color", "rgba(0,0,0,.5)");
2503      }, 0);
2504      $(".cbot-overlay").css("transition", ".5s");
2505      // $(".cbot-overlay").css("display", "block");
2506      $(".cbot-overlay-text").stop().slideDown(500, function () {
2507        // console.log("slide down");
2508      })
2509      $(".cbot-overlay-text").stop().animate({ scrollTop: /* $('.cbot-overlay-text').prop("scrollHeight") */0 }, 500, function () {
2510      });
2511      // $(".cbot-overlay").animate({ "marginTop": "0" });
2512      // $(".cbot-overlay").animate({ "bottom": "" });
2513      cbotSendButtonInfoToggle = true;
2514
2515    }
2516    function hideHelperMenu() {
2517      $(".cbot-overlay").css("background-color", "rgba(0,0,0,0)");
2518      $(".cbot-overlay-text").stop().slideUp(500, function () {
2519        $(".cbot-overlay").css("display", "none")
2520        // console.log("slide up")
2521      })
2522      cbotSendButtonInfoToggle = false;
2523    }
2524
2525    // $(".cbot-dialog-button-regular").hover(function () {
2526
2527    //   if (closing_popup_is_showing) return;
2528    //   if (!dialogCloseSurveyShowed) {
2529
2530    //     $(".cbot-dialog-button-help-message").css("opacity", "0");
2531    //     $(".cbot-dialog-button-help-message").css("display", "block");
2532    //     $(".cbot-dialog-button-help-message").stop().animate({ opacity: 1 }, 400, function () {
2533
2534    //     });
2535    //   }
2536
2537    // }, function () {
2538    //   if (closing_popup_is_showing) return;
2539    //   $(".cbot-dialog-button-help-message").stop().animate({ opacity: 0 }, 400, function () {
2540    //     $(".cbot-dialog-button-help-message").css("display", "none");
2541    //   });
2542
2543    // })
2544
2545
2546    $(".cbot-new-help-sentences").find("li").each(function (index, item) {
2547      $(item).click(function () {
2548        // console.log("li clicked", $(item).text());
2549
2550        dialog(cbotUserId, $(item).text());
2551        // $('#cbot-form-message').attr('disabled', true)
2552        $('#cbot-form-message').val('');
2553        hideHelperMenu();
2554      })
2555    })
2556
2557    // setTimeout(function() {
2558    //     $(".cbot-dialog-button-help-message").fadeOut();
2559    // }, 4 * 1000); // POC-55 // POC-71
2560
2561    //     if (!data_full_page) {
2562    //         elCbotTripleDot.onclick = function (event) {
2563    //             event.stopPropagation();
2564    //             if ($("#cbot-web-area").css("display") == "none") {
2565    //                 fadeIn(elCbotWebArea);
2566    //             } else {
2567    //                 fadeOut(elCbotWebArea);
2568    //             }/* 
2569    //             if (elCbotHelp.style.display == "none") {
2570    //                 slideIn(elCbotHelp);
2571    //             } else {
2572    //                 slideOut(elCbotHelp);
2573    //             }
2574    //  */
2575    //         }
2576    //     }
2577    // elCbotHelpIcon.onclick = function () {
2578    //     // console.log(elCbotHelp.style.display);
2579    //     if (elCbotHelp.style.display == "none") {
2580    //         slideIn(elCbotHelp);
2581    //     } else {
2582    //         slideOut(elCbotHelp);
2583    //     }
2584    //     // slideIn(elCbotHelp);
2585    // }
2586
2587    elCbotFormMessage.oninput = function () {
2588
2589
2590      if (!elCbotFormMessage.value || elCbotFormMessage.value == " ") {
2591        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
2592        $('#cbot-form-message').removeAttr('disabled');
2593        $(".cbot-illusion-placeholder").css("display", "block");
2594      }
2595      else {
2596        $(".cbot-illusion-placeholder").css("display", "none");
2597      }
2598
2599
2600
2601    }
2602
2603    function handleScrollCheck() {
2604      setTimeout(function () {
2605        const chatEl = document.getElementById("cbot-chat");
2606        const scrollTop = chatEl.scrollTop;
2607        const height = parseInt($("#cbot-chat").height());
2608        const scrollHeight = chatEl.scrollHeight;
2609        const total = scrollTop + height + 500;
2610
2611        if (total > scrollHeight) {
2612          scrollChatScreen(500);
2613        }
2614      }, 300);
2615    }
2616
2617    elCbotFormMessage.onfocus = function () {
2618      cbotInputKeyboardClicked = true;
2619      cbotKeyboardScrollInitialized = false;
2620      setTimeout(function () {
2621        cbotKeyboardScrollInitialized = true;
2622      }, 1000);
2623
2624      if (document.getElementById("cbot-chat").scrollTop + parseInt($("#cbot-chat").height()) + 500 > document.getElementById("cbot-chat").scrollHeight) {
2625        scrollChatScreen(500);
2626      }
2627
2628    }
2629    elCbotFormMessage.addEventListener('focus', handleScrollCheck);
2630    elCbotFormMessage.addEventListener('click', handleScrollCheck);
2631    elCbotFormMessage.addEventListener('touchstart', handleScrollCheck);
2632    elCbotFormMessage.onblur = function () {
2633      // console.log("blurred")
2634      cbotInputKeyboardClicked = false;
2635      soc_typing(false);
2636
2637      if (!elCbotFormMessage.value) {
2638
2639        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
2640        $('#cbot-form-message').removeAttr('disabled');
2641        $(".cbot-illusion-placeholder").css("display", "block");
2642        elCbotFormMessage.value = " "
2643      }
2644
2645    }
2646
2647
2648    setClickEventToInteractiveButtons(cbotUserId);
2649
2650    $("#cbot-form-message").keypress(function (event) {
2651      if (event.which == 13) {
2652        soc_typing(false);
2653        event.preventDefault();
2654        var message = elCbotFormMessage.value;
2655        // console.log("MESSAGE:", message);
2656        var typing = default_messages[botlanguage].TYPING
2657        var text_control = new RegExp(`${typing}\\.\\.\\.`, "i");
2658        if (message != "" && !/^\s+$/.test(message) && !text_control.test(message)) {
2659          // if (/^([cçÇ]+[ıiİ]*k+([ıiİ]*[sşŞ$]+)?|k+[a@4]*p[a@4]*t+|kend[ıiİ]n[ıiİ] k+[a@4]*p[a@4]*t*)$/i.test(message)) {
2660          //     elCbotFormMessage.value = "";
2661          //     /* fadeOut(elCbotDialogButtonClose); */
2662          //     fadeIn(elCbotDialogButton);
2663          //     fadeOut(elCbotDialog);
2664          // } else {
2665          message = cleanTags(message);
2666          dialog(cbotUserId, message);
2667          // elCbotFormMessage.setAttribute('readonly', true);
2668          if (document.getElementById("cbot-send-button"))
2669            document.getElementById("cbot-send-button").setAttribute("disabled", true);
2670          elCbotFormMessage.value = ' ';
2671          $(".cbot-illusion-placeholder").html(`${typing}...`)
2672          $('#cbot-form-message').attr('disabled', 'disabled');
2673          // }
2674        } else {
2675          $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
2676          $('#cbot-form-message').removeAttr('disabled');
2677          elCbotFormMessage.value = " ";
2678        }
2679        $(".cbot-illusion-placeholder").css("display", "block");
2680
2681
2682      }
2683    });
2684    $("#cbot-form-message").keyup(function (event) {
2685      if ((elCbotFormMessage.value || "").trim().length > 0) {
2686        soc_typing(true);
2687      } else {
2688        soc_typing(false);
2689      }
2690    })
2691
2692    // Mesaj gönderme fonksiyonu - direkt text ile çalışır
2693    sendMessage = (messageText, conversation_type = "text") => {
2694      if (conversation_type == "audio") {
2695        if (isSpeechEnabled()) {
2696          $("#particles-thinking").css("opacity", "1");
2697        }
2698        dialog(cbotUserId, messageText, undefined, undefined, undefined, undefined, undefined, conversation_type);
2699        return;
2700      }
2701      var typing = default_messages[botlanguage].TYPING;
2702      var text_control = new RegExp(`${typing}\\.\\.\\.`, "i");
2703
2704      if (messageText != "" && !/^\s+$/.test(messageText) && !text_control.test(messageText)) {
2705        // Geçerli mesaj - gönder
2706        var cleanedMessage = cleanTags(messageText);
2707        dialog(cbotUserId, cleanedMessage);
2708
2709        // UI durumlarını güncelle
2710        elCbotFormMessage.value = ' ';
2711        isRecognitionStopped = true;
2712        if (cbot_voice_bot_is_active && recognition && recognition.stop) recognition.stop();
2713        $(".ripple_effect").css("display", "none");
2714        $("#cbot-form-message").css("display", "block");
2715        $("#cbot-voice-area").removeClass("active");
2716
2717        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
2718        $('#cbot-form-message').removeAttr('disabled');
2719
2720        if (document.getElementById("cbot-send-button"))
2721          document.getElementById("cbot-send-button").setAttribute("disabled", true);
2722        elCbotFormMessage.value = ' ';
2723        $(".cbot-illusion-placeholder").html(`${typing}...`);
2724        $(".cbot-illusion-placeholder").css("display", "block");
2725        $('#cbot-form-message').attr('disabled', 'disabled');
2726
2727        if (cbotRightBeforeFocused)
2728          cbotFocus(elCbotFormMessage);
2729      } else {
2730        // Geçersiz mesaj - sadece UI'yi temizle
2731        elCbotFormMessage.value = " ";
2732        isRecognitionStopped = true;
2733        if (cbot_voice_bot_is_active && recognition && recognition.stop) recognition.stop();
2734        $(".ripple_effect").css("display", "none");
2735        $("#cbot-form-message").css("display", "block");
2736        $("#cbot-voice-area").removeClass("active");
2737        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
2738        $('#cbot-form-message').removeAttr('disabled');
2739        $(".cbot-illusion-placeholder").css("display", "block");
2740
2741        if (cbotRightBeforeFocused)
2742          cbotFocus(elCbotFormMessage);
2743      }
2744    }
2745
2746    $(document).on("click", "#cbot-send-button", function (event) {
2747      // console.log('event => ', event);
2748      event.preventDefault();
2749      var message = elCbotFormMessage.value;
2750      // console.log("MESSAGE:", message);
2751      sendMessage(message);
2752    });
2753
2754    // ripple effect js
2755    // class AudioVisualizer {
2756    //   constructor(audioContext, processFrame, processError) {
2757    //     this.audioContext = audioContext;
2758    //     this.processFrame = processFrame;
2759    //     this.connectStream = this.connectStream.bind(this);
2760    //     navigator.mediaDevices.getUserMedia({ audio: true, video: false }).
2761    //       then(this.connectStream).
2762    //       catch(error => {
2763    //         if (processError) {
2764    //           processError(error);
2765    //         }
2766    //       });
2767    //   }
2768
2769    //   connectStream(stream) {
2770    //     this.analyser = this.audioContext.createAnalyser();
2771    //     const source = this.audioContext.createMediaStreamSource(stream);
2772    //     source.connect(this.analyser);
2773    //     this.analyser.smoothingTimeConstant = 0.6;
2774    //     this.analyser.fftSize = 32;
2775
2776    //     this.rippleEffectRenderLoop(this.analyser);
2777    //   }
2778
2779    //   rippleEffectRenderLoop() {
2780    //     let bufferLength = this.analyser.frequencyBinCount;
2781    //     const frequencyData = new Uint8Array(bufferLength);
2782
2783    //     const processFrame = this.processFrame || (() => { });
2784
2785    //     const renderFrame = () => {
2786    //       this.analyser.getByteFrequencyData(frequencyData);
2787    //       processFrame(frequencyData);
2788
2789    //       requestAnimationFrame(renderFrame);
2790    //     };
2791    //     requestAnimationFrame(renderFrame);
2792    //   }
2793
2794
2795    // const visualMainElement = document.querySelector('main');
2796    // const visualValueCount = 16;
2797    // let visualElements;
2798    // const createDOMElements = () => {
2799    //   let i;
2800    //   for (i = 0; i < visualValueCount; ++i) {
2801    //     const elm = document.createElement('div');
2802    //     visualMainElement.appendChild(elm);
2803    //   }
2804
2805    //   visualElements = document.querySelectorAll('main div');
2806    // };
2807    // createDOMElements();
2808
2809    // const ripple_effect = () => {
2810    //   // Creating initial DOM elements
2811    //   const audioContext = new AudioContext();
2812    //   const rippleEffectDOM = () => {
2813    //     visualMainElement.innerHTML = '';
2814    //     createDOMElements();
2815    //   };
2816    //   rippleEffectDOM();
2817
2818    //   // Swapping values around for a better visual effect
2819    //   const dataMap = {
2820    //     0: 15,
2821    //     1: 10,
2822    //     2: 8,
2823    //     3: 9,
2824    //     4: 6,
2825    //     5: 5,
2826    //     6: 2,
2827    //     7: 1,
2828    //     8: 0,
2829    //     9: 4,
2830    //     10: 3,
2831    //     11: 7,
2832    //     12: 11,
2833    //     13: 12,
2834    //     14: 13,
2835    //     15: 14
2836    //   };
2837    //   const processFrame = data => {
2838    //     const values = Object.values(data);
2839    //     let i;
2840    //     var total = 0;
2841    //     for (i = 0; i < visualValueCount; ++i) {
2842    //       const value = values[dataMap[i]] / 255;
2843    //       const elmStyles = visualElements[i].style;
2844    //       elmStyles.transform = `scaleY( ${value} )`;
2845    //       elmStyles.opacity = Math.max(.25, value);
2846
2847    //       var x = values[i];
2848    //       total += x * x;
2849    //     }
2850    //     var rms = Math.sqrt(total / audioContext.createAnalyser().frequencyBinCount);
2851    //     var db = 20 * (Math.log(rms) / Math.log(10));
2852    //     db = Math.max(db, 0); // sanity check
2853
2854    //   };
2855
2856    //   const processError = () => {
2857    //     visualMainElement.classList.add('error');
2858    //     visualMainElement.innerText = 'Please allow access to your microphone.';
2859    //   };
2860
2861    //   const a = new AudioVisualizer(audioContext, processFrame, processError);
2862    // };
2863    // ripple effect js finish
2864
2865    elCbotFormMessage.addEventListener("click", function () {
2866      if (cbotIsMobile.any()) {
2867        elCbotFormMessage.value = elCbotFormMessage.value + " ";
2868        elCbotFormMessage.value = elCbotFormMessage.value.slice(0, -1);
2869        var message = elCbotFormMessage.value;
2870        var typing = default_messages[botlanguage].TYPING
2871        var text_control = new RegExp(`${typing}\\.\\.\\.`, "i");
2872        if (!(message != "" && !/^\s+$/.test(message) && !text_control.test(message))) {
2873          event.preventDefault();
2874          elCbotFormMessage.value = "  ";
2875          $("#cbot-form-message").css("display", "block");
2876          $("#cbot-voice-area").removeClass("active");
2877          $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
2878          $('#cbot-form-message').removeAttr('disabled');
2879          $(".cbot-illusion-placeholder").css("display", "block");
2880          cbotFocus(elCbotFormMessage);
2881        }
2882      }
2883    });
2884
2885    elCbotFormMessage.addEventListener("input", function () {
2886      if (elCbotFormMessage.value.trim() === "") {
2887        if (cbotIsMobile.any()) {
2888          elCbotFormMessage.value = "  ";
2889        } else {
2890          elCbotFormMessage.value = " ";
2891        }
2892      }
2893    });
2894
2895    document.getElementById("cbot-overlay-background").addEventListener("click", cbotCloseIcon);
2896
2897    if (voice_assistant) {
2898      $(".cbot-voice-area").on("click", toggleSpeechView);
2899    } else {
2900      $(".cbot-voice-area").mousedown(function (event) {
2901        isRecognitionStopped = false
2902        startRecording();
2903        event.preventDefault();
2904        try {
2905          // ripple_effect()
2906        } catch (error) {
2907          console.log("ripple effect error:", error)
2908        }
2909      })
2910      $(".cbot-voice-area").mouseup(function () {
2911        if (cbot_voice_bot_is_active && recognition && recognition.stop) recognition.stop();
2912        isRecognitionStopped = true
2913        $(".ripple_effect").css("display", "none");
2914        $("#cbot-form-message").css("display", "block");
2915        $("#cbot-voice-area").removeClass("active");
2916      })
2917
2918      $(".cbot-voice-area").on('touchstart', function () {
2919        isRecognitionStopped = false
2920        startRecording();
2921        event.preventDefault();
2922        try {
2923          // ripple_effect()
2924        } catch (error) {
2925          console.log("ripple effect error:", error)
2926        }
2927      });
2928      $(".cbot-voice-area").on('touchend', function () {
2929        if (cbot_voice_bot_is_active && recognition && recognition.stop) recognition.stop();
2930        isRecognitionStopped = true
2931        $(".ripple_effect").css("display", "none");
2932        $("#cbot-form-message").css("display", "block");
2933        $("#cbot-voice-area").removeClass("active");
2934      });
2935    }
2936
2937    $(document).on("click", ".cbot-dialog-speech-content-bottom-close-button", function (e) {
2938      e.preventDefault();
2939      e.stopPropagation();
2940
2941      // Speech view'ı kapat (fade out animasyonu ile)
2942      if (showSpeechView) {
2943        showSpeechView = false;
2944        cancelOngoingPlayback();
2945        particlesUpdateByEnergy(0);
2946
2947        // Speech dialog'u fade out yap
2948        $(".cbot-dialog-speech").removeClass("fade-in").addClass("fade-out");
2949
2950        // Animasyon bitince display:none yap ve ana dialog'u fade in yap
2951        setTimeout(() => {
2952          $(".cbot-dialog-speech").css("display", "none");
2953          $(".cbot-dialog").removeClass("fade-out").addClass("fade-in");
2954        }, 500);
2955
2956        if (isSpeechViewMicButtonOpen) {
2957          toggleSpeechViewMicButton();
2958        }
2959      }
2960    });
2961    // Push-to-talk modunda farklı event handler'lar
2962    if (voice_bot_button_push_to_talk) {
2963      // Muted button için normal click (ses izinlerini almak için)
2964      $(document).on("click", ".cbot-dialog-speech-content-bottom-mic-button-muted", toggleSpeechViewMicButton);
2965
2966      // Open button için mousedown/mouseup ve touchstart/touchend
2967      $(document).on("mousedown touchstart", ".cbot-dialog-speech-content-bottom-mic-button-open", function (e) {
2968        e.preventDefault();
2969        if (isSpeechViewMicButtonOpen) {
2970          startPushToTalkRecording();
2971        }
2972      });
2973
2974      $(document).on("mouseup touchend mouseleave", ".cbot-dialog-speech-content-bottom-mic-button-open", function (e) {
2975        e.preventDefault();
2976        if (isPushToTalkActive) {
2977          stopPushToTalkRecording();
2978        }
2979      });
2980
2981      // Sayfa dışına çıkıldığında da durdur
2982      $(document).on("mouseup touchend", function () {
2983        if (isPushToTalkActive) {
2984          stopPushToTalkRecording();
2985        }
2986      });
2987
2988    } else {
2989      // Normal mode için eski event handler'lar
2990      $(document).on("click", ".cbot-dialog-speech-content-bottom-mic-button-open", toggleSpeechViewMicButton);
2991      $(document).on("click", ".cbot-dialog-speech-content-bottom-mic-button-muted", toggleSpeechViewMicButton);
2992    }
2993
2994    var isDragging = false;
2995
2996    $(document).on("mousedown", ".cbot-suggestion-button-slider", function (event) {
2997      var $slider = $(this);
2998      var startX = event.pageX || event.originalEvent.touches[0].pageX;
2999      var scrollLeft = $slider.scrollLeft();
3000
3001      isDragging = false;
3002
3003      $slider.on("mousemove", function (event) {
3004        isDragging = true;
3005        $slider.find("button").css("pointer-events", "none")
3006        var currentX = event.pageX || event.originalEvent.touches[0].pageX;
3007        var distance = startX - currentX;
3008        $slider.scrollLeft(scrollLeft + distance);
3009      });
3010
3011      if (isDragging == false) {
3012        $slider.find("button").css("pointer-events", "auto")
3013      }
3014    });
3015
3016    $(document).on("mouseup", ".cbot-suggestion-button-slider", function () {
3017      var $slider = $(this);
3018      $slider.off("mousemove");
3019    });
3020
3021    $(document).on('mouseenter', '.cbot-rating-label', function () {
3022      $(this).prevAll('.cbot-rating-label').addClass('hover');
3023    });
3024
3025    $(document).on('mouseleave', '.cbot-rating-label', function () {
3026      $(this).prevAll('.cbot-rating-label').removeClass('hover');
3027    });
3028
3029    $(document).on('touchstart mousedown', '.cbot-survey-type .cbot-button', function () {
3030      $('.cbot-survey-type .cbot-button.clicked').removeClass('clicked');
3031      $(this).addClass('clicked');
3032    });
3033
3034    // $(document).on('click', '.cbot-survey-type .cbot-button', function () {
3035    //     $(this).addClass('clicked');
3036    // });
3037
3038    // $(document).on("click", "#cbot-send-button", function (event) {
3039    //     event.preventDefault();
3040    //     var message = elCbotFormMessage.value;
3041    //     // console.log("MESSAGE:", message);
3042    //     if (message != "" && !/^\s+$/.test(message) && !/yazıyor.../i.test(message)) {
3043    //         message = cleanTags(message);
3044    //         dialog(cbotUserId, message);
3045    //         /* elCbotFormMessage.setAttribute('disabled', true);
3046    //         document.getElementById("cbot-send-button").setAttribute("disabled", true); */
3047    //         elCbotFormMessage.value = '';
3048    //     } else {
3049    //         elCbotFormMessage.value = "";
3050    //     }
3051    // });
3052
3053    /*$('#cbot-form').submit(function (e) {
3054     var message = $('#cbot-form-message').val();
3055     if (message != "") {
3056     message = cleanTags(message);
3057     console.log(message);
3058     dialog(cbotUserId, message);
3059     $('#cbot-form-message').attr('disabled', true)
3060     $('#cbot-form-message').val('yazıyor...');
3061     }
3062     return false;
3063     });*/
3064
3065
3066    // ! BU HEP EN ALTTA KALSIN.
3067    setDefaultMessages()
3068    sendCustomPostMessage("CBOT_WIDGET_INITIALIZED", {});
3069
3070  }, time * 1000);
3071}
3072
3073function afterAppend() {
3074  let tags = Array.from(document.querySelectorAll('[data-style]'));
3075  for (var tag of tags) {
3076    var attr = tag.getAttribute('data-style')
3077    var arr = attr.split(';').map((el, index) => el.trim());
3078    for (var i = 0, tmp; i < arr.length; ++i) {
3079      if (! /:/.test(arr[i])) continue;        // Empty or wrong style
3080      tmp = arr[i].split(':').map((el, index) => el.trim());
3081      tag.style[camelize(tmp[0])] = tmp.splice(1).join(":");
3082    }
3083
3084    tag.removeAttribute("data-style");
3085  }
3086
3087  var tagsonclick = document.querySelectorAll('[data-onclick]');
3088  for (var tag of tagsonclick) {
3089    var attr = tag.getAttribute('data-onclick')
3090    var functionName = attr.split("(")[0];
3091    var parameters = attr.match(/\((.*?)\)/)[1].split(",")
3092    tag.onclick = (function () {
3093      var params = parameters
3094      var funcName = functionName + ""
3095      return function () {
3096        window[funcName](...params)
3097      }
3098    })()
3099    tag.removeAttribute("data-onclick");
3100  }
3101
3102  $(".clipboard").on("click", function () {
3103    var value = $(this).attr("data-value");
3104    navigator.clipboard.writeText(value);
3105    const copyDiv = $(this).closest(".cbot-list-item-text-wrap").find("[class*=copyAlert]").filter(':not(.animate)');
3106    if (copyDiv[0]) {
3107      copyDiv[0].classList.add('animate');
3108      copyDiv[0].addEventListener('animationend', function () {
3109        copyDiv[0].classList.remove('animate')
3110      });
3111    }
3112  });
3113
3114  function camelize(str) {
3115    return str
3116      .split('-')
3117      .map((word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1))
3118      .join('');
3119  }
3120}
3121
3122
3123function dialogButtonRegular(next = () => { }) {
3124  hideTimeoutPopup();
3125  if (ia_take_attention_state_timer) clearTimeout(ia_take_attention_state_timer);
3126  if (!welcomeMessageSent && getChannelValue(clients.clear_after_close_bot, CHANNEL)) {
3127    if (welcomeMessage)
3128      appendMessageToDialogBox(welcomeMessage, "cbot-other", null, { /* unique_id: "hehe" */ }, function () {
3129        // setClickEventToFeedbackButtons("hehe");
3130
3131      });
3132
3133    sendTriggerMessages(trigger_messages);
3134  }
3135
3136  var elCbotDialogRegularButton = document.getElementsByClassName('cbot-dialog-button-regular')[0];
3137  var elCbotDialog = document.getElementsByClassName('cbot-dialog')[0];
3138
3139  $(".cbot-survey-fadebg").css("display", "none")
3140  isWidgetOpen = true;
3141  setIsWidgetOpenedTLS(true);
3142  newMsgCount = 0;
3143  toggleBadge(newMsgCount);
3144  $(".cbot-dialog-end-survey").hide();
3145  try {
3146    // force close ad
3147    $(".modal.fade.ec-modal.in").css("display", "none");
3148    $(".modal.fade.ec-modal.in").find(".close").click();
3149  } catch (error) {
3150    console.log(error)
3151  }
3152  fadeOut(elCbotDialogRegularButton);
3153  // fadeIn(elCbotDialogButtonClose);
3154  fadeIn(elCbotDialog);
3155  /* GTM ID NOT CONFIGURATED */
3156  $(".cbot-dialog-button-help-message").fadeOut();
3157
3158
3159  // if (conversations.length == 0)
3160  //     sendTriggerMessages(trigger_messages);
3161
3162  // sadece widget'a tıklandığında bir defaya mahsus mesaj yükelmelerini y
3162ap
3163
3164  document.getElementById("cbot-overlay-background").style.display = "block";
3165
3166  dialogOpenFunctions(next);
3167
3168  scrollChatScreen(1000);
3169
3170}
3171
3172function dialogOpenFunctions(next = () => { }) {
3173  sendCustomPostMessage("CBOT_WIDGET_OPENED", {});
3174  var elCbotFormMessage = document.getElementById('cbot-form-message');
3175  if (!firstLoad) {
3176    firstLoad = true;
3177    if (LIVE_CHAT) {
3178      var socketIO = document.createElement('script');
3179      socketIO.type = "text/javascript";
3180      socketIO.src = staticAddress + "/js/socket.io.js" + "?client=" + CLIENT;
3181      document.getElementsByTagName('head')[0].insertBefore(socketIO, document.getElementsByTagName('head')[0].firstChild);
3182
3183      // var lvInterval = setInterval(function () {
3184      //   if (window.io && cbotSessionId && cbotUserId) {
3185      //     if (isLive) {
3186      //       if (is_liveagent_typed) {
3187      //         toggleCloseChatButton("block");
3188      //       }
3189      //     }
3190      //     /* socket = io.connect(soc_connect, {
3191      //       transports: ["websocket"], secure: true, upgrade: false, auth: {
3192      //         session_id: cbotSessionId,
3193      //         user_id: cbotUserId
3194      //       }
3195      //     });
3196      //     socket.on('connect', function () {
3197      //       sendCustomPostMessage("CBOT_WEBSOCKET_CONNECTED", {});
3198      //       clearLostConnectionMsg();
3199      //       var newClientInterval = setInterval(function () {
3200      //         if (cbotUserId && cbotSessionId) {
3201      //           socket.emit('new_client', { userId: cbotUserId, sessionId: cbotSessionId });
3202      //           clearInterval(newClientInterval);
3203      //         }
3204      //       }, 500);
3205
3206      //     }); */
3207      //     socket_connection_widget();
3208      //     soc_cli_data();
3209      //     soc_survey();
3210      //     soc_stop();
3211      //     soc_client_typing();
3212      //     socket_alert();
3213      //     socket_delete_message();
3214      //     soc_transfer_agent();
3215      //     soc_cbot_meet_events();
3216      //     soc_error();
3217      //     clearInterval(lvInterval);
3218      //     soc_queue_data();
3219      //   }
3220      // }, 100);
3221    }
3222
3223    $('#cbot-form-message').attr('disabled', true);
3224    if (data_function) {
3225      triggerFunction(function (data) {
3226        triggerGetConversations(next);
3227      });
3228    } else {
3229      triggerGetConversations(next);
3230    }
3231  } else {
3232    triggerFunction();
3233  }
3234
3235  function triggerGetConversations(next = () => { }) {
3236    // * Hem trigger message çalışıp hem de history calısamaz önlem amaçlı koydum.
3237    if (isSendTriggerMessage) {
3238      isSendTriggerMessage = false;
3239      $('#cbot-form-message').attr('disabled', false);
3240      return;
3241    }
3242    getConversations(function () {
3243      browserNotifications();
3244      if (conversations.length == 0) {
3245        if (!ia_take_attention_state.is_executed && !isLive) {
3246          sendTriggerMessages(trigger_messages);
3247        }
3248      }
3249      else
3250        writeConversations();
3251
3252      if (isLive) {
3253        if (is_liveagent_typed) {
3254          toggleCloseChatButton("block");
3255        }
3256      }
3257
3258      // yazıları temizle&
3259      $('#cbot-form-message').css('pointer-events', 'auto');
3260      $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
3261      $('#cbot-form-message').removeAttr('disabled');
3262      elCbotFormMessage.value = " ";
3263      elCbotFormMessage.removeAttribute('readonly');
3264      cbotFocus(elCbotFormMessage);
3265
3266
3267      handleMessageArea();
3268
3269      disablePostbackButtonsInHistory();
3270      disableLocationButtonsInHistory();
3271
3272      $(".cbot-dropdown-input").attr("disabled", "disabled");
3273
3274      scrollChatScreen(300);
3275    },
3276      next
3277    );
3278  }
3279}
3280
3281function disablePostbackButtonsInHistory() {
3282  var messages = $("#cbot-chat li");
3283  var lastMessages = messages[[messages.length - 1]]
3284  // var lastIndexOfUserMsg = messages.toArray().findLastIndex(function(m) { $(m).attr("class").includes("cbot-self"); });
3285  var lastIndexOfUserMsg = messages.length - 1 - messages.toArray().slice().reverse().findIndex(function (m) {
3286    if ($(m).attr("class")) {
3287      $(m).attr("class").includes("cbot-self");
3288    }
3289  }) // For Safari!
3290  if (lastIndexOfUserMsg < messages.length - 1) {
3291    for (var i = lastIndexOfUserMsg - 1; i >= 0; i--) {
3292      var buttons = $(messages[i]).find(".cbot-button.postback");
3293
3294      if (clients.remove_clicked_button_family) {
3295        e.parentElement.remove();
3296      }
3297
3298      for (var j = 0; j < buttons.length; j++) {
3299        buttons[j].disabled = true;
3300      }
3301    }
3302
3303  } else {
3304    var elCbotInteractiveButtons = document.getElementsByClassName('postback');
3305    for (var j = elCbotInteractiveButtons.length - 1; j >= 0; j--) {
3306      e = elCbotInteractiveButtons[j];
3307
3308      if (clients.remove_clicked_button_family) {
3309        e.parentElement.remove();
3310        continue; // Element removed, skip to next iteration
3311      }
3312
3313      if (e.getAttribute('data-branch') != "true") {
3314        e.disabled = true;
3315      }
3316    }
3317
3318    // Enable buttons in last message separately
3319    if (lastMessages && lastMessages.getElementsByTagName("button").length > 0) {
3320      var lastMessageButtons = lastMessages.getElementsByTagName("button");
3321      for (var index = 0; index < lastMessageButtons.length; index++) {
3322        if (lastMessageButtons[index]) {
3323          lastMessageButtons[index].disabled = false;
3324        }
3325      }
3326    }
3327  }
3328}
3329
3330function disablePostbackButtons(class_name = "postback") {
3331  $(".cbot-rating-group").addClass("cbot-rating-disabled");
3332  var elCbotInteractiveButtons = document.getElementsByClassName(class_name);
3333  for (var j = 0; j < elCbotInteractiveButtons.length; j++) {
3334    e = elCbotInteractiveButtons[j];
3335    if (e.getAttribute('data-branch') != "true") {
3336      e.disabled = true;
3337    }
3338  }
3339}
3340
3341function sendCustomPostMessage(action, data) {
3342  // console.log("sendCustomPostMessage", { action, data });
3343  try {
3344    window.postMessage({ action: action, data: data }, window.location.origin);
3345    if (window.parent) {
3346      var parentOrigin = getAddr();
3347      if (parentOrigin) window.parent.postMessage({ action: action, data: data }, parentOrigin);
3348    }
3349    if (window.ReactNativeWebView) {
3350      window.ReactNativeWebView.postMessage(JSON.stringify({ action: action, data: data }));
3351    } else if (cbotIsMobile.iOS()) {
3352      if (window.webkit && window.webkit.messageHandlers) {
3353        if (window.webkit.messageHandlers.start) {
3354          window.webkit.messageHandlers.start.postMessage({ action: action, data: data });
3355        } else {
3356          window.webkit.messageHandlers.ChatbotEventBridge.postMessage({ action: action, data: data });
3357        }
3358      } else if (window.ChatbotEventBridge) {
3359        window.ChatbotEventBridge.postMessage({ action: action, data: data });
3360      }
3361    } else if (cbotIsMobile.Android()) {
3362      if (window.ChatbotEventBridge) {
3363        window.ChatbotEventBridge.postMessage(JSON.stringify({ action: action, data: data }));
3364      }
3365    }
3366  } catch (error) {
3367    console.log(error);
3368  }
3369}
3370
3371function disableLocationButtonsInHistory() {
3372  var messages = $("#cbot-chat li");
3373  var lastMessages = messages[[messages.length - 1]]
3374  // var lastIndexOfUserMsg = messages.toArray().findLastIndex(function(m) { $(m).attr("class").includes("cbot-self"); });
3375  var lastIndexOfUserMsg = messages.length - 1 - messages.toArray().slice().reverse().findIndex(function (m) {
3376    if ($(m).attr("class")) {
3377      $(m).attr("class").includes("cbot-self");
3378    }
3379  }) // For Safari!
3380  if (lastIndexOfUserMsg < messages.length - 1) {
3381    for (var i = lastIndexOfUserMsg - 1; i >= 0; i--) {
3382      var buttons = $(messages[i]).find(".cbot-button.cbot-location");
3383
3384      if (clients.remove_clicked_button_family) {
3385        e.parentElement.remove();
3386      }
3387
3388      for (var j = 0; j < buttons.length; j++) {
3389        buttons[j].disabled = true;
3390      }
3391    }
3392
3393  } else {
3394    var elCbotInteractiveButtons = document.getElementsByClassName('cbot-location');
3395    for (var j = elCbotInteractiveButtons.length - 1; j >= 0; j--) {
3396      e = elCbotInteractiveButtons[j];
3397
3398      if (clients.remove_clicked_button_family)
3399        e.parentElement.remove();
3400
3401      if (e.getAttribute('data-branch') != "true") {
3402        e.disabled = true;
3403      }
3404    }
3405  }
3406}
3407
3408let firstTrigger = true;
3409function triggerFunction(next) {
3410  if (!next) next = function () { };
3411  if (data_function && typeof window[data_function] == "function") {
3412    window[data_function](function (data) {
3413      if (data.headers) {
3414        data_script_qs = data.headers;
3415      }
3416      getCustomHeaders(firstTrigger);
3417      firstTrigger = false;
3418      next(data);
3419    });
3420  }
3421}
3422
3423
3424function delay(callback, ms) {
3425  var timer = 0;
3426  return function () {
3427    var context = this, args = arguments;
3428    clearTimeout(timer);
3429    timer = setTimeout(function () {
3430      callback.apply(context, args);
3431    }, ms || 0);
3432  };
3433}
3434function setClickEventToInteractiveButtons(cbotUserId) {
3435  //console.log("setClickEventToInteractiveButtons");
3436  var elCbotInteractiveButtons = document.getElementsByClassName('postback');
3437  var btn;
3438  for (var i = 0; i < elCbotInteractiveButtons.length; i++) {
3439    btn = elCbotInteractiveButtons[i];
3440    if (btn.tagName && btn.tagName.toLowerCase() === "a") {
3441      btn.removeAttribute("href");
3442      btn.setAttribute("role", "button");
3443    }
3444    btn.style.webkitTouchCallout = "none";
3445    btn.style.webkitUserSelect = "none";
3446    btn.style.userSelect = "none";
3447    btn.oncontextmenu = function (event) {
3448      event.preventDefault();
3449    };
3450    btn.onclick = function (event) {
3451      var e = event.target;
3452      var elCbotInteractiveButtons = document.getElementsByClassName('postback');
3453      var payload = e.getAttribute('data-payload');
3454      var data_full_action = e.getAttribute('data-full-action');
3455
3456      // console.log("PAYLOAD: ", payload, e);
3457
3458      cbotgtag('event', 'cbot', {
3459        'event_category': 'cbot-button',
3460        'event_action': "click",
3461        'event_label': payload
3462      })
3463
3464      if (clients.remove_clicked_button_family)
3465        e.parentElement.remove();
3466
3467
3468      $(".cbot-dropdown-input").attr("disabled", "disabled")
3469      $(".cbot-rating-group").addClass("cbot-rating-disabled"); // mesaj gönderildiğinde yıldız anketler bloklansın
3470      $(".cbot-colorful-radio-main-container").addClass("cbot-rating-disabled"); // mesaj gönderildiğinde yıldız anketler bloklansın
3471      dialog(cbotUserId, e.innerText || payload, null, payload, !e.className.includes("cbot-rating-label") && (e.parentElement.parentElement && !e.parentElement.parentElement.className.includes("cbot-survey-type")), data_full_action);
3472      e.classList.add('clicked');
3473      for (var j = 0; j < elCbotInteractiveButtons.length; j++) {
3474        e = elCbotInteractiveButtons[j];
3475        if (e.getAttribute('data-branch') != "true") {
3476          e.disabled = true;
3477        }
3478      }
3479    }
3480  }
3481
3482  // For file upload
3483  elCbotInteractiveButtons = document.getElementsByClassName('fileupload');
3484  var file_btn;
3485  for (var ii = 0;
3485 ii < elCbotInteractiveButtons.length; ii++) {
3486    file_btn = elCbotInteractiveButtons[ii];
3487    fileUploadListener(file_btn.attributes['data-payload'].nodeValue);
3488    file_btn.onclick = function (event) {
3489      var e = event.target;
3490      var index = e.getAttribute('data-payload');
3491      $("#cbot-attachment-file-input-" + index).click();
3492
3493
3494    }
3495  }
3496
3497}
3498
3499function setClickEventToFeedbackButtons(unique_id) {
3500
3501  var feedback_areas = $('.cbot-feedback-id-' + unique_id);
3502
3503  $(feedback_areas).each(function (index, feedback_area) {
3504
3505    var voteButtons = $(feedback_area).find('.cbot-feedback-vote-button');
3506    $(voteButtons).each(function (index, item) {
3507
3508      $(item).on("click", function (event) {
3509
3510
3511
3512        $(voteButtons).each(function (index, btn) {
3513          // $(btn).prop("disabled", true);
3514          // $(btn).css("pointer-events", "none")
3515        });
3516        var cbot_feedback_status = feedback_area.querySelector(".cbot-feedback-status");
3517
3518        $(item).siblings("button.cbot-feedback-vote-button").eq(0).removeClass("cbot-vote-selected")
3519
3520
3521        if ($(item).hasClass("cbot-vote-up-selectable") && !$(item).hasClass("cbot-vote-selected")) {
3522          $(item).addClass("cbot-vote-selected");
3523          /* LIKE REQUEST */
3524          sendFeedbackPost({
3525            unique_id: unique_id,
3526            feedback_like: "Positive"
3527          }, function () {
3528            if (clients.feedback.show_vote_result_message) {
3529              $(cbot_feedback_status).text(clients.feedback.vote_up_message);
3530              if (clients.feedback.hide_after_user_sent_vote)
3531                setTimeout(function () {
3532                  fadeOut(cbot_feedback_status);
3533                }, clients.feedback.hide_after_user_sent_vote_timeout || 1000);
3534            }
3535          })
3536        } else if ($(item).hasClass("cbot-vote-up-selectable") && $(item).hasClass("cbot-vote-selected")) {
3537          $(item).removeClass("cbot-vote-selected");
3538          fadeOut(feedback_area.querySelector(".cbot-feedback-comment-area"))
3539          //fadeOut(cbot_feedback_comment_area);
3540          sendFeedbackPost({
3541            unique_id: unique_id,
3542            feedback_like: ""
3543          }, function () {
3544            // if (clients.feedback.show_vote_result_message) {
3545
3546            //     $(cbot_feedback_status).text(clients.feedback.vote_up_message);
3547            //     if (clients.feedback.hide_after_user_sent_vote)
3548            //         setTimeout(function () {
3549            //             fadeOut(cbot_feedback_status);
3550            //         }, clients.feedback.hide_after_user_sent_vote_timeout || 1000);
3551            // }
3552          })
3553
3554        }
3555        if ($(item).hasClass("cbot-vote-down-selectable") && !$(item).hasClass("cbot-vote-selected")) {
3556          $(item).addClass("cbot-vote-selected");
3557          /* DISLIKE REQUEST */
3558          sendFeedbackPost({
3559            unique_id: unique_id,
3560            feedback_like: "Negative"
3561          }, function () {
3562            if (clients.feedback.show_vote_result_message) {
3563
3564              $(cbot_feedback_status).text(clients.feedback.vote_down_message)
3565              if (clients.feedback.hide_after_user_sent_vote)
3566                setTimeout(function () {
3567                  fadeOut(cbot_feedback_status);
3568                }, clients.feedback.hide_after_user_sent_vote_timeout || 1000);
3569            }
3570          })
3571        } else if ($(item).hasClass("cbot-vote-down-selectable") && $(item).hasClass("cbot-vote-selected")) {
3572          $(item).removeClass("cbot-vote-selected");
3573          /* DISLIKE REQUEST */
3574          sendFeedbackPost({
3575            unique_id: unique_id,
3576            feedback_like: ""
3577          }, function () {
3578            // if (clients.feedback.show_vote_result_message) {
3579
3580            //     $(cbot_feedback_status).text(clients.feedback.vote_down_message)
3581            //     if (clients.feedback.hide_after_user_sent_vote)
3582
3583            //         setTimeout(function () {
3584            //             fadeOut(cbot_feedback_status);
3585            //         }, clients.feedback.hide_after_user_sent_vote_timeout || 1000);
3586            // }
3587          })
3588        }
3589
3590        if (((clients.feedback.positive_comment_is_active && $(item).hasClass("cbot-vote-up-selectable") && $(item).hasClass("cbot-vote-selected")) || (clients.feedback.negative_comment_is_active && $(item).hasClass("cbot-vote-down-selectable") && $(item).hasClass("cbot-vote-selected")))) {
3591          var cbot_feedback_comment_area = feedback_area.querySelector(".cbot-feedback-comment-area");
3592          fadeIn(cbot_feedback_comment_area);
3593          scrollChatScreen(200)
3594          var textarea = $(feedback_area).find(".cbot-feedback-textarea");
3595          var send = $(feedback_area).find(".cbot-feedback-form-send");
3596          $(textarea).keypress(function (e) {
3597            if (e.which == 13) {
3598              senderFunction(e);
3599            }
3600          });
3601          function senderFunction(event) {
3602            $(send).prop("disabled", true)
3603            $(textarea).prop("disabled", true)
3604            sendFeedbackPost({
3605              unique_id: unique_id,
3606              user_comment: textarea.val()
3607            }, function () {
3608              $(feedback_area).find(".cbot-feedback-status-form").text(clients.feedback.form_success_message);
3609              if (clients.feedback.hide_form_after_user_sent_feedback)
3610                setTimeout(function () {
3611                  fadeOut(cbot_feedback_comment_area)
3612                  setTimeout(function () {
3613
3614                    $(send).prop("disabled", false)
3615                    $(textarea).prop("disabled", false)
3616                  }, 1000);
3617                }, clients.feedback.hide_form_after_user_sent_feedback_timeout || 1000);
3618
3619
3620            })
3621          }
3622          $(send).on("click", senderFunction);
3623        }
3624        else {
3625
3626          var cbot_feedback_comment_area = feedback_area.querySelector(".cbot-feedback-comment-area");
3627          fadeOut(cbot_feedback_comment_area)
3628        }
3629      })
3630    })
3631  })
3632}
3633
3634function addFontFile(filename, version) {
3635  var preloadFont = document.createElement('link');
3636  preloadFont.type = "font/woff2";
3637  preloadFont.rel = "preload";
3638  preloadFont.as = "font";
3639  // preloadFont.crossOrigin = "anonymous"
3640  if (data_cdn_url) {
3641    preloadFont.href = data_cdn_url + '/' + filename + '.woff2' + (version ? '?v=' + version : '');
3642  } else {
3643    preloadFont.href = staticAddress + '/fonts/' + filename + '.woff2' + (version ? '?v=' + version : '');
3644  }
3645  document.getElementsByTagName('head')[0].appendChild(preloadFont);
3646}
3647
3648function addChartJs() {
3649  let script = document.createElement('script');
3650  // script.src = "https://cdn.jsdelivr.net/npm/chart.js";
3651  script.src = staticAddress + "/js/chart.js" + "?client=" + CLIENT;
3652  document.getElementsByTagName('head')[0].appendChild(script);
3653}
3654
3655function addCssFile(filename, version) {
3656  var preloadcss = document.createElement('link');
3657  preloadcss.type = "text/css";
3658  preloadcss.rel = "preload";
3659  preloadcss.as = "style";
3660  preloadcss.href = staticAddress + '/css/' + filename + '.css' + (version ? '?v=' + version + "&client=" + CLIENT : "?client=" + CLIENT);
3661  document.getElementsByTagName('head')[0].appendChild(preloadcss);
3662
3663  var customstyle = document.createElement('link');
3664  customstyle.type = "text/css";
3665  customstyle.rel = "stylesheet";
3666  customstyle.href = staticAddress + '/css/' + filename + '.css' + (version ? '?v=' + version + "&client=" + CLIENT : "?client=" + CLIENT);
3667  document.getElementsByTagName('head')[0].appendChild(customstyle);
3668}
3669
3670function cleanTags(text) {
3671
3672  return (text || "").replace(/[^\p{L}\p{N}\p{Sc}\p{Emoji} _@.,$€₺:£%+*#&?\-\/='"!()[\]\{\}]/gu, function (match, offset, org) {
3673    // Safari'deki emoji bozulma sorunu sebebiyle aşağıdaki fonksiyon eklendi.
3674    return isValidUnicodeCharacter(match) ? match : " ";
3675  });
3676}
3677
3678function isValidUnicodeCharacter(str) {
3679  try {
3680    // Gelen değeri JSON.parse ile dönüştürmeye çalış
3681    var parsedValue = JSON.parse('"' + str + '"');
3682
3683    // Dönüştürme başarılı ise ve bir karaktere eşitse, geçerli bir Unicode karakteridir
3684    if (typeof parsedValue === "string" && parsedValue.length === 1) {
3685      // ASCII karakter değilse, geçerli bir Unicode karakteridir
3686      return parsedValue.charCodeAt(0) > 127;
3687    }
3688
3689    return false;
3690  } catch (e) {
3691    // JSON.parse başarısız olursa veya dönüştürülen değer birden fazla karakter içeriyorsa geçerli değil
3692    return false;
3693  }
3694}
3695
3696function sanitize(text, wrongChars, normalChars) {
3697  if (typeof text == "string" && wrongChars && normalChars && wrongChars.length == normalChars.length) {
3698
3699    for (var i = 0; i < wrongChars.length; i++) {
3700      // console.log(new RegExp(wrongChars[i],"gi"));
3701      text = text.replace(new RegExp(wrongChars[i].replace(/([^a-zA-ZÖÇŞİĞÜöçşığü0-9\\|])/g, "\\$1"), "gi"), normalChars[i]);
3702    }
3703
3704  } else {
3705    //console.log("sanitize WARNING: wrongChars array's length must be equals to normalChars array");
3706  }
3707  return text;
3708}
3709
3710function handleAndAddEmoji(userMessage, responseMessage, next) {
3711  var matches = userMessage.match(new RegExp("(" + emojies.join("|").replace(/([^a-zA-ZÖÇŞİĞÜöçşığü0-9\\|])/g, "\\$1") + ")", "g"));
3712  var emoji;
3713  // console.log("handleAndAddEmoji REGEX: ", new RegExp("("+emojies.join("|").replace(/([^a-zA-ZÖÇŞİĞÜöçşığü0-9\\|])/g,"\\$1")+")", "g"));
3714  //console.log("handleAndAddEmoji MATCHES: ", matches);
3715  if (matches && matches.length > 0 && typeof responseMessage === "string") {
3716    emoji = matches[0];
3717    responseMessage += " " + emoji;
3718    return responseMessage;
3719  }
3720  return responseMessage;
3721}
3722
3723var video_conference=false;
3724var auth;
3725var kvk;
3726var isLive = false;
3727var lastConversationStepValue = false;
3728var lastCategory;
3729function dialog(cbotUserId, message, next, payload, showClientMessage, data_full_action, is_triggered = false, conversation_type = "text") {
3730  if (!isWidgetOpen) dialogButtonRegular()
3731  if (!data_full_action || data_full_action == "{}") data_full_action = "";
3732  if (showClientMessage == undefined) showClientMessage = true;
3733  if (typeof next !== "function") next = function () { };
3734  if (showClientMessage) {
3735    if (conversation_type == "text") {
3736      appendMessageToDialogBox(message, "cbot-self", null, {}, function () { });
3737    }
3738    appendTypingIconToDialogBox("");
3739  }
3740  //$('#cbot-chat').append($('<li>').addClass("cbot-self").html('<div class="avatar"><img src="'+staticAddress+'/img/cbot-user.png" draggable="false"/></div><div class="cbot-msg">'+message+'</div>'));
3741  //$("#cbot-chat").scrollTop(50000);
3742  // addMessageToCache({ senderName: "User_" + cbotUserId, userId: cbotUserId, message: message, intents: 
3742intents, client: cbot_config.client });
3743  var elCbotFormMessage = document.getElementById('cbot-form-message');
3744  // $.post(staticAddress + "/" + CLIENT, { senderName: "User_" + cbotUserId, userId: cbotUserId, message: message, intents: intents, client: cbot_config.client }, function (data) {
3745  //console.log("Geldi!!!");
3746  if (isLive || !new RegExp("^(" + emojies.join("|").replace(/([^a-zA-ZÖÇŞİĞÜöçşığü0-9\\|])/g, "\\$1") + ")$", "ig").test(message)) {
3747    setLastMessageSentDateTLS();
3748    $(".cbot-dropdown-input").attr("disabled", "disabled");
3749    firstMessageSent = true;
3750    setFirstMessageSentTLS(firstMessageSent);
3751    lastMessageReceiveDate = Date.now();
3752
3753    $(".cbot-rating-group").addClass("cbot-rating-disabled"); // mesaj gönderildiğinde yıldız anketler bloklansın
3754    $(".cbot-colorful-radio-main-container").addClass("cbot-rating-disabled"); // mesaj gönderildiğinde yıldız anketler bloklansın
3755    if (!isLive) {
3756      let _payload = {
3757        senderName: "User_" + cbotUserId,
3758        userId: cbotUserId,
3759        sessionId: cbotSessionId,
3760        message: payload || message,
3761        data_full_action: data_full_action,
3762        intents: intents,
3763        client: cbot_config.client,
3764        live_chat: isLive,
3765        is_triggered: is_triggered,
3766        conversation_type: conversation_type
3767      }
3768      if (conversation_type == "audio") {
3769        _payload.base64_audio = message;
3770        _payload.message = "audio_message";
3771      }
3772      sendPost(_payload, function (data) {
3773        if (cbotInputKeyboardClicked)
3774          cbotFocus(elCbotFormMessage);
3775
3776        if (data) {
3777          socketHandshake();
3778          if (lastCategory != data.category || (!data.conversationStep && !lastConversationStepValue) || (data.conversationStep && !lastConversationStepValue)) {
3779            setLastMessageTLS([message]);
3780          } else {
3781            var msgFLS = getLastMessageFLS();
3782            msgFLS.push(message);
3783            setLastMessageTLS(msgFLS);
3784          }
3785          lastConversationStepValue = data.conversationStep;
3786          lastCategory = data.category;
3787
3788
3789
3790          intents = data.intents;
3791          // data.message = handleAndAddEmoji(message, data.message);
3792          clearTimeout(auth);
3793
3794          if (data.smsAuth == true) {
3795            auth = setTimeout(function () {
3796              appendMessageToDialogBox(data.smsMessage, "cbot-other", data.category, { unique_id: data.unique_id }, function () {
3797                setClickEventToInteractiveButtons(data.userId);
3798                setClickEventToFeedbackButtons(data.unique_id);
3799              });
3800            }, 180000);
3801          }
3802          clearTimeout(kvk);
3803          if (data.kvkConfirm == true) {
3804            kvk = setTimeout(function () {
3805              appendMessageToDialogBox(data.kvkConfirmMessage, "cbot-other", data.category, { unique_id: data.unique_id }, function () {
3806                setClickEventToInteractiveButtons(data.userId);
3807                setClickEventToFeedbackButtons(data.unique_id);
3808                if (data.survey) {
3809                  surveyTrigger(data.survey, data.userId);
3810                }
3811                triggerTimingResponses(data);
3812              });
3813            }, 30000);
3814          }
3815          appendMessageToDialogBox(data.message, "cbot-other", data.category, { unique_id: data.unique_id, notification: data.speak, survey_response: !showClientMessage, serviceOutput: data.serviceOutput }, function () {
3816            setClickEventToInteractiveButtons(data.userId);
3817            setClickEventToFeedbackButtons(data.unique_id);
3818            // console.log("data", data);
3819            if (data.survey) {
3820              if (data.live_chat) {
3821                if (data.live_chat != true) {
3822                  surveyTrigger(data.survey, data.userId);
3823                }
3824              }
3825              else {
3826                surveyTrigger(data.survey, data.userId);
3827              }
3828
3829            }
3830            triggerTimingResponses(data);
3831            isLive = setIsLive(data.live_chat);
3832            setisLiveTLS(isLive);
3833            handleMessageArea();
3834            if (isLive) {
3835              FIRST_LIVE_MESSAGE = true;
3836              socket_widget(message);
3837            }
3838            next();
3839          });
3840        } else {
3841          appendMessageToDialogBox(WIDGET_TIMEOUT_MESSAGE, "cbot-other", null, { notification: WIDGET_TIMEOUT_MESSAGE }, function () { });
3842          /*lastRequestTime = parseInt(Date.now() / 1000);
3843          surveyInterval || (surveyInterval = setInterval(function () {
3844            parseInt(Date.now() / 1000) - lastRequestTime > 20 && !isSurveyShowed && (clearInterval(surveyInterval), surveyInterval = null, addSurvey(data.userId), isSurveyShowed = true)
3845          }, 5000));*/
3846          next();
3847        }
3848      });
3849    } else {
3850      $(".cbot-typing").remove();
3851      $(".cbot-refresh-icon").css('opacity', '1')
3852      $(".cbot-refresh-icon").css('pointer-events', 'painted')
3853      socket_widget(message);
3854      setTimeout(function () { // Temizliği yapmadan önce keypress'in çalışmasını beklemek gerek. Yoksa burası önce çalıştığı için karışıyor.
3855        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
3856        $('#cbot-form-message').removeAttr('disabled');
3857        elCbotFormMessage.value = " ";
3858        elCbotFormMessage.removeAttribute('readonly');
3859        if (document.getElementById("cbot-send-button")) {
3860          document.getElementById("cbot-send-button").removeAttribute('disabled');
3861          $(".cbot-send-button").removeClass("active");
3862        }
3863        cbotFocus(elCbotFormMessage);
3864      }, 200);
3865      // AI öner sistemi için canlı destekte müşterinin son yazışmasının AI cevabı:
3866      // if (data.message) {
3867      //     if (!Array.isArray(data.message))
3868      //         data.message = [data.message];
3869      //     var resp_answer = data.message;
3870      //     socket_suggestion(resp_answer[0], data.category, data.userId);
3871      // }
3872      next();
3873    }
3874  } else { // Sadece emoji gönderildiyse direkt aynı emoji ile cevap ver!
3875    //console.log("just emoji");
3876    setTimeout(function () {
3877      $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
3878      $('#cbot-form-message').removeAttr('disabled');
3879      elCbotFormMessage.value = " ";
3880      elCbotFormMessage.removeAttribute('readonly');
3881      document.getElementById("cbot-send-button").removeAttribute('disabled');
3882      cbotFocus(elCbotFormMessage);
3883      appendMessageToDialogBox(message, "cbot-other", null, { notification: message }, function () {
3884        //console.log("#CALLBACK appendMessageToDialogBox 2");
3885        setClickEventToInteractiveButtons(cbotUserId);
3886      });
3887    }, 1500);
3888    next();
3889
3890  }
3891}
3892
3893function clearMessages() {
3894  let cbotChatArea = document.getElementById("cbot-chat");
3895
3896  cbotChatArea.innerHTML = "";
3897  if (welcomeMessage) {
3898    appendMessageToDialogBox(welcomeMessage, "cbot-other", null, {}, function () { });
3899  } else {
3900    // appendMessageToDialogBox(undefined, "cbot-other", null, {}, function () { });
3901  }
3902  $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
3903  $('#cbot-form-message').removeAttr('disabled');
3904  $('#cbot-form-message').val('');
3905  $('#cbot-form-message').removeAttr('readonly');
3906  $('#cbot-send-button').removeAttr('disabled');
3907  cbotFocus($('#cbot-form-message'));
3908  setSessionIdTLS(null);
3909
3910  sendTriggerMessages(trigger_messages);
3911}
3912
3913function appendTextLastAddedBox(textContent) {
3914
3915  document.querySelector("#cbot-chat > li:last-child > div > div").textContent = textContent;
3916
3917}
3918function removeLastAddedBox() {
3919
3920  document.querySelector("#cbot-chat > li:last-child").remove();
3921
3922}
3923
3924function sendPost(jsonData, next, isTimingResponse) {
3925  if (!(isTimingResponse && (WAITING_FOR_LOGIN || WAITING_FOR_POLLING))) { // polling açıkken timing resp. çalışmamalıdır.
3926    cancelTTS();
3927    if (document.querySelector('#cbot-mini-web-toggle')) {
3928      document.querySelector('#cbot-mini-web-toggle').remove();
3929      document.querySelector('.cbot-avatar').style.display = 'block';
3930    }
3931    jsonData.referrer = CHANNEL || "WIDGET";
3932    if (focookie) jsonData.focookie = focookie;
3933    // dinamik olarak data-session üzerinden botun çalıştığı tab bilgisini alma.
3934    if (!!(getParameterFromScript("data-session"))) { jsonData.loginId = getParameterFromScript("data-session") }
3935    if (loginId) jsonData.loginId = loginId;
3936    if (data_user) jsonData.userInfo = data_user;
3937    if (interactive_recommends) jsonData.interactive_recommends = interactive_recommends;
3938    jsonData.live_bot = FIRST_LIVE_MESSAGE;
3939    jsonData = addSurveyRequestData(jsonData);
3940    jsonData.widget_lang = widget_lang
3941    // $(".cbot-send-button").css("background-image", "url(" + staticAddress + "/img/flat/send-disabled.png)");
3942    $(".cbot-send-button").removeClass("active");
3943    // console.log("giden data", jsonData);
3944
3945    clearSurveyTimeout();
3946    if (!isTimingResponse) clearTimingResponseTimeout();
3947
3948    var xhr = new XMLHttpRequest();
3949
3950
3951    xhr.onreadystatechange = function () {
3952      if (this.readyState == 2) {
3953        if (stream_response)
3954          appendMessageToDialogBox("", "cbot-other", "", {}, function () { });
3955      }
3956      else if (this.readyState == 3) {
3957        if (stream_response) {
3958          appendTextLastAddedBox(xhr.responseText);
3959          scrollChatScreen(30);
3960        }
3961      }
3962      else if (this.readyState == 4 && this.status == 200) {
3963        if (isSpeechEnabled()) {
3964          $("#particles-thinking").css("opacity", "0");
3965        }
3966        let receivedData = this.responseText;
3967        if (stream_response) {
3968          removeLastAddedBox();
3969          let matchResult = receivedData.match(/(?:\n\n|^)*data: (.*?)\n\n$/i);
3970          if (matchResult && matchResult[1]) {
3971            receivedData = matchResult[1];
3972          }
3973        }
3974        var json = JSON.parse(receivedData);
3975
3976        if (kvkk_is_active) {
3977          if (json.entities && json.entities.hasOwnProperty("kvkk") && Array.isArray(json.entities.kvkk) && json.entities.kvkk.length > 0) {
3978            let _kvkk = parseInt(json.entities.kvkk[0]);
3979            if (_kvkk === 0) {
3980              kvkk_status = KVKK_STATUS_ENUM.DECLINED;
3981              is_kvkk_progress_done = true;
3982            } else if (_kvkk === 1) {
3983              kvkk_status = KVKK_STATUS_ENUM.ACCEPTED;
3984              is_kvkk_progress_done = true;
3985            } else {
3986              kvkk_status = KVKK_STATUS_ENUM.UNHANDLED;
3987              is_kvkk_progress_done = false;
3988              console.log("unhandled kvkk status!", _kvkk);
3989            }
3990          } else {
3991            kvkk_status = KVKK_STATUS_ENUM.ASKED;
3992          }
3993        }
3994
3995        if (json.input_audio_transcript) {
3996          appendMessageToDialogBox(json.input_audio_transcript, "cbot-self", null, {}, function () { });
3997        }
3998        if (json.base64_response_audio) {
3999          // Backend'ten gelen base64 encoded sesi çal
4000          playBase64Audio(json.base64_response_audio);
4001        }
4002
4003        if (json.message && Array.isArray(json.message)) {
4004          json.message.forEach(msg => {
4005            if (msg.message && typeof msg.message === 'string') {
4006              msg.message = msg.message.replace(/data: /g, '');
4007            }
4008          });
4009        }
4010
4011
4012        if (json.speak) {
4013          json.speak = json.speak.replace(/data: /g, '');
4014        }
4015
4016        if (jsonData.is_survey) {
4017          json.is_survey_message = true
4018        }
4019        if (hasSurveyFeedback) {
4020          json.is_survey_feedback = true
4021        }
4022        if (json && json.speak && tts_is_active && !voice_assistant) {
4023          // if (json.serviceOutput && json.serviceOutput.nestedBots) {
4024          //   webkitTTS(json.message[0].message.speak)
4025          //   // sendTTSService(json.message[0].message.speak)
4026          // } else {
4027          webkitTTS(json.speak)
4028          // sendTTSService(json.speak)
4029          // }
4030        }
4031        hasSurveyFeedback = json.survey_feedback;
4032
4033        if (json.user_display_name) {
4034          addAvatarLetters(json.user_display_name);
4035        }
4036
4037        if (json.action == "CLEAR") {
4038          clearMessages();
4039          return;
4040          // return next(json);
4041        }
4042
4043        if (json.cleanSession) {
4044          cbotClearUserDialog(false);
4045        } else {
4046          setUserIdTLS(json.userId);
4047          setSessionIdTLS(json.session_id);
4048        }
4049
4050
4051        if (Array.isArray(json.entities.LONG_POLLING) && json.entities.LONG_POLLING[0] == "true")
4052          waitForLongPolling();
4053
4054        if (!showedSurvey) {
4055          exitSurvey = json.exit_survey;
4056        }
4057
4058        if (json.send_message) {
4059          jsonData.message = json.send_message;
4060          appendTypingIconToDialogBox("");
4061          jsonData.userId = json.userId || null
4062          jsonData.sessionId = json.session_id || null
4063          jsonData.is_triggered = true
4064          jsonData.is_survey_feedback = false;
4065          jsonData.is_survey = false;
4066          sendPost(jsonData, next);
4067        }
4068
4069        if (json.lang_vars) {
4070          setLangVars(json.lang_vars);
4071        }
4072
4073        if (json.serviceOutput && json.serviceOutput.postMessage) {
4074          window.postMessage(json.serviceOutput, getAddr());
4075          if (window.ReactNativeWebView) {
4076            window.ReactNativeWebView.postMessage(JSON.stringify(json.serviceOutput), getAddr());
4077          }
4078
4079          if (json.serviceOutput.send_message) {
4080            jsonData.message = json.serviceOutput.send_message;
4081            jsonData.is_triggered = true;
4082            jsonData.is_survey_feedback = false;
4083            jsonData.is_survey = false;
4084            appendTypingIconToDialogBox("");
4085            sendPost(jsonData, next);
4086          }
4087        }
4088
4089        socket_newclient();
4090
4091        next(json);
4092
4093        let handleSurveyResult = handleExitSurveyAnswer(json.category, hasSurveyFeedback, json.survey_redirected_intent_id, json.conversationStep)
4094        if (handleSurveyResult) {
4095          if (exitSurvey.clear_chat_session_after_this_survey_triggered) {
4096            reset(false);
4097          }
4098        }
4099
4100      } else if (this.readyState == 4) {
4101        // console.log("READY STATE", this.readyState);
4102        // console.log("STATUS", this.status);
4103        if (isSpeechEnabled()) {
4104          $("#particles-thinking").css("opacity", "0");
4105        }
4106        next();
4107      }
4108    }
4109    xhr.open("POST", rootAddress + "/" + CLIENT, true);
4110    xhr.setRequestHeader('Content-Type', 'application/json');
4111    xhr.setRequestHeader("Accept", "application/json");
4112    xhr.setRequestHeader('CBOT-Token', "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH");
4113    xhr.setRequestHeader('CBOT-URL', generateCBOTURL(location.href));
4114    xhr.withCredentials = with_credentials;
4115
4116    var customheaders = clients.gateway_custom_headers || [];
4117
4118    for (var i = 0; i < customheaders.length; i++) {
4119      var header = customheaders[i];
4120      xhr.setRequestHeader(header.key, header.value);
4121    }
4122
4123
4124    xhr.send(JSON.stringify(jsonData));
4125    if (jsonData.is_survey == true) {
4126      sendCustomPostMessage("CBOT_SURVEY_ANSWERED_BY_USER", { message: jsonData.message, survey_id: jsonData.survey_id });
4127      let surveyGtaResultData = {
4128        "survey_result": jsonData.message,
4129        "survey_name": jsonData.survey_name
4130      }
4131      sendSurveyResultToGA(surveyGtaResultData)
4132    } else {
4133      sendCustomPostMessage("CBOT_MESSAGE_SENT", { message: jsonData.message })
4134    }
4135
4136    disablePostbackButtons()
4137    disablePostbackButtons("cbot-location")
4138  }
4139}
4140
4141function sendToEndChat() {
4142  if (SEND_ENDCHAT && cbotUserId) {
4143    $.ajax({
4144      url: rootAddress + "/conversations/endchat?client=" + CLIENT,
4145      type: "POST",
4146      headers: {
4147        "Content-Type": "application/json",
4148        "CBot-Token": "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH",
4149        "CBOT-URL": generateCBOTURL(location.href)
4150      },
4151      timeout: 10000,
4152      data: JSON.stringify({
4153        client: CLIENT,
4154        client_id: cbotUserId,
4155        sessionId: cbotSessionId,
4156        live_chat: isLive
4157      }),
4158      success: function (json) {
4159        // console.log("sendToEndChat", json);
4160      },
4161      error: function (err) {
4162        console.error(err);
4163      }
4164    });
4165  }
4166}
4167
4168function setLangVars(lang_vars_response) {
4169  let keys = Object.keys(lang_vars_response);
4170  for (let i = 0; i < keys.length; i++) {
4171    let key = keys[i];
4172    let langVar = lang_vars_response[key];
4173    lang_vars[key] = langVar;
4174  }
4175  updateUIWithLangVars();
4176}
4177
4178
4179function updateUIWithLangVars() {
4180  if (lang_vars.LANGVARS_LCHAT_CLOSE_BTN_TEXT) {
4181    $('.cbot-livechat-close').text(lang_vars.LANGVARS_LCHAT_CLOSE_BTN_TEXT);
4182  }
4183  if (lang_vars.LANGVARS_CLOSE_TEXT_MESSAGE) {
4184    $('.cbot-close-icon-new').attr('cbot-tooltip', lang_vars.LANGVARS_CLOSE_TEXT_MESSAGE);
4185  }
4186  if (lang_vars.LANGVARS_MINIMIZE_TEXT_MESSAGE) {
4187    $('.cbot-minimize-icon').attr('cbot-tooltip', lang_vars.LANGVARS_MINIMIZE_TEXT_MESSAGE);
4188  }
4189  if (lang_vars.LANGVARS_TTS_MUTE_MESSAGE) {
4190    $('.cbot-mute-icon').attr('cbot-tooltip', lang_vars.LANGVARS_TTS_MUTE_MESSAGE);
4191  }
4192  if (lang_vars.LANGVARS_REFRESH_BUTTON_TOOLTIP_MESSAGE) {
4193    $('.cbot-refresh-icon').attr('cbot-tooltip', lang_vars.LANGVARS_REFRESH_BUTTON_TOOLTIP_MESSAGE);
4194  }
4195  if (lang_vars.LANGVARS_HELP_TEXT_MESSAGE) {
4196    $('.cbot-cog-icon').attr('cbot-tooltip', lang_vars.LANGVARS_HELP_TEXT_MESSAGE);
4197  }
4198  if (lang_vars.LANGVARS_PLACEHOLDER_MESSAGE) {
4199    $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
4200  }
4201  if (lang_vars.LANGVARS_HELP_TEXT_CONTENT) {
4202    $(".cbot-help-text").html(lang_vars.LANGVARS_HELP_TEXT_CONTENT);
4203  }
4204  if (lang_vars.LANGVARS_WIDGET_TITLE) {
4205    $(".cbot-avatar-title-span").text(lang_vars.LANGVARS_WIDGET_TITLE);
4206  }
4207  if (lang_vars.LANGVARS_HELP_TEXT_TITLE) {
4208    $(".cbot-help-text-title").text(lang_vars.LANGVARS_HELP_TEXT_TITLE);
4209  }
4210  if (lang_vars.LANGVARS_WIDGET_TIME_OUT_MESSAGE) {
4211    WIDGET_TIMEOUT_MESSAGE = lang_vars.LANGVARS_WIDGET_TIME_OUT_MESSAGE;
4212  }
4213  if (lang_vars.LANGVARS_NETWORK_ERROR_MESSAGE) {
4214    WIDGET_NETWORK_ERROR_MESSAGE = lang_vars.LANGVARS_NETWORK_ERROR_MESSAGE;
4215  }
4216  setDefaultMessages();
4217  setUserTimeout();
4218}
4219
4220function sendTimeOutMessage(timeout_message) {
4221  emitUserSessionTimeout(timeout_message);
4222  appendMessageToDialogBox(timeout_message, "cbot-other", null, { notification: timeout_message }, function () { });
4223  cbotSessionId = null;
4224  setSessionIdTLS(null);
4225  setIsTimeoutMessageSentTLS(true);
4226}
4227
4228function emitUserSessionTimeout(timeout_message) {
4229  if (!timeout_message || getIsTimeoutMessageSentTLS()) {
4230    return;
4231  }
4232
4233  if (!socket || !socket.connected || !cbotUserId || !cbotSessionId) {
4234    return;
4235  }
4236  socket.emit("user_session_timeout", {
4237    client_id: cbotUserId,
4238    session_id: cbotSessionId,
4239    client: CLIENT,
4240    referrer: CHANNEL || "WIDGET",
4241    message: timeout_message
4242  });
4243}
4244
4245function appendMessageToDialogBox(message, elemClass, category, options, next) {
4246  if (!next || typeof next != "function") next = function () { };
4247  if (!options) options = {}
4248
4249  var elCbotChat = document.getElementById('cbot-chat');
4250
4251  // jQuery yüklü değilse bekle
4252  if (typeof jQuery === 'undefined' || typeof $ === 'undefined') {
4253    console.log('jQuery bekleniyor...');
4254    var jQueryCheckInterval = setInterval(function () {
4255      if (typeof jQuery !== 'undefined' && typeof $ !== 'undefined') {
4256        clearInterval(jQueryCheckInterval);
4257        console.log('jQuery yüklendi, devam ediliyor...');
4258        appendMessageToDialogBox(message, elemClass, category, options, next);
4259      }
4260    }, 100);
4261    return;
4262  }
4263
4264  message = sanitize(message, emojies, emojiIcons)
4265  if (elemClass === "cbot-self") {
4266    if (cbot_messages_sending_time) {
4267
4268      var hours, minutes;
4269      if (options.messageTimestamp) {
4270        var messageDate = new Date(options.messageTimestamp);
4271        hours = (messageDate.getHours() < 10 ? "0" : "") + messageDate.getHours();
4272        minutes = (messageDate.getMinutes() < 10 ? "0" : "") + messageDate.getMinutes();
4273      } else {
4274        currentTime = new Date();
4275        hours = (currentTime.getHours() < 10 ? "0" : "") + currentTime.getHours();
4276        minutes = (currentTime.getMinutes() < 10 ? "0" : "") + currentTime.getMinutes();
4277      }
4278
4279      $('#cbot-chat').append('<li class="' + elemClass + '"><div class="cbot-flexible"><div class="cbot-msg" style="' + user_message_bubble_color + user_message_text_color + '">' + generateComponentHTML(message, category, options) + `<div class="cbot-messages-sending-time">${hours}:${minutes}</div></div></div></li>`);
4280      afterAppend();
4281    }
4282    else {
4283      $('#cbot-chat').append('<li class="' + elemClass + '"><div class="cbot-flexible"><div class="cbot-msg" style="' + user_message_bubble_color + user_message_text_color + '">' + generateComponentHTML(message, category, options) + '</div></div></li>');
4284      afterAppend();
4285    }
4286    if (!options.instantWrite)
4287      scrollChatScreen(300);
4288
4289    hideAlertedDialogMessage();
4290  } else {
4291
4292    // if (options && options.serviceOutput && options.serviceOutput.nestedBots) {
4293    //   message = message[0].message.message
4294    // }
4295
4296    hideAlertedDialogMessage();
4297
4298    if (options.notification) {
4299      showNotification(cbot_config.dialogTitle, options.notification);
4300      sendCustomPostMessage("CBOT_MESSAGE_RECEIVED", options.notification);
4301    }
4302
4303    if (!Array.isArray(message)) message = [message];
4304
4305    message = message.filter(x => !x.message?.includes("NO_MESSAGE"));
4306
4307    var w = 0;
4308
4309    $(".cbot-typing").remove();
4310    appendTypingIconToDialogBox("");
4311    var is_increased = false
4312    var interval = setInterval((function selfInterval() {
4313      if (w < message.length) {
4314
4315        if (message) {
4316          if (Array.isArray(message) && message.length > 0 && message[w].message_type == "TEXT" && (message[w].message == "NO_MESSAGE" || message[w].message == "<p>NO_MESSAGE</p>")) {
4317            w++;
4318            is_increased = true
4319            return selfInterval();
4320          }
4321        }
4322        $(".cbot-typing").remove();
4323        $(".cbot-refresh-icon").css('opacity', '1')
4324        $(".cbot-refresh-icon").css('pointer-events', 'painted')
4325        if (message) {
4326          if (Array.isArray(message) && message.length > 0 && message[w].message_type == "TEXT" && (message[w].message == "NO_MESSAGE" || message[w].message == "<p>NO_MESSAGE</p>")) {
4327            w++;
4328            is_increased = true
4329            var elCbotFormMessage = document.getElementById('cbot-form-message');
4330            // $(".cbot-illusion-placeholder").html(clients.placeholder_message);
4331            elCbotFormMessage.value = " ";
4332            elCbotFormMessage.removeAttribute('readonly');
4333            if (document.getElementById("cbot-send-button"))
4334              document.getElementById("cbot-send-button").removeAttribute('disabled');
4335            cbotFocus(elCbotFormMessage);
4336            return selfInterval();
4337          }
4338        }
4339        var bgNone = data_owl && isGenericComponent(message[w]) ? " cbot-bg-none" : "";
4340        var cbot_text_component = isTextComponent(message[w]) ? " cbot_text_component" : "";
4341        var cbot_msg_custom_generic = isGenericComponent(message[w]) ? " cbot-msg-custom-generic" : "";
4342        var cbot_msg_custom_component = isCustomComponent(message[w]) ? " cbot-" + message[w].name : "";
4343        var feedbackButtons = "";
4344        var custom_class = "";
4345        if (w + 1 == message.length)
4346          feedbackButtons = generateFeedbackButtons(options, category);
4347        if (!message[w].from_file || (message[w].from_file && !message[w].auto_open)) {
4348          if (message[w].custom_class) {
4349            custom_class = " " + message[w].custom_class
4350          }
4351          if (cbot_messages_sending_time && (message[w].message_type != "DONUT_COMPONENT" && message[w].message_type != "GENERIC_COMPONENT_V3" && message[w].message_type != "GENERIC_COMPONENT_V1")) {
4352
4353            var hours, minutes;
4354            if (options.messageTimestamp) {
4355              var messageDate = new Date(options.messageTimestamp);
4356              hours = (messageDate.getHours() < 10 ? "0" : "") + messageDate.getHours();
4357              minutes = (messageDate.getMinutes() < 10 ? "0" : "") + messageDate.getMinutes();
4358            } else {
4359              currentTime = new Date();
4360              hours = (currentTime.getHours() < 10 ? "0" : "") + currentTime.getHours();
4361              minutes = (currentTime.getMinutes() < 10 ? "0" : "") + currentTime.getMinutes();
4362            }
4363            $('#cbot-chat').append('<li data-message-id="' + message[w].message_id + '" class="' + elemClass + custom_class + '"><div class="cbot-flexible"><div class="cbot-msg' + bgNone + cbot_text_component + cbot_msg_custom_generic + cbot_msg_custom_component + '" style="' + bot_message_bubble_color + bot_message_text_color + '">' + generateComponentHTML(message[w], category, options) + feedbackButtons + `<div class="cbot-messages-sending-time">${hours}:${minutes}</div></div></div></li>`);
4364            afterAppend();
4365          } else {
4366            $('#cbot-chat').append('<li data-message-id="' + message[w].message_id + '" class="' + elemClass + custom_class + '"><div class="cbot-flexible"><div class="cbot-msg' + bgNone + cbot_text_component + cbot_msg_custom_generic + cbot_msg_custom_component + '" style="' + bot_message_bubble_color + bot_message_text_color + '">' + generateComponentHTML(message[w], category, options) + feedbackButtons + '</div></div></li>');
4367            if (animated_button) {
4368              animateBorderAngle();
4369            }
4370            afterAppend();
4371          }
4372
4373          var cbotSpeedMeterElements = document.querySelectorAll('[class*="cbot-speedmeter"]');
4374          if (cbotSpeedMeterElements && cbotSpeedMeterElements.length > 0) {
4375            cbotSpeedMeterElements.forEach((element, index) => {
4376              const speedMeterElement = element.querySelector('.cbot-speed-meter[data-speed]');
4377              if (speedMeterElement) {
4378                const uniqueId = 'progress-bar-' + Date.now() + '-' + index;
4379                const progressBar = speedMeterElement.querySelector('#progress-bar');
4380                if (progressBar) {
4381                  progressBar.id = uniqueId;
4382
4383                  const pathLength = progressBar.getTotalLength();
4384                  progressBar.style.strokeDasharray = pathLength;
4385                  progressBar.style.strokeDashoffset = pathLength;
4386                }
4387
4388                const speedValue = parseInt(speedMeterElement.getAttribute('data-speed')) || 0;
4389
4390                const speedLabels = speedMeterElement.querySelectorAll('path[data-speed]');
4391                const activeColor = speedMeterElement.getAttribute('data-active-color') || '#006777';
4392                const inactiveColor = speedMeterElement.getAttribute('data-inactive-color') || '#DEE3ED';
4393
4394                speedLabels.forEach(path => {
4395                  const labelSpeed = parseInt(path.getAttribute('data-speed'));
4396                  if (labelSpeed <= speedValue) {
4397                    path.setAttribute('fill', activeColor);
4398                  } else {
4399                    path.setAttribute('fill', inactiveColor);
4400                  }
4401                });
4402
4403                const config = {
4404                  currentSpeed: speedValue,
4405                  speedLevels: JSON.parse(speedMeterElement.getAttribute('data-speed-levels') || '[0,16,24,35,50,100,200,500,1000]'),
4406                  speedAngleMap: (() => {
4407                    const levels = JSON.parse(speedMeterElement.getAttribute('data-speed-levels') || '[0,16,24,35,50,100,200,500,1000]');
4408                    const angles = JSON.parse(speedMeterElement.getAttribute('data-speed-angles') || '[-245,-220,-185,-150,-115,-75,-40,-10,15]');
4409                    const map = {};
4410                    levels.forEach((level, index) => {
4411                      map[level] = angles[index];
4412                    });
4413                    return map;
4414                  })(),
4415                  progressOffsetMap: (() => {
4416                    const levels = JSON.parse(speedMeterElement.getAttribute('data-speed-levels') || '[0,16,24,35,50,100,200,500,1000]');
4417
4418                    let pathLength = 240;
4419                    if (progressBar && progressBar.tagName === 'path' && typeof progressBar.getTotalLength === 'function') {
4420                      try {
4421                        pathLength = progressBar.getTotalLength();
4422                      } catch (error) {
4423                        pathLength = 240;
4424                      }
4425                    }
4426
4427                    const map = {};
4428                    levels.forEach((level, index) => {
4429                      const ratio = (levels.length - 1 - index) / (levels.length - 1);
4430                      map[level] = pathLength * ratio;
4431                    });
4432                    return map;
4433                  })(),
4434                  containerSelector: `#${speedMeterElement.id || 'cbot-speed-meter-' + index}`,
4435                  arrowSelector: speedMeterElement.getAttribute('data-arrow-selector') || 'g[filter]',
4436                  progressBarSelector: `#${uniqueId}`,
4437                  colors: {
4438                    activeLabel: activeColor,
4439                    inactiveLabel: inactiveColor
4440                  },
4441                  transformOrigin: speedMeterElement.getAttribute('data-transform-origin') || '60px 60px'
4442                };
4443
4444                if (!speedMeterElement.id) {
4445                  speedMeterElement.id = 'cbot-speed-meter-' + index;
4446                }
4447
4448                cbotUpdateSpeedMeter(config);
4449              }
4450            });
4451          }
4452          if (message[w] && (message[w].message_type === "LIVE_CHAT" && message[w].chat_type == "agent")) {
4453            let live_chat_started_html = '<div class="cbot-livechat-started"><div class="cbot-agent-started-livechat"> <svg width="98" height="1" viewBox="0 0 98 1" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 0.5H98" stroke="#DCDCDC"/></svg><svg width="22" height="22" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.5 13.75C10.9375 13.75 13.75 10.9375 13.75 7.5C13.75 4.0625 10.9375 1.25 7.5 1.25C4.0625 1.25 1.25 4.0625 1.25 7.5C1.25 10.9375 4.0625 13.75 7.5 13.75Z" stroke="#848484" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.84375 7.5002L6.6125 9.26895L10.1562 5.73145" stroke="#848484" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg><p class="cbot-livechat-started-text">Canlı destek başladı</p><svg width="98" height="1" viewBox="0 0 98 1" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 0.5H98" stroke="#DCDCDC"/></svg></div>'
4454            $(live_chat_started_html).appendTo($('.cbot-subtitle').closest('#cbot-chat'));
4455          }
4456        } else {
4457          generateComponentHTML(message[w], category, options)
4458        }
4459
4460        if (w < message.length)
4461          appendTypingIconToDialogBox("");
4462
4463        if (!options.instantWrite)
4464          scrollChatScreen(300);
4465
4466        var arrows = document.getElementsByClassName("cbot-arrow");
4467        if (arrows && arrows.length > 0) {
4468          for (var j = 0; j < arrows.length; j++) {
4469            arrows[j].onclick = slide;
4470          }
4471        }
4472
4473        var carouselDots = document.getElementsByClassName("cbot-carousel-dot");
4474        if (carouselDots && carouselDots.length > 0) {
4475          for (var j = 0; j < carouselDots.length; j++) {
4476            carouselDots[j].onclick = carouselDotClick;
4477          }
4478        }
4479
4480        var blurWrappers = document.getElementsByClassName("cbot-has-blur");
4481        if (blurWrappers && blurWrappers.length > 0) {
4482          for (var j = 0; j < blurWrappers.length; j++) {
4483            var components = $(blurWrappers[j]).find('.cbot-component');
4484            components.each(function (index) {
4485              if (index !== 0) {
4486                $(this).addClass('cbot-carousel-inactive');
4487              }
4488            });
4489          }
4490        }
4491
4492        if (bottom_arrows_right && bottom_arrows_right.length > 0) {
4493          for (var i = 0; i < bottom_arrows_right.length; i++) {
4494            bottom_arrows_right[i].onclick = carousel_bottom_arrow_slide;
4495          }
4496        }
4497        if (bottom_arrows_left && bottom_arrows_left.length > 0) {
4498          for (var i = 0; i < bottom_arrows_left.length; i++) {
4499            bottom_arrows_left[i].onclick = carousel_bottom_arrow_slide;
4500          }
4501        }
4502
4503        if (w == message.length) {
4504          var elCbotFormMessage = document.getElementById('cbot-form-message');
4505          $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
4506          $('#cbot-form-message').removeAttr('disabled');
4507          // elCbotFormMessage.value = " ";
4508          elCbotFormMessage.removeAttribute('readonly');
4509          if (document.getElementById("cbot-send-button"))
4510            document.getElementById("cbot-send-button").removeAttribute('disabled');
4511          cbotFocus(elCbotFormMessage);
4512          clearInterval(interval);
4513          next();
4514          scrollChatScreen(1000);
4515
4516          // Tüm mesajlar yazıldıktan sonra ek mesaj gönder
4517          sendPendingUpdateDataUserMessage();
4518        }
4519
4520
4521      } else {
4522        clearInterval(interval);
4523
4524        next();
4525        scrollChatScreen(1000);
4526
4527      }
4528      if (!is_increased) w++;
4529      is_increased = false
4530
4531      if (data_owl && $('.cbot-owl-carousel').owlCarousel)
4532        $('.cbot-owl-carousel').owlCarousel({
4533          loop: false,
4534          nav: true,
4535          items: 1,
4536          dots: true,
4537          margin: data_owl_margin ? parseInt(data_owl_margin) : 10,
4538          navText: ['<div class="cbot-arrow left"></div>', '<div class="cbot-arrow right cbot-stick-right"></div>'],
4539          stagePadding: 30
4540        });
4541
4542      if (w === message.length) {
4543        $(".cbot-typing").remove();
4544        $(".cbot-refresh-icon").css('opacity', '1')
4545        $(".cbot-refresh-icon").css('pointer-events', 'painted')
4546        if (exitSurvey && exitSurvey.disable_message_box_after_survey && message[0] && message[0].message_type == "SURVEY_STAR_COMPONENT") {
4547          $('.cbot-send-button').css("display", "none");
4548          $('.cbot-attachment-area').css("display", "none");
4549          $('#cbot-form-message').attr('disabled', 'disabled');
4550          $(".cbot-illusion-placeholder").html(clients.send_survey_placeholder_message);
4551        }
4552        else if (clients.disable_user_chat_input_button_component && isButtonExist()) {
4553          $(".cbot-illusion-placeholder").html("");
4554          $('.cbot-send-button').css("display", "none");
4555          $('#cbot-form-message').attr('disabled', 'disabled');
4556          $('.cbot-form-message-area').addClass('disabled-background');
4557          $('.cbot-chat').addClass('cbot-disabled-background-chat');
4558        }
4559        else {
4560          $('.cbot-send-button').css("display", "block");
4561          viewVoiceButton()
4562          $('#cbot-form-message').attr('disabled', false)
4563          $('#cbot-send-button').attr('disabled', false)
4564          $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
4565          cbotFocus($('#cbot-form-message'));
4566          $('.cbot-form-message-area').removeClass('disabled-background');
4567          $('.cbot-chat').removeClass('cbot-disabled-background-chat');
4568        }
4569      }
4570      return selfInterval;
4571    })(), options.instantWrite ? 1 : 500);
4572
4573  }
4574
4575  var arrows = document.getElementsByClassName("cbot-arrow");
4576  var bottom_arrows_right = document.getElementsByClassName("cbot-bottom-arrow-right");
4577  var bottom_arrows_left = document.getElementsByClassName("cbot-bottom-arrow-left");
4578  if (arrows && arrows.length > 0) {
4579    for (var i = 0; i < arrows.length; i++) {
4580      arrows[i].onclick = slide;
4581    }
4582  }
4583  var carouselDots = document.getElementsByClassName("cbot-carousel-dot");
4584  if (carouselDots && carouselDots.length > 0) {
4585    for (var i = 0; i < carouselDots.length; i++) {
4586      carouselDots[i].onclick = carouselDotClick;
4587    }
4588  }
4589
4590  var blurWrappers = document.getElementsByClassName("cbot-has-blur");
4591  if (blurWrappers && blurWrappers.length > 0) {
4592    for (var i = 0; i < blurWrappers.length; i++) {
4593      var components = $(blurWrappers[i]).find('.cbot-component');
4594      components.each(function (index) {
4595        if (index !== 0) {
4596          $(this).addClass('cbot-carousel-inactive');
4597        }
4598      });
4599    }
4600  }
4601  if (bottom_arrows_right && bottom_arrows_right.length > 0) {
4602    for (var i = 0; i < bottom_arrows_right.length; i++) {
4603      bottom_arrows_right[i].onclick = carousel_bottom_arrow_slide;
4604    }
4605  }
4606  if (bottom_arrows_left && bottom_arrows_left.length > 0) {
4607    for (var i = 0; i < bottom_arrows_left.length; i++) {
4608      bottom_arrows_left[i].onclick = carousel_bottom_arrow_slide;
4609    }
4610  }
4611  if (clients.disable_user_chat_input && user_chat_input_state == user_chat_input_states.DISABLED) {
4612    disableUserMessageArea(clients.disable_user_chat_input_message);
4613  }
4614}
4615
4616function carousel_bottom_arrow_slide() {
4617  let arrow = $(this);
4618  let arrow_right = arrow.siblings('.cbot-bottom-arrow-right');
4619  let arrow_left = arrow.siblings('.cbot-bottom-arrow-left');
4620  let indicators = arrow.siblings('.cbot-bottom-arrow-indicators');
4621  let wrapper = $(this).closest('.cbot-carousel-wrapper');
4622  let carousel = wrapper.children('.cbot-card-carousel');
4623  let carousel_count = carousel.children('.generic-template').length;
4624  let carousel_index;
4625  if (arrow[0].className == 'cbot-bottom-arrow-right') {
4626    direction = '-=260px';
4627  } else {
4628    direction = '+=260px';
4629  }
4630  if (!carousel.css("left") || carousel.css("left") == "auto") {
4631    carousel.css("left", 0);
4632  }
4633  let current_position = parseFloat(carousel.css('left'));
4634  if (current_position == 0) {
4635    carousel_index = 0;
4636  } else {
4637    carousel_index = current_position / 260 * -1;
4638  }
4639  if ((carousel_count - 1 <= carousel_index && direction == '-=260px') || (carousel_index == 0 && direction == '+=260px')) {
4640    // do not animate, you have reached the limits!
4641  } else {
4642    for (let index = 0; index < indicators.length; index++) {
4643      indicators[index].classList.remove('active');
4644    }
4645    if (direction == '-=260px') {
4646      if (indicators[carousel_index + 1]) {
4647        indicators[carousel_index + 1].classList.add('active');
4648      }
4649    } else {
4650      if (indicators[carousel_index - 1]) {
4651        indicators[carousel_index - 1].classList.add('active');
4652      }
4653    }
4654    arrow.css('pointer-events', 'none');
4655    arrow_left.css('pointer-events', 'none');
4656    arrow_right.css('pointer-events', 'none');
4657    carousel.animate({
4658      "left": direction
4659    }, 600, "swing", function () {
4660      arrow.css('pointer-events', 'unset');
4661      arrow_left.css('pointer-events', 'unset');
4662      arrow_right.css('pointer-events', 'unset');
4663    });
4664  }
4665  let activeIndex = indicators.filter(".active").index();
4666
4667  if (activeIndex % 5 == 1) {
4668    let startIndex = activeIndex - 1;
4669    let endIndex = startIndex + 5;
4670
4671    indicators.slice(startIndex, endIndex).css("display", "block");
4672    indicators.not(indicators.slice(startIndex, endIndex)).css("display", "none");
4673  } else if (activeIndex % 5 == 2) {
4674    let startIndex = activeIndex - 1;
4675    let endIndex = startIndex + 4;
4676
4677    indicators.slice(startIndex, endIndex).css("display", "block");
4678    indicators.not(indicators.slice(startIndex, endIndex)).css("display", "none");
4679    indicators.eq(startIndex - 1).css("display", "block");
4680  } else if (activeIndex % 5 == 3) {
4681    let startIndex = activeIndex - 1;
4682    let endIndex = startIndex + 3;
4683
4684    indicators.slice(startIndex, endIndex).css("display", "block");
4685    indicators.not(indicators.slice(startIndex, endIndex)).css("display", "none");
4686    indicators.eq(startIndex - 1).css("display", "block");
4687    indicators.eq(startIndex - 2).css("display", "block");
4688  } else if (activeIndex % 5 == 4) {
4689    let startIndex = activeIndex - 1;
4690    let endIndex = startIndex + 2;
4691
4692    indicators.slice(startIndex, endIndex).css("display", "block");
4693    indicators.not(indicators.slice(startIndex, endIndex)).css("display", "none");
4694    indicators.eq(startIndex - 1).css("display", "block");
4695    indicators.eq(startIndex - 2).css("display", "block");
4696    indicators.eq(startIndex - 3).css("display", "block");
4697  } else if (activeIndex % 5 == 0) {
4698    let startIndex = activeIndex - 1;
4699    let endIndex = startIndex + 1;
4700
4701    indicators.slice(startIndex, endIndex).css("display", "block");
4702    indicators.not(indicators.slice(startIndex, endIndex)).css("display", "none");
4703    indicators.eq(startIndex - 1).css("display", "block");
4704    indicators.eq(startIndex - 2).css("display", "block");
4705    indicators.eq(startIndex - 3).css("display", "block");
4706    indicators.eq(startIndex - 4).css("display", "block");
4707  }
4708}
4709
4710
4711function slide(event) {
4712  event.preventDefault();
4713  var el = event.target;
4714  var element = event.target;
4715  el.onclick = null;
4716
4717  if (element.nextSibling) {
4718    while (element.nextSibling.className != "cbot-card-carousel")
4719      element = element.nextSibling;
4720    element = element.nextSibling;
4721
4722    var slideValue = 260;
4723    var found = $(element).find(".cbot-carousel-full-width");
4724
4725    if (found.length > 0) {
4726      slideValue = parseInt(found.data("cbot-slide-value"), 10);
4727    }
4728
4729    var updateCarouselDots = function (carousel) {
4730      var wrapper = $(carousel).parent('.cbot-custom-component-carousel-wrapper');
4731      var currentLeft = Math.abs(+$(carousel).css("left").replace("px", ""));
4732      var currentIndex = Math.round(currentLeft / slideValue);
4733
4734      if (wrapper.hasClass('cbot-has-dots')) {
4735        wrapper.find('.cbot-carousel-dot').removeClass('cbot-active');
4736        wrapper.find('.cbot-carousel-dot[data-slide-index="' + currentIndex + '"]').addClass('cbot-active');
4737      }
4738
4739      if (wrapper.hasClass('cbot-has-blur')) {
4740        $(carousel).find('.cbot-component').each(function (index) {
4741          if (index === currentIndex) {
4742            $(this).removeClass('cbot-carousel-inactive');
4743          } else {
4744            $(this).addClass('cbot-carousel-inactive');
4745          }
4746        });
4747      }
4748    };
4749
4750    // console.log("SLIDE!", el.className.indexOf("left"));
4751
4752    if (el.className.indexOf("left") >= 0) { // Sol oka tıklandı
4753
4754      if (!$(element).css("left") || $(element).css("left") == "auto") {
4755        $(element).css("left", 0);
4756        // console.log("ATTR ATANDI");
4757      }
4758
4759      // console.log("CARD: ", $(element).html());
4760      if (+$(element).css("left").replace("px", "") < 0) {
4761        $(element).siblings(".cbot-arrow.right").css("display", "block");
4762        $(element).animate({
4763          "left": "+=" + slideValue + "px"
4764        }, 600, "swing", function () {
4765          el.onclick = slide;
4766
4767          if (Math.abs(+$(element).css("left").replace("px", "")) == 0) {
4768            $(el).css("display", "none");
4769          } else {
4770            $(el).css("display", "block");
4771          }
4772
4773          updateCarouselDots(element);
4774
4775        });
4776      } else {
4777        el.onclick = slide;
4778
4779        // console.log("LEFT NOT WORK!", +$(element).css("left").replace("px",""));
4780      }
4781
4782    } else { // Sağ oka tıklandı
4783
4784      if (!$(element).css("left") || $(element).css("left") == "auto") {
4785        $(element).css("left", 0);
4786        // console.log("ATTR ATANDI");
4787      }
4788
4789      if (Math.abs(+$(element).css("left").replace("px", "")) + slideValue < $(element).width()) {
4790        $(element).siblings(".cbot-arrow.left").css("display", "block");
4791        $(element).animate({
4792          "left": "-=" + slideValue + "px"
4793        }, 600, "swing", function () {
4794          el.onclick = slide;
4795
4796
4797          if (Math.abs(+$(element).css("left").replace("px", "")) + slideValue >= $(element).width()) {
4798            $(el).css("display", "none");
4799          } else {
4800            $(el).css("display", "block");
4801          }
4802
4803          var currentIndex = $(element).prop("data-currentIndex") || 0;
4804          $(element).prop("data-currentIndex", ++currentIndex);
4805
4806          updateCarouselDots(element);
4807
4808
4809          // console.log(">>>RIGHT", +$(element).css("left").replace("px",""), $(element).width());
4810        });
4811      } else {
4812        el.onclick = slide;
4813        // console.log("RIGHT NOT WORKING!", +$(element).css("left").replace("px",""), $(element).width());
4814      }
4815
4816    }
4817
4818  }
4819}
4820
4821function carouselDotClick(event) {
4822  event.preventDefault();
4823  var dot = event.target;
4824  var targetIndex = parseInt($(dot).attr('data-slide-index'), 10);
4825
4826  var wrapper = $(dot).closest('.cbot-custom-component-carousel-wrapper');
4827  var carousel = wrapper.find('.cbot-card-carousel');
4828
4829  if (carousel.length === 0) return;
4830
4831  var slideValue = 260;
4832  var found = carousel.find(".cbot-carousel-full-width");
4833  if (found.length > 0) {
4834    slideValue = parseInt(found.data("cbot-slide-value"), 10);
4835  }
4836
4837  var targetLeft = -(targetIndex * slideValue);
4838  var currentLeft = parseInt(carousel.css("left") || 0, 10);
4839
4840  if (targetLeft === currentLeft) return;
4841
4842  carousel.animate({
4843    "left": targetLeft + "px"
4844  }, 600, "swing", function () {
4845    wrapper.find('.cbot-carousel-dot').removeClass('cbot-active');
4846    $(dot).addClass('cbot-active');
4847
4848    if (wrapper.hasClass('cbot-has-blur')) {
4849      carousel.find('.cbot-component').each(function (index) {
4850        if (index === targetIndex) {
4851          $(this).removeClass('cbot-carousel-inactive');
4852        } else {
4853          $(this).addClass('cbot-carousel-inactive');
4854        }
4855      });
4856    }
4857
4858    var leftArrow = wrapper.find('.cbot-arrow.left');
4859    var rightArrow = wrapper.find('.cbot-arrow.right');
4860
4861    if (targetIndex === 0) {
4862      leftArrow.css("display", "none");
4863    } else {
4864      leftArrow.css("display", "block");
4865    }
4866
4867    var totalItems = wrapper.find('.cbot-carousel-dot').length;
4868    if (Math.abs(targetLeft) + slideValue >= carousel.width()) {
4869      rightArrow.css("display", "none");
4870    } else {
4871      rightArrow.css("display", "block");
4872    }
4873  });
4874}
4875
4876function addMessageToCache(data) {
4877  var messages = (localStorage[getDynamicLSName("messages")] && localStorage[getDynamicLSName("messages")] != "") ? JSON.parse(localStorage[getDynamicLSName("messages")]) : [];
4878  //if(!messages) messages = [];
4879
4880  // console.log(messages);
4881  if (messages.length > 10) {
4882    messages.splice(0, 1);
4883    // console.log(messages.length);
4884  }
4885
4886  messages.push(data);
4887
4888  // localStorage['cbot-messages'] = "";
4889  localStorage[getDynamicLSName("messages")] = JSON.stringify(messages);
4890}
4891
4892
4893function fadeIn(el) {
4894  if (!el) return; // * yüklenmeden yapılan çağırımlar var.
4895  el.style.opacity = 0;
4896  var tick = function () {
4897    el.style.opacity = +el.style.opacity + 0.1;
4898
4899    if (el.style.opacity < 1) {
4900      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
4901    } else {
4902      el.style.display = 'block';
4903    }
4904  };
4905
4906  tick();
4907}
4908
4909function fadeOut(el) {
4910  if (!el) return; // * yüklenmeden yapılan çağırımlar var.
4911  el.style.opacity = 1;
4912  var tick = function () {
4913    el.style.opacity = +el.style.opacity - 0.1;
4914
4915    if (el.style.opacity > 0.2) {
4916      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
4917    } else {
4918      el.style.opacity = 0;
4919      el.style.display = 'none';
4920    }
4921  };
4922
4923  tick();
4924}
4925
4926function slideIn(el) {
4927  el.style.display = 'block';
4928  var i = 1;
4929  var tick = function () {
4930    i += 5;
4931    el.style.height = i + '%';
4932
4933    if (i < 100) {
4934      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
4935    }
4936  };
4937
4938  tick();
4939}
4940
4941function slideOut(el) {
4942  // el.style.width = '100%';
4943  var i = 100;
4944  var tick = function () {
4945    i -= 5;
4946    el.style.height = i + '%';
4947
4948    if (i > 0) {
4949      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
4950    } else {
4951      el.style.display = 'none';
4952    }
4953  };
4954
4955  tick();
4956}
4957
4958
4959function generateFeedbackButtons(options, category) {
4960  if (options.unique_id && clients.feedback && clients.feedback.is_active) {
4961    if ((!clients.feedback.blocked_rulesets || !clients.feedback.blocked_rulesets.includes(category)) &&
4962      (!clients.feedback.blocked_intents || !clients.feedback.blocked_intents.includes(category))) {
4963      return '<div class="cbot-feedback-area cbot-feedback-id-' + options.unique_id + '">' +
4964        '<div class="cbot-feedback-status"></div>' +
4965        '<button class="cbot-feedback-vote-button cbot-vote-down-selectable"></button>' +
4966        '<button class="cbot-feedback-vote-button cbot-vote-up-selectable"></button>' +
4967        '<div class="cbot-clearfix"></div>' +
4968        '<div class="cbot-feedback-comment-area" style="display:none">
4968' +
4969        '<textarea class="cbot-feedback-textarea" placeholder=""></textarea>' +
4970        '<div class="cbot-feedback-status-form"></div>' +
4971        '<button class="cbot-feedback-form-send"></button>' +
4972        '<div class="cbot-clearfix"></div>' +
4973        '</div>' +
4974        '</div>';
4975    }
4976  }
4977  return "";
4978}
4979
4980
4981
4982function sendFeedbackPost(options, next) {
4983
4984  var jsonData = {
4985    client: CLIENT,
4986    userId: cbotUserId,
4987    unique_id: options.unique_id,
4988    user_comment: options.user_comment,
4989    feedback_like: options.feedback_like
4990  }
4991  var xhr = new XMLHttpRequest();
4992  xhr.onreadystatechange = function () {
4993    if (this.readyState == 4 && (this.status == 200 || this.status == 429)) {
4994      var json = JSON.parse(this.responseText);
4995      // console.log("XHR",json, typeof json == "object");
4996      next(json);
4997    } else if (this.readyState == 4) {
4998      // console.log("READY STATE", this.readyState);
4999      // console.log("STATUS", this.status);
5000      next();
5001    }
5002  }
5003  xhr.open("POST", rootAddress + "/" + CLIENT + "/savecomment", true);
5004  xhr.setRequestHeader("Accept", "application/json");
5005  // xhr.setRequestHeader("Accept-Encoding", "gzip");
5006  xhr.setRequestHeader('Content-Type', 'application/json');
5007  xhr.setRequestHeader('CBOT-Token', "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH");
5008  xhr.setRequestHeader('CBOT-URL', generateCBOTURL(location.href));
5009
5010  var customheaders = clients.gateway_custom_headers || [];
5011
5012  for (var i = 0; i < customheaders.length; i++) {
5013    var header = customheaders[i];
5014    xhr.setRequestHeader(header.key, header.value);
5015  }
5016
5017
5018  xhr.send(JSON.stringify(jsonData));
5019}
5020
5021var uploadIndex = 1;
5022
5023function isGenericComponent(component) {
5024  if (component && component.message_type == "GENERIC_COMPONENT" && component.elements && component.elements.length > 1)
5025    return true;
5026  return false;
5027}
5028
5029function isTextComponent(component) {
5030  if (component && component.message_type == "TEXT")
5031    return true;
5032  if (component && typeof component == "string")
5033    return true;
5034  return false;
5035}
5036
5037function isCustomComponent(component) {
5038  if (component && component.message_type == "CUSTOM_COMPONENT")
5039    return true;
5040  return false;
5041}
5042
5043function locatePieChartsMidText() {
5044  let chartWidth = $('.cbot-chart-container').width()
5045  let chartHeight = $('.cbot-chart-container').height()
5046  let midWidth = $('.cbot-pie-chart-midtext').width()
5047  let midHeight = $('.cbot-pie-chart-midtext').height()
5048  let left = (chartWidth - midWidth) / 2 + 10 + 40
5049  let top = (chartHeight - midHeight) / 2 + 10 + 10
5050  $('.cbot-pie-chart-midtext').css("left", left + "px");
5051  $('.cbot-pie-chart-midtext').css("top", top + "px");
5052  $('.cbot-pie-chart-midtext').css("position", "absolute");
5053  $('.cbot-pie-chart-midtext').css("display", "block");
5054}
5055
5056function createChart(chartid, chartdata, chartcolors, chartlabels, chartValue) {
5057  const ctx = $('#chart-' + chartid);
5058
5059  new Chart(ctx, {
5060    type: 'doughnut',
5061    data: {
5062      labels: chartlabels,
5063      datasets: [{
5064        data: chartdata,
5065        backgroundColor: chartcolors,
5066        hoverOffset: 4
5067      }]
5068    },
5069    options: {
5070      cutout: 60,
5071      scales: {
5072        x: {
5073          display: false,
5074        },
5075        y: {
5076          display: false,
5077        },
5078      },
5079      plugins: {
5080        legend: {
5081          display: false,
5082        },
5083        title: {
5084          display: false,
5085        },
5086        tooltip: {
5087          enabled: true,
5088          callbacks: {
5089            label: function (tooltipItem, data) {
5090              var value = chartValue[tooltipItem.dataIndex];
5091              return value;
5092            },
5093          },
5094        },
5095      },
5096    },
5097  });
5098}
5099
5100function linkify(inputText) {
5101  var hasHtmlTags = /<\/?(a|p|div|span|strong|b|em|i|u|ul|ol|li|table|thead|tbody|tr|td|th|img|button|label|input|select|option|textarea|section|article|h[1-6])\b[^<>]*\/?>/i.test(inputText);
5102  if (!isLive || hasHtmlTags) {
5103    return inputText;
5104  }else{
5105    var replacedText, replacePattern1, replacePattern2;
5106
5107    //URLs starting with http://, https://
5108    replacePattern1 = /(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
5109    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
5110
5111    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
5112    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
5113    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
5114
5115    return replacedText;
5116  }
5117}
5118
5119function generateComponentHTML(component, category, options) {
5120  if (!options) options = {};
5121  var html = "";
5122  var msg;
5123  category = "";
5124  // if (!category) category = "";
5125  // else category += " - ";
5126  if (!component.is_survey && $('#cbot-meet iframe').length == 0) closeMiniWeb();
5127  // console.log("COMPONENT: ", component);
5128  if (typeof component === "object") {
5129    if (component.message_type == "PIE_CHART_COMPONENT") {
5130      let chartid = Math.floor(Math.random() * 10000);
5131      html += '<div class="cbot-pie-chart-wrapper">'
5132      html += '<div class="cbot-chart-container">'
5133      html += '<div class="cbot-pie-chartjs">'
5134      html += '<canvas i
5134d="chart-' + chartid + '" class="cbot-canvas"></canvas>'
5135      html += '</div>'
5136      html += '<div class="cbot-pie-chart-midtext" style="display:none;">'
5137      html += '<div class="cbot-pie-chart-headtext">'
5138      html += component.headText || ""
5139      html += '</div>'
5140      html += '<div class="cbot-pie-chart-centertext">'
5141      html += component.centerText || ""
5142      html += '</div>'
5143      html += '</div>'
5144      html += '</div>'
5145      html += '</div>'
5146      html += '<div class="cbot-pie-chart-table-container">'
5147      html += '<table style="width:100%;">'
5148      html += '<tbody>'
5149      for (let index = 0; index < component.elements.length; index++) {
5150        const element = component.elements[index];
5151        html += '<tr class="cbot-pie-chart-tr">'
5152        html += '<td class="cbot-pie-chart-table-index">' + '<div class="cbot-pie-chart-table-index-card" style="background-color:' + element.color + '"></div>' + '</td>'
5153        html += '<td class="cbot-pie-chart-table-category">' + element.category + '</td>'
5154        html += '<td class="cbot-pie-chart-table-value">' + element.valueAsString + '</td>'
5155        html += '</tr>'
5156      }
5157      html += '</tbody>'
5158      html += '</table>'
5159      html += '</div>'
5160
5161      setTimeout(() => {
5162        let chartdata = component.elements.map(x => x.valueAsNumber.replace(/\./g, '').replace(/\,/g, '.'))
5163        let chartcolors = component.elements.map(x => x.color);
5164        let chartlabels = component.elements.map(x => x.category);
5165        let chartvalue = component.elements.map(x => x.valueAsString);
5166
5167        createChart(chartid, chartdata, chartcolors, chartlabels, chartvalue);
5168        setTimeout(() => {
5169          locatePieChartsMidText();
5170        }, 100);
5171      }, 100);
5172    } else if (component.message_type == "GENERIC_COMPONENT") {
5173      if (component.elements.length > 1) { // Birden fazla kart var!
5174        var elements = component.elements;
5175        html += '<div class="cbot-carousel-wrapper">';
5176        if (data_owl) {
5177          html += '<div class="cbot-owl-carousel">';
5178        }
5179        else {
5180          if (!component.bottom_arrows) {
5181            html += '<div class="cbot-arrow left" style="display: none;"></div>' +
5182              '<div class="cbot-arrow right"></div>' +
5183              '<div class="cbot-card-carousel" style="width:' + (elements.length * 260) + 'px; position: relative; display:flex">'
5184          } else {
5185            html += '<div class="cbot-card-carousel" style="width:' + (elements.length * 260) + 'px; position: relative; display:flex">'
5186          }
5187        }
5188        for (var i = 0; i < elements.length; i++) {
5189          msg = category + elements[i].title;
5190          options.button_template = elements[i].button_template;
5191          if (data_owl) {
5192
5193            html += '<div class="item">';
5194            html += '<div class="cbot-component generic-template cbot-owl-item-box">';
5195          }
5196          else {
5197            html += '<div class="cbot-component generic-template" style="float:left; max-width:250px; margin-right:10px;">';
5198          }
5199          if (elements[i].image_url)
5200            html += '<div class="cbot-image"><img src="' + elements[i].image_url + '"></div>';
5201
5202          if (elements[i].subtitle) {
5203            elements[i].subtitle = numberToString((elements[i] || {}).subtitle);
5204            sendUrlsToGA(elements[i].subtitle);
5205          }
5206
5207          html += '<div class="cbot-generic-numarator">' + (i + 1) + '</div>' +
5208            '<div class="cbot-description" style="position: relative;">' +
5209            '<p class="cbot-title" style="' + bot_message_text_title_color + '">' + msg + '</p>' +
5210            '<p class="cbot-subtitle">' + elements[i].subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5211          html += generateButtonsHTML(elements[i].buttons, options);
5212
5213          if (data_owl) {
5214            html += "</div>";
5215          }
5216          html += "</div>";
5217        }
5218        html += '</div>';
5219        if (component.bottom_arrows) {
5220          html += '<div class="cbot-bottom-arrow-container">';
5221          html += '<div class="cbot-bottom-arrow-left"></div>';
5222          for (var i = 0; i < elements.length; i++) {
5223            if (i == 0) {
5224              html += '<div class="cbot-bottom-arrow-indicators active"></div>';
5225            } else {
5226              if (i >= 5) {
5227                html += '<div class="cbot-bottom-arrow-indicators" style="display:none;"></div>';
5228              } else {
5229                html += '<div class="cbot-bottom-arrow-indicators"></div>';
5230              }
5231            }
5232          }
5233          html += '<div class="cbot-bottom-arrow-right"></div>';
5234          html += '</div>';
5235        }
5236
5237        html += '</div>';
5238
5239      } else { // Sadece bir tane kart var!
5240        var element = component.elements[0];
5241        options.button_template = component.elements[0].button_template
5242        html += '<div class="cbot-component generic-template cbot-one-item">';
5243
5244        if (element.image_url)
5245          html += '<div class="cbot-image"><img src="' + element.image_url + '"></div>';
5246
5247        msg = category + element.title;
5248
5249        if (element.subtitle) {
5250          element.subtitle = numberToString((element || {}).subtitle);
5251          sendUrlsToGA(element.subtitle);
5252        }
5253
5254        html += '<div class="cbot-description">' +
5255          '<p class="cbot-title" style="' + bot_message_text_title_color + '">' + msg + '</p>' +
5256          '<p class="cbot-subtitle">' + element.subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5257        html += generateButtonsHTML(element.buttons, options);
5258        html += "</div>";
5259      }
5260    } else if (component.message_type == "LIVE_CHAT") {
5261      if (component.elements.length > 1) { // Birden fazla kart var!
5262        var elements = component.elements;
5263        html += '<div class="cbot-arrow left"></div>' +
5264          '<div class="cbot-arrow right"></div>' +
5265          '<div class="cbot-card-carousel" style="width:' + (elements.length * 255) + 'px; position: relative;">';
5266        for (var i = 0; i < elements.length; i++) {
5267          options.button_template = elements[i].button_template
5268          if (elements[i].title == "") elements[i].title = answerisnotdefined_message || "Answer is not defined";
5269          msg = elements[i].title;
5270          html += '<div class="cbot-component generic-template" style="float:left; max-width:250px; margin-right:5px;">';
5271          if (elements[i].image_url)
5272            html += '<div class="cbot-image"><img src="' + elements[i].image_url + '"></div>';
5273
5274          if (elements[i].subtitle) {
5275            elements[i].subtitle = numberToString((elements[i] || {}).subtitle);
5276            sendUrlsToGA(elements[i].subtitle);
5277          }
5278
5279          html += '<div class="cbot-description">' +
5280            '<p class="cbot-title" style="' + bot_message_text_title_color + '">' + category + msg + '</p>' +
5281            '<p class="cbot-subtitle">' + elements[i].subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5282          html += generateButtonsHTML(elements[i].buttons, options);
5283          html += "</div>";
5284        }
5285
5286        html += '</div>';
5287
5288      } else { // Sadece bir tane kart var!
5289        var element = component.elements[0];
5290        options.button_template = component.elements[0].button_template
5291        html += '<div class="cbot-component generic-template cbot-livechat-starting">';
5292
5293        if (element.image_url)
5294          html += '<div class="cbot-image"><img src="' + element.image_url + '"></div>';
5295        // if (element.title == "") element.title = answerisnotdefined_message || "Answer is not defined";
5296        msg = element.title;
5297
5298        if (element.subtitle) {
5299          element.subtitle = numberToString((element || {}).subtitle);
5300          sendUrlsToGA(element.subtitle);
5301        }
5302
5303        html += '<div class="cbot-description">' +
5304          '<p class="cbot-title" style="' + bot_message_text_title_color + '">' + category + msg + '</p>' +
5305          '<p class="cbot-subtitle">' + element.subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5306        html += generateButtonsHTML(element.buttons, options);
5307        html += "</div>";
5308        html += "</div>";
5309      }
5310    } else if (component.message_type == "IMAGE_COMPONENT") {
5311
5312      var element = component.elements[0];
5313      options.button_template = component.elements[0].button_template
5314
5315      if (component.auto_open && firstMessageSent && element.url && !options.instantWrite)
5316        openMiniWeb("image", element.url)
5317      html += '<div class="cbot-component generic-template">';
5318
5319      if (element.url) {
5320        if (cbotIsMobile.any()) {
5321          html += '<div class="cbot-tooltip" style="opacity: 1; z-index: 1;"><div onclick="cbotModalImage(\'' + (element.url || "") + '\')"><div class="cbot-image" style="margin-bottom: 0px !important;"><img src="' + element.url + '"><span class="cbot-tooltiptext">' + (botlanguage == "en" ? "Zoom in" : "Büyüt") + '</span></div></div>';
5322        }
5323        else {
5324          html += '<div class="cbot-tooltip" style="opacity: 1; z-index: 1;"><div onclick="openMiniWeb(\'image\',\'' + (element.url || "") + '\')"><div class="cbot-image" style="margin-bottom: 0px !important;"><img src="' + element.url + '"><span class="cbot-tooltiptext">' + (botlanguage == "en" ? "Zoom in" : "Büyüt") + '</span></div></div>';
5325        }
5326      }
5327      html += generateButtonsHTML(element.buttons, options);
5328      html += "</div>";
5329
5330    } else if (component.message_type == "VIDEO_COMPONENT") {
5331      var element = component.elements[0];
5332      options.button_template = component.elements[0].button_template
5333      if (component.auto_open && firstMessageSent && element.url && !options.instantWrite)
5334        openMiniWeb("video", element.url)
5335      html += '<div class="cbot-component generic-template">';
5336
5337      if (element.url) {
5338        if (element.url.includes('youtube'))
5339          html += '<div class="cbot-image" style="margin-bottom: 0px !important; max-height:200px"><iframe width="200" height="200" src="' + element.url + '" frameborder="0"></iframe></div>';
5340        else if (element.url.includes("facebook")) {
5341          html += `<div class="cbot-image" 
5342                    style="margin-bottom: 0px !important; max-height:200px">
5343                    <iframe 
5344                    src="https://www.facebook.com/plugins/video.php?height=314&href=${element.url}&show_text=false&width=560&t=0" 
5345                    width="200" 
5346                    height="200" 
5347                    style="border:none;overflow:hidden"
5348                    scrolling="no" 
5349                    frameborder="0" 
5350                    allowfullscreen="true" 
5351                    allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" allowFullScreen="true"></iframe>
5352                    </div>`
5353        }
5354        else
5355          html += '<div class="cbot-image" style="margin-bottom: 11px !important; max-height:200px"><video width="200" height="200" controls><source src="' + element.url + '" type="video/mp4"></video></div>';
5356      }
5357      html += generateButtonsHTML([{ type: "mini_web", data_type: "video", title: "Mini-web'te görüntüle", url: element.url }].concat(element.buttons || []), options);
5358      html += "</div>";
5359
5360    } else if (component.message_type == "FILE_COMPONENT") {
5361      html += '<div class="cbot-component generic-template">' +
5362        '<a style="cursor:pointer;" href="' + component.url + '" target="_blank">' +
5363        '<div style="float:left">' +
5364        '<img alt="file icon" title="file icon" src="' + staticAddress + '/img/cbot-file-icon.png?client=' + CLIENT + '" style="width:16px; box-shadow:none;">' +
5365        '</div>' +
5366        '<div style="float:left; padding: 0 5px; color:#fff;
5366 max-width:200px;">' + component.filename || component.description + '</div>' +
5367        '<div style="float:right" style="pointer:cursor;">' +
5368
5369        '<img src="' + staticAddress + '/img/cbot-download-icon.png?client=' + CLIENT + '" style="width:16px; box-shadow:none;" />' +
5370        '</div>' +
5371        '</a>' +
5372        '</div>';
5373      // html += '<div class="cbot-image"><img style="cursor: pointer;" src="' + staticAddress + '/img/location.png"></div>';
5374      // if (element.title == "") element.title = answerisnotdefined_message || "Answer is not defined";
5375
5376
5377      html += '<div class="cbot-description">';
5378      if (component.name)
5379        html += '<p class="cbot-title" style="' + bot_message_text_title_color + '">' + category + "" + (component.name || "") + '</p>';
5380      if (component.address)
5381        html += '<p class="cbot-subtitle">' + (component.address || "").replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5382      // html += generateButtonsHTML(element.buttons);
5383      html += "</a></div>";
5384    } else if (component.message_type == "LOCATION_COMPONENT") {
5385      if (component.auto_open && firstMessageSent && !options.instantWrite)
5386        openMiniWeb("location", null, JSON.stringify({ lat: component.lat, lng: component.lng }))
5387
5388      html += '<div class="cbot-component generic-template"><a href="https://www.google.com.tr/maps/place/' + component.lat + ',' + component.lng + '" target="_blank">';
5389
5390      html += '<div class="cbot-image"><img alt="location icon" title="location icon" style="cursor: pointer;" src="https://static-maps.yandex.ru/1.x/?lang=tr-TR&ll=' + component.lng + ',' + component.lat + '&z=15&l=map&size=300,200&pt=' + component.lng + ',' + component.lat + ',pmgrm"></div>';
5391      // html += '<div class="cbot-image"><img style="cursor: pointer;" src="' + staticAddress + '/img/location.png"></div>';
5392      // if (element.title == "") element.title = answerisnotdefined_message || "Answer is not defined";
5393
5394      if (component.address) {
5395        component.address = numberToString((component || {}).address);
5396        sendUrlsToGA(component.address);
5397      }
5398
5399      html += '<div class="cbot-description">';
5400      if (component.name)
5401        html += '<p class="cbot-title" style="' + bot_message_text_title_color + '">' + category + "" + (component.name || "") + '</p>';
5402      if (component.address)
5403        html += '<p class="cbot-subtitle">' + (component.address || "").replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5404      // html += generateButtonsHTML(element.buttons);
5405      html += "</a>";
5406      html += generateButtonsHTML([
5407        { type: "mini_web", data_type: "location", title: "Mini-map'te Görüntüle", url: 'https://www.google.com.tr/maps/place/' + component.lat + ',' + component.lng + '', lng: component.lng, lat: component.lat },
5408        { type: "web_url", title: "Haritada Görüntüle", url: 'https://www.google.com.tr/maps/place/' + component.lat + ',' + component.lng + '' }], options);
5409      html += "</div>";
5410    } else if (component.message_type === "THRESHOLD_BAR_CHART_COMPONENT") {
5411      var elements = component.elements;
5412      html += '<div class="cbot-component cbot-threshold-bar-chart-template">';
5413
5414      elements.forEach(function (element, elementIndex) {
5415        if (elementIndex > 0) {
5416          html += '<hr class="cbot-element-divider">';
5417        }
5418        var rows = element.rows;
5419        var total = rows.reduce(function (sum, row) {
5420          return sum + parseFloat(row.value.replace(',', '.'));
5421        }, 0);
5422        var average = (total / rows.length).toFixed(2);
5423
5424        if (element.titles && element.titles.length > 0) {
5425          html += '<div class="cbot-chart-header">';
5426          element.titles.forEach(function (title) {
5427            html += '<p class="cbot-chart-title">' + title.value + '</p>';
5428          });
5429          html += '</div>';
5430        }
5431
5432        html += '<div class="cbot-chart-body">';
5433        rows.forEach(function (row) {
5434          var value = parseFloat(row.value.replace(',', '.'));
5435          var isAboveAverage = value > average;
5436
5437          html += '<div class="cbot-chart-column">';
5438          html += '<div class="cbot-bar-value">' + row.value + '</div>';
5439          html += '<div class="cbot-bar ' + (isAboveAverage ? 'above-average' : '') + '">';
5440          if (isAboveAverage) {
5441            html += '<div class="cbot-bar-red"></div>';
5442          }
5443          html += '<div class="cbot-bar-blue"></div>';
5444          html += '</div>';
5445          html += '<div class="cbot-bar-label">' + row.key + '</div>';
5446          html += '</div>';
5447        });
5448        html += '</div>';
5449      });
5450
5451      html += '</div>';
5452    } else if (component.message_type === "TABLE_COMPONENT") {
5453      var elements = component.elements;
5454      html += '<div class="cbot-component cbot-table-template">';
5455
5456      elements.forEach(function (element, elementIndex) {
5457        if (elementIndex > 0) {
5458          html += '<hr class="cbot-element-divider">';
5459        }
5460
5461        html += '<div class="cbot-table-header">';
5462        if (element.titles && element.titles.length > 0) {
5463          element.titles.forEach(function (title) {
5464            html += '<p class="cbot-table-header-p">' + title.value + '</p>';
5465          });
5466        }
5467        html += '</div>';
5468
5469        if (element.rows && element.rows.length > 0) {
5470          html += '<div class="cbot-table-body">';
5471          element.rows.forEach(function (row) {
5472            html += '<div class="cbot-table-body-row">';
5473            html += '<div class="cbot-table-body-row-key">' + row.key + '</div>';
5474            html += '<div class="cbot-table-body-row-value">' + row.value + '</div>';
5475            html += '</div>';
5476          });
5477          html += '</div>';
5478        }
5479      });
5480
5481      html += '</div>';
5482    } else if (component.message_type == "LIST_COMPONENT") {
5483      var elements = component.elements;
5484      options.button_template = component.button_template
5485      html += '<div class="cbot-component list-template">';
5486
5487      for (var i = 0; i < elements.length; i++) {
5488
5489        if (i == 0)
5490          html += '<div class="cbot-list-item" style="border-top:none; margin-top:-10px;">';
5491        else
5492          html += '<div class="cbot-list-item">';
5493
5494        if (elements[i].image_url) {
5495          html += '<div class="cbot-list-item-description">';
5496          html += '<div class="cbot-list-item-image"><img src="' + elements[i].image_url + '"></div>';
5497        } else {
5498          html += '<div class="cbot-list-item-description" style="width:100%;">';
5499        }
5500
5501        msg = category + elements[i].title;
5502
5503        if (elements[i].subtitle) {
5504          elements[i].subtitle = numberToString((elements[i] || {}).subtitle)
5505          sendUrlsToGA(elements[i].subtitle);
5506        }
5507
5508        elements[i].subtitle = (elements[i].subtitle || "").replace(/<p>|<\/p>/g, "")
5509
5510        html += '<p class="cbot-list-item-title">' + msg + '</p>' +
5511          '<div class="cbot-list-item-text-wrap"><p class="cbot-list-item-text">' + elements[i].subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5512        var buttons = elements[i].buttons;
5513
5514
5515        // html += '<div class="cbot-buttons">'
5516        if (elements[i].button_template == "SUGGESTION") {
5517
5518          html += '<div class="cbot-suggestion-button-slider">'
5519        }
5520        for (var j = 0; buttons && j < buttons.length; j++) {
5521          triple_button_css = "";
5522          triple_button_class = "";
5523          suggestion_button_style = "";
5524          text_button_class = "";
5525
5526          if (elements[i].button_template == "TEXT BUTTON") {
5527            text_button_class = " cbot-text-button-class";
5528          }
5529          if (elements[i].button_template == "TRIPLE") {
5530
5531            triple_button_class = " cbot-triple-button-class ";
5532            if (j == 1) {
5533              triple_button_css = "; width: calc(50% - 1px); margin-right: 1px; margin-left:0;";
5534            }
5535            if (j == 2) {
5536              triple_button_css = "; width: calc(50% - 1px); margin-left: 1px; margin-right:0;";
5537            }
5538          }
5539          if (elements[i].button_template == "SUGGESTION") {
5540            suggestion_button_style = "; width: initial; padding-left: 5px; padding-right: 5px; margin-right: 5px; display: inline-block; float: initial;";
5541          }
5542          if (buttons[j].type == "web_url") {
5543            if (firstMessageSent && buttons[j].auto_open && !options.instantWrite)
5544              openMiniWeb("web_url", buttons[j].url);
5545            // var target = getUrlTarget(buttons[j].url, CHANNEL);
5546            // html += '<a ontouchstart="" href="' + buttons[j].url + '" target="' + target + '" class="cbot-list-item-button' + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" onclick="clickTheURLs(this)">' + buttons[j].title + '</a>';
5547            html += renderPostMessageButton(buttons[j].url, buttons[j].title, component.message_type);
5548          } else if (buttons[j].type == "phone_number") {
5549            html += '<a ontouchstart="" href="tel:' + (buttons[j].payload || buttons[j].phone_number) + '"class="cbot-list-item-button" style="' + suggestion_button_style + triple_button_css + '" onclick="clickTheURLs(this)">' + buttons[j].title + '</a>';
5550          } else if (buttons[j].type == "account_link") {
5551            html += '<div ontouchstart="" class="cbot-button cbot-list-item-button' + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" onclick="waitForLogin(); popupwindow(\'' + (buttons[j].web_url || buttons[j].url || "") + '\', \'\', 800, 600)">' + (buttons[j].title || "Giriş için Tıklayın") + '</div>';
5552            // waitForLogin();
5553          } else if (buttons[j].type == "location") {
5554            html += '<button ontouchstart="" class="cbot-button cbot-list-item-button cbot-location' + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" data-onclick="shareLocation()">' + buttons[j].title + '</button>';
5555          } else if (buttons[j].type == "file_download") {
5556            html += '<a ontouchstart="" href="' + buttons[j].url + '" target="_blank" class="cbot-list-item-button' + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" onclick="clickTheURLs(this)">' + buttons[j].title + '</a>';
5557          } else if (buttons[j].type == "file_upload") {
5558            html += "<input class='cbot-attachment-file-input' id='cbot-attachment-file-input-" + uploadIndex + "' accept='" + buttons[j].mimetypes.map(function (m) { return m.mimetype }).join(",") + "' type='file' hidden/>" +
5559              '<button ontouchstart="" class="cbot-button cbot-list-item-button fileupload' + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" data-payload="' + uploadIndex + '">' + buttons[j].title + '</button>';
5560            uploadIndex++;
5561          } else if (buttons[j].type == "iframe_button") {
5562            if (buttons[j].auto_open && firstMessageSent && !options.instantWrite)
5563              openMiniWeb("web_url", buttons[j].url);
5564
5565            cbotgtag('event', 'cbot', {
5566              'event_category': 'cbot-button',
5567              'event_action': buttons[j].title,
5568              'event_label': buttons[j].url
5569            })
5570            html += '<button ontouchstart="" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button cbot-list-item-button ' + buttons[j].theme + triple_button_class + text_button_class + '"  onclick=' + "openMiniWeb('web_url','" + buttons[j].url + "')" + '>' + buttons[j].title + '</button>';
5571          } else {
5572            html += '<button ontouchstart="" class="cbot-button cbot-list-item-button postback' + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" data-payload="' + (buttons[j].payload ? buttons[j].payload : buttons[j].title) + '" data-full-action=\'' + JSON.stringify(buttons[j] || {}).replace(/'/g, '&#39;') + '\'>' + buttons[j].title + '</button>';
5573          }
5574        }
5575
5576        if (elements[i].button_template == "SUGGESTION") {
5577          html += '</div>'
5578        }
5579
5580        // html += '</div>'
5581
5582        html += '</div><div style="clear:both;"></div></div>';
5583        // html += generateButtonsHTML(elements[i].buttons);
5584      }
5585
5586      html += '</div>';
5587    } else if (component.message_type == "COMBOBOX_COMPONENT") {
5588
5589      html += '<span>' + component.message + '</span>';
5590      html += ' <div class="cbot-dropdown">';
5591      html += '<input type="text" placeholder="Arama.." class="cbot-dropdown-input">'
5592      html += '<div id="myDropdown" class="cbot-dropdown-content">'
5593      component.combobox_items.forEach(function (item) {
5594
5595        html += '<button type="button" class="cbot-combobox" data-payload="' + item + '">' + item + '</button>'
5596
5597      })
5598
5599      html += ' </div> </div> '
5600
5601
5602    } else if (component.message_type == "BUTTON_COMPONENT") {
5603
5604      var buttons = component.buttons || [];
5605
5606      options.button_template = component.button_template
5607      if (component.from_file) {
5608        if (!Array.isArray(component.buttons)) component.buttons = [];
5609        buttons = [{
5610          type: "mini_web", data_type: "html", title: "Mini-web'te görüntüle", html: b64encode(component.message)
5611        }].concat(buttons)
5612        if (firstMessageSent && component.auto_open && !options.instantWrite)
5613          openMiniWeb("html", null, JSON.stringify({ html: b64encode(component.message) }))
5614      }
5615
5616      sendUrlsToGA(component.message);
5617
5618      if (!component.auto_open) {
5619        html += '<div class="cbot-component generic-template button-template"><div class="cbot-description"><p class="cbot-subtitle">' + component.message + '</p></div>';
5620        if (component.is_survey && component.type) {
5621          html += '<div class="cbot-survey-type survey-' + component.type + '">' + generateButtonsHTML(buttons, options) + '</div>';
5622        } else {
5623          html += generateButtonsHTML(buttons, options);
5624        }
5625      }
5626    } else if (component.message_type == "TRANSACTION_COMPONENT") {
5627
5628      html += '<div class="cbot-component generic-template"><div class="cbot-description">' + component.message + "</div>";
5629
5630      html += '<hr class="cbot-dashed-hr" />';
5631      var elements = component.elements || [];
5632      for (var i = 0; i < elements.length; i++) {
5633        var subtitle = (elements[i].subtitle || "").replace(/\n/g, "<br />");
5634        html += '<div class="cbot-txn-title">' + elements[i].title + '</div>';
5635        html += '<div class="cbot-txn-subtitle">' + subtitle + '</div>';
5636        if (elements.length != i + 1) {
5637
5638          html += '<hr class="cbot-solid-hr" />';
5639        }
5640      }
5641      html += generateButtonsHTML(component.buttons, options);
5642      html += '</div>';
5643
5644    } else if (component.message_type == "LIST_NEW_COMPONENT") {
5645      html += '<div class="cbot-component generic-template"><div class="cbot-description">' + component.message + "</div>";
5646
5647      html += '<hr class="cbot-dashed-hr" />';
5648      var elements = component.elements || [];
5649      for (var i = 0; i < elements.length; i++) {
5650        var subtitle = (elements[i].subtitle || "").replace(/\n/g, "<br />");
5651        html += '<div class="cbot-list-new-container">'
5652        html += '<div style="display:block;float:left">'
5653        html += '<div class="cbot-list-new-img" style="background-image:url(.' + elements[i].image_url + ')"></div>';
5654        html += "</div>"
5655
5656        html += '<div style="display:block;float:left;width:calc(100% - 50px)">'
5657        html += '<div class="cbot-list-new-title">' + elements[i].title + '</div>';
5658        html += '<div class="cbot-list-new-subtitle">' + subtitle + '</div>';
5659        html += "</div>"
5660        html += '<div style="clear:both"></div>'
5661        html += "</div>"
5662        if (elements.length != i + 1) {
5663
5664        }
5665        html += '<hr class="cbot-dashed-hr" />';
5666      }
5667      // html += '<a href="https://cbot.ai" target="_blank" style="display:block; margin: 0 auto;text-align:center;padding:5px 0;cursor:pointer;color: #2599fc;font-family: "Proxima";font-size: 14px;font-weight: 400;line-height: 15px;"> Tümünü Gör</a>'
5668      // html += generateButtonsHTML(component.buttons, options.instantWrite);
5669      html += '</div>';
5670
5671    } else if (component.message_type == "CURRENCY_COMPONENT") {
5672
5673      html += '<div class="cbot-component generic-template"><div class="cbot-description"><p class="cbot-subtitle">' + component.message + '</p></div>';
5674      html += ""
5675
5676    } else if (component.message_type == "PREVIEW_COMPONENT") {
5677      var element = component.elements[0];
5678      return category + (element.message || "").replace(/(\n|\\n)/g, "<br/>");
5679
5680    } else if (component.message_type == "SURVEY_STAR_COMPONENT") {
5681
5682      // sendUrlsToGA(component.message);
5683
5684
5685      html += '<p>' + component.message + '</p>';
5686      html += '      <div class="cbot-rating-group">';
5687      html += '      <label class="cbot-rating-label postback" data-payload="0" for="cbot-rating-' + (++ratingSelector) + '" style="display: none;">';
5688      html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5689      html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="
56890" type="radio" style="display: none;" checked>';
5690      html += '      <label class="cbot-rating-label postback" data-payload="1" for="cbot-rating-' + (++ratingSelector) + '">';
5691      html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5692      html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="1" type="radio">';
5693      html += '      <label class="cbot-rating-label postback" data-payload="2" for="cbot-rating-' + (++ratingSelector) + '">';
5694      html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5695      html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="2" type="radio">';
5696      html += '      <label class="cbot-rating-label postback" data-payload="3" for="cbot-rating-' + (++ratingSelector) + '">';
5697      html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5698      html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="3" type="radio">';
5699      html += '      <label class="cbot-rating-label postback" data-payload="4" for="cbot-rating-' + (++ratingSelector) + '">';
5700      html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5701      html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="4" type="radio">';
5702      html += '      <label class="cbot-rating-label postback" data-payload="5" for="cbot-rating-' + (++ratingSelector) + '">';
5703      html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5704      html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="5" type="radio">';
5705      if (component.type == "1-10") {
5706
5707        html += '      <label class="cbot-rating-label postback" data-payload="6" for="cbot-rating-' + (++ratingSelector) + '">';
5708        html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5709        html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="6" type="radio">';
5710        html += '      <label class="cbot-rating-label postback" data-payload="7" for="cbot-rating-' + (++ratingSelector) + '">';
5711        html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5712        html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="7" type="radio">';
5713        html += '      <label class="cbot-rating-label postback" data-payload="8" for="cbot-rating-' + (++ratingSelector) + '">';
5714        html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5715        html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="8" type="radio">';
5716        html += '      <label class="cbot-rating-label postback" data-payload="9" for="cbot-rating-' + (++ratingSelector) + '">';
5717        html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5718        html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="9" type="radio">';
5719        html += '      <label class="cbot-rating-label postback" data-payload="10" for="cbot-rating-' + (++ratingSelector) + '">';
5720        html += '              <i class="cbot-rating-star cbot-icon-star"></i></label>';
5721        html += '      <input class="cbot-rating-input" name="rating' + (ratingGroup) + '" id="cbot-rating-' + (ratingSelector) + '" value="10" type="radio">';
5722      }
5723      ratingGroup++;
5724      html += '</div>';
5725    }
5726    else if (component.message_type == "SURVEY_COLORFUL_COMPONENT") {
5727
5728
5729
5730      html += '<p>' + component.message + '</p>';
5731      html += '<div class="cbot-colorful-radio-main-container"> '
5732      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-0">';
5733      html += '    <input type="radio" name="radio">';
5734      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-0 postback" data-payload="0">0</span>';
5735      html += '</label> ';
5736
5737      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-1">';
5738      html += '    <input type="radio" name="radio">';
5739      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-1 postback" data-payload="1">1</span>';
5740      html += '</label>';
5741
5742      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-2">';
5743      html += '    <input type="radio" name="radio">';
5744      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-2 postback" data-payload="2">2</span>';
5745      html += '</label>';
5746
5747      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-3">';
5748      html += '    <input type="radio" name="radio">';
5749      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-3 postback" data-payload="3">3</span>';
5750      html += '</label>';
5751
5752      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-4">';
5753      html += '    <input type="radio" name="radio">';
5754      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-4 postback" data-payload="4">4</span>';
5755      html += '</label>';
5756
5757      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-5">';
5758      html += '    <input type="radio" name="radio">';
5759      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-5 postback" data-payload="5">5</span>';
5760      html += '</label>';
5761
5762      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-6">';
5763      html += '    <input type="radio" name="radio">';
5764      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-6 postback" data-payload="6">6</span>';
5765      html += '</label>';
5766
5767      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-7">';
5768      html += '    <input type="radio" name="radio">';
5769      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-7 postback" data-payload="7">7</span>';
5770      html += '</label>';
5771
5772      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-8">';
5773      html += '    <input type="radio" name="radio">';
5774      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-8 postback" data-payload="8">8</span>';
5775      html += '</label>';
5776
5777      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-9">';
5778      html += '    <input type="radio" name="radio">';
5779      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-9 postback" data-payload="9">9</span>';
5780      html += '</label>';
5781
5782
5783      html += '<label class="cbot-colorful-radio-container cbot-colorful-radio-container-styling-10">';
5784      html += '    <input type="radio" name="radio">';
5785      html += '    <span class="cbot-colorful-radio-span cbot-colorful-radio-span-styling-10 postback" data-payload="10">10</span>';
5786      html += '</label>';
5787
5788
5789
5790
5791      html += '   </div>';
5792      html += '<div style="clear:both"></div>';
5793
5794    } else if (component.message_type == "TEXT") {
5795      if (options.survey_response == true) {
5796        return '<span class="survey-response" width>' + category + linkify((component.message || '').replace(/(\n|\\n)/g, "<br/>")) + '</span>';
5797      } else {
5798        return '<span width>' + category + linkify((component.message || '').replace(/(\n|\\n)/g, "<br/>")) + '</span>';
5799      }
5800    } else if (component.message_type == "CUSTOM_COMPONENT") {
5801      if (component.elements.length > 1) {
5802        var elements = component.elements;
5803        var hasCarouselDots = false;
5804        var hasCarouselBlur = false;
5805
5806        for (var i = 0; i < elements.length; i++) {
5807          var elementHtmlCheck = elements[i].html || '';
5808          if (elementHtmlCheck.indexOf('data-cbot-carousel-dots') >= 0) {
5809            hasCarouselDots = true;
5810          }
5811          if (elementHtmlCheck.indexOf('data-cbot-carousel-blur') >= 0) {
5812            hasCarouselBlur = true;
5813          }
5814        }
5815
5816        var wrapperClasses = 'cbot-custom-component-carousel-wrapper';
5817        if (hasCarouselDots) wrapperClasses += ' cbot-has-dots';
5818        if (hasCarouselBlur) wrapperClasses += ' cbot-has-blur';
5819
5820        html += '<div class="' + wrapperClasses + '">';
5821        if (data_owl) {
5822          html += '<div class="cbot-owl-carousel">';
5823        }
5824        else {
5825          html += '<div class="cbot-arrow left" style="display: none;"></div>' +
5826            '<div class="cbot-arrow right"></div>' +
5827            '<div class="cbot-card-carousel" style="width:' + (elements.length * 260) + 'px; position: relative; display:flex">'
5828        }
5829        for (var i = 0; i < elements.length; i++) {
5830          if (data_owl) {
5831            html += '<div class="item">';
5832            html += '<div class="cbot-component custom-component cbot-owl-item-box">';
5833          }
5834          else {
5835            html += '<div class="cbot-component custom-component" style="float:left; max-width:250px; margin-right:10px;">';
5836          }
5837
5838          let elementHtml = elements[i].html || '';
5839
5840          let buttons = '';
5841          if (elements[i].buttons) {
5842            buttons = generateButtonsHTML(elements[i].buttons, options);
5843            elementHtml = elementHtml.replace("{buttons}", buttons);
5844          }
5845
5846          html += elementHtml;
5847
5848          if (data_owl) {
5849            html += "</div>";
5850          }
5851          html += "</div>";
5852        }
5853        html += '</div>';
5854
5855        if (hasCarouselDots && !data_owl) {
5856          html += '<div class="cbot-carousel-dots">';
5857          for (var i = 0; i < elements.length; i++) {
5858            html += '<span class="cbot-carousel-dot' + (i === 0 ? ' cbot-active' : '') + '" data-slide-index="' + i + '"></span>';
5859          }
5860          html += '</div>';
5861        }
5862
5863        html += '</div>';
5864      } else {
5865        let element = component.elements && component.elements.length > 0 ? component.elements[0] : component;
5866        let buttons = '';
5867        if (element.buttons) {
5868          buttons = generateButtonsHTML(element.buttons, options);
5869        }
5870        html += element.html.replace("{buttons}", buttons || '');
5871      }
5872    }
5873
5874    else if (component.message && component.message.quick_replies) {
5875      msg = category + component.message.text;
5876      html += '<div class="cbot-component generic-template"><div class="cbot-description"><p class="cbot-subtitle">' + msg + '</p></div>';
5877      html += generateButtonsHTML(component.message.quick_replies, options);
5878    } else if (component.message && component.message.attachment.type === "template") { // Mesaj tipi template ise
5879      msg = category + component.message.attachment.payload.text;
5880      if (component.message.attachment.payload.template_type === "button") {
5881
5882        sendUrlsToGA(msg);
5883
5884        html += '<div class="cbot-component generic-template"><div class="cbot-description"><p class="cbot-subtitle">' + msg + '</p></div>';
5885        html += generateButtonsHTML(component.message.attachment.payload.buttons, options);
5886      } else if (component.message.attachment.payload.template_type === "generic") {
5887        if (component.message.attachment.payload.elements.length > 1) { // Birden fazla kart var!
5888          var elements = component.message.attachment.payload.elements;
5889          html += '<div class="cbot-arrow left"></div>' +
5890            '<div class="cbot-arrow right"></div>' +
5891            '<div class="cbot-card-carousel" style="width:' + (elements.length * 260) + 'px; position: relative;">';
5892          for (var i = 0; i < elements.length; i++) {
5893            msg = category + elements[i].title;
5894            html += '<div class="cbot-component generic-template" style="float:left; max-width:250px; margin-right:10px;">';
5895            if (elements[i].image_url)
5896              html += '<div class="cbot-image"><img src="' + elements[i].image_url + '"></div>';
5897
5898            if (elements[i].subtitle) {
5899              elements[i].subtitle = numberToString((elements[i] || {}).subtitle)
5900              sendUrlsToGA(elements[i].subtitle);
5901            }
5902
5903            html += '<div class="cbot-description">' +
5904              '<p class="cbot-title">' + msg + '</p>' +
5905              '<p class="cbot-subtitle">' + elements[i].subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5906            html += generateButtonsHTML(elements[i].buttons, options);
5907            html += "</div>";
5908          }
5909
5910          html += '</div>';
5911
5912        } else { // Sadece bir tane kart var!
5913          var element = component.message.attachment.payload.elements[0];
5914          html += '<div class="cbot-component generic-template">';
5915
5916          if (element.image_url)
5917            html += '<div class="cbot-image"><img src="' + element.image_url + '"></div>';
5918
5919          msg = category + element.title;
5920
5921          if (element.subtitle) {
5922
5923            element.subtitle = numberToString((element || {}).subtitle)
5924            sendUrlsToGA(element.subtitle);
5925          }
5926
5927          html += '<div class="cbot-description">' +
5928            '<p class="cbot-title">' + msg + '</p>' +
5929            '<p class="cbot-subtitle">' + element.subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5930          html += generateButtonsHTML(element.buttons, options);
5931          html += "</div>";
5932        }
5933      } else if (component.message.attachment.payload.template_type === "list") {
5934        var elements = component.message.attachment.payload.elements;
5935        html += '<div class="cbot-component list-template">';
5936        for (var i = 0; i < elements.length; i++) {
5937          if (i == 0)
5938            html += '<div class="cbot-list-item" style="border-top:none; margin-top:-10px;">';
5939          else
5940            html += '<div class="cbot-list-item">';
5941
5942          if (elements[i].image_url) {
5943            html += '<div class="cbot-list-item-image"><img src="' + elements[i].image_url + '"></div>';
5944            html += '<div class="cbot-list-item-description">';
5945          } else {
5946            html += '<div class="cbot-list-item-description" style="width:100%;">';
5947          }
5948
5949          msg = category + elements[i].title;
5950
5951          if (elements[i].subtitle) {
5952            elements[i].subtitle = numberToString((elements[i] || {}).subtitle)
5953            sendUrlsToGA(elements[i].subtitle);
5954          }
5955
5956          html += '<p class="cbot-list-item-title">' + msg + '</p>' +
5957            '<div class="cbot-list-item-text-wrap"><p class="cbot-list-item-text">' + elements[i].subtitle.replace(/(\n|\\n)/g, "<br/>") + '</p></div>';
5958          var buttons = elements[i].buttons;
5959          for (var j = 0; buttons && j < buttons.length; j++) {
5960            if (buttons[j].type == "web_url") {
5961              // var target = getUrlTarget(buttons[j].url, CHANNEL);
5962              // html += '<a href="' + buttons[j].url + '" target="' + target + '" class="cbot-list-item-button" onclick="clickTheURLs(this)">' + buttons[j].title + '</a>';
5963              html += renderPostMessageButton(buttons[j].url, buttons[j].title, component.message.attachment.payload.template_type);
5964            } else if (buttons[j].type == "phone_number") {
5965              html += '<a href="tel:' + (buttons[j].payload || buttons[j].phone_number) + '" target="_blank" class="cbot-list-item-button" onclick="clickTheURLs(this)">' + buttons[j].title + '</a>';
5966            } else if (buttons[j].type == "file_download") {
5967              html += '<a href="' + buttons[j].url + '" target="_blank" class="cbot-list-item-button" onclick="clickTheURLs(this)">' + buttons[j].title + '</a>';
5968            } else if (buttons[j].type == "file_upload") {
5969              html += "<input class='cbot-attachment-file-input' id='cbot-attachment-file-input-" + uploadIndex + "' accept='" + buttons[j].mimetypes.map(function (m) { return m.mimetype }).join(",") + "' type='file' hidden/>" +
5970                '<button class="cbot-button cbot-list-item-button fileupload" data-payload="' + uploadIndex + '">' + buttons[j].title + '</button>';
5971              uploadIndex++;
5972            } else {
5973              html += '<div class="cbot-button cbot-list-item-button postback">' + buttons[j].title + '</div>';
5974            }
5975          }
5976          html += '</div><div style="clear:both;"></div></div>';
5977          // html += generateButtonsHTML(elements[i].buttons);
5978        }
5979
5980        html += '</div>';
5981      }
5982    } else {
5983      // TODO: Diğer yapılar buraya!
5984    }
5985    return html;
5986  }
5987
5988  sendUrlsToGA(component);
5989
5990  return category + (component || "").replace(/(\n|\\n)/g, "<br/>");
5991}
5992
5993function appendTypingIconToDialogBox(value) {
5994  // Refresh butonunu devre dışı bırak
5995  $(".cbot-refresh-icon").css('opacity', '0.5')
5996  $(".cbot-refresh-icon").css('pointer-events', 'none')
5997
5998  // var e = document.getElementById("cbot-chat");
5999  // e.innerHTML += '<li class="cbot-other cbot-typing"><div class="cbot-msg"><div class="cbot-typing-loader"></div></div></li>', e.scrollTop = 5e6
6000  if (value != "" && value != undefined) {
6001    if (!botlanguage || botlanguage == "tr") {
6002      // $('#cbot-form-message').attr('disabled', 'disabled');
6003      $("#cbot-chat").append('<li class="cbot-other cbot-typing ' + (isLive ? "cbot-typing-agent" : "") + '"><div class="cbot-msg" style="height: 30px; border-bottom-left-radius: 0; border-top-left-radius: 15px;' + bot_message_bubble_color + '"><p class="cbot-typing-text">' + value + ' yazıyor </p><div class="cbot-typing-loader"></div></div></li>');
6004      afterAppend();
6005    } else {
6006      // $('#cbot-form-message').attr('disabled', 'disabled');
6007      $("#cbot-chat").append('<li class="cbot-other cbot-typing ' + (isLive ? "cbot-typing-agent" : "") + '"><div class="cbot-msg" style="height: 30px; border-bottom-left-radius: 0; border-top-left-radius: 15px;' + bot_message_bubble_color + '"><p class="cbot-typing-text">' + value + ' is typing </p><div class="cbot-typing-loader"></div></div></li>');
6008      afterAppend();
6009    }
6010  }
6011  else {
6012    if (!isLive) $('#cbot-form-message').attr('disabled', 'disabled');
6013    $("#cbot-chat").append('<li class="cbot-other cbot-typing ' + (isLive ? "cbot-typing-agent" : "") + '"><div class="cbot-msg" style="height: 20px; border-bottom-left-radius: 0; border-top-left-radius: 15px;' + bot_message_bubble_color + '"><div class="cbot-typing-loader"></div></div></li>');
6014    afterAppend();
6015  }
6016  if (clients.chat_avatar_activation && clients.chat_agent_avatar && isLive) {
6017    let custom_cbot_other_icon_agent = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">.cbot-typing-agent:before { content: "";width: 35px;height: 35px;position: absolute;left: 16px;top: 0;border: 1px solid #DCDCDC;border-radius: 24px;display: flex;justify-content: center;align-items: center;background-image: url(${clients.chat_agent_avatar});background-repeat: no-repeat;background-position-x: center;background-position-y: center;}</style>`);
6018    $('head').append(custom_cbot_other_icon_agent);
6019    afterAppend();
6020  }
6021  // console.log("SCROLL 8");
6022  scrollChatScreen(300);
6023}
6024
6025var cbotModal;
6026var cbotModalImg;
6027
6028function cbotModalImage(url) {
6029  cbotModal.style.display = "block";
6030  cbotModalImg.src = url;
6031}
6032
6033function isExitSurveyExists() {
6034  if (kvkk_is_active && (kvkk_status === KVKK_STATUS_ENUM.DECLINED || kvkk_status === KVKK_STATUS_ENUM.ASKED)) {
6035    return false;
6036  }
6037  return !showedSurvey && exitSurvey;
6038}
6039
6040function showExitSurvey() {
6041  if (isExitSurveyExists()) {
6042
6043    // if (LIVE_CHAT && isLive) {
6044    //   closeLivechat(true);
6045    //   return true;
6046    // }
6047
6048    surveyTrigger(exitSurvey, cbotUserId, true);
6049
6050    return true;
6051  }
6052
6053  return false;
6054}
6055
6056var surveyRedirectedIntentId = null;
6057
6058function handleExitSurveyAnswer(category, hasSurveyFeedback, redirectedIntentId, conversationStep) {
6059  if (redirectedIntentId) surveyRedirectedIntentId = redirectedIntentId;
6060  if (surveyRedirectedIntentId) {
6061    if (!hasSurveyFeedback && !redirectedIntentId && !conversationStep) {
6062      if (clients.disable_user_chat_input) {
6063        disableUserMessageArea(clients.disable_user_chat_input_message);
6064        surveyRedirectedIntentId = null;
6065
6066        return true;
6067      }
6068
6069    }
6070
6071
6072    // $("#cbot-close-icon-new").click();
6073    // reset();
6074    return false;
6075  }
6076
6077  return false;
6078}
6079
6080
6081
6082function surveyTrigger(survey, cbotUserId, is_live_survey = false) {
6083  if (kvkk_is_active && (kvkk_status === KVKK_STATUS_ENUM.DECLINED || kvkk_status === KVKK_STATUS_ENUM.ASKED)) {
6084    return;
6085  }
6086  clearSurveyTimeout();
6087  // console.log("surveyTrigger", survey);
6088
6089
6090  if (!showedSurvey && survey) {
6091    hasSurveyShowAsPopUp = survey.show_as_popup;
6092    surveyTimeout = setTimeout(function () {
6093      // console.log("TIMEOUT", survey);
6094      var comp = {};
6095      if (survey.show_type == "STAR")
6096        comp = { message_type: "SURVEY_STAR_COMPONENT", type: survey.type, message: survey.question, buttons: [] };
6097      else if (survey.show_type == "0-10Colorful")
6098        comp = { message_type: "SURVEY_COLORFUL_COMPONENT", type: survey.type, message: survey.question, buttons: [] };
6099      else if (survey.type == "YESNO") {
6100        comp = { message_type: "BUTTON_COMPONENT", type: survey.type, message: survey.question, buttons: [] };
6101        survey.popup_question_yes = survey.popup_question_yes || "Evet";
6102        survey.popup_question_no = survey.popup_question_no || "Hayır";
6103        comp.buttons.push({
6104          type: "postback",
6105          title: survey.popup_question_yes,
6106          payload: survey.popup_question_yes
6107        })
6108        comp.buttons.push({
6109          type: "postback",
6110          title: survey.popup_question_no,
6111          payload: survey.popup_question_no
6112        })
6113      }
6114      else {
6115        comp = { message_type: "BUTTON_COMPONENT", type: survey.type, message: survey.question, buttons: [] };
6116        for (var i = 0; i < survey.buttons.length; i++) {
6117          comp.buttons.push({
6118            type: "postback",
6119            title: survey.buttons[i],
6120            payload: survey.buttons[i]
6121          })
6122        }
6123      }
6124      if (!is_live_survey && isLive) {
6125        return;
6126      }
6127      if (survey.show_as_popup && !isWidgetOpen)
6128        starAnketShow(survey);
6129
6130      comp.is_survey = true;
6131
6132      if (survey.disable_message_box_after_survey && comp.message_type == "SURVEY_STAR_COMPONENT") {
6133        $('.cbot-send-button').css("display", "none");
6134        $('.cbot-attachment-area').css("display", "none");
6135        $('#cbot-form-message').attr('disabled', 'disabled');
6136        $(".cbot-illusion-placeholder").html(clients.send_survey_placeholder_message);
6137      }
6138
6139      appendMessageToDialogBox(comp, "cbot-other", "SURVEY", { notification: survey.question }, function () {
6140        setClickEventToInteractiveButtons(cbotUserId);
6141        /* ANIMATION RATING */
6142        // var latest = $(".cbot-rating-group").eq(-1) || [];
6143        // if (latest.length > 0) {
6144        //     var items = $(latest).find(".cbot-rating-input");
6145        //     for (var i = 1; i <= items.length; i++) {
6146        //         var item = items[i];
6147        //         setTimeout(function () {
6148        //             (item || {}).checked = true;
6149        //         }, i * 100)
6150        //         if (i == items.length) {
6151        //             setTimeout(function() {
6152        //                 items.checked = false;
6153        //                 items[0].checked = true;
6154        //             }, i * 100);
6155        //         }
6156        //     }
6157        // }
6158      });
6159      // if (!survey.survey_from_agent)
6160      showedSurvey = survey;
6161      sentSurveyFeedback = false;
6162      sendCustomPostMessage("CBOT_SURVEY_SENT_TO_USER", survey);
6163      let surveyGtaViewData = {
6164        "survey_type": survey.type,
6165        "survey_name": survey.name
6166      }
6167      sendSurveyViewToGA(surveyGtaViewData)
6168    }, (survey.show_when_close ? 0 : survey.delay) * 1000);
6169  }
6170}
6171function clearSurveyTimeout() {
6172  if (surveyTimeout) {
6173    clearTimeout(surveyTimeout);
6174    surveyTimeout = null;
6175  }
6176  // showedSurvey = null;
6177}
6178function addSurveyRequestData(jsonData) {
6179  if (showedSurvey) {
6180    if (!sentSurvey) { // Anket gönderilmiş ve cevaplanmamışsa, kullanıcı cevabı önce
6181      jsonData.is_survey = true;
6182      jsonData.survey_id = showedSurvey.id;
6183      jsonData.survey_name = showedSurvey.name;
6184      jsonData.agent_id = agentId || showedSurvey.agent_id;
6185      sentSurvey = true;
6186      // agentId = null;
6187    } else if (hasSurveyFeedback && sentSurvey && !sentSurveyFeedback) { // The survey is sent and answered. But feedback doesn't send.
6188      sentSurveyFeedback = true;
6189      jsonData.is_survey_feedback = true;
6190      jsonData.survey_id = showedSurvey.id;
6191      jsonData.agent_id = agentId || showedSurvey.agent_id;
6192    }
6193  }
6194
6195  return jsonData;
6196}
6197
6198function reset(clear_dialog) {
6199  cbotClearUserDialog(clear_dialog);
6200  welcomeMessageSent = true;
6201  firstLoad = false;
6202  showedSurvey = null;
6203  exitSurvey = null;
6204  sentSurvey = false;
6205}
6206
6207function getParameterByName(name, url) {
6208  if (!url) url = window.location.href;
6209  name = name.replace(/[\[\]]/g, '\\$&');
6210  var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
6211    results = regex.exec(url);
6212  if (!results) return null;
6213  if (!results[2]) return '';
6214  return decodeURIComponent(results[2].replace(/\+/g, ' '));
6215}
6216
6217function hasAttributeOnScript(name) {
6218  if (document.getElementById("cbot-widget-script")) {
6219    return document.getElementById("cbot-widget-script").hasAttribute(name);
6220  }
6221  return false;
6222}
6223
6224function getParameterFromScript(name) {
6225  var script = document.getElementById("cbot-widget-script");
6226  if (script && script.getAttribute(name)) {
6227    return script.getAttribute(name);
6228  }
6229
6230  var hiddenInput = document.getElementById("cbot-" + name);
6231  if (hiddenInput) {
6232    return hiddenInput.value || "";
6233  }
6234
6235  return "";
6236
6237}
6238
6239function generateButtonsHTML(buttons, options) {
6240
6241  if (!options) options = {};
6242  var html = '<div class="cbot-buttons">';
6243  if (options.button_template == "SUGGESTION") {
6244
6245    html += '<div class="cbot-suggestion-button-slider">'
6246  }
6247  for (var i = 0; buttons && i < buttons.length; i++) {
6248
6249    triple_button_css = "";
6250    triple_button_class = "";
6251    suggestion_button_style = "";
6252    text_button_class = "";
6253
6254    if (options.button_template == "TEXT BUTTON") {
6255      text_button_class = " cbot-text-button-class";
6256    }
6257
6258    buttons[i].theme = buttons[i].theme || "";
6259    if (options.button_template == "TRIPLE") {
6260
6261      triple_button_class = " cbot-triple-button-class";
6262      if (i == 1) {
6263        triple_button_css = "; width: calc(50% - 1px); margin-right: 1px; margin-left:0;";
6264      }
6265      if (i == 2) {
6266        triple_button_css = "; width: calc(50% - 1px); margin-left: 1px; margin-right:0;";
6267      }
6268    }
6269    if (options.button_template == "SUGGESTION") {
6270      suggestion_button_style = "; width: initial; float: initial; padding-left: 5px; padding-right: 5px; margin-right: 5px;";
6271    }
6272    if (buttons[i].type == "web_url") {
6273      if (buttons[i].auto_open && firstMessageSent && !options.instantWrite)
6274        openMiniWeb("web_url", buttons[i].url);
6275      cbotgtag('event', 'cbot', {
6276        'event_category': 'cbot-button',
6277        'event_action': buttons[i].title,
6278        'event_label': buttons[i].url
6279      })
6280      // var target = getUrlTarget(buttons[i].url, CHANNEL);
6281      // html += '<a ontouchstart="" href="' + buttons[i].url + '" target="' + target + '" onclick="clickTheURLs(this)" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button ' + buttons[i].theme + triple_button_class + text_button_class + '">' + buttons[i].title + '</a>';
6282      html += renderPostMessageButton(buttons[i].url, buttons[i].title);
6283    } else if (buttons[i].type == "iframe_button") {
6284      if (buttons[i].auto_open && firstMessageSent && !options.instantWrite)
6285        openMiniWeb("web_url", buttons[i].url);
6286
6287      cbotgtag('event', 'cbot', {
6288        'event_category': 'cbot-button',
6289        'event_action': buttons[i].title,
6290        'event_label': buttons[i].url
6291      })
6292      html += '<button ontouchstart="" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button ' + buttons[i].theme + triple_button_class + text_button_class + '"  onclick=' + "openMiniWeb('web_url','" + buttons[i].url + "')" + '>' + buttons[i].title + '</button>';
6293    } else if (buttons[i].type == "mini_web") {
6294      cbotgtag('event', 'cbot', {
6295        'event_category': 'cbot-button',
6296        'event_action': buttons[i].title,
6297        'event_label': buttons[i].url
6298      })
6299      var options = {};
6300      if (buttons[i].lng && buttons[i].lat) {
6301        options.lng = buttons[i].lng;
6302        options.lat = buttons[i].lat;
6303      }
6304      if (buttons[i].html) {
6305        options.html = buttons[i].html;
6306      }
6307      options = JSON.stringify(options)
6308      html += '<button ontouchstart="" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button ' + buttons[i].theme + triple_button_class + text_button_class + '"  onclick=' + "openMiniWeb('" + buttons[i].data_type + "','" + buttons[i].url + "','" + options + "')" + '>' + buttons[i].title + '</button>';
6309    } else if (buttons[i].type == "phone_number") {
6310      if (buttons[i].payload) buttons[i].payload = buttons[i].payload.replace(/\s+/g, "");
6311      if (buttons[i].phone_number) buttons[i].phone_number = buttons[i].phone_number.replace(/\s+/g, "");
6312
6313      cbotgtag('event', 'cbot', {
6314        'event_category': 'cbot-button',
6315        'event_action': buttons[i].title,
6316        'event_label': buttons[i].payload || buttons[i].phone_number
6317      })
6318      html += '<a ontouchstart="" href="tel:' + (buttons[i].payload || buttons[i].phone_number) + '" onclick="clickTheURLs(this)" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button ' + buttons[i].theme + triple_button_class + text_button_class + '">' + buttons[i].title + '</a>';
6319
6320    } else if (buttons[i].type == "account_link") {
6321      // waitForLogin();
6322      cbotgtag('event', 'cbot', {
6323        'event_category': 'cbot-button',
6324        'event_action': buttons[i].title,
6325        'event_label': buttons[i].url
6326      })
6327
6328      html += '<div ontouchstart="" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button ' + buttons[i].theme + triple_button_class + text_button_class + '" onclick="waitForLogin(); popupwindow(\'' + (buttons[i].web_url || buttons[i].url || "") + '\', \'\', 800, 600)">' + (buttons[i].title || "Giriş için Tıklayın") + '</div>';
6329    } else if (buttons[i].type == "location") {
6330
6331      cbotgtag('event', 'cbot', {
6332        'event_category': 'cbot-button',
6333        'event_action': "SHARE_LOCATION",
6334        'event_label': buttons[i].title
6335      })
6336      html += '<button ontouchstart="" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button cbot-location ' + buttons[i].theme + triple_button_class + text_button_class + '" data-onclick="shareLocation()">' + buttons[i].title + '</button>';
6337    } else if (buttons[i].type == "file_download") {
6338
6339      cbotgtag('event', 'cbot', {
6340        'event_category': 'cbot-button',
6341        'event_action': buttons[i].title,
6342        'event_label': buttons[i].url
6343      })
6344      var target = getUrlTarget(buttons[i].url, CHANNEL);
6345      html += '<a ontouchstart="" href="' + buttons[i].url + '" target="' + target + '" onclick="clickTheURLs(this)"><div style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button ' + buttons[i].theme + triple_button_class + text_button_class + '">' + buttons[i].title + '</div></a>';
6346
6347    } else if (buttons[i].type == "file_upload") {
6348
6349      cbotgtag('event', 'cbot', {
6350        'event_category': 'cbot-button',
6351        'event_action': buttons[i].title,
6352        'event_label': buttons[i].url
6353      })
6354      html += "<input class='cbot-attachment-file-input' id='cbot-attachment-file-input-" + uploadIndex + "' accept='" + buttons[i].mimetypes.map(function (m) { return m.mimetype }).join(",") + "' type='file' hidden/>" +
6355        '<button ontouchstart="" class="cbot-button fileupload ' + buttons[i].theme + triple_button_class + text_button_class + '" data-payload="' + uploadIndex + '" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '">' + buttons[i].title + '</button>';
6356
6357
6358      uploadIndex++;
6359    } else { // postback
6360      //console.log('<1button class="cbot-button postback" data-payload="' + (buttons[i].payload ? buttons[i].payload : buttons[i].title) + '">' + buttons[i].title + '</button>');
6361      cbotgtag('event', 'cbot', {
6362        'event_category': 'cbot-button',
6363        'event_action': buttons[i].title,
6364        'event_label': 'postback'
6365      })
6366      html += '<button ontouchstart="" style="' + bot_button_text_color + bot_button_background_color + triple_button_css + suggestion_button_style + '" class="cbot-button postback ' + buttons[i].theme + triple_button_class + text_button_class + '" data-branch="' + buttons[i].branch + '" data-payload="' + (buttons[i].payload ? buttons[i].payload : buttons[i].title) + '" data-full-action=\'' + JSON.stringify(buttons[i] || {}).replace(/'/g, '&#39;') + '\'>' + buttons[i].title + '</button>';
6367    }
6368  }
6369
6370  if (options.button_template == "SUGGESTION") {
6371    html += '</div>'
6372  }
6373
6374  return html + "</div>";
6375}
6376
6377/**
6378 * ALL OF THE SOCKET PROCESSES.
6379 */
6380var agentId = null;
6381// var live_handover = false;
6382
6383function soc_survey() {
6384  if (LIVE_CHAT) {
6385    socket.on('cbot_survey', function (data) {
6386      exitSurvey = data.exit_survey;
6387      if (data.client_id == cbotUserId) {
6388        //console.log("anket23",data.survey[0]);
6389        if (data.IsSurvey && data.IsSurvey == true) {
6390          surveyTrigger(data.survey[0], cbotUserId, true);
6391          sentSurvey = false;
6392          /* if (data.survey[0].agent_id) {
6393              agentId = data.survey[0].agent_id;
6394          } */
6395          triggerTimingResponses(data);
6396        }
6397        else {
6398          appendMessageToDialogBox(data.survey_message, "cbot-other", null, { notification: data.survey_message }, function () { });
6399          agentId = null;
6400        }
6401        isLive = setIsLive(false);
6402        setisLiveTLS(isLive);
6403
6404
6405      }
6406    });
6407  }
6408}
6409
6410function soc_cbot_meet_events() {
6411  socket.on('cbot_meet_events', (data) => {
6412    if (data.eventType == 'participantLeft') {
6413      forceCloseJitsiMeet();
6414    } else if (data.eventType == 'windowCloseEvent') {
6415      forceCloseJitsiMeet();
6416    } else if (data.eventType == 'videoConferenceLeft') {
6417      forceCloseJitsiMeet();
6418    }
6419  })
6420}
6421
6422function moveMiniWebForMobile() {
6423  document.querySelector('.cbot-web-close').style.display = 'none';
6424  var widget_position = document.querySelector('.cbot-dialog').getBoundingClientRect();
6425  document.querySelector('#cbot-web-area').style.right = widget_position.right;
6426  document.querySelector('#cbot-web-area').style.left = widget_position.left;
6427  document.querySelector('#cbot-web-area').style.top = widget_position.top;
6428  document.querySelector('#cbot-web-area').style.bottom = widget_position.bottom;
6429  document.querySelector('#cbot-web-area').style.width = widget_position.width;
6430  document.querySelector('#cbot-web-area').style.height = widget_position.height;
6431  document.querySelector('#cbot-web-area').style.transform = 'unset';
6432  document.querySelector('.cbot-dialog').style.zIndex = 0;
6433  document.querySelector('#cbot-web-area').style.zIndex = 999999999999999;
6434  var web_header_height = document.querySelector('.cbot-web-area-header').getBoundingClientRect().height;
6435  document.querySelector('.cbot-web-area-content').style.height = `calc(100% - 59px)`;
6436  document.querySelector('.cbot-web-area-header').insertAdjacentHTML('afterbegin', `
6437  <div id="cbot-mini-web-toggle" style="
6438  display: inline;
6439  border-radius: 10px;
6440  position: relative;
6441  left: 144px;
6442  bottom: -22px;
6443  padding: 10px;
6444  background: #5a729e;
6445  color: white;
6446  ">
6447  Widget'a Dön
6448  </div>`
6449  )
6450  // document.querySelector('#cbot-mini-web-toggle').style.left = `calc(50% - ${document.querySelector('#cbot-mini-web-toggle').getBoundingClientRect().width / 2}px)`;
6451  // document.querySelector('#cbot-mini-web-toggle').style.top = `calc(50% - ${document.querySelector('#cbot-mini-web-toggle').getBoundingClientRect().height / 2}px)`;
6452
6453}
6454
6455function toggleMiniWebForMobile() {
6456  if (document.querySelector('#cbot-mini-web-toggle').innerHTML.includes("Widget'a Dön")) {
6457    document.querySelector('#cbot-mini-web-toggle').remove();
6458    document.querySelector('.cbot-dialog-head').insertAdjacentHTML('afterbegin', `
6459    <div id="cbot-mini-web-toggle" style="
6460    display: inline;
6461    border-radius: 10px;
6462    position: relative;
6463    left: 130px;
6464    bottom: 1px;
6465    padding: 10px;
6466    background: #5a729e;
6467    color: white;
6468    ">
6469    Mini-web'e Dön
6470    </div>`
6471    );
6472    document.querySelector('.cbot-dialog').style.zIndex = 999999999999999;
6473    document.querySelector('#cbot-web-area').style.zIndex = 0;
6474    document.querySelector('#cbot-web-area').style.display = 'none';
6475    document.querySelector('.cbot-avatar').style.display = 'none';
6476  } else {
6477    document.querySelector('#cbot-mini-web-toggle').innerHTML = "Widget'a Dön";
6478    document.querySelector('#cbot-mini-web-toggle').remove();
6479    document.querySelector('.cbot-web-area-header').insertAdjacentHTML('afterbegin', `
6480    <div id="cbot-mini-web-toggle" style="
6481    display: inline;
6482    border-radius: 10px;
6483    position: relative;
6484    left: 144px;
6485    bottom: -22px;
6486    padding: 10px;
6487    background: #5a729e;
6488    color: white;
6489    ">
6490    Widget'a Dön
6491    </div>`
6492    )
6493    document.querySelector('.cbot-dialog').style.zIndex = 0;
6494    document.querySelector('#cbot-web-area').style.zIndex = 999999999999999;
6495    document.querySelector('#cbot-web-area').style.display = 'block';
6496    document.querySelector('.cbot-avatar').style.display = 'block';
6497    // document.querySelector('#cbot-mini-web-toggle').style.left = `calc(50% - ${document.querySelector('#cbot-mini-web-toggle').getBoundingClientRect().width / 2}px)`;
6498    // document.querySelector('#cbot-mini-web-toggle').style.top = `calc(50% - ${document.querySelector('#cbot-mini-web-toggle').getBoundingClientRect().height / 2}px)`;
6499    // document.querySelector('#cbot-mini-web-toggle').style.left = `calc(50% - ${103 / 2}px)`;
6500    // document.querySelector('#cbot-mini-web-toggle').style.bottom = `-22px`;
6501
6502
6503  }
6504}
6505
6506
6507
6508
6509var WAITING_FOR_LOGIN = false;
6510var POLLING_ERR_COUNT = 0;
6511function waitForLogin() {
6512
6513  if (!WAITING_FOR_LOGIN) {
6514    var headers = {
6515      "Content-Type": "application/json",
6516      "CBot-Token": "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH",
6517      "CBOT-URL": generateCBOTURL(location.href)
6518    }
6519
6520    var customheaders = clients.gateway_custom_headers || [];
6521
6522    for (var i = 0; i < customheaders.length; i++) {
6523      var header = customheaders[i];
6524      headers[header.key] = header.value
6525    }
6526
6527    WAITING_FOR_LOGIN = true;
6528    $.ajax({
6529      url: rootAddress + "/login/wait/" + CLIENT,
6530      type: "POST",
6531      timeout: 240000,
6532      headers: headers,
6533      data: JSON.stringify({
6534        "client": CLIENT,
6535        "user_id": cbotUserId,
6536        "session_id": cbotSessionId,
6537        "referrer": CHANNEL || "WIDGET"
6538      }),
6539      success: function (resp) {
6540        WAITING_FOR_LOGIN = false;
6541        POLLING_ERR_COUNT = 0;
6542        if (resp && resp.messages) {
6543          for (var i = 0; i < resp.messages.length; i++) {
6544            appendMessageToDialogBox(resp.messages[i], "cbot-other", resp.category, { notification: resp.messages[i] }, function () {
6545              setClickEventToInteractiveButtons(cbotUserId);
6546            });
6547          }
6548        }
6549
6550        isLive = setIsLive(resp.live_chat);
6551        setisLiveTLS(isLive);
6552        if (isLive) {
6553          FIRST_LIVE_MESSAGE = true;
6554          socket_widget(resp.message);
6555        }
6556
6557        if (resp.send_message) {
6558          var jsonData = {
6559            // userId: userId,
6560            userId: cbotUserId,
6561            sessionId: cbotSessionId,
6562            message: resp.send_message,
6563            is_triggered: true
6564          };
6565          jsonData.is_survey_feedback = false;
6566          jsonData.is_survey = false;
6567          sendPost(jsonData, function (resp2) {
6568            isLive = setIsLive(resp2.live_chat);
6569            setisLiveTLS(isLive);
6570            if (isLive) {
6571              FIRST_LIVE_MESSAGE = true;
6572              socket_widget(resp2.message.message);
6573            }
6574
6575
6576
6577            handleMessageArea();
6578
6579            appendMessageToDialogBox(resp2.message, "cbot-other", null, { notification: resp2.speak }, function () {
6580              setClickEventToInteractiveButtons(resp2.userId);
6581              setClickEventToFeedbackButtons(resp2.unique_id);
6582            });
6583          });
6584        }
6585
6586      },
6587      error: function (request, status, err) {
6588        WAITING_FOR_LOGIN = false;
6589        POLLING_ERR_COUNT += 1
6590        console.log("login error", status, err);
6591        if (POLLING_ERR_COUNT < 10) {
6592          waitForLogin();
6593        }
6594      }
6595    });
6596  }
6597}
6598
6599var WAITING_FOR_POLLING = false;
6600function waitForLongPolling() {
6601  if (!WAITING_FOR_POLLING) {
6602
6603    var headers = {
6604      "Content-Type": "application/json",
6605      "CBot-Token": "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH",
6606      "CBOT-URL": generateCBOTURL(location.href)
6607    }
6608
6609    var customheaders = clients.gateway_custom_headers || [];
6610
6611    for (var i = 0; i < customheaders.length; i++) {
6612      var header = customheaders[i];
6613      headers[header.key] = header.value
6614    }
6615
6616
6617    WAITING_FOR_POLLING = true;
6618    $.ajax({
6619      url: rootAddress + "/" + CLIENT + "/userdata/wait",
6620      type: "POST",
6621      timeout: 240000,
6622      headers: headers,
6623      data: JSON.stringify({
6624        "client": CLIENT,
6625        "user_id": cbotUserId,
6626        "session_id": cbotSessionId,
6627        "referrer": CHANNEL || "WIDGET"
6628      }),
6629      success: function (resp) {
6630        WAITING_FOR_POLLING = false;
6631        if (resp && resp.messages) {
6632          for (var i = 0; i < resp.messages.length; i++) {
6633            if (resp.messages[i] != "NO_MESSAGE") {
6634              appendMessageToDialogBox(resp.messages[i], "cbot-other", resp.category, { notification: resp.messages[i] }, function () {
6635                setClickEventToInteractiveButtons(cbotUserId);
6636              });
6637            }
6638          }
6639        }
6640        if (resp.send_message) {
6641          var jsonData = {
6642            // userId: userId,
6643            userId: cbotUserId,
6644            sessionId: cbotSessionId,
6645            message: resp.send_message,
6646            is_triggered: true
6647          };
6648          jsonData.is_survey_feedback = false;
6649          jsonData.is_survey = false;
6650          sendPost(jsonData, function (resp2) {
6651            isLive = setIsLive(resp2.live_chat);
6652            setisLiveTLS(isLive);
6653            if (isLive) {
6654              FIRST_LIVE_MESSAGE = true;
6655              socket_widget(resp2.message.message);
6656            }
6657
6658
6659
6660            handleMessageArea();
6661
6662            appendMessageToDialogBox(resp2.message, "cbot-other", null, { notification: resp2.speak }, function () {
6663              setClickEventToInteractiveButtons(resp2.userId);
6664              setClickEventToFeedbackButtons(resp2.unique_id);
6665            });
6666          });
6667        }
6668      },
6669      error: function (request, status, err) {
6670        WAITING_FOR_POLLING = false;
6671        if (status == "timeout")
6672          waitForLongPolling();
6673      }
6674    });
6675  }
6676}
6677
6678function socket_connection(autoConnect = false) {
6679  var lvInterval = setInterval(function () {
6680    if (window.io && cbotSessionId && cbotUserId) {
6681      if (isLive) {
6682        if (is_liveagent_typed) {
6683          toggleCloseChatButton("block");
6684        }
6685      }
6686      if (socket) {
6687        clearInterval(lvInterval);
6688        return;
6689      }
6690      if (!socket || !socket.connected) {
6691        socket = io.connect(soc_connect, {
6692          transports: ["websocket"], secure: true, upgrade: false, auth: {
6693            session_id: cbotSessionId,
6694            user_id: cbotUserId
6695          },
6696          autoConnect: autoConnect
6697        });
6698        socket.on('connect', function () {
6699          sendCustomPostMessage("CBOT_WEBSOCKET_CONNECTED", {});
6700          retryConnection = false;
6701          clearLostConnectionMsg();
6702          var newClientInterval = setInterval(function () {
6703            if (cbotUserId && cbotSessionId && isLive) {
6704              socket.emit('new_client', { userId: cbotUserId, sessionId: cbotSessionId });
6705              clearInterval(newClientInterval);
6706            }
6707          }, 500);
6708
6709        });
6710        socket_connection_widget();
6711        soc_cli_data();
6712        soc_survey();
6713        soc_stop();
6714        soc_client_typing();
6715        socket_alert();
6716        socket_delete_message();
6717        soc_transfer_agent();
6718        soc_cbot_meet_events();
6719        soc_error();
6720        clearInterval(lvInterval);
6721        soc_queue_data();
6722        socket_on_pass_control();
6723      }
6724    }
6725  }, 100);
6726}
6727
6728function socket_connection_widget() {
6729  if (LIVE_CHAT) {
6730    socket.on("user_" + cbotUserId, function (data) {
6731      // console.log("user_" + cbotUserId, data);
6732      isLive = setIsLive(data.live_chat);
6733      setisLiveTLS(isLive);
6734      if (isLive) {
6735        FIRST_LIVE_MESSAGE = true;
6736        socket_widget(data.message.message);
6737      }
6738      if (!JSON.stringify(data.message || {}).includes("account_link")) {
6739        appendMessageToDialogBox(data.message, "cbot-other", data.category, { notification: data.message }, function () { });
6740      }
6741    });
6742  }
6743}
6744
6745function soc_cli_data() {
6746  if (LIVE_CHAT) {
6747
6748    socket.on('cbot_agent', function (data, next) {
6749      if (data.client_id == cbotUserId) {
6750        if (data.handover) {
6751          appendMessageToDialogBox(data.handover_message, "cbot-other", null, { notification: data.handover_message }, function () {
6752            if (next && typeof next == "function") next({ is_delivered: true });
6753          });
6754          isLive = setIsLive(false);
6755          setisLiveTLS(isLive);
6756          agentId = null;
6757          // live_handover = true;
6758          sendPost({
6759            senderName: "User_" + cbotUserId,
6760            userId: cbotUserId,
6761            sessionId: cbotSessionId,
6762            message: data.message.message || data.message,
6763            intents: intents,
6764            client: cbot_config.client,
6765            live_chat: isLive,
6766            is_handover: data.handover || false
6767          }, function (resp) {
6768
6769            isLive = setIsLive(resp.live_chat);
6770            setisLiveTLS(isLive);
6771            if (isLive) {
6772              FIRST_LIVE_MESSAGE = true;
6773              socket_widget(data.message.message);
6774            }
6775
6776            appendMessageToDialogBox(resp.message, "cbot-other", null, { notification: resp.speak }, function () {
6777              if (next && typeof next == "function") next({ is_delivered: true });
6778              setClickEventToInteractiveButtons(resp.client_id);
6779              setClickEventToFeedbackButtons(resp.unique_id);
6780            });
6781            // socket.emit("hand_stop", { handover_message: true });
6782          });
6783
6784        } else if (data.missed) {
6785
6786          agentId = null;
6787          toggleCloseChatButton("none");
6788          livechatTimeoutEndNotifier(true);
6789
6790          appendMessageToDialogBox(data.message, "cbot-other", "", { notification: data.message.message || data.message }, function () {
6791            if (next && typeof next == "function") next({ is_delivered: true });
6792            setClickEventToInteractiveButtons(data.client_id);
6793            setClickEventToFeedbackButtons(data.unique_id);
6794          });
6795        } else {
6796          if (isLive) {
6797            agentId = data.agent_id;
6798            if (!data.is_system) {
6799              toggleCloseChatButton("block");
6800              if (data.message) {
6801                livechatTimeoutEndNotifier();
6802              }
6803            }
6804            // Görüntülü görüşme başlat.
6805            if (vc_url && data.message && data.message.message == 'Görüntülü görüşme kabul edildi.') {
6806              openMiniWeb('cbot_meet', 'https://' + vc_url + '/' + (cbotUserId || userId) || getUserIDFLS() + '?lang=tr&userInfo.displayName=' + (cbotUserId || userId) || getUserIDFLS());
6807            } else if (data.message && data.message.message == 'Üzgünüm, görüntülü görüşme gerçekleştirilemiyor.') {
6808              // Buton stilini değiştir.
6809              $('.cbot-start-meeting').text('Görüntülü Görüşme Talep Et 🖥️');
6810              $('.cbot-start-meeting').css('background', '#18bc39');
6811            }
6812
6813
6814          }
6815          if (data.message && data.message.message_id) {
6816            if (!document.querySelector(`li[data-message-id='${data.message.message_id}']`)) {
6817              var message_id = data.message.message_id;
6818              let agentName = ""
6819              if (agent_name && Array.isArray(agent_name) && agent_name.length > 0) {
6820                agentName = agent_name[0];
6821              }
6822
6823              appendMessageToDialogBox(data.message, "cbot-other", "", { notification: data.message.message || data.message }, function () {
6824                if (next && typeof next == "function") next({ is_delivered: true });
6825                setClickEventToInteractiveButtons(data.client_id);
6826                setClickEventToFeedbackButtons(data.unique_id);
6827              });
6828              $(`[data-message-id=${message_id}] .cbot-msg.cbot_text_component`).append(`<div class="cbot-vector"><svg style="margin-top: 18px;" width="321" height="2" viewBox="0 0 321 2" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 1H321" stroke="#DCDCDC"/></svg></div><div class="cbot-agent-name-wrapper"><svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4.03125 15.75C4.03125 12.8505 6.38176 10.5 9.28125 10.5C12.1807 10.5 14.5312 12.8505 14.5312 15.75M12.2812 5.25C12.2812 6.90685 10.9381 8.25 9.28125 8.25C7.6244 8.25 6.28125 6.90685 6.28125 5.25C6.28125 3.59315 7.6244 2.25 9.28125 2.25C10.9381 2.25 12.2812 3.59315 12.2812 5.25Z" stroke="#848484" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg><p class="cbot-agent-name">${show_agent_name ? (before_agent_name + " " + (agent_name ? agent_name : agent_display_name)) : ""}</p></div>`);
6829              if (clients.chat_avatar_activation) {
6830                let cbot_other_icon_agent = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">[data-message-id="${message_id}"]:before { content: "${agentName}"; width: 35px; height: 35px; position: absolute; left:16px; border: 1px solid #DCDCDC; border-radius: 24px; background-image: unset; background-repeat: no-repeat; background-size: 100% 100%; background-position-x: center; background-position-y: center; }</style>`);
6831                $('head').append(cbot_other_icon_agent);
6832                if (clients.chat_agent_avatar) {
6833                  let custom_cbot_other_icon_agent = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">[data-message-id="${message_id}"]:before { content: "";width: 35px;height: 35px;position: absolute;
6833left: 16px;top: 0;border: 1px solid #DCDCDC;border-radius: 24px;display: flex;justify-content: center;align-items: center;background-image: url(${clients.chat_agent_avatar});background-repeat: no-repeat;background-position-x: center;background-position-y: center;}</style>`);
6834                  $('head').append(custom_cbot_other_icon_agent);
6835                }
6836              }
6837              let cbot_other_icon_green_dot = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">[data-message-id="${message_id}"]:after { content: url(../img/cbot-other-icon-green-dot.png?client=${CLIENT});position: absolute;top:0;left: 48;transform: translateY(36px); }</style>`);
6838              $('head').append(cbot_other_icon_green_dot);
6839            } else {
6840              if (next && typeof next == "function") next({ is_delivered: true });
6841            }
6842          } else {
6843            appendMessageToDialogBox(data.message, "cbot-other", "", { notification: data.message.message || data.message }, function () {
6844              if (next && typeof next == "function") next({ is_delivered: true });
6845              setClickEventToInteractiveButtons(data.client_id);
6846              setClickEventToFeedbackButtons(data.unique_id);
6847            });
6848          }
6849        }
6850        handleMessageArea();
6851      }
6852    });
6853  }
6854}
6855
6856function soc_queue_data() {
6857  if (LIVE_CHAT) {
6858    socket.on('cbot_queue', function (data, next) {
6859      if (next && typeof next == "function") next({ is_delivered: true });
6860      if (data.client_id == cbotUserId) {
6861        if (data.message && data.message.message_id) {
6862          const queueMessageItem = document.querySelector(`li[data-message-id='${data.message.message_id}']`)
6863          if (!queueMessageItem) {
6864            var message_id = data.message.message_id;
6865
6866            appendMessageToDialogBox(data.message, "cbot-other", "", { notification: data.message.message || data.message }, function () {
6867              setClickEventToInteractiveButtons(data.client_id);
6868              setClickEventToFeedbackButtons(data.unique_id);
6869            });
6870            $(`[data-message-id=${message_id}] .cbot-msg.cbot_text_component`).append(`<div class="cbot-vector"><svg style="margin-top: 18px;" width="321" height="2" viewBox="0 0 321 2" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0 1H321" stroke="#DCDCDC"/></svg></div><div class="cbot-agent-name-wrapper"><svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4.03125 15.75C4.03125 12.8505 6.38176 10.5 9.28125 10.5C12.1807 10.5 14.5312 12.8505 14.5312 15.75M12.2812 5.25C12.2812 6.90685 10.9381 8.25 9.28125 8.25C7.6244 8.25 6.28125 6.90685 6.28125 5.25C6.28125 3.59315 7.6244 2.25 9.28125 2.25C10.9381 2.25 12.2812 3.59315 12.2812 5.25Z" stroke="#848484" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg><p class="cbot-agent-name">${before_agent_name}</p></div>`);
6871            afterAppend();
6872            if (clients.chat_avatar_activation) {
6873              let cbot_other_icon_agent = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">[data-message-id="${message_id}"]:before { content: ""; width: 35px; height: 35px; position: absolute; left:16px; border: 1px solid #DCDCDC; border-radius: 24px; background-image: url(../img/cbot-chat-agent-icon.svg); background-repeat: no-repeat; background-size: 100% 100%; background-position-x: center; background-position-y: center; }</style>`);
6874              $('head').append(cbot_other_icon_agent);
6875              if (clients.chat_agent_avatar) {
6876                let custom_cbot_other_icon_agent = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">[data-message-id="${message_id}"]:before { content: "";width: 35px;height: 35px;position: absolute;left: 16px;top: 0;border: 1px solid #DCDCDC;border-radius: 24px;display: flex;justify-content: center;align-items: center;background-image: url(${clients.chat_agent_avatar});background-repeat: no-repeat;background-position-x: center;background-position-y: center;}</style>`);
6877                $('head').append(custom_cbot_other_icon_agent);
6878              }
6879            }
6880            let cbot_other_icon_green_dot = $(`<style nonce="8IBTHwOdqNKAWeKl7plt8g==">[data-message-id="${message_id}"]:after { content: url(../img/cbot-other-icon-green-dot.png?client=${CLIENT});position: absolute;top:0;left: 48;transform: translateY(36px); }</style>`);
6881            $('head').append(cbot_other_icon_green_dot);
6882          } else {
6883            const queueMessage = queueMessageItem.querySelector(".cbot_text_component span");
6884            if (queueMessage) {
6885              queueMessage.textContent = data.message.message;
6886              showNotification(cbot_config.dialogTitle, data.message.message || data.message);
6887            } else {
6888              appendMessageToDialogBox(data.message, "cbot-other", "", { notification: data.message.message || data.message }, function () {
6889                setClickEventToInteractiveButtons(data.client_id);
6890                setClickEventToFeedbackButtons(data.unique_id);
6891              });
6892            }
6893          }
6894        }
6895
6896      }
6897    });
6898  }
6899}
6900
6901function socket_newclient() {
6902  if (socket && socket.connected && isLive) {
6903    socket.emit('new_client', { userId: cbotUserId, sessionId: cbotSessionId });
6904    //  isLive = true;
6905    //  toggleCloseChatButton("block");
6906  }
6907}
6908
6909async function socket_widget(message, is_triggered = false, optional_data = {}) {
6910  return new Promise((resolve, reject) => {
6911    if (isLive && LIVE_CHAT) {
6912      var sckt = {
6913        message: message,
6914        // answer: resp.message,
6915        client_id: cbotUserId,
6916        session_id: cbotSessionId,
6917        referrer: CHANNEL || "WIDGET",
6918        client: CLIENT,
6919        is_first: FIRST_LIVE_MESSAGE,
6920        agent_id: agentId,
6921        optional_data // ihtiyaç durumunda ek veri göndermek için
6922      };
6923      if (is_triggered) {
6924        sckt.is_triggered = true
6925      }
6926
6927      let intrvl;
6928
6929      function checkAndEmit() {
6930        if (socket && socket.connected) {
6931          clearInterval(intrvl);
6932          if (FIRST_LIVE_MESSAGE) {
6933            FIRST_LIVE_MESSAGE = false;
6934            livechatStopSendMessageFired = false;
6935            socket.emit("chat_live_client", sckt);
6936            sendCustomPostMessage("CBOT_LIVECHAT_STARTED", {});
6937          }
6938
6939          soc_typing(false);
6940          sendCustomPostMessage("CBOT_MESSAGE_SENT", { message: sckt.message });
6941          livechatTimeoutEndNotifier(true);
6942          socket.emit("chat_widget", sckt, (resp) => {
6943            resolve();
6944          });
6945        }
6946      }
6947
6948      if (socket && socket.connected) {
6949        checkAndEmit();
6950      } else {
6951        intrvl = setInterval(checkAndEmit, 500);
6952      }
6953
6954    }
6955  });
6956
6957}
6958
6959function socket_alert() {
6960  if (LIVE_CHAT) {
6961    socket.on("cbot_alert", function (data) {
6962      if (data.message && data.client_id == cbotUserId) {
6963        alertMessageDialogHead(data.message);
6964
6965      }
6966    });
6967  }
6968}
6969
6970function alertMessageDialogHead(message) {
6971  $(".cbot-alert-welcome-message").html(message);
6972  $(".cbot-alert-welcome-message").css("display", "block");
6973}
6974
6975function hideAlertedDialogMessage() {
6976  $(".cbot-alert-welcome-message").slideUp();
6977}
6978
6979function socket_delete_message() {
6980  if (LIVE_CHAT) {
6981    socket.on("cbot_message_delete", function (data) {
6982      if (data.client_id == cbotUserId) {
6983        var isRemoved = false;
6984        $("li.cbot-other").each(function (index, li) {
6985          if (isRemoved) return;
6986          var msgId = $(li).attr("data-message-id");
6987          if (msgId == data.message_id) {
6988            $(li).remove();
6989            isRemoved = true;
6990          }
6991        });
6992      }
6993    });
6994  }
6995}
6996
6997function socket_file_upload(filename) {
6998  if (isLive && LIVE_CHAT) {
6999
7000    setLastMessageSentDateTLS();
7001    var sckt = {
7002      filename: filename,
7003      client_id: cbotUserId,
7004      session_id: cbotUserId,
7005      referrer: CHANNEL || "WIDGET",
7006      client: CLIENT,
7007      agent_id: agentId
7008    };
7009
7010    socket.emit("chat_file_upload", sckt);
7011  }
7012}
7013
7014function soc_stop() {
7015  if (LIVE_CHAT) {
7016    socket.on("cbot_stop_ack", function (data, next) {
7017      sendCustomPostMessage("CBOT_LIVECHAT_STOPPED", {});
7018      if (clients.disable_user_chat_input) {
7019        disableUserMessageArea(clients.disable_user_chat_input_message);
7020      }
7021      if (next && typeof next == "function") next({ is_delivered: true });
7022      if (data.status && data.client_id == cbotUserId && data.session_id == cbotSessionId) {
7023        isLive = setIsLive(false);
7024        setisLiveTLS(isLive);
7025        livechatTimeoutEndNotifier(true);
7026        agentId = null;
7027        agent_name = null;
7028
7029        if (data.clear_session) {
7030          setCloseIconPressed();
7031          setSessionIdTLS(null);
7032        }
7033
7034        handleMessageArea();
7035
7036        if (!stopped_by_customer && (data.timed_out || data.missed)) {
7037          appendMessageToDialogBox(data.message, "cbot-other", "", { notification: data.message.message || data.message }, function () {
7038            setClickEventToInteractiveButtons(data.client_id);
7039            // setClickEventToFeedbackButtons(data.unique_id);
7040          });
7041        }
7042        stopped_by_customer = false;
7043
7044        if (data.send_message && !livechatStopSendMessageFired) {
7045          livechatStopSendMessageFired = true;
7046          var jsonData = {
7047            userId: cbotUserId,
7048            sessionId: cbotSessionId,
7049            message: data.send_message,
7050            is_triggered: true
7051          };
7052          jsonData.is_survey_feedback = false;
7053          jsonData.is_survey = false;
7054          sendPost(jsonData, function (resp2) {
7055            isLive = setIsLive(resp2.live_chat);
7056            setisLiveTLS(isLive);
7057            if (isLive) {
7058              FIRST_LIVE_MESSAGE = true;
7059              socket_widget(resp2.message.message);
7060            }
7061
7062            handleMessageArea();
7063
7064            appendMessageToDialogBox(resp2.message, "cbot-other", null, { notification: resp2.speak }, function () {
7065              setClickEventToInteractiveButtons(resp2.userId);
7066              setClickEventToFeedbackButtons(resp2.unique_id);
7067            });
7068          });
7069        }
7070      }
7071    });
7072
7073    socket.on("cbot_sync_stop_by_customer", function (data) {
7074      if (data.client_id == cbotUserId && data.send_message && !livechatStopSendMessageFired) {
7075        livechatStopSendMessageFired = true;
7076        var jsonData = {
7077          userId: cbotUserId,
7078          sessionId: cbotSessionId,
7079          message: data.send_message,
7080          is_triggered: true
7081        };
7082        jsonData.is_survey_feedback = false;
7083        jsonData.is_survey = false;
7084        sendPost(jsonData, function (resp2) {
7085          isLive = setIsLive(resp2.live_chat);
7086          setisLiveTLS(isLive);
7087          if (isLive) {
7088            FIRST_LIVE_MESSAGE = true;
7089            socket_widget(resp2.message.message);
7090          }
7091
7092          handleMessageArea();
7093
7094          appendMessageToDialogBox(resp2.message, "cbot-other", null, { notification: resp2.speak }, function () {
7095            setClickEventToInteractiveButtons(resp2.userId);
7096            setClickEventToFeedbackButtons(resp2.unique_id);
7097          });
7098        });
7099      }
7100    });
7101  }
7102}
7103
7104function socket_suggestion(message, category, cbotUserId) {
7105  if (isLive && LIVE_CHAT) {
7106    var sckt = { message: message, client_id: cbotUserId };
7107    socket.emit("chat_suggestion", sckt);
7108  }
7109
7110}
7111
7112function soc_typing(status) {
7113  if (LIVE_CHAT && isLive && IS_TYPING != status) {
7114    IS_TYPING = status;
7115    socket.emit('chat_typing', { client_id: cbotUserId, status: status, type: "CLIENT" });
7116  }
7117}
7118function soc_client_typing() {
7119  if (LIVE_CHAT) {
7120    socket.on('cbot_typing', function (data) {
7121      if (data.type == "AGENT" && data.client_id == cbotUserId) {
7122        if (data.status) {
7123          $(".cbot-typing").remove();
7124          $(".cbot-refresh-icon").css('opacity', '1')
7125          $(".cbot-refresh-icon").css('pointer-events', 'painted')
7126          appendTypingIconToDialogBox(data.agent);
7127          agent_name = data.agent
7128        } else {
7129          $(".cbot-typing").remove();
7130          $(".cbot-refresh-icon").css('opacity', '1')
7131          $(".cbot-refresh-icon").css('pointer-events', 'painted')
7132        }
7133      }
7134    })
7135  }
7136}
7137
7138function soc_transfer_agent() {
7139  if (LIVE_CHAT) {
7140    socket.on('cbot_customer_list', function (data) {
7141      if ((data.type == "TRANSFER" || data.type == "TAKEOVER") && cbotUserId == data.customer.client_id) {
7142        agentId = data.agentId;
7143      }
7144      if (data.type == "WAITING2ACTIVE") {
7145        toggleCloseChatButton("block");
7146      }
7147    });
7148  }
7149}
7150
7151function cbotGetCookie(cname) {
7152  var name = cname + "=";
7153  var decodedCookie = document.cookie;
7154  var ca = decodedCookie.split(';');
7155  for (var i = 0; i < ca.length; i++) {
7156    var c = ca[i];
7157    while (c.charAt(0) == ' ') {
7158      c = c.substring(1);
7159    }
7160    if (c.indexOf(name) == 0) {
7161      return c.substring(name.length, c.length);
7162    }
7163  }
7164  return "";
7165}
7166
7167var dialogEndSurveyTimeout = null;
7168function starAnketShow(survey) {
7169  if (!survey) survey = {};
7170  dialogCloseSurveyShowed = true;
7171  $(".cbot-dialog-end-survey").find("span").text(survey.popup_question || "Anketimize katılmak ister misiniz?");
7172  $(".cbot-dialog-end-survey").find("button").eq(0).text(survey.popup_question_yes || "Evet");
7173  $(".cbot-dialog-end-survey").find("button").eq(1).text(survey.popup_question_no || "Hayır");
7174  $(".cbot-dialog-end-survey").fadeIn();
7175  if (survey.shadow_background)
7176    $(".cbot-survey-fadebg").css("display", "block")
7177
7178}
7179
7180function fileUpload(URL, fd, next) {
7181  var typing = default_messages[botlanguage].TYPING
7182  sendCustomPostMessage("CBOT_FILE_IS_UPLOADING", {})
7183  $(".cbot-illusion-placeholder").html(`${typing}...`)
7184  $('#cbot-form-message').attr('disabled', 'disabled');
7185  var xhr = new XMLHttpRequest();
7186  xhr.onreadystatechange = function () {
7187    if (this.readyState == 4 && this.status == 200) {
7188      var json = JSON.parse(this.responseText);
7189      sendCustomPostMessage("CBOT_FILE_UPLOADED_SUCCESSFULLY", {})
7190      next(null, json);
7191    } else if (this.readyState == 4) {
7192      // console.log("READY STATE", this.readyState);
7193      // console.log("STATUS", this.status);
7194      var json = JSON.parse(this.responseText);
7195      sendCustomPostMessage("CBOT_FILE_UPLOAD_FAILED", {})
7196      next(json);
7197    }
7198  }
7199  xhr.open("POST", URL, true);
7200  xhr.setRequestHeader("Accept", "application/json");
7201  // xhr.setRequestHeader("Accept-Encoding", "gzip");
7202  xhr.setRequestHeader('CBOT-Token', "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH");
7203  xhr.setRequestHeader('CBOT-URL', generateCBOTURL(location.href));
7204
7205  var customheaders = clients.gateway_custom_headers || [];
7206
7207  for (var i = 0; i < customheaders.length; i++) {
7208    var header = customheaders[i];
7209    xhr.setRequestHeader(header.key, header.value);
7210  }
7211  xhr.send(fd);
7212}
7213
7214function fileUploadListener(index) {
7215  if (index || index == 0) {
7216    if (!$._data($("#cbot-attachment-file-input-" + index).get(0), "events")) {
7217      $("#cbot-attachment-file-input-" + index).on("change", function (item) {
7218        var file = document.getElementById("cbot-attachment-file-input-" + index).files[0];
7219        var fd = new FormData();
7220        fd.append("client", CLIENT);
7221        fd.append("userId", cbotUserId);
7222        fd.append("referrer", "WIDGET");
7223        fd.append('cbot_file', file, file.name);
7224
7225        var elCbotFormMessage = document.getElementById('cbot-form-message');
7226        if (document.getElementById("cbot-send-button"))
7227          document.getElementById("cbot-send-button").setAttribute("disabled", true);
7228        elCbotFormMessage.value = ' ';
7229        appendTypingIconToDialogBox();
7230        var typing = default_messages[botlanguage].TYPING
7231        $(".cbot-illusion-placeholder").html(`${typing}...`)
7232
7233
7234        fileUpload(rootAddress + "/files/upload", fd, function (err, json) {
7235          var message = { message_type: "TEXT", message: "" };
7236          if (err) {
7237            message.message = err.error.description;
7238          } else {
7239            message.message = json.message;
7240            if (isLive) {
7241              socket_file_upload(json.filename);
7242            } else {
7243
7244              var elCbotFormMessage = document.getElementById('cbot-form-message');
7245              if (document.getElementById("cbot-send-button"))
7246                document.getElementById("cbot-send-button").setAttribute("disabled", true);
7247              elCbotFormMessage.value = ' ';
7248              $(".cbot-illusion-placeholder").html(`${typing}...`)
7249              $('#cbot-form-message').attr('disabled', 'disabled');
7250
7251              sendPost({
7252                senderName: "User_" + cbotUserId,
7253                userId: cbotUserId,
7254                sessionId: cbotSessionId,
7255                request_type: "DOC",
7256                data: json.url,
7257                filename: json.filename,
7258                live_chat: isLive
7259              }, function (data) {
7260                var elCbotFormMessage = document.getElementById('cbot-form-message');
7261                $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
7262                $(".cbot-illusion-placeholder").html(`${typing}...`)
7263                $('#cbot-form-message').attr('disabled', 'disabled');
7264                elCbotFormMessage.value = " ";
7265                elCbotFormMessage.removeAttribute('readonly');
7266                if (document.getElementById("cbot-send-button"))
7267                  document.getElementById("cbot-send-button").removeAttribute('disabled');
7268                if (document)
7269                  cbotFocus(elCbotFormMessage);
7270                if (data) {
7271                  intents = data.intents;
7272                  var elCbotFormMessage = document.getElementById('cbot-form-message');
7273                  if (document.getElementById("cbot-send-button"))
7274                    document.getElementById("cbot-send-button").setAttribute("disabled", true);
7275                  elCbotFormMessage.value = ' ';
7276                  appendTypingIconToDialogBox();
7277                  $(".cbot-illusion-placeholder").html(`${typing}...`)
7278                  setTimeout(() => {
7279
7280                    appendMessageToDialogBox(data.message, "cbot-other", null, { notification: data.speak }, function () {
7281
7282                      var elCbotFormMessage = document.getElementById('cbot-form-message');
7283                      $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
7284                      elCbotFormMessage.value = " ";
7285                      elCbotFormMessage.removeAttribute('readonly');
7286                      if (document.getElementById("cbot-send-button"))
7287                        document.getElementById("cbot-send-button").removeAttribute('disabled');
7288                      if (document)
7289                        cbotFocus(elCbotFormMessage);
7290
7291                      setClickEventToInteractiveButtons(data.userId);
7292                      if (data.survey) {
7293                        surveyTrigger(data.survey, data.userId);
7294                      }
7295                      triggerTimingResponses(data);
7296                    });
7297                  }, 500);
7298                } else {
7299                  appendMessageToDialogBox(WIDGET_TIMEOUT_MESSAGE, "cbot-other", null, { notification: WIDGET_TIMEOUT_MESSAGE }, function () { });
7300                }
7301              });
7302            }
7303
7304
7305
7306          }
7307          appendMessageToDialogBox(message, "cbot-other", "", { notification: message.message }, function () { })
7308          // console.log("UPLOAD RESULT", json);
7309          if (!err) {
7310            $("#cbot-chat").append('<li class="cbot-other cbot-typing"><div class="cbot-msg" style="height: 20px; border-bottom-left-radius: 0; border-top-left-radius: 15px; margin: 0 0 0 10px;' + bot_message_bubble_color + '"><div class="cbot-typing-loader"></div></div></li>');
7311            $(".cbot-illusion-placeholder").html(`${typing}...`)
7312            $('#cbot-form-message').attr('disabled', 'disabled');
7313            afterAppend();
7314
7315            let elCbotInteractiveButtons = document.getElementsByClassName('fileupload');
7316            for (var j = 0; j < elCbotInteractiveButtons.length; j++) {
7317              let e = elCbotInteractiveButtons[j];
7318              e.disabled = true;
7319            }
7320          }
7321        });
7322
7323      })
7324    }
7325  } else {
7326    $("#cbot-attachment-file-input").on("change", function (item) {
7327      var file = document.getElementById("cbot-attachment-file-input").files[0];
7328      if (!file) return;
7329      var fd = new FormData();
7330      fd.append("client", CLIENT);
7331      fd.append("userId", cbotUserId);
7332      fd.append("referrer", "WIDGET");
7333      fd.append('cbot_file', file, file.name);
7334
7335      fileUpload(rootAddress + "/files/upload", fd, function (err, json) {
7336        var message = { message_type: "TEXT", message: "" };
7337        if (err) {
7338          message.message = err.error.description;
7339        } else {
7340          message.message = json.message;
7341
7342          socket_widget(json.url, undefined, json);
7343
7344          // sendPost({
7345          //     senderName: "User_" + cbotUserId,
7346          //     userId: cbotUserId,
7347          //     sessionId: cbotSessionId,
7348          //     request_type: uploadFileType || "DOC",
7349          //     data: json.url,
7350          //     live_chat: isLive
7351          // }, function (data) {
7352          //     var elCbotFormMessage = document.getElementById('cbot-form-message');
7353          //     elCbotFormMessage.value = "";
7354          //     elCbotFormMessage.removeAttribute('disabled');
7355          //     if (document.getElementById("cbot-send-button"))
7356          //         document.getElementById("cbot-send-button").removeAttribute('disabled');
7357          //     elCbotFormMessage.focus();
7358          //     if (data) {
7359          //         intents = data.intents;
7360          //         appendMessageToDialogBox(data.message, "cbot-other", null, { notification: data.speak }, function () {
7361          //             setClickEventToInteractiveButtons(data.userId);
7362          //             if (data.survey) {
7363          //                 surveyTrigger(data.survey, data.userId);
7364          //             }
7365          //             triggerTimingResponses(data);
7366          //         });
7367          //     } else {
7368          //         appendMessageToDialogBox("WIDGET_TIME_OUT_MESSAGE", "cbot-other", null, { notification: "WIDGET_TIME_OUT_MESSAGE" }, function () { });
7369          //     }
7370          // })
7371
7372        }
7373        appendMessageToDialogBox(message, "cbot-other", "", { notification: message.message }, function () { })
7374        // console.log("UPLOAD RESULT", json);
7375      });
7376
7377    })
7378  }
7379}
7380
7381function showAttachmentMenu() {
7382  $(".cbot-attachment-container").css("display", "block")
7383}
7384
7385function hideAttachmentMenu() {
7386  $(".cbot-attachment-container").css("display", "none")
7387}
7388
7389function toggleAttachmentMenu() {
7390
7391  if ($(".cbot-attachment-container").css("display") == "block")
7392    $(".cbot-attachment-container").css("display", "none")
7393  else $(".cbot-attachment-container").css("display", "block")
7394}
7395function popupwindow(url, title, w, h) {
7396  var left = (screen.width / 2) - (w / 2);
7397  var top = (screen.height / 2) - (h / 2);
7398  return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
7399}
7400
7401function shareLocation() {
7402  var elCbotFormMessage = document.getElementById('cbot-form-message');
7403  navigator.geolocation.getCurrentPosition(function receiveData(data) {
7404
7405
7406    var elCbotInteractiveButtons = document.getElementsByClassName('cbot-location');
7407    for (var j = 0; j < elCbotInteractiveButtons.length; j++) {
7408      e = elCbotInteractiveButtons[j];
7409      e.disabled = true;
7410    }
7411
7412    var message = { message_type: "LOCATION_COMPONENT", lat: data.coords.latitude, lng: data.coords.longitude };
7413    if (!lastConversationStepValue) {
7414      appendMessageToDialogBox(message, "cbot-self", "", {}, function () {
7415
7416      })
7417    }
7418
7419    sendPost({
7420      userId: cbotUserId,
7421      sessionId: cbotSessionId,
7422      message: "",
7423      data: message,
7424      live_chat: isLive,
7425      request_type: "LOCATION",
7426      client: cbot_config.client
7427    }, function (data) {
7428
7429      $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
7430      $('#cbot-form-message').removeAttr('disabled')
7431      elCbotFormMessage.value = " ";
7432      elCbotFormMessage.removeAttribute('readonly');
7433      if (document.getElementById("cbot-send-button"))
7434        document.getElementById("cbot-send-button").removeAttribute('disabled');
7435      cbotFocus(elCbotFormMessage);
7436      if (data) {
7437        intents = data.intents;
7438        appendMessageToDialogBox(data.message, "cbot-other", null, { notification: data.speak }, function () {
7439          setClickEventToInteractiveButtons(data.userId);
7440          if (data.survey) {
7441            surveyTrigger(data.survey, data.userId);
7442          }
7443          triggerTimingResponses(data);
7444        });
7445      } else {
7446        appendMessageToDialogBox(WIDGET_TIMEOUT_MESSAGE, "cbot-other", null, { notification: WIDGET_TIMEOUT_MESSAGE }, function () { });
7447      }
7448    })
7449  }, function error(data) {
7450    if (lastConversationStepValue) {
7451      let message = { message_type: "LOCATION_COMPONENT", lat: null, lng: null };
7452      sendPost({
7453        userId: cbotUserId,
7454        sessionId: cbotSessionId,
7455        message: "",
7456        data: message,
7457        live_chat: isLive,
7458        request_type: "LOCATION",
7459        client: cbot_config.client
7460      }, function (data) {
7461        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
7462        $('#cbot-form-message').removeAttr('disabled')
7463        elCbotFormMessage.value = " ";
7464        elCbotFormMessage.removeAttribute('readonly');
7465        if (document.getElementById("cbot-send-button"))
7466          document.getElementById("cbot-send-button").removeAttribute('disabled');
7467        cbotFocus(elCbotFormMessage);
7468        if (data) {
7469          intents = data.intents;
7470          appendMessageToDialogBox(data.message, "cbot-other", null, { notification: data.speak }, function () {
7471            setClickEventToInteractiveButtons(data.userId);
7472            if (data.survey) {
7473              surveyTrigger(data.survey, data.userId);
7474            }
7475            triggerTimingResponses(data);
7476          });
7477        } else {
7478          appendMessageToDialogBox(WIDGET_TIMEOUT_MESSAGE, "cbot-other", null, { notification: WIDGET_TIMEOUT_MESSAGE }, function () { });
7479        }
7480      })
7481    } else {
7482      appendMessageToDialogBox({ message_type: "TEXT", message: "Hata oluştu,Tarayıcınızın konum bilgisine erişme özelliğini aktifleştirin." }, "cbot-other", "", {}, function () { })
7483    }
7484
7485  }
7485/* , function options(...args) { console.log("options", args) } */)
7486
7487}
7488
7489var timingResponseTimeouts = [];
7490function triggerTimingResponses(resp) {
7491  var timingResponses = resp.timing_response;
7492  clearTimingResponseTimeout();
7493  // if (resp.conversationStep) return;
7494  if (resp.live_chat) return;
7495  if (!Array.isArray(timingResponses) || timingResponses.length == 0) return;
7496  if (isLive) return;
7497  var time = 0;
7498  for (var i = 0; i < timingResponses.length; i++) {
7499    if (timingResponses[i].is_active) {
7500      time += timingResponses[i].time * 1000;
7501      sendTimingResponse(timingResponses[i], time);
7502    }
7503  }
7504
7505}
7506
7507function sendTimingResponse(timingResponse, time) {
7508  var timeout = setTimeout(function () {
7509    sendPost({
7510      userId: cbotUserId,
7511      sessionId: cbotSessionId,
7512      message: timingResponse.message,
7513      client: cbot_config.client
7514    }, function (data) {
7515
7516      if (document.getElementById("cbot-send-button"))
7517        document.getElementById("cbot-send-button").removeAttribute('disabled');
7518      if (data) {
7519        intents = data.intents;
7520        appendMessageToDialogBox(data.message, "cbot-other", null, { notification: data.speak }, function () {
7521          setClickEventToInteractiveButtons(data.userId);
7522          if (data.survey) {
7523            surveyTrigger(data.survey, data.userId);
7524          }
7525        });
7526      } else {
7527        appendMessageToDialogBox(WIDGET_TIMEOUT_MESSAGE, "cbot-other", null, { notification: WIDGET_TIMEOUT_MESSAGE }, function () { });
7528      }
7529    }, true);
7530  }, time || timingResponse.time * 1000);
7531  timingResponseTimeouts.push(timeout);
7532}
7533
7534function clearTimingResponseTimeout() {
7535  for (var i = 0; i < timingResponseTimeouts.length; i++) {
7536    clearTimeout(timingResponseTimeouts[i]);
7537  }
7538}
7539
7540var is_liveagent_typed = getIsLiveAgentTypedFLS();
7541var isConversationHistoryFetched = false;
7542function getConversations(next, getConversationsCallback = () => { }, retryCount = 0) {
7543  if (cbotUserId && cbotSessionId) {
7544    var headers = {
7545      "Content-Type": "application/json",
7546      "CBot-Token": "r0BfunEz42uAnfrcb4HyKzcbSjiu73tH",
7547      "CBOT-URL": generateCBOTURL(location.href)
7548    }
7549
7550    var customheaders = clients.gateway_custom_headers || [];
7551
7552    for (var i = 0; i < customheaders.length; i++) {
7553      var header = customheaders[i];
7554      headers[header.key] = header.value;
7555    }
7556
7557    $.ajax({
7558      url: rootAddress + "/conversations?client=" + CLIENT,
7559      type: "POST",
7560      timeout: 5000,
7561      headers: headers,
7562      data: JSON.stringify({
7563        "client": CLIENT,
7564        "user_id": cbotUserId,
7565        "session_id": cbotSessionId,
7566        "referrer": CHANNEL || "WIDGET",
7567        "userInfo": data_user
7568      }),
7569      success: function (resp) {
7570        isConversationHistoryFetched = true;
7571        sendCustomPostMessage("CBOT_CONVERSATION_HISTORY_FETCHED", {});
7572        checkAndSetSessionId(resp.session_id)
7573        setUserIdTLS(resp.user_id);
7574        socket_newclient();
7575        if (resp.userInfo && resp.userInfo.user_display_name) {
7576          addAvatarLetters(resp.userInfo.user_display_name);
7577        }
7578
7579        if (!showedSurvey) {
7580          exitSurvey = resp.exit_survey;
7581        }
7582
7583        if (resp && resp.lang_vars) {
7584          setLangVars(resp.lang_vars);
7585        }
7586
7587        if (resp && typeof resp == "object" && resp.data && Array.isArray(resp.data)) {
7588          conversations = resp.data;
7589          conversations.reverse();
7590          conversations.forEach(response => {
7591            let agent_messages = (response.answer || []).filter(x => x.chat_type == 'agent');
7592            if (agent_messages.length > 0) {
7593              is_liveagent_typed = true;
7594              setIsLiveAgentTypedTLS(true);
7595            }
7596
7597            if (response.stop === true) {
7598              is_liveagent_typed = false;
7599              setIsLiveAgentTypedTLS(false);
7600            }
7601
7602            if (response.answer && Array.isArray(response.answer)) {
7603              response.answer.forEach(msg => {
7604                if (msg.message && typeof msg.message === 'string') {
7605                  msg.message = msg.message.replace(/data: /g, '');
7606                }
7607              });
7608            }
7609          })
7610        }
7611        // console.log("CONV RECEIVED", conversations)
7612        next();
7613        if (getConversationsCallback && typeof getConversationsCallback === "function") getConversationsCallback(resp.user_id, interactive_popup_message);
7614      },
7615      error: function (err) {
7616        // console.log("conversation history error", err)
7617
7618        if (retryCount < 3) {
7619          // Retry up to 3 times
7620          getConversations(next, getConversationsCallback, retryCount + 1);
7621        } else {
7622          next();
7623          if (getConversationsCallback && typeof getConversationsCallback === "function") getConversationsCallback(cbotUserId, interactive_popup_message);
7624        }
7625      }
7626    });
7627  } else {
7628    next();
7629    if (getConversationsCallback && typeof getConversationsCallback === "function") getConversationsCallback(cbotUserId, interactive_popup_message);
7630  }
7631}
7632
7633function checkAndSetSessionId(val) {
7634  if (val) {
7635    // cbotSessionId = Date.now();
7636    cbotSessionId = val;
7637    // isLive = setIsLive(false);
7638    // setisLiveTLS(isLive);
7639    setSessionIdTLS(cbotSessionId);
7640
7641  }
7642}
7643
7644function sendRepeatedMessages(messages, cbotUserId, i) {
7645  $('#cbot-form-message').css('pointer-events', 'auto');
7646  dialog(cbotUserId, messages[i], function () {
7647    i++;
7648    if (i < messages.length) {
7649      sendRepeatedMessages(messages, cbotUserId, i);
7650    } else {
7651      return true;
7652    }
7653  });
7654
7655}
7656
7657let isSendTriggerMessage = false;
7658
7659function sendTriggerMessages(trigger_messages, suffix = '') {
7660  setTimeout(function () {
7661    $('#cbot-form-message').css('pointer-events', 'none');
7662
7663    // Refresh butonunu devre dışı bırak
7664    $(".cbot-refresh-icon").css('opacity', '0.5')
7665    $(".cbot-refresh-icon").css('pointer-events', 'none')
7666
7667    var elCbotFormMessage = document.getElementById('cbot-form-message');
7668    cbotFocus(elCbotFormMessage);
7669
7670    if (suffix.length > 0) {
7671      setIsTimeoutMessageSentTLS(false);
7672    }
7673
7674    if (getIsTimeoutMessageSentTLS() && user_timeout.message) {
7675      appendMessageToDialogBox(user_timeout.message, "cbot-other", null, { notification: user_timeout.message }, function () { });
7676      setIsTimeoutMessageSentTLS(false);
7677    }
7678
7679    var messages = getLastMessageFLS();
7680    if (queryStringVars.cbot_repeat && Array.isArray(messages) && messages.length > 0) {
7681      sendRepeatedMessages(messages, cbotUserId, 0);
7682    } else if (queryStringVars.cbot_message || (Array.isArray(trigger_messages) && trigger_messages.length > 0 && trigger_messages[0] != "" && trigger_messages_count == 0 || sendCategory)) {
7683      // if (trigger_messages[0].indexOf("trigger#") >= 0) {
7684      var message
7685      if (sendCategory) {
7686        message = "intent"
7687      } else {
7688        message = queryStringVars.cbot_message || trigger_messages[0] + suffix; //trigger_messages[0].split("#")[1];
7689      }
7690      if (message) {
7691        isSendTriggerMessage = true;
7692      }
7693
7694      trigger_messages_count++;
7695
7696      $('#cbot-form-message').attr('disabled', true)
7697      $('#cbot-send-button').attr('disabled', true)
7698
7699      sendPost({
7700        senderName: "User_" + cbotUserId,
7701        userId: cbotUserId,
7702        sessionId: cbotSessionId,
7703        message: message,
7704        is_triggered: true,
7705        intents: intents,
7706        live_chat: isLive,
7707        client: cbot_config.client,
7708        presetCategory: sendCategory
7709      }, function (data) {
7710        sendCustomPostMessage("CBOT_TRIGGER_MESSAGE_SENT", {})
7711        setLastMessageSentDateTLS();
7712        setLastMessageTLS([message]);
7713        $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
7714        $('#cbot-form-message').removeAttr('disabled')
7715        elCbotFormMessage.value = " ";
7716        elCbotFormMessage.removeAttribute('readonly');
7717        if (document.getElementById("cbot-send-button"))
7718          document.getElementById("cbot-send-button").removeAttribute('disabled');
7719        cbotFocus(elCbotFormMessage);
7720
7721
7722        handleMessageArea();
7723
7724        var element = document.getElementById('cbot-chat');
7725        if (data) {
7726          $(".cbot-refresh-icon").css('opacity', '1')
7727          $(".cbot-refresh-icon").css('pointer-events', 'painted')
7728          intents = data.intents;
7729          if (refresh_button_clicked) {
7730            refresh_button_clicked = false;
7731          }
7732          appendMessageToDialogBox(data.message, "cbot-other", null, { notification: data.speak, serviceOutput: data.serviceOutput || false }, function () {
7733            setClickEventToInteractiveButtons(data.userId);
7734            if (data.survey) {
7735              surveyTrigger(data.survey, data.userId);
7736            }
7737            toggleCloseChatButton("none")
7738            livechatTimeoutEndNotifier(true);
7739            triggerTimingResponses(data);
7740            isLive = setIsLive(data.live_chat);
7741            setisLiveTLS(isLive);
7742            if (isLive) {
7743              FIRST_LIVE_MESSAGE = true;
7744              socket_widget(message);
7745            }
7746
7747            // Trigger mesajları yazıldıktan sonra
7748            sendPendingUpdateDataUserMessage();
7749          });
7750        } else {
7751          $(".cbot-refresh-icon").css('opacity', '1')
7752          $(".cbot-refresh-icon").css('pointer-events', 'painted')
7753          appendMessageToDialogBox(WIDGET_TIMEOUT_MESSAGE, "cbot-other", null, { notification: WIDGET_TIMEOUT_MESSAGE }, function () { });
7754        }
7755        $('#cbot-form-message').css('pointer-events', 'auto');
7756      });
7757      /* } else {
7758        loopTrigger(0, trigger_messages);
7759      } */
7760    } else {
7761      $('#cbot-form-message').css('pointer-events', 'auto');
7762    }
7763    scrollChatScreen(300);
7764
7765  }, 200);
7766}
7767
7768function writeConversations() {
7769  var isLastMessage = function (currentIndex, currentJ, currentBotAnswer) {
7770    // Son conversation mu?
7771    if (currentIndex !== conversations.length - 1) return false;
7772
7773    // Bot answer varsa, son bot answer elemanı mı?
7774    if (currentBotAnswer && currentBotAnswer.length > 0) {
7775      return currentJ === currentBotAnswer.length - 1;
7776    }
7777
7778    return true;
7779  };
7780
7781  for (var i = 0; i < conversations.length; i++) {
7782    if (!conversations[i].is_triggered) // trigger mesajı ise yazma
7783    {
7784
7785      var message = "";
7786      if (conversations[i].data_full_action && conversations[i].data_full_action.title)
7787        message = conversations[i].data_full_action.title;
7788      else
7789        message = conversations[i].message;
7790
7791      if (message.match(/LOCATION\[STD]/g)) {
7792        var locations = message.split('LOCATION[STD]:')[1].split(",")
7793        message = { message_type: "LOCATION_COMPONENT", lat: locations[0].trim(), lng: locations[1].trim() };
7794      }
7795
7796      if (typeof message == 'string' && !/^DOC/.test(message.substring(0, 3))) {
7797        var messageOptions = {
7798          instantWrite: !!1,
7799          messageTimestamp: conversations[i].date || conversations[i].requestTime
7800        };
7801
7802        appendMessageToDialogBox(message, "cbot-self", null, messageOptions, function () {
7803          // person
7804        });
7805      }
7806
7807    }
7808    var botAnswer = conversations[i].answer;
7809    if (botAnswer) {
7810      if (!conversations[i].live_chat) {
7811        if (typeof botAnswer == "string") botAnswer = [{ message_type: "TEXT", message: botAnswer }];
7812        else if (typeof botAnswer == "object") botAnswer == [botAnswer];
7813        for (var j = 0; j < botAnswer.length; j++) {
7814          var element = botAnswer[j];
7815          if (!element.is_deleted) {
7816            (function (isLast, convDate) {
7817              var botMessageOptions = {
7818                instantWrite: !!1,
7819                messageTimestamp: convDate
7820              };
7821
7822              appendMessageToDialogBox(element, "cbot-other", null, botMessageOptions, function () { // bot
7823                setClickEventToInteractiveButtons(cbotUserId);
7824                if (isLast) {
7825                  sendPendingUpdateDataUserMessage();
7826                }
7827              })
7828            })(isLastMessage(i, j, botAnswer), conversations[i].date || conversations[i].requestTime);
7829          }
7830        }
7831      }
7832      else {
7833        if (typeof botAnswer == "string") botAnswer = [{ message_type: "TEXT", message: botAnswer }];
7834        else if (typeof botAnswer == "object") botAnswer == [botAnswer];
7835        botAnswer = botAnswer.filter(function (x) { return x.chat_type == "agent" || !x.chat_type })
7836        for (var j = 0; j < botAnswer.length; j++) {
7837          var element = botAnswer[j];
7838          if (!element.is_deleted) {
7839            (function (isLast, convDate) {
7840              var liveMessageOptions = {
7841                instantWrite: !!1,
7842                messageTimestamp: convDate
7843              };
7844
7845              appendMessageToDialogBox(element, "cbot-other", null, liveMessageOptions, function () { // bot
7846                setClickEventToInteractiveButtons(cbotUserId);
7847                if (isLast) {
7848                  sendPendingUpdateDataUserMessage();
7849                }
7850              })
7851            })(isLastMessage(i, j, botAnswer), conversations[i].date || conversations[i].requestTime);
7852          }
7853        }
7854      }
7855    }
7856  }
7857
7858  closeMiniWeb();
7859}
7860
7861
7862// FLS > FROM LOCAL STORAGE
7863// TLS > TO LOCAL STORAGE
7864function getSessionIdFLS() {
7865  return localStorage[getDynamicLSName("sessionId")] || 0;
7866}
7867function setSessionIdTLS(val) {
7868  cbotSessionId = val;
7869  if (!cbotSessionId) {
7870    localStorage.removeItem(getDynamicLSName("sessionId"));
7871    xdLocalStorage.removeItem(getDynamicLSName("sessionId"));
7872  } else {
7873    localStorage[getDynamicLSName("sessionId")] = val;
7874    xdLocalStorage.setItem(getDynamicLSName("sessionId"), val);
7875  }
7876}
7877
7878function setUserIdTLS(userId) {
7879  cbotUserId = userId;
7880  if (!cbotUserId) {
7881    localStorage.removeItem(getDynamicLSName("userid"));
7882    xdLocalStorage.removeItem(getDynamicLSName("userid"));
7883  } else {
7884    localStorage[getDynamicLSName("userid")] = cbotUserId;
7885    xdLocalStorage.setItem(getDynamicLSName("userid"), cbotUserId);
7886
7887  }
7888}
7889
7890function getisLiveFLS() {
7891  let res = (localStorage[getDynamicLSName("isLive")] === "true" || localStorage[getDynamicLSName("isLive")] === "fal
7891se") ? JSON.parse(localStorage[getDynamicLSName("isLive")]) : isLive;
7892  if (res) {
7893    socket_connection()
7894    sendCustomPostMessage("CBOT_LIVECHAT_RECONNECTED", {});
7895  }
7896  return res;
7897}
7898function setisLiveTLS(val) {
7899  if (val === true) {
7900    if (!hasSurveyFeedback) {
7901      showedSurvey = null;
7902    }
7903  }
7904
7905  localStorage[getDynamicLSName("isLive")] = val;
7906  xdLocalStorage.setItem(getDynamicLSName("isLive"), val);
7907}
7908
7909function getIsLiveAgentTypedFLS() {
7910  return (localStorage[getDynamicLSName("isLiveAgentTyped")] === "true" || localStorage[getDynamicLSName("isLiveAgentTyped")] === "false") ? JSON.parse(localStorage[getDynamicLSName("isLiveAgentTyped")]) : false;
7911}
7912
7913function setIsLiveAgentTypedTLS(val) {
7914  localStorage[getDynamicLSName("isLiveAgentTyped")] = !!val;
7915  xdLocalStorage.setItem(getDynamicLSName("isLiveAgentTyped"), !!val);
7916}
7917
7918function setUserInfoTLS(val) {
7919
7920  localStorage[getDynamicLSName("userInfo")] = val;
7921  xdLocalStorage.setItem(getDynamicLSName("userInfo"), val);
7922}
7923function getUserInfoFLS() {
7924  return localStorage[getDynamicLSName("userInfo")] || "";
7925}
7926
7927/**
7928 * Eğer X butonuna basıldığında görüşmenin temizlenmesi özelliği aktifse
7929 * Sayfa yenilenmesi durumunda bu özelliğin çalışabilmesi için localStorage'a bir alan ekleniyor.
7930 */
7931function setCloseIconPressed() {
7932  if (getChannelValue(clients.clear_after_close_bot, CHANNEL)) {
7933    localStorage.setItem(getDynamicLSName("cbot-close-icon-pressed"), "true");
7934    xdLocalStorage.setItem(getDynamicLSName("cbot-close-icon-pressed"), "true");
7935  }
7936}
7937
7938function getCloseIconPressed() {
7939  return localStorage.getItem(getDynamicLSName("cbot-close-icon-pressed"))
7940}
7941
7942function removeCloseIconPressed() {
7943  return localStorage.removeItem(getDynamicLSName("cbot-close-icon-pressed"))
7944}
7945
7946function setIsLive(val) {
7947
7948  if (LIVE_CHAT && val) {
7949    socket_connection()
7950  }
7951
7952  if (!val) {
7953
7954    if ((data_vip || data_livechat) && LIVE_CHAT) {
7955
7956      if (LIVE_CHAT && val) {
7957        toggleAttachmentIcon("block");
7958      } else {
7959        toggleCloseChatButton("none");
7960        livechatTimeoutEndNotifier(true);
7961      }
7962
7963      FIRST_LIVE_MESSAGE = true;
7964      return true;
7965    }
7966
7967    toggleAttachmentIcon("none");
7968    toggleCloseChatButton("none");
7969    livechatTimeoutEndNotifier(true);
7970    agentId = null;
7971    agent_name = null;
7972    return val;
7973  }
7974
7975  if (LIVE_CHAT && val) {
7976    toggleAttachmentIcon("block");
7977  }
7978
7979  return LIVE_CHAT && val;
7980}
7981
7982function clearLastMessageSentDateTLS(client) {
7983  if (!client) client = CLIENT;
7984  localStorage[getDynamicLSName("lastmessagedate", false)] = "0";
7985  xdLocalStorage.setItem(getDynamicLSName("lastmessagedate", false), "0");
7986}
7987
7988function setLastMessageSentDateTLS(client) {
7989  if (!client) client = CLIENT;
7990  localStorage[getDynamicLSName("lastmessagedate", false)] = Date.now();
7991  xdLocalStorage.setItem(getDynamicLSName("lastmessagedate", false), Date.now());
7992}
7993function getLastMessageSentDateFLS(client) {
7994  if (!client) client = CLIENT;
7995  return JSON.parse(localStorage[getDynamicLSName("lastmessagedate", false)] || 0);
7996}
7997
7998function setLastMessageTLS(message, client) {
7999  if (!client) client = CLIENT;
8000  localStorage[getDynamicLSName("lastmessages", false)] = JSON.stringify(message);
8001  xdLocalStorage.setItem(getDynamicLSName("lastmessages", false), JSON.stringify(message));
8002}
8003function getLastMessageFLS(client) {
8004  if (!client) client = CLIENT;
8005  return JSON.parse(localStorage[getDynamicLSName("lastmessages", false)] || "[]");
8006}
8007
8008function setFirstMessageSentTLS(val) {
8009  localStorage[getDynamicLSName("firstmessagesent")] = val;
8010  xdLocalStorage.setItem(getDynamicLSName("firstmessagesent"), val);
8011}
8012function getFirstMessageSentFLS(client) {
8013  if (!client) client = CLIENT;
8014  return localStorage[getDynamicLSName("firstmessagesent")] == "true";
8015}
8016
8017function setIsTimeoutMessageSentTLS(val) {
8018  localStorage[getDynamicLSName("istimeoutmessagesent")] = val;
8019  xdLocalStorage.setItem(getDynamicLSName("istimeoutmessagesent"), val);
8020}
8021function getIsTimeoutMessageSentTLS(client) {
8022  if (clients.send_timeout_message_to_new_session) {
8023    if (!client) client = CLIENT;
8024    return localStorage[getDynamicLSName("istimeoutmessagesent")] == "true";
8025  } else {
8026    return false
8027  }
8028}
8029
8030function setIsWidgetOpenedTLS(val) {
8031  localStorage[getDynamicLSName("iswidgetopened")] = val;
8032  xdLocalStorage.setItem(getDynamicLSName("iswidgetopened"), val);
8033}
8034function getIsWidgetOpenedTLS(client) {
8035  if (clients.stay_open_widget) {
8036    if (!client) client = CLIENT;
8037    return localStorage[getDynamicLSName("iswidgetopened")] == "true";
8038  } else {
8039    return false
8040  }
8041}
8042
8043function checkLastMessageDate(client) {
8044  var lastmessagedate = getLastMessageSentDateFLS(client);
8045  if (lastmessagedate) {
8046    lastMessageReceiveDate = parseInt(lastmessagedate);
8047    return new Date(parseInt(lastmessagedate) + parseInt(clients.user_timeout_minute || clients.user_timeout_notify_second || 30) * 60 * 1000) >= Date.now();
8048  }
8049  return false;
8050}
8051
8052function openMidPagePopup(url, login_button) {
8053  openMiniWeb("web_url", url);
8054}
8055
8056function openMiniWeb(type, url, options) {
8057
8058  if (cbotIsMobile.any())
8059    moveMiniWebForMobile();
8060  if (options)
8061    options = JSON.parse(options)
8062  var elCbotWebArea = document.getElementById('cbot-web-area');
8063  if (type)
8064    fadeIn(elCbotWebArea);
8065
8066  if (type === "web_url") {
8067
8068    $(".cbot-web-area-content").html('<iframe frameBorder="0" src="' + url + '"></iframe>')
8069  }
8070  else if (type === "cbot_meet") {
8071
8072    $(".cbot-web-area-content").html('<iframe frameBorder="0" allow="camera; microphone; fullscreen; display-capture; autoplay" src="' + url + '"></iframe>')
8073    // Buton stilini değiştir.
8074    $('.cbot-start-meeting').text('Görüntülü Görüşmeyi Sonlandır ❌');
8075    $('.cbot-start-meeting').css('background', 'orange');
8076
8077  }
8078  else if (type === "html") {
8079    $(".cbot-web-area-content").html('<div class="cbot-doc-content">' + b64decode(options.html) + '</div>');
8080
8081  }
8082  if (type === "location") {
8083
8084    $(".cbot-web-area-content").html('<iframe frameBorder="0" src="https://www.google.com/maps/embed/v1/view?key=AIzaSyD1Z6ndI5vaUA_aE5OmpGrTvpLYCtc3KpU&center=' + options.lat + ',' + options.lng + '&zoom=15"></iframe>')
8085  }
8086  else if (type === "image") {
8087    $(".cbot-web-area-content").html('<div class="cbot-web-image"><img src="' + url + '"/></div>');
8088
8089  }
8090  else if (type === "video") {
8091    if (url.includes('youtube'))
8092      $(".cbot-web-area-content").html('<iframe width=100 allow="autoplay;" frameBorder="0" src="' + url + '"></iframe>');
8093    else if (url.includes('facebook')) {
8094      const html = `<iframe
8095            src="https://www.facebook.com/plugins/video.php?height=314&href=${url}&show_text=false&width=560&t=0"
8096            width="560"
8097            height="314"
8098            style="border:none;overflow:hidden"
8099            scrolling="no"
8100            frameborder="0"
8101            allowfullscreen="true"
8102            allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" allowFullScreen="true"></iframe>`
8103      $(".cbot-web-area-content").html(html);
8104    }
8105    else
8106      $(".cbot-web-area-content").html('<div class="cbot-web-video-container"><div class="cbot-web-video"><video autoplay width="100%" controls><source src="' + url + '" type="video/mp4">Tarayıcınızda video desteği mevcut değil.</video></div></div>');
8107    // $(".cbot-web-area-content").html('<video frameBorder="0" src="' + url + '"></video>');
8108
8109
8110
8111  } else if (type?.includes("data:")) {
8112    $(".cbot-web-area-content").html('<iframe frameBorder="0" src="' + type + '"></iframe>')
8113  }
8114}
8115
8116function closeMiniWeb() {
8117  if (document.querySelector('#cbot-mini-web-toggle')) {
8118    document.querySelector('#cbot-mini-web-toggle').remove();
8119    document.querySelector('.cbot-avatar').style.display = 'block';
8120  }
8121  var elCbotWebArea = document.getElementById('cbot-web-area');
8122  if ($("#cbot-web-area").css("display") != "none") {
8123    fadeOut(elCbotWebArea);
8124  }
8125}
8126
8127function b64encode(data) {
8128  return btoa(unescape(encodeURIComponent(data)));
8129}
8130function b64decode(data) {
8131  return decodeURIComponent(escape(atob(data)));
8132}
8133
8134function browserNotifications() {
8135  if ("Notification" in window) {
8136
8137    var permission = Notification.permission;
8138    if (permission === "granted") {
8139      showNotification();
8140    } else if (permission === "default") {
8141      requestAndShowPermission();
8142    } else {
8143      // alert("Use normal alert");
8144    }
8145  }
8146}
8147
8148function showNotification(title, body) {
8149  function playLongSound() {
8150    if (audioElement) {
8151      audioElement.play();
8152    }
8153  }
8154
8155  title = title || "";
8156
8157  if ("Notification" in window) {
8158    if (!isWidgetOpen) {
8159      newMsgCount++;
8160      toggleBadge(newMsgCount);
8161    }
8162
8163    if (document.visibilityState === "visible") {
8164      return;
8165    }
8166
8167    if (typeof body === "string") {
8168      body = (body || "").replace(/<.+?>/g, ""); // #526
8169      body = body.replace(/NO_MESSAGE/g, "");
8170      body = body.trim();
8171    }
8172
8173    if (body) {
8174      icon = cbot_config.dialogImageURL;
8175      try {
8176        var notification = new Notification(title, { body: body, icon: icon }); // es6
8177        playLongSound()
8178        notification.onclick = function () {
8179          notification.close();
8180          cbotFocus(window.parent);
8181          if (!isWidgetOpen) {
8182            dialogButtonRegular();
8183          }
8184        }
8185      } catch (err) {
8186        console.error(err);
8187      }
8188    }
8189  }
8190}
8191function requestAndShowPermission() {
8192  Notification.requestPermission(function (permission) {
8193    if (permission === "granted") {
8194      showNotification();
8195    }
8196  });
8197}
8198
8199function toggleBadge(newMsgCount) {
8200  if (newMsgCount > 0) {
8201    $("#cbot-count-badge").text(newMsgCount);
8202    $("#cbot-count-badge").css("display", "block");
8203  } else {
8204    $("#cbot-count-badge").css("display", "none");
8205  }
8206}
8207
8208function clickToCloseLivechatButton() {
8209  if (getChannelValue(clients.close_widget_after_leave_livechat, CHANNEL)) {
8210    cbotCloseIcon();
8211  } else {
8212    closeLivechat(() => {
8213      showExitSurvey();
8214    }, "customer")
8215  }
8216}
8217
8218async function closeLivechat(next = () => { }, reason) {
8219  if (LIVE_CHAT && isLive) {
8220
8221    forceCloseJitsiMeet();
8222    toggleCloseChatButton("none");
8223    livechatTimeoutEndNotifier(true);
8224    if (!SOCKET_CONNECT_ON_START) {
8225      await socket_widget("Görüşme kullanıcı tarafından sonlandırıldı.", true);
8226    }
8227    stopped_by_customer = true;
8228    socket.emit('chat_stop_by_customer', { client_id: cbotUserId, session_id: cbotSessionId, reason });
8229    // setTimeout(function () {
8230    //     socket.emit('chat_stop_by_customer', { client_id: cbotUserId, session_id: cbotSessionId });
8231    // }, 1000);
8232    handleMessageArea();
8233
8234    isLive = setIsLive(false);
8235    setisLiveTLS(isLive); // ekledim hataya sebep oluyordu
8236
8237    appendMessageToDialogBox(lang_vars.LIVECHAT_CUSTOMER_CLOSE_MESSAGE, "cbot-other", "", {}, function () {
8238      next();
8239    });
8240
8241
8242    sendCustomPostMessage("CBOT_LIVECHAT_STOPPED", {});
8243    if (clients.disable_user_chat_input) {
8244      disableUserMessageArea(clients.disable_user_chat_input_message);
8245    }
8246  }
8247}
8248
8249function toggleAttachmentIcon(display) {
8250  if (display == "block") {
8251    if (!bool_attachments) display = "none";
8252  }
8253  $("#cbot-attachment-area").css("display", display);
8254}
8255
8256function toggleCloseChatButton(display) {
8257  if (display == "none") {
8258    is_liveagent_typed = false;
8259    setIsLiveAgentTypedTLS(false);
8260    $("#cbot-chat").css("height", "calc(100% - 155px);")
8261  } else {
8262    is_liveagent_typed = true;
8263    setIsLiveAgentTypedTLS(true);
8264    $("#cbot-chat").css("height", "calc(100% - 175px);")
8265    $(".cbot-livechat-started").css("display", "flex");
8266
8267  }
8268  $(".cbot-livechat-close").css("display", display);
8269  if (video_conference) {
8270    $(".cbot-start-meeting").css("display", display);
8271  }
8272}
8273
8274function setUserTimeout() {
8275  if (!clients.user_timeout) {
8276    return;
8277  }
8278  user_timeout = clients.user_timeout;
8279  for (const key of Object.keys(user_timeout)) {
8280    if (!user_timeout[key]) {
8281      user_timeout[key] = {
8282        message: ""
8283      }
8284    }
8285    user_timeout[key].message = lang_vars.LANGVARS_USER_TIMEOUT_MESSAGE || (user_timeout[key].message || "");
8286  }
8287}
8288
8289var user_timeout_for_bot = 30;
8290function chatEndNotifier() {
8291  setUserTimeout();
8292  if (clients.user_timeout_minute) {
8293    user_timeout_for_bot = parseInt(clients.user_timeout_minute)
8294  }
8295  if (clients.user_timeout_notify_second) {
8296    timeoutNotifySecPeriod = parseInt(clients.user_timeout_notify_second)
8297  }
8298  setInterval(function () {
8299    if (cbotShowMessageArea == "show")
8300      $(".cbot-dialog-end-timer").css("bottom", "94px")
8301    else
8302      $(".cbot-dialog-end-timer").css("bottom", "0")
8303    if (!isLive && (new Date(lastMessageReceiveDate + user_timeout_for_bot * 1000 * 60 - (timeoutNotifySecPeriod * 1000)).getTime() < new Date().getTime() && new Date(lastMessageReceiveDate + user_timeout_for_bot * 1000 * 60).getTime() > new Date().getTime())) {
8304      var sn = parseInt((new Date(lastMessageReceiveDate + user_timeout_for_bot * 1000 * 60).getTime() - new Date().getTime()) / 1000);
8305
8306      // if (new Date(lastMessageReceiveDate + 1000 * 3).getTime() < new Date().getTime() && new Date(lastMessageReceiveDate + 1000 * 123).getTime() > new Date().getTime()) {
8307      //     var sn = parseInt((new Date(lastMessageReceiveDate + 1000 * 123).getTime() - new Date().getTime()) / 1000);
8308      // console.log(sn, "saniye kaldı")
8309      if ($(".cbot-dialog-end-timer").css("display") != "block")
8310        $(".cbot-dialog-end-timer").css("display", "block")
8311      if (clients.user_timeout_banner_message || lang_vars.LANGVARS_USER_TIMEOUT_BANNER_MESSAGE) {
8312        $(".cbot-dialog-end-timer").html("<span>" + sn + `</span><span class="cbot-dialog-end-timer-banner-message">${lang_vars.LANGVARS_USER_TIMEOUT_BANNER_MESSAGE || clients.user_timeout_banner_message}</span>`)
8313      } else {
8314        $(".cbot-dialog-end-timer").html("<span>" + sn + "</span> saniye içerisinde yazmazsanız oturumunuz sonlanacaktır.")
8315      }
8316      if (sn <= 0.5)
8317        setTimeout(function () {
8318          if (user_timeout.message || user_timeout[CHANNEL == "WIDGET" ? "DEFAULT" : CHANNEL].message)
8319            if (isWidgetOpen) {
8320              sendTimeOutMessage(user_timeout.message || user_timeout[CHANNEL == "WIDGET" ? "DEFAULT" : CHANNEL].message);
8321            }
8322        }, 1000);
8323    } else if (!isLive && timeoutNotifySecPeriod === 0 &&
8324      new Date(lastMessageReceiveDate + user_timeout_for_bot * 1000 * 60).getTime() > new Date().getTime() &&
8325      parseInt((new Date(lastMessageReceiveDate + user_timeout_for_bot * 1000 * 60).getTime() - new Date().getTime()) / 1000) === 0
8326    ) {
8327      if (user_timeout.message || user_timeout[CHANNEL == "WIDGET" ? "DEFAULT" : CHANNEL].message) {
8328        sendTimeOutMessage(user_timeout.message || user_timeout[CHANNEL == "WIDGET" ? "DEFAULT" : CHANNEL].message);
8329      }
8330    } else {
8331      if ($(".cbot-dialog-end-timer").css("display") != "none") {
8332        $(".cbot-dialog-end-timer").css("display", "none")
8333      }
8334    }
8335  }, 1000);
8336}
8337
8338function resolveStaticLottieUrl(url) {
8339  if (url && url.startsWith('static-lottie://')) {
8340    const raw = url.replace('static-lottie://', '');
8341    const dashIndex = raw.indexOf('-');
8342    const clientSlug = dashIndex > 0 ? raw.slice(0, dashIndex) : CLIENT;
8343    const filePart = dashIndex > 0 ? raw.slice(dashIndex + 1) : raw;
8344    const fileName = filePart.endsWith('.json') || filePart.endsWith('.lottie') ? filePart : `${filePart}.json`;
8345    return `${staticAddress}/firm-${clientSlug}/lottie/static-lottie/animations/${fileName}`;
8346  }
8347  return url;
8348}
8349
8350async function loadLottieLibrary(animationUrl) {
8351  try {
8352    if (cbot_lottie || !animationUrl) {
8353      return;
8354    }
8355    const resolvedUrl = resolveStaticLottieUrl(animationUrl);
8356    if (resolvedUrl.endsWith('.lottie')) {
8357      await new Promise((resolve, reject) => {
8358        const dotLottieScript = document.createElement('script');
8359        dotLottieScript.src = staticAddress + "/js/lottie-5.13.0.min.js";
8360        dotLottieScript.onload = resolve;
8361        dotLottieScript.onerror = reject;
8362        document.getElementsByTagName('head')[0].insertBefore(dotLottieScript, document.getElementsByTagName('head')[0].firstChild);
8363      });
8364    }
8365    else {
8366      await new Promise((resolve, reject) => {
8367        const lottieScript = document.createElement('script');
8368        lottieScript.src = staticAddress + "/js/lottie-2.0.12.js";
8369        lottieScript.onload = resolve;
8370        lottieScript.onerror = reject;
8371        document.getElementsByTagName('head')[0].insertBefore(lottieScript, document.getElementsByTagName('head')[0].firstChild);
8372      });
8373    }
8374
8375  } catch (error) {
8376    console.error("Lottie kütüphanesi yüklenirken bir hata oluştu:", error);
8377  }
8378}
8379
8380
8381
8382var livechat_timeout_for_bot = 0;
8383var livechat_timeout_interval;
8384function livechatTimeoutEndNotifier(stop = false) {
8385  if (stop) {
8386    clearInterval(livechat_timeout_interval);
8387    if ($(".cbot-livechat-end-timer").css("display") != "none") {
8388      $(".cbot-livechat-end-timer").css("display", "none")
8389    }
8390    return;
8391  }
8392  let livechat_timeout = (clients.livechat_timeout || {})["DEFAULT"] || {
8393    "DEFAULT": {
8394      message: ""
8395    }
8396  }
8397  if (clients.livechat_timeout_minute) {
8398    livechat_timeout_for_bot = parseInt(clients.livechat_timeout_minute)
8399  }
8400  if (clients.livechat_timeout_notify_second) {
8401    timeoutNotifySecPeriod = parseInt(clients.livechat_timeout_notify_second)
8402  }
8403  var lastMessageReceiveDateInlivechat = Date.now();
8404  clearInterval(livechat_timeout_interval);
8405  livechat_timeout_interval = setInterval(function () {
8406    if (cbotShowMessageArea == "show")
8407      $(".cbot-livechat-end-timer").css("bottom", "")
8408    else
8409      $(".cbot-livechat-end-timer").css("bottom", "0")
8410    if (new Date(lastMessageReceiveDateInlivechat + livechat_timeout_for_bot * 1000 * 60 - (timeoutNotifySecPeriod * 1000)).getTime() < new Date().getTime() && new Date(lastMessageReceiveDateInlivechat + livechat_timeout_for_bot * 1000 * 60).getTime() > new Date().getTime()) {
8411      var sn = parseInt((new Date(lastMessageReceiveDateInlivechat + livechat_timeout_for_bot * 1000 * 60).getTime() - new Date().getTime()) / 1000);
8412      if ($(".cbot-livechat-end-timer").css("display") != "block")
8413        $(".cbot-livechat-end-timer").css("display", "block")
8414      var livechat_timeout_banner_message = clients.livechat_timeout_banner_message ? clients.livechat_timeout_banner_message : " saniye içerisinde livechat sonlanacaktır.";
8415      $(".cbot-livechat-end-timer").html("<span>" + sn + "</span> " + livechat_timeout_banner_message)
8416      if (sn <= 1) {
8417        clearInterval(livechat_timeout_interval);
8418        setTimeout(function () {
8419          if (livechat_timeout.message)
8420            appendMessageToDialogBox(livechat_timeout.message, "cbot-other", null, { notification: livechat_timeout.message }, function () { });
8421          closeLivechat();
8422        }, 1000);
8423      }
8424    } else if (timeoutNotifySecPeriod === 0 &&
8425      new Date(lastMessageReceiveDateInlivechat + livechat_timeout_for_bot * 1000 * 60).getTime() > new Date().getTime() &&
8426      parseInt((new Date(lastMessageReceiveDateInlivechat + livechat_timeout_for_bot * 1000 * 60).getTime() - new Date().getTime()) / 1000) === 0
8427    ) {
8428      if (livechat_timeout.message) {
8429        appendMessageToDialogBox(livechat_timeout.message, "cbot-other", null, { notification: livechat_timeout.message }, function () { });
8430        closeLivechat();
8431        clearInterval(livechat_timeout_interval);
8432      }
8433    } else {
8434      if ($(".cbot-livechat-end-timer").css("display") != "none") {
8435        $(".cbot-livechat-end-timer").css("display", "none")
8436      }
8437    }
8438  }, 1000);
8439}
8440
8441function checkURLs(urls) {
8442  if (!urls || urls.length == 0) return {};
8443  var s = document.createElement("script");
8444  s.type = "text/javascript";
8445  var i = 0;
8446  while (i < urls.length && window.location.href.indexOf(urls[i].url) < 0) i++;
8447
8448  if (i < urls.length) {
8449    return urls[i];
8450  }
8451}
8452
8453function appendLocalStorageIFrame(url, next) {
8454  $("body").append('<iframe src="' + url + '" id="cbot-localstorage"></iframe>');
8455  afterAppend();
8456  var iframe = document.getElementById('cbot-localstorage');
8457  if (iframe) {
8458    iframe.onload = next;
8459  }
8460}
8461
8462function getXdLocalStorage() {
8463  var iframe = document.getElementById('cbot-localstorage');
8464  var win;
8465  if (iframe) {
8466    try {
8467      win = iframe.contentWindow;
8468    } catch (e) {
8469      try {
8470        win = iframe.contentWindow;
8471      } catch (err) {
8472        // console.log("getXdLocalStorage ERR", err);
8473      }
8474    }
8475  }
8476
8477
8478  return win;
8479}
8480
8481var xdLocalStorage = {
8482  getItem: function (key) {
8483    var win = getXdLocalStorage();
8484    if (win) {
8485      win.postMessage({
8486        action: 'get',
8487        key: key
8488      }, getAddr());
8489    }
8490
8491  },
8492  setItem: function (key, value) {
8493    var win = getXdLocalStorage();
8494    if (win) {
8495      win.postMessage({
8496        action: 'save',
8497        key: key,
8498        value: value
8499      }, getAddr());
8500    }
8501  },
8502  removeItem: function (key) {
8503    var win = getXdLocalStorage();
8504    if (win) {
8505      win.postMessage({
8506        action: 'remove',
8507        key: key
8508      }, getAddr());
8509    }
8510  },
8511  checkIFrameLocalStorage: function () {
8512    return getXdLocalStorage() != undefined;
8513  },
8514  clearAll: function () {
8515    var win = getXdLocalStorage();
8516    if (win) {
8517      win.postMessage({
8518        action: 'clearAll'
8519      }, getAddr());
8520    }
8521  }
8522}
8523
8524window.addEventListener("message", messageHandler, false);
8525function messageHandler(event) {
8526  if (event.data.action == 'returnData' && event.data.value) {
8527    setToLocalStorage(event.data.key, event.data.value)
8528  } else {
8529    storageCount++;
8530  }
8531}
8532
8533function getAddr() {
8534  try {
8535    if (window.self !== window.top) {
8536      if (window.location.ancestorOrigins && window.location.ancestorOrigins.length > 0) {
8537        return window.location.ancestorOrigins[0];
8538      }
8539      if (document.referrer) {
8540        return new URL(document.referrer).origin;
8541      }
8542      return null;
8543    }
8544  } catch (e) {}
8545  return window.location.origin;
8546}
8547
8548function setToLocalStorage(key, value) {
8549  localStorage[key] = value;
8550  storageCount++;
8551}
8552
8553function getVarsFromLocalStorageIFrame(client) {
8554  xdLocalStorage.getItem(getDynamicLSName("userid"));
8555  xdLocalStorage.getItem(getDynamicLSName("sessionId"));
8556  xdLocalStorage.getItem(getDynamicLSName("userInfo"));
8557  xdLocalStorage.getItem(getDynamicLSName("isLive"));
8558  xdLocalStorage.getItem(getDynamicLSName("lastmessagedate", false));
8559  xdLocalStorage.getItem(getDynamicLSName("firstmessagesent"));
8560  xdLocalStorage.getItem(getDynamicLSName("lastmessages", false));
8561}
8562
8563
8564
8565function getCustomPositionings() {
8566  var width = getParameterFromScript("data-pos-" + CHANNEL + "-width");
8567  var height = getParameterFromScript("data-pos-" + CHANNEL + "-height");
8568  var bottom = getParameterFromScript("data-pos-" + CHANNEL + "-bottom");
8569  var right = getParameterFromScript("data-pos-" + CHANNEL + "-right");
8570  var left = getParameterFromScript("data-pos-" + CHANNEL + "-left");
8571
8572  return { width: width, height: height, bottom: bottom, right: right, left: left }
8573
8574}
8575
8576
8577function cbotClearUserDialog(clear_dialog, refresh_button_clicked) {
8578  welcomeMessageSent = false;
8579  if (!refresh_button_clicked) {
8580    cbotUserId = null;
8581    setUserIdTLS(cbotUserId);
8582  }
8583  cbotSessionId = null;
8584  isLive = setIsLive(false);
8585  setisLiveTLS(isLive);
8586  setSessionIdTLS(cbotSessionId);
8587  clearLastMessageSentDateTLS()
8588
8589
8590  if (clear_dialog) {
8591    enableUserMessageArea()
8592    $("#cbot-chat").find("li").each(function (index, item) {
8593      $(item).remove();
8594    })
8595    var elCbotWebArea = document.getElementById('cbot-web-area');
8596    if (elCbotWebArea) {
8597      $('.cbot-web-close').click();
8598    }
8599
8600  }
8601
8602
8603}
8604let interactive_popup_message;
8605function openAndSendMessage(message, dont_get_trigger_message = false, new_welcome_message = "", showClientMessage = false) {
8606  if (new_welcome_message) {
8607    if (clients.welcome_message) {
8608      clients.welcome_message = new_welcome_message
8609      ChangeWelcomeMessage(new_welcome_message)
8610    } else {
8611      appendMessageToDialogBox(new_welcome_message, "cbot-other", null, {}, function () { });
8612    }
8613  }
8614  if (dont_get_trigger_message) ia_take_attention_state.is_executed = true;
8615  if (ia_take_attention_state_timer) clearTimeout(ia_take_attention_state_timer);
8616  let next = () => { }
8617  if (dont_get_trigger_message && message) {
8618    interactive_popup_message = message;
8619    next = (userId, message) => { dialog(userId, message, () => { }, undefined, showClientMessage, undefined, false); }
8620  }
8621  if (!new_welcome_message) {
8622    if (localStorage.getItem(getDynamicLSName("iswidgetopened")) == 'true') {
8623      next = (userId, message) => { appendMessageToDialogBox(message, "cbot-self", null, {}, function () { }); dialog(userId, message, () => { }, undefined, showClientMessage, undefined, true); }
8624    }
8625  }
8626  dialogButtonRegular(next);
8627  $(".cbot-join-chat-container").attr("style", "display: none !important;");
8628}
8629
8630function hideTimeoutPopup() {
8631  $(".cbot-join-chat-container").attr("style", "display: none !important;");
8632}
8633
8634function getQueryVariable(url) {
8635  if (url.indexOf("?") == -1) return {};
8636  var query = url.slice(url.indexOf("?") + 1);
8637  var vars = query.split('&');
8638  var obj = {}
8639  for (var i = 0; i < vars.length; i++) {
8640    var pair = vars[i].split('=');
8641    if (pair[0] && pair[1]) {
8642      obj[pair[0]] = decodeURIComponent(pair[1]);
8643    }
8644  }
8645
8646  return obj;
8647}
8648
8649function generateCBOTURL(url) {
8650  let fields = [
8651    { key: "cbot_dynamic_id", value: cbot_dynamic_id }
8652  ];
8653  if (url.indexOf("?") == -1) {
8654    return url + "?" + fields.map(x => x.key + "=" + x.value).join("&");
8655  } else {
8656    return url + "&" + fields.map(x => x.key + "=" + x.value).join("&");
8657  }
8658}
8659
8660function loadDataOwl() {
8661  var jqueryScript = document.createElement('script');
8662  jqueryScript.type = "text/javascript";
8663  jqueryScript.src = staticAddress + "/js/owl.carousel.min.js" + "?client=" + CLIENT;
8664  jqueryScript.async = true;
8665  document.getElementsByTagName('head')[0].insertBefore(jqueryScript, document.getElementsByTagName('head')[0].firstChild);
8666}
8667
8668
8669function getCustomHeaders(replace) {
8670
8671  clients.gateway_custom_headers = (clients.gateway_custom_headers || []).filter(function (header) {
8672    header.value = header.value.replace(/\$\{([a-zA-Z_ÇÖĞŞÜİçöğşüı\-]+)\}/g, function (fullmatch, match) {
8673      if (data_script_qs[match]) {
8674        return data_script_qs[match]
8675      } else if (document.getElementById(match)) {
8676        if (document.getElementById(match).value) {
8677          return document.getElementById(match).value;
8678        } else {
8679          return replace ? "" : fullmatch;
8680        }
8681      } else {
8682        return replace ? "" : fullmatch;
8683      }
8684
8685    });
8686    if (replace) { checkAuthHeader(); }
8687    return !!header.value;
8688  })
8689}
8690
8691function checkAuthHeader() {
8692  var cbotUserChanged = clients.gateway_custom_headers.find(function (header) {
8693    return header.key == "cbot-userchanged";
8694  }) || {};
8695
8696  if (cbotUserChanged.value == true || cbotUserChanged.value == "true" || data_clear_session == "true") {
8697    setSessionIdTLS(null);
8698    setUserIdTLS(null);
8699    isLive = setIsLive(false);
8700    setisLiveTLS(isLive);
8701    // setAuthHeaderTLS(authHeader.value);
8702  }
8703
8704  var authHeader = clients.gateway_custom_headers.find(function (header) {
8705    return (header.key || "").toLowerCase() == "authorization";
8706  }) || {};
8707
8708  if (!authHeader || !(authHeader.value || "").trim()) {
8709    setLastMessageTLS([]);
8710  }
8711
8712
8713}
8714
8715function getUrlTarget(url, channel) {
8716  channel = (channel == "WIDGET" ? "DEFAULT" : channel) || "DEFAULT";
8717  return ((clients.link_list || {})[channel] || []).find(function (x) {
8718    return url.includes(x);
8719  }) == null ? "_blank" : "_self";
8720}
8721
8722function getChannelValue(value, channel) {
8723  channel = (channel == "WIDGET" ? "DEFAULT" : channel) || "DEFAULT";
8724  return (value || {})[channel];
8725}
8726
8727function checkChannelName(value = "", channel) {
8728  channel = (channel == "WIDGET" ? "DEFAULT" : channel) || "DEFAULT";
8729  return value.indexOf(channel) !== -1;
8730}
8731
8732function checkPageTransition() {
8733  if (previousURL !== currentURL) {
8734    return false;
8735  } else {
8736    return true;
8737  }
8738}
8739
8740
8741function hideMessageArea() {
8742  cbotShowMessageArea = "hide"
8743  $(".cbot-form-message-area").css("display", "none");
8744  $(".cbot-chat").css("height", "calc(100% - 75px)");
8745  scrollChatScreen(300);
8746
8747}
8748function showMessageArea() {
8749  cbotShowMessageArea = "show"
8750  $(".cbot-form-message-area").css("display", "block");
8751  $(".cbot-chat").css({ height: '' });
8752
8753  scrollChatScreen(300);
8754}
8755
8756function handleMessageArea() {
8757
8758  if (clients.button_mode) {
8759    hideMessageArea();
8760
8761    if (isLive) {
8762      showMessageArea();
8763    }
8764  }
8765}
8766
8767function renderPostMessageButton(urlData, title, component) {
8768  if (!component) component = ""
8769  var comp = "";
8770  if (/list/i.test(component)) {
8771    comp = "cbot-list-item-button"
8772  }
8773  let html = "";
8774  if (typeof urlData === "object") {
8775    html += `<a onclick="sendPostMessage(${JSON.stringify(urlData).replace(/'/g, '&apos;').replace(/"/g, '&quot;')})" style="cursor:pointer"><div class="cbot-button">${title}</div></a>`;
8776  } else if (typeof urlData === "string") {
8777    const target = getUrlTarget(urlData, CHANNEL)
8778    html += '<a ontouchstart="" href="' + urlData + '" target="' + target + '" class="cbot-button ' + comp + triple_button_class + text_button_class + '" style="' + suggestion_button_style + triple_button_css + '" onclick="clickTheURLs(this)">' + title + '</a>';
8779  }
8780  return html;
8781}
8782
8783function sendPostMessage(urlData) {
8784  window.postMessage(JSON.stringify(urlData), getAddr());
8785
8786  if (window.ReactNativeWebView) {
8787    window.ReactNativeWebView.postMessage(JSON.stringify(urlData));
8788  }
8789}
8790
8791function scrollChatScreen(time) {
8792  // console.log("Scrolling is started")
8793  setTimeout(function () {
8794
8795    $("#cbot-chat").stop().animate({ scrollTop: $('#cbot-chat').prop("scrollHeight") }, 1, function () {
8796      // console.log("Scrolling is DONE!");
8797    });
8798  }, time);
8799}
8800
8801function scrollMessageBox(time) {
8802  // console.log("Scrolling is started")
8803  setTimeout(function () {
8804    $("#cbot-form-message").stop().animate({ scrollTop: $('#cbot-form-message').prop("scrollHeight") }, 1, function () {
8805    });
8806  }, time);
8807}
8808
8809function cbotShowHelpTextMenu() {
8810  $(".cbot-dialog-head").fadeOut();
8811  $("#cbot-help").fadeIn(0, function () {
8812    // fadeIn animasyonu tamamlandığında çalışacak kod
8813    $(".cbot-dialog-sozlesme").fadeIn(0);
8814    $("#cbot-help").addClass("active");
8815    $(".cbot-head-cover").addClass("active");
8816  })
8817  // slideIn(elCbotHelp);
8818  $(".cbot-form-message-area").css("display", "none");
8819}
8820function cbotHideHelpTextMenu() {
8821
8822  $(".cbot-dialog-head").fadeIn(0);
8823  $("#cbot-help").fadeOut(100, function () {
8824    // fadeIn animasyonu tamamlandığında çalışacak kod
8825    $(".cbot-dialog-sozlesme").fadeOut(0);
8826    $("#cbot-help").removeClass("active");
8827    $(".cbot-head-cover").removeClass("active");
8828  })
8829  // slideOut(elCbotHelp);
8830  if (cbotShowMessageArea == "show")
8831    $(".cbot-form-message-area").css("display", "block");
8832}
8833
8834
8835// #1510
8836function cbotHelpTextToDialog(message) {
8837
8838  cbotHideHelpTextMenu();
8839  dialog(cbotUserId, message, function () { });
8840}
8841
8842
8843
8844
8845function getUserIDFLS() {
8846  var cbotUserId = localStorage[getDynamicLSName("userid")];
8847
8848  return cbotUserId
8849}
8850
8851function getUserIDName() {
8852  if (clients.is_dynamic_user_id) {
8853    return "cbot-" + CLIENT + '-' + CHANNEL + '-userid';
8854  }
8855  return "cbot-" + CLIENT + '-userid'
8856}
8857
8858function getDynamicLSName(lsName, change_by_channel = true) {
8859  if (clients.is_dynamic_user_id && change_by_channel) {
8860    return "cbot-" + CLIENT + '-' + (cbot_dynamic_id || CHANNEL) + '-' + lsName;
8861  }
8862  return "cbot-" + CLIENT + '-' + lsName
8863}
8864
8865function isJSON(data) {
8866  try {
8867    JSON.parse(data)
8868    return true;
8869  } catch (error) {
8870    return false;
8871  }
8872}
8873
8874function socket_reconnect() {
8875  if (LIVE_CHAT) {
8876    var reconnectInterval = setInterval(function () {
8877      if (window.io && cbotSessionId && cbotUserId) {
8878        if (!socket.connected) {
8879          if (isLive) {
8880            if (is_liveagent_typed) {
8881              toggleCloseChatButton("block");
8882            }
8883          }
8884          socket = io.connect(soc_connect, {
8885            transports: ["websocket"], secure: true, upgrade: false, auth: {
8886              session_id: cbotSessionId,
8887              user_id: cbotUserId
8888            },
8889            autoConnect: false
8890          });
8891          socket.on('connect', function () {
8892            clearLostConnectionMsg();
8893            retryConnection = false;
8894            var reNewClientInterval = setInterval(function () {
8895              if (cbotUserId && cbotSessionId && isLive) {
8896                socket.emit('new_client', { userId: cbotUserId, sessionId: cbotSessionId });
8897                clearInterval(reNewClientInterval);
8898              }
8899            }, 500);
8900
8901          });
8902          socket_connection_widget();
8903          soc_cli_data();
8904          soc_survey();
8905          soc_stop();
8906          soc_client_typing();
8907          socket_alert();
8908          socket_delete_message();
8909          soc_transfer_agent();
8910          soc_error();
8911          clearInterval(reconnectInterval);
8912          soc_queue_data();
8913        }
8914      }
8915    }, 1000);
8916  }
8917}
8918
8919/**
8920 * Bu bölüm socket'in autoConnect fonksiyonunun logic problemlere sebep olması
8921 * nedeniyle eklenmiştir.
8922 * Bu bölümün çalışması için socket connection alanına autoConnect: false eklenmiştir.
8923 */
8924/* setInterval(() => {
8925  console.log("IS SOCKET CONNECTED?", (socket || {}).connected);
8926}, 1000) */
8927
8928let retryConnection = false;
8929setInterval(() => {
8930  // Timeout'tan sonra bağlantı koparsa tekrar bağlanmamak için (cbotSessionId && cbotUserId) kontrolü eklendi.
8931  if (socket && !socket.connected && (isLive || SOCKET_CONNECT_ON_START) && !retryConnection && cbotSessionId && cbotUserId) {
8932    retryConnection = true;
8933    socket.auth = { session_id: cbotSessionId, user_id: cbotUserId };
8934    socket.io.opts.auth = { session_id: cbotSessionId, user_id: cbotUserId };
8935    socket.connect();
8936  }
8937}, 1000);
8938
8939function soc_error() {
8940  if (LIVE_CHAT) {
8941    socket.on('connect_error', function (error) {
8942      console.log('connect_error => ', error);
8943      retryConnection = false;
8944      if (error.data && error.data.type === "authentication_error") {
8945        if (isLive) {
8946          agentId = null;
8947          cbotClearUserDialog(true);
8948          clearSurveyTimeout();
8949          setTimeout(() => {
8950            var msg = WIDGET_NETWORK_ERROR_MESSAGE
8951            showNotification(cbot_config.dialogTitle, msg);
8952            appendMessageToDialogBox(msg, "cbot-other", "", {}, function () { });
8953          }, 500);
8954          socket_reconnect();
8955        } else if (SOCKET_CONNECT_ON_START) {
8956          socket_reconnect();
8957        }
8958      }
8959    });
8960    socket.on('disconnect', function (reason) {
8961      sendCustomPostMessage("CBOT_WEBSOCKET_DISCONNECTED", {});
8962      console.log('disconnect=> ', reason);
8963      if (reason === "io server disconnect") {
8964        // the disconnection was initiated by the server, you need to reconnect manually
8965        socket.connect();
8966      } else if (reason === "ping timeout") {
8967        if (isLive) {
8968          triggerLostConnectionMsg();
8969          console.log('disconnect => ', "ping timeout");
8970        }
8971        //The server did not send a PING within the pingInterval + pingTimeout range
8972      } else if (reason === "transport close") {
8973        if (isLive) {
8974          console.log('disconnect => ', "transport close");
8975          triggerLostConnectionMsg();
8976        }
8977        // The connection was closed (example: the user has lost connection, or the network was changed from WiFi to 4G)
8978      } else if (reason === "transport error") {
8979        if (isLive) {
8980          console.log('disconnect => ', "transport error");
8981          triggerLostConnectionMsg();
8982        }
8983        // The connection has encountered an error (example: the server was killed during a HTTP long-polling cycle)
8984      }
8985      // else the socket will automatically try to reconnect
8986      //reasonlists ping timeout,transport close,transport error
8987      //
8988    })
8989  }
8990}
8991function socketHandshake() {
8992  if (LIVE_CHAT && socket) {
8993    if (!socket.connected && !isLive) {
8994      socket.auth = {
8995        session_id: cbotSessionId,
8996        user_id: cbotUserId
8997      }
8998      socket.io.opts.auth = {
8999        session_id: cbotSessionId,
9000        user_id: cbotUserId
9001      }
9002      socket.connect();
9003    }
9004  }
9005}
9006
9007function viewVoiceButton() {
9008  if (voice_bot_button_option) {
9009    var message_length = $('#cbot-form-message').val().trim().length;
9010    if (message_length > 0) {
9011      $(".cbot-send-button").css("display", "block");
9012      $(".cbot-voice-area").css("display", "none");
9013    } else {
9014      // $(".cbot-send-button").css("display", "none");
9015      $(".cbot-voice-area").css("display", "block");
9016    }
9017  }
9018}
9019
9020
9021var connection_msg_id = null
9022window.addEventListener('online', function () {
9023  clearLostConnectionMsg();
9024  showMessageArea();
9025  stopLoading();
9026});
9027window.addEventListener('offline', function () {
9028  triggerLostConnectionMsg();
9029  hideMessageArea();
9030  startLoading();
9031});
9032function triggerLostConnectionMsg() {
9033  if (!connection_msg_id) {
9034    connection_msg_id = (new Date()).getTime();
9035  }
9036  var connectionMsgElement = document.querySelector(`[data-message-id="${connection_msg_id}"]`);
9037  if (!connectionMsgElement) {
9038    var msg = WIDGET_NETWORK_ERROR_MESSAGE
9039    showNotification(cbot_config.dialogTitle, msg);
9040    var msg_data = {
9041      message: msg,
9042      message_type: 'TEXT',
9043      message_id: connection_msg_id
9044    }
9045    appendMessageToDialogBox(msg_data, "cbot-other", "", {}, function () { });
9046  }
9047}
9048
9049function clearLostConnectionMsg() {
9050  var connectionMsgElement = document.querySelector(`[data-message-id="${connection_msg_id}"]`);
9051  if (connectionMsgElement) {
9052    connectionMsgElement.remove();
9053  }
9054  connection_msg_id = null;
9055}
9056
9057function startLoading() {
9058  $('.cbot-spinner-overlay').css('display', 'flex')
9059  $('.cbot-spinner').css('display', 'block')
9060}
9061function stopLoading() {
9062  $('.cbot-spinner-overlay').css('display', 'none')
9063  $('.cbot-spinner').css('display', 'none')
9064}
9065
9066
9067            function initRecorder() {}
9068            function startRecording() {}
9069            
9070
9071            function webkitTTS() {}
9072            function cancelTTS() {}
9073            
9074
9075function messageCleanerForSpeech(message) {
9076  if (botlanguage == 'ar') {
9077    return message.replace(/\//g, '');
9078  }
9079  return message;
9080}
9081
9082// Interaktif bilgi toplayıcı
9083const interactive_class = {
9084  getWeekNumber: (date = new Date()) => {
9085    const d = new Date(date);
9086    const yearStart = new Date(d.getFullYear(), 0, 1);
9087    const dayCount = Math.floor((d - yearStart) / (24 * 60 * 60 * 1000));
9088    const weekNumber = Math.ceil((dayCount + yearStart.getDay() + 1) / 7);
9089    return weekNumber;
9090  },
9091  getDayOfMonth: (date = new Date()) => {
9092    const currentDate = new Date(date);
9093    const dayOfMonth = currentDate.getDate();
9094    return dayOfMonth;
9095  },
9096  getDayName: (date = new Date()) => {
9097    let days = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
9098    const currentDate = new Date(date);
9099    const day = currentDate.getDay();
9100    return days[day];
9101  },
9102  getDayIndexOfWeek: (date = new Date()) => {
9103    let daymap = [7, 1, 2, 3, 4, 5, 6]
9104    return daymap[new Date(date).getDay()];
9105  },
9106  getMonth: (date = new Date()) => {
9107    const currentDate = new Date(date);
9108    return currentDate.getMonth();
9109  },
9110  getMonthName: (date = new Date()) => {
9111    let days = ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"];
9112    const currentDate = new Date(date);
9113    const dayOfMonth = currentDate.getMonth();
9114    return days[dayOfMonth];
9115  },
9116  isWeekday: (date = new Date()) => {
9117    const currentDate = new Date(date);
9118    const dayOfWeek = currentDate.getDay();
9119    return dayOfWeek >= 1 && dayOfWeek <= 5;
9120  },
9121  getTimeOfDay(date = new Date()) {
9122    const currentDate = new Date(date);
9123    const currentHour = currentDate.getHours();
9124    if (currentHour >= 5 && currentHour < 12) {
9125      return "morning";
9126    } else if (currentHour >= 12 && currentHour < 17) {
9127      return "afternoon";
9128    } else if (currentHour >= 17 && currentHour < 20) {
9129      return "evening";
9130    } else {
9131      return "night";
9132    }
9133  },
9134  generateStats: (date = new Date()) => {
9135    return {
9136      date: new Date(date).getTime(),
9137      monthNumber: interactive_class.getMonth() + 1,
9138      weekNumber: interactive_class.getWeekNumber(),
9139      dayNumber: interactive_class.getDayOfMonth(),
9140      dayIndexOfWeek: interactive_class.getDayIndexOfWeek(),
9141      month: interactive_class.getMonthName(),
9142      day: interactive_class.getDayName(),
9143      daylight: interactive_class.getTimeOfDay(),
9144      isWeekDay: interactive_class.isWeekday(),
9145    }
9146  },
9147  setStats: () => {
9148    localStorage.setItem(getDynamicLSName("interactive_stats"), JSON.stringify(interactive_class.generateStats()));
9149  },
9150
9151  getStats: () => {
9152    return JSON.parse(localStorage.getItem(getDynamicLSName("interactive_stats")))
9153  },
9154
9155  recommend: () => {
9156    let history = interactive_class.getStats();
9157    let current_stats = interactive_class.generateStats();
9158    let turnback = {
9159      first_time_in_this_month: true,
9160      first_time_in_this_week: true,
9161      first_time_in_this_day: true
9162    }
9163    if (history) {
9164      turnback.delta = {
9165        as_minutes: (current_stats.date - history.date) / (1000 * 60),
9166        as_hours: (current_stats.date - history.date) / (1000 * 60 * 60),
9167        as_days: (current_stats.date - history.date) / (1000 * 60 * 60 * 24),
9168        as_week: (current_stats.date - history.date) / (1000 * 60 * 60 * 24 * 7),
9169        as_month: (current_stats.date - history.date) / (1000 * 60 * 60 * 24 * 30),
9170      }
9171      turnback.diff_as_month = current_stats.monthNumber - history.monthNumber;
9172      turnback.diff_as_week = current_stats.weekNumber - history.weekNumber;
9173      turnback.diff_as_day = current_stats.dayNumber - history.dayNumber;
9174      turnback.is_same_month = current_stats.month == history.month;
9175      turnback.is_same_week = current_stats.weekNumber == history.weekNumber;
9176      turnback.is_same_day_of_month = current_stats.dayNumber == history.dayNumber;
9177      turnback.is_same_day_of_week = current_stats.day == history.day;
9178      turnback.is_same_daylight = current_stats.daylight == history.daylight;
9179      turnback.first_time_in_this_month = turnback.diff_as_month > 0
9180      turnback.first_time_in_this_week = turnback.diff_as_week > 0
9181      turnback.first_time_in_this_day = turnback.diff_as_day > 0
9182    }
9183    return {
9184      current_stats,
9185      recommends: turnback
9186    }
9187  }
9188}
9189
9190const interactive_actions_executer = {
9191  checkOpenWidget: () => {
9192    let res = false;
9193    if (interactive_actions && interactive_actions.open_widget && Array.isArray(interactive_actions.open_widget) && interactive_actions.open_widget.length > 0) {
9194      for (let i = 0; i < interactive_actions.open_widget.length; i++) {
9195        const action = interactive_actions.open_widget[i];
9196        const state = interactive_recommends.recommends[action.behaviour];
9197        if (action.operator == 'equal') {
9198          res = `${state}` == action.equity
9199        } else if (action.operator == 'not_equal') {
9200          res = `${state}` != action.equity
9201        }
9202        if (res) break;
9203      }
9204    }
9205    return res;
9206  },
9207  checkDisplayPopup: () => {
9208    let res = false;
9209    let popups = [];
9210    let visitorDataCurrent, count;
9211    let visitCountAdded = false;
9212
9213    if (interactive_actions) {
9214      if (interactive_actions.display_popup && Array.isArray(interactive_actions.display_popup) && interactive_actions.display_popup.length > 0) {
9215        for (let i = 0; i < interactive_actions.display_popup.length; i++) {
9216          const action = interactive_actions.display_popup[i];
9217          if (checkChannelName(action.channels, CHANNEL)) {
9218            if (action.behaviour == "site_urls") {
9219              let current_site = window.location.href.split("?")[0];
9220              let signed_sites = action.equity.map(x => x.value);
9221              visitor_countable = action.visitor_countable
9222              if (visitor_countable) count = action.visitor_count
9223              if (visitor_countable && !visitCountAdded) {
9224                refreshvisitcount()
9225                addvisitcount(current_site)
9226                visitCountAdded = true
9227              }
9228              is_schedule = action.is_schedule
9229              if (action.operator.toLowerCase() == "equal") {
9230                if (signed_sites.includes(current_site)) {
9231                  if (visitor_countable) {
9232                    if (localStorage.getItem(getDynamicLSName("visitcount"))) {
9233                      visitorDataCurrent = JSON.parse(localStorage.getItem(getDynamicLSName("visitcount")));
9234                      if (visitorDataCurrent[current_site] && visitorDataCurrent[current_site].count && count) {
9235                        if (visitorDataCurrent[current_site].count == count) {
9236                          if (is_schedule) {
9237                            let currentDate = new Date();
9238                            let startDate = new Date(action?.start_date);
9239                            let endDate = new Date(action?.end_date);
9240
9241                            if (currentDate >= startDate && currentDate <= endDate) {
9242                              res = true;
9243                              popups.push(action.popup);
9244                            }
9245                          } else {
9246                            res = true;
9247                            popups.push(action.popup);
9248                          }
9249                        }
9250                      }
9251                    }
9252                  }
9253                  else if (is_schedule) {
9254                    let currentDate = new Date();
9255                    let startDate = new Date(action?.start_date);
9256                    let endDate = new Date(action?.end_date);
9257
9258                    if (currentDate >= startDate && currentDate <= endDate) {
9259                      res = true;
9260                      popups.push(action.popup);
9261                    }
9262                  } else {
9263                    res = true;
9264                    popups.push(action.popup);
9265                  }
9266                }
9267              } else if (action.operator.toLowerCase() == "greater_than") {
9268                if (!signed_sites.includes(current_site) && signed_sites.some(site => current_site.startsWith(site) && current_site !== site)) {
9269                  if (visitor_countable) {
9270                    if (localStorage.getItem(getDynamicLSName("visitcount"))) {
9271                      visitorDataCurrent = JSON.parse(localStorage.getItem(getDynamicLSName("visitcount")));
9272                      if (visitorDataCurrent[current_site] && visitorDataCurrent[current_site].count && count) {
9273                        if (visitorDataCurrent[current_site].count == count) {
9274                          if (is_schedule) {
9275                            let currentDate = new Date();
9276                            let startDate = new Date(action?.start_date);
9277                            let endDate = new Date(action?.end_date);
9278
9279                            if (currentDate >= startDate && currentDate <= endDate) {
9280                              res = true;
9281                              popups.push(action.popup);
9282                            }
9283                          } else {
9284                            res = true;
9285                            popups.push(action.popup);
9286                          }
9287                        }
9288                      }
9289                    }
9290                  }
9291                  else if (is_schedule) {
9292                    let currentDate = new Date();
9293                    let startDate = new Date(action?.start_date);
9294                    let endDate = new Date(action?.end_date);
9295
9296                    if (currentDate >= startDate && currentDate <= endDate) {
9297                      res = true;
9298                      popups.push(action.popup);
9299                    }
9300                  } else {
9301                    res = true;
9302                    popups.push(action.popup);
9303                  }
9304                }
9305              } else if (action.operator.toLowerCase() == "greater_than_or_equal") {
9306                if (signed_sites.some(site => current_site.startsWith(site))) {
9307                  if (visitor_countable) {
9308                    if (localStorage.getItem(getDynamicLSName("visitcount"))) {
9309                      visitorDataCurrent = JSON.parse(localStorage.getItem(getDynamicLSName("visitcount")));
9310                      if (visitorDataCurrent[current_site] && visitorDataCurrent[current_site].count && count) {
9311                        if (visitorDataCurrent[current_site].count == count) {
9312                          if (is_schedule) {
9313                            let currentDate = new Date();
9314                            let startDate = new Date(action?.start_date);
9315                            let endDate = new Date(action?.end_date);
9316
9317                            if (currentDate >= startDate && currentDate <= endDate) {
9318                              res = true;
9319                              popups.push(action.popup);
9320                            }
9321                          } else {
9322                            res = true;
9323                            popups.push(action.popup);
9324                          }
9325                        }
9326                      }
9327                    }
9328                  }
9329                  else if (is_schedule) {
9330                    let currentDate = new Date();
9331                    let startDate = new Date(action?.start_date);
9332                    let endDate = new Date(action?.end_date);
9333
9334                    if (currentDate >= startDate && currentDate <= endDate) {
9335                      res = true;
9336                      popups.push(action.popup);
9337                    }
9338                  } else {
9339                    res = true;
9340                    popups.push(action.popup);
9341                  }
9342                }
9343              } else if (action.operator.toLowerCase() == "not_equal") {
9344                if (!signed_sites.includes(current_site)) {
9345                  if (visitor_countable) {
9346                    if (localStorage.getItem(getDynamicLSName("visitcount"))) {
9347                      visitorDataCurrent = JSON.parse(localStorage.getItem(getDynamicLSName("visitcount")));
9348                      if (visitorDataCurrent[current_site] && visitorDataCurrent[current_site].count && count) {
9349                        if (visitorDataCurrent[current_site].count == count) {
9350                          if (is_schedule) {
9351                            let currentDate = new Date();
9352                            let startDate = new Date(action?.start_date);
9353                            let endDate = new Date(action?.end_date);
9354
9355                            if (currentDate >= startDate && currentDate <= endDate) {
9356                              res = true;
9357                              popups.push(action.popup);
9358                            }
9359                          } else {
9360                            res = true;
9361                            popups.push(action.popup);
9362                          }
9363                        }
9364                      }
9365                    }
9366                  }
9367                  else if (is_schedule) {
9368                    let currentDate = new Date();
9369                    let startDate = new Date(action?.start_date);
9370                    let endDate = new Date(action?.end_date);
9371
9372                    if (currentDate >= startDate && currentDate <= endDate) {
9373                      res = true;
9374                      popups.push(action.popup);
9375                    }
9376                  } else {
9377                    res = true;
9378                    popups.push(action.popup);
9379                  }
9380                }
9381              }
9382            }
9383          }
9384        }
9385      }
9386    }
9387    return { res, popups };
9388  },
9389  checkTakeAttention: () => {
9390    let status = false;
9391    let trigger_message;
9392    let delay;
9393    if (interactive_actions) {
9394      if (interactive_actions.take_attention && Array.isArray(interactive_actions.take_attention) && interactive_actions.take_attention.length > 0) {
9395        for (let i = 0; i < interactive_actions.take_attention.length; i++) {
9396          const action = interactive_actions.take_attention[i];
9397          if (checkChannelName(action.channels, CHANNEL)) {
9398            if (action.behaviour == "site_urls") {
9399              let current_site = window.location.href.split("?")[0];
9400              let signed_sites = action.equity.map(x => x.value);
9401              if (action.operator.toLowerCase() == "equal") {
9402                if (signed_sites.includes(current_site)) {
9403                  status = true;
9404                  trigger_message = action.trigger_message;
9405                  delay = action.delay;
9406                  break;
9407                }
9408              } else if (action.operator.toLowerCase() == "not_equal") {
9409                if (!signed_sites.includes(current_site)) {
9410                  status = true;
9411                  trigger_message = action.trigger_message;
9412                  delay = action.delay;
9413                  break;
9414                }
9415              }
9416            }
9417          }
9418        }
9419      }
9420    }
9421    return { status, trigger_message, delay };
9422  }
9423}
9424function addvisitcount(URL) {
9425  let visitorData = {};
9426  const now = new Date();
9427
9428  if (localStorage.getItem(getDynamicLSName("visitcount"))) {
9429    visitorData = JSON.parse(localStorage.getItem(getDynamicLSName("visitcount")));
9430  }
9431  if (visitorData[URL]) {
9432    visitorData[URL] = { count: visitorData[URL].count + 1, addedTime: now.getTime() };
9433  } else {
9434    visitorData[URL] = { count: 1, addedTime: now.getTime() };
9435  }
9436
9437  localStorage.setItem(getDynamicLSName("visitcount"), JSON.stringify(visitorData));
9438}
9439
9440function refreshvisitcount() {
9441  let visitorData = {};
9442  const now = new Date();
9443  const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1).getTime();
9444
9445  if (localStorage.getItem(getDynamicLSName("visitcount"))) {
9446    visitorData = JSON.parse(localStorage.getItem(getDynamicLSName("visitcount")));
9447  }
9448
9449  for (const key in visitorData) {
9450    if (visitorData[key].addedTime < midnight - 24 * 60 * 60 * 1000) {
9451      delete visitorData[key];
9452    }
9453  }
9454
9455  localStorage.setItem(getDynamicLSName("visitcount"), JSON.stringify(visitorData));
9456}
9457
9458function disableUserMessageArea(chat_end_message = "Görüşme sonlandırılmıştır. 👋") {
9459  user_chat_input_state = user_chat_input_states.DISABLED;
9460  $(".cbot-form-message-area").addClass("disabled-background");
9461  $(".cbot-illusion-placeholder").addClass("disabled-illussion");
9462  $(".cbot-send-button").css("pointer-events", "none")
9463  disablePostbackButtons()
9464  $('.cbot-send-button').css("display", "block");
9465  viewVoiceButton()
9466  $("#cbot-attachment-area").css("display", "none");
9467  $("#cbot-send-button").css("display", "none")
9468  document.getElementById("cbot-form-message").disabled = true;
9469  document.getElementById("cbot-form-message").placeholder = "";
9470  document.getElementById("cbot-send-button").disabled = true;
9471  document.getElementById("cbot-illusion-placeholder").innerText = chat_end_message;
9472  $('#cbot-form-message').blur()
9473  sendCustomPostMessage("CBOT_CHAT_CAN_BE_POPPED", {});
9474}
9475
9476function enableUserMessageArea() {
9477  if (user_chat_input_state == user_chat_input_states.DISABLED) {
9478    $(".cbot-send-button").css("pointer-events", "unset")
9479    $(".cbot-form-message-area").removeClass("disabled-background");
9480    $(".cbot-illusion-placeholder").removeClass("disabled-illussion");
9481    $("#cbot-send-button").css("display", "block")
9482    document.getElementById("cbot-form-message").disabled = false;
9483    document.getElementById("cbot-send-button").disabled = false;
9484    $(".cbot-illusion-placeholder").html(lang_vars.LANGVARS_PLACEHOLDER_MESSAGE);
9485    user_chat_input_state = user_chat_input_states.ENABLED;
9486  }
9487}
9488
9489function cbotCloseIcon() {
9490  sendCustomPostMessage("CBOT_WIDGET_CLOSED", {});
9491
9492  if (isLive && getChannelValue(clients.leave_livechat_after_close_bot, CHANNEL)) {
9493    closeLivechat(() => {
9494      showExitSurvey();
9495    }, "customer");
9496    if (isExitSurveyExists()) {
9497      setCloseIconPressed();
9498      return;
9499    }
9500
9501  } else if (isExitSurveyExists()) {
9502    showExitSurvey();
9503    setCloseIconPressed();
9504    return;
9505  }
9506  setIsWidgetOpenedTLS(false);
9507  isWidgetOpen = false;
9508  if (!data_full_page && elCbotDialogRegularButton) { // Full page açıldığı zaman kapama özelliği olmamalı
9509    fadeIn(elCbotDialogRegularButton);
9510    fadeOut(elCbotDialog);
9511  }
9512  $(".cbot-dialog-button-regular").removeClass("cbot-slide-right")
9513  $(".cbot-dialog-button-regular").removeClass("cbot-slide-left")
9514
9515  document.getElementById("cbot-overlay-background").style.display = "none";
9516
9517  if (clients.slide_from_left)
9518    $(".cbot-dialog-button-regular").css("left", "20px");
9519
9520
9521
9522  if (getChannelValue(clients.clear_after_close_bot, CHANNEL)) {
9523    queryStringVars.cbot_repeat = false;
9524    trigger_messages_count = 0;
9525    sendToEndChat();
9526    reset(true);
9527    
9528    USER_LOGGING_OUT_FLAG = false;
9529    cbotClearUserDialog(true);
9530    cbotSessionId = null;
9531    setSessionIdTLS(cbotSessionId);
9532    isLive = setIsLive(false);
9533    setisLiveTLS(isLive);
9534    agentId = null;
9535    agent_name = null;
9536    clearLastMessageSentDateTLS();
9537    welcomeMessageSent = false;
9538    firstLoad = false;
9539    trigger_messages_count = 0;
9540    pendingUpdateDataUserMessage = null;
9541
9542    sendCustomPostMessage("CBOT_CHAT_CAN_BE_POPPED", {});
9543    $(".cbot-livechat-started").css("display", "none");
9544    if (clients.closing_popup_is_active && !hasSurveyShowAsPopUp) {
9545      $(".cbot-dialog-button-help-message").text(clients.closing_popup_text || "Güle Güle");
9546      if (!isWidgetOpen) {
9547        $(".cbot-dialog-button-help-message").css("display", "flex");
9548        $(".cbot-dialog-button-help-message").stop().animate({ opacity: 1 }, 400, function () {
9549
9550        });
9551        $(".cbot-dialog-button-help-message").fadeIn();
9552        closing_popup_is_showing = true
9553
9554      }
9555      setTimeout(function () {
9556        $(".cbot-dialog-button-help-message").fadeOut(() => {
9557          closing_popup_is_showing = false
9558          var popup_msg = clients.popup_text || 'Ben kişisel asistanınız ' + clients.bot_name + ',  size nasıl yardımcı olabilirim?'
9559          $(".cbot-dialog-button-help-message").text(popup_msg);
9560        });
9561      }, parseInt((clients.closing_popup_show_time || 3) * 1000)); // POC-55 // POC-71
9562    }
9563  }
9564
9565}
9566
9567function cbotRefreshIcon() {
9568  var keepUserId = !getChannelValue(clients.reset_client_on_refresh, CHANNEL);
9569  refresh_button_clicked = true;
9570  enableUserMessageArea();
9571  if (isLive) {
9572    closeLivechat(function () {
9573      lastMessageReceiveDate = Date.now();
9574      resetSocketOnRefresh();
9575      cbotClearUserDialog(true, keepUserId);
9576      trigger_messages_count = 0;
9577      sendTriggerMessages(trigger_messages, '_refresh');
9578    });
9579  } else {
9580    lastMessageReceiveDate = Date.now();
9581    resetSocketOnRefresh();
9582    cbotClearUserDialog(true, keepUserId);
9583    trigger_messages_count = 0;
9584    sendTriggerMessages(trigger_messages, '_refresh');
9585  }
9586}
9587
9588function resetSocketOnRefresh() {
9589  if (!getChannelValue(clients.reset_client_on_refresh, CHANNEL) || !socket) {
9590    return;
9591  }
9592
9593  try {
9594    if (typeof socket.removeAllListeners === "function") {
9595      socket.removeAllListeners();
9596    }
9597
9598    if (typeof socket.disconnect === "function") {
9599      socket.disconnect();
9600    }
9601  } catch (error) {
9602    console.warn("resetSocketOnRefresh", error);
9603  } finally {
9604    socket = null;
9605  }
9606}
9607
9608
9609function detectBrowser() {
9610  if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
9611    return 'Opera';
9612  } else if (navigator.userAgent.indexOf("Edg") != -1) {
9613    return 'Edge';
9614  } else if (navigator.userAgent.indexOf("Chrome") != -1) {
9615    return 'Chrome';
9616  } else if (navigator.userAgent.indexOf("Safari") != -1) {
9617    return 'Safari';
9618  } else if (navigator.userAgent.indexOf("Firefox") != -1) {
9619    return 'Firefox';
9620  } else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) //IF IE > 10
9621  {
9622    return 'IE';
9623  } else {
9624    return undefined;
9625  }
9626}
9627
9628function initializeLottieAnimation(containerId, Url) {
9629  if (cbot_lottie_icon_activation) {
9630    var container = document.getElementById(containerId);
9631
9632    var animationUrl = resolveStaticLottieUrl(Url || `/firm-${CLIENT}/lottie/animation.json`);
9633
9634    if (animationUrl.endsWith('.lottie')) {
9635      var dotLottiePlayer = document.createElement("dotlottie-player");
9636      dotLottiePlayer.src = animationUrl;
9637      dotLottiePlayer.background = "transparent";
9638      dotLottiePlayer.speed = "1";
9639      dotLottiePlayer.setAttribute("loop", "");
9640      dotLottiePlayer.setAttribute("autoplay", "");
9641
9642      container.innerHTML = "";
9643      container.appendChild(dotLottiePlayer);
9644    } else {
9645      var lottiePlayer = document.createElement("lottie-player");
9646      lottiePlayer.src = animationUrl;
9647      lottiePlayer.background = "transparent";
9648      lottiePlayer.speed = "1";
9649      lottiePlayer.setAttribute("loop", "");
9650      lottiePlayer.setAttribute("autoplay", "");
9651      lottiePlayer.setAttribute("disableShadowDOM", "");
9652
9653      container.innerHTML = "";
9654      container.appendChild(lottiePlayer);
9655    }
9656
9657    /*dotLottiePlayer.addEventListener("loadeddata", function () {
9658        console.log("Lottie animation (.lottie) loaded successfully!");
9659    });
9660    dotLottiePlayer.addEventListener("error", function (e) {
9661        console.error("Lottie animation failed to load:", e);
9662    });*/
9663  }
9664}
9665
9666document.addEventListener("DOMContentLoaded", function () {
9667  sendCustomPostMessage("CBOT_DOM_CONTENT_LOADED", {});
9668});
9669
9670let pendingUpdateDataUserMessage;
9671window.addEventListener('message', event => {
9672  if (event && event.data?.action == 'EXTERNAL_CBOT_CLOSE_ICON' || event.data?.eventName == 'CBOT_CLOSE_WIDGET' || event.data?.action == 'CBOT_CLOSE_WIDGET') {
9673    cbotCloseIcon();
9674  }
9675
9676  if (event && (event.data?.action == 'UPDATE_DATA_USER' || event.data?.action == 'CBOT_UPDATE_DATA_USER')) {
9677    try {
9678      if (!event.data || !event.data.data_user) {
9679        pendingUpdateDataUserMessage = null;
9680        throw new Error('UPDATE_DATA_USER: Invalid event data or missing data_user');
9681      }
9682      data_user = event.data.data_user;
9683      if (event.data.message) {
9684        if (isWidgetOpen) {
9685          appendMessageToDialogBox(event.data.message, "cbot-other", null, {}, function () {
9686          });
9687        }
9688        else if (isSendTriggerMessage || isConversationHistoryFetched) {
9689          appendMessageToDialogBox(event.data.message, "cbot-other", null, {}, function () {
9690          });
9691        }
9692        else {
9693          newMsgCount++;
9694          toggleBadge(newMsgCount);
9695          pendingUpdateDataUserMessage = event.data.message;
9696        }
9697      }
9698    } catch (error) {
9699      pendingUpdateDataUserMessage = null;
9700      console.error('UPDATE_DATA_USER: Error updating user data', error);
9701    }
9702  }
9703
9704  if (event && event.data?.action == 'CBOT_USER_LOGGED_OUT') {
9705    cbotUserLoggedOutEvent();
9706  }
9707
9708  if (dark_mode_is_active) {
9709    if (event && (event.data?.action == 'dark_mode' || event.data?.action == 'light_mode')) {
9710      const action = event.data.action;
9711      const dialog = document.querySelector('.cbot-dialog');
9712
9713      if (!dialog) {
9714        return;
9715      }
9716
9717      const hasDarkClass = dialog.classList.contains('cbot-dark');
9718
9719      if (action === 'dark_mode' && hasDarkClass) {
9720        return;
9721      }
9722
9723      if (action === 'light_mode' && !hasDarkClass) {
9724        return;
9725      }
9726
9727      if (action === 'dark_mode') {
9728        cbotDarkModeToogle('dark');
9729      } else if (action === 'light_mode') {
9730        cbotDarkModeToogle('light');
9731      }
9732    }
9733  }
9734});
9735
9736function isButtonExist() {
9737  const lastCbotOther = $('li.cbot-other').last();
9738
9739  if (lastCbotOther.find('.cbot-button').length > 0) {
9740    return true;
9741  } else {
9742    return false;
9743  }
9744}
9745
9746function handlePopup(ia_display_popup_state, clients, cbot_config) {
9747  let appendHtmL = "";
9748
9749  handlePopupTimeouts.forEach(clearTimeout);
9750  handlePopupTimeouts = [];
9751
9752  function displayMessage(popup) {
9753    return new Promise((resolve) => {
9754      if (!isWidgetOpen) {
9755        $('.cbot-proactive-rule').not(".cbot-" + popup.rule_code).css('display', 'none');
9756        $(".cbot-dialog-button-regular").off("mouseenter mouseleave");
9757        $(".cbot-dialog-button-regular").off("hover");
9758        $(".cbot-" + popup.rule_code).off("mouseenter mouseleave");
9759        $(".cbot-" + popup.rule_code).off("hover");
9760        $(".cbot-" + popup.rule_code).css("opacity", "0");
9761        $(".cbot-" + popup.rule_code).css("display", "flex");
9762        $(".cbot-" + popup.rule_code).stop().animate({ opacity: 1 }, 400);
9763
9764        handlePopupTimeouts.push(setTimeout(() => {
9765          $(".cbot-" + popup.rule_code).stop().animate({ opacity: 1 }, 400, function () {
9766            $(".cbot-" + popup.rule_code).css("display", "none");
9767            $(".cbot-dialog-button-regular").off("mouseenter mouseleave");
9768            $(".cbot-dialog-button-regular").off("hover");
9769            resolve();
9770          });
9771        }, popup.duration * 1000)
9772        )
9773      }
9774    });
9775  }
9776
9777  function repeatDisplayMessage(times, delay, popup) {
9778    if (times !== 0) {
9779      handlePopupTimeouts.push(setTimeout(async () => {
9780        await displayMessage(popup);
9781        repeatDisplayMessage(times > 0 ? times - 1 : times, delay, popup);
9782      }, delay * 1000)
9783      )
9784    }
9785  }
9786
9787  function displayPopup(popup) {
9788    return new Promise((resolve) => {
9789      if (!isWidgetOpen) {
9790        $('.cbot-proactive-rule').not(".cbot-" + popup.rule_code).css('display', 'none');
9791        let container = document.getElementsByClassName("cbot-" + popup.rule_code)[0];
9792        let closed = document.createElement("div");
9793        closed.className = "cbot-join-chat-container-close";
9794        container.appendChild(closed);
9795        $(".cbot-" + popup.rule_code).css("display", "block");
9796        handlePopupTimeouts.push(setTimeout(() => {
9797          $(".cbot-" + popup.rule_code).css("display", "none");
9798          resolve();
9799        }, popup.duration * 1000)
9800        )
9801      }
9802    });
9803  }
9804
9805  function repeatDisplayPopup(times, delay, popup) {
9806    if (times !== 0) {
9807      handlePopupTimeouts.push(setTimeout(async () => {
9808        await displayPopup(popup);
9809        repeatDisplayPopup(times > 0 ? times - 1 : times, delay, popup);
9810      }, delay * 1000)
9811      )
9812    }
9813  }
9814
9815  function processShortTextPopup(popup) {
9816    var popup_message = popup.message;
9817    var popup_background_color = clients.popup_background_color || cbot_config.dialogButtonColor || "#000";
9818    var popup_text_color = clients.popup_text_color || cbot_config.title_font_color || "#FFF";
9819    var colors = "background: " + popup_background_color + "; color: " + popup_text_color + ";";
9820    var slidefromleftselected = "";
9821
9822    if (popup.convert_trigger_message) {
9823      trigger_messages = [popup_message];
9824    }
9825
9826    if (clients.slide_from_left) {
9827      slidefromleftselected += "; left: 40px; padding-left: 50px;";
9828    }
9829    if (popup.proactive_welcome_message && localStorage.getItem(getDynamicLSName("iswidgetopened")) != 'true') {
9830      appendHtmL += '' +
9831        `<div class="cbot-dialog-button-help-message cbot-proactive-rule cbot-${popup.rule_code}" onclick="openAndSendMessage('${popup_message}', true, new_welcome_message='${popup.proactive_welcome_message}')"` +
9832        `style="${colors + slidefromleftselected}; width:346px;padding-right: 45px; font-size: 16px;padding-top: 15px; padding-left: 0px; line-height: 1.5; text-align: center; word-break: break-word; overflow-wrap: break-word;"> <p class="cbot-popup-message">${popup_message}</p></div>`;
9833
9834    } else {
9835      appendHtmL += '' +
9836        '<div class="cbot-dialog-button-help-message cbot-proactive-rule cbot-' + popup.rule_code + '" onclick="openAndSendMessage(' + "'" + popup_message + "'" + ', true)"' +
9837        'style="' + colors + slidefromleftselected +
9838        '; width:346px;padding-right: 45px; font-size: 16px;padding-top: 15px; padding-left: 0px; line-height: 1.5; text-align: center; word-break: break-word; overflow-wrap: break-word;"> <p class="cbot-popup-message">' + popup_message + '</p></div>';
9839    }
9840    handlePopupTimeouts.push(setTimeout(async () => {
9841      await displayMessage(popup);
9842
9843      if (popup.show_again) {
9844        let showAgainTime = parseInt(popup.show_again_time, 10);
9845        let showAgainLoop = parseInt(popup.show_again_loop, 10);
9846
9847        if (!isNaN(showAgainTime)) {
9848          if (isNaN(showAgainLoop)) {
9849            repeatDisplayMessage(-1, showAgainTime, popup); // Sonsuz döngü
9850          } else if (showAgainLoop > 0) {
9851            repeatDisplayMessage(showAgainLoop, showAgainTime, popup);
9852          }
9853        }
9854      }
9855    }, popup.opening_delay * 1000)
9856    )
9857  }
9858
9859  function processRichContentPopup(popup) {
9860    appendHtmL += "<div class='cbot-join-chat-container cbot-proactive-rule cbot-" + popup.rule_code + "'>";
9861    appendHtmL += "<span class='cbot-join-chat-text'>" + popup.message + "</span>";
9862
9863    if (popup.image_url && popup.image_url.length > 0) {
9864      appendHtmL += "<img src='" + popup.image_url + "' class='cbot-join-chat-image'></img>";
9865    }
9866
9867    if (popup.buttons && popup.buttons.length > 0) {
9868      appendHtmL += '<div class="cbot-msg-custom-button rich_content">';
9869      appendHtmL += '<div class="cbot-buttons">';
9870      for (let i = 0; i < popup.buttons.length; i++) {
9871        const button = popup.buttons[i];
9872        if (button.type === "POSTBACK") {
9873          if (popup.proactive_welcome_message && localStorage.getItem(getDynamicLSName("iswidgetopened")) != 'true') {
9874            appendHtmL += `<button class="cbot-button cbot-secondary cbot-proactive" onclick="openAndSendMessage('${button.payload}', true, new_welcome_message= '${popup.proactive_welcome_message}')">`;
9875          } else {
9876            appendHtmL += '<button class="cbot-button cbot-secondary cbot-proactive" onclick="openAndSendMessage(' + "'" + button.payload + "'" + ', true)">';
9877          }
9878          appendHtmL += button.title;
9879          appendHtmL += '</button>';
9880        } else if (button.type === "URL") {
9881          appendHtmL += '<a href="' + button.payload + '" target="_blank" class="cbot-button cbot-secondary cbot-proactive">';
9882          appendHtmL += button.title;
9883          appendHtmL += '</a>';
9884        }
9885      }
9886      appendHtmL += '</div></div>';
9887    }
9888    appendHtmL += "</div>";
9889
9890    handlePopupTimeouts.push(setTimeout(async () => {
9891      await displayPopup(popup);
9892
9893      if (popup.show_again) {
9894        let showAgainTime = parseInt(popup.show_again_time, 10);
9895        let showAgainLoop = parseInt(popup.show_again_loop, 10);
9896
9897        if (!isNaN(showAgainTime)) {
9898          if (isNaN(showAgainLoop)) {
9899            repeatDisplayPopup(-1, showAgainTime, popup); // Sonsuz döngü
9900          } else if (showAgainLoop > 0) {
9901            repeatDisplayPopup(showAgainLoop, showAgainTime, popup);
9902          }
9903        }
9904      }
9905    }, popup.opening_delay * 1000)
9906    )
9907  }
9908
9909  function processImagePopup(popup) {
9910    appendHtmL += "<div class='cbot-join-chat-container cbot-proactive-rule cbot-" + popup.rule_code + "'>";
9911    const imageUrl = popup.image_url;
9912    const imagePayload = popup.image_payload;
9913    const isPostback = popup.image_payload_postback;
9914
9915    if (imageUrl && imageUrl.length > 0) {
9916      const fileExtension = imageUrl.split('.').pop().toLowerCase();
9917      if (fileExtension === 'json') {
9918        cbot_lottie_icon_activation = true;
9919        loadLottieLibrary(imageUrl);
9920        setTimeout(() => {
9921          initializeLottieAnimation("cbot-join-chat-image", imageUrl);
9922        }, 500);
9923        appendHtmL += "<div id='cbot-join-chat-image' style='cursor: pointer; margin-bottom:unset'";
9924      } else if (fileExtension === 'mp4') {
9925        appendHtmL += "<video src='" + imageUrl + "' class='cbot-join-chat-image' style='cursor: pointer; margin-bottom:unset' autoplay loop muted";
9926      } else {
9927        appendHtmL += "<img src='" + imageUrl + "' class='cbot-join-chat-image' style='cursor: pointer; margin-bottom:unset'";
9928      }
9929
9930      if (isPostback) {
9931        if (popup.proactive_welcome_message && localStorage.getItem(getDynamicLSName("iswidgetopened")) != 'true') {
9932          appendHtmL += " onclick=\"openAndSendMessage('" + imagePayload + "', true, new_welcome_message='" + popup.proactive_welcome_message + "')\"";
9933        } else {
9934          appendHtmL += " onclick=\"openAndSendMessage('" + imagePayload + "', true)\"";
9935        }
9936        if (popup.convert_trigger_message) {
9937          trigger_messages = [imagePayload];
9938        }
9939      } else {
9940        appendHtmL += " onclick=\"window.open('" + imagePayload + "', '_blank')\"";
9941      }
9942
9943      if (fileExtension === 'json') {
9944        appendHtmL += "></div>";
9945      } else if (fileExtension === 'mp4') {
9946        appendHtmL += "></video>";
9947      } else {
9948        appendHtmL += "></img>";
9949      }
9950    }
9951    appendHtmL += "</div>";
9952
9953    handlePopupTimeouts.push(setTimeout(async () => {
9954      await displayPopup(popup);
9955
9956      if (popup.show_again) {
9957        let showAgainTime = parseInt(popup.show_again_time, 10);
9958        let showAgainLoop = parseInt(popup.show_again_loop, 10);
9959
9960        if (!isNaN(showAgainTime)) {
9961          if (isNaN(showAgainLoop)) {
9962            repeatDisplayPopup(-1, showAgainTime, popup); // Sonsuz döngü
9963          } else if (showAgainLoop > 0) {
9964            repeatDisplayPopup(showAgainLoop, showAgainTime, popup);
9965          }
9966        }
9967      }
9968    }, popup.opening_delay * 1000)
9969    )
9970  }
9971
9972  function processButtonPopup(popup) {
9973    appendHtmL += "<div class='cbot-join-chat-container cbot-proactive-rule cbot-" + popup.rule_code + "'>";
9974    appendHtmL += "<span class='cbot-join-chat-text'>" + popup.message + "</span>";
9975
9976    if (popup.buttons && popup.buttons.length > 0) {
9977      appendHtmL += '<div class="cbot-msg-custom-button">';
9978      appendHtmL += '<div class="cbot-buttons">';
9979
9980      for (let i = 0; i < popup.buttons.length; i++) {
9981        const button = popup.buttons[i];
9982        if (button.type === "POSTBACK") {
9983          if (popup.proactive_welcome_message && localStorage.getItem(getDynamicLSName("iswidgetopened")) != 'true') {
9984            appendHtmL += `<button class="cbot-button cbot-secondary cbot-proactive" onclick="openAndSendMessage('${button.payload}', true, new_welcome_message= '${popup.proactive_welcome_message}')">`;
9985          } else {
9986            appendHtmL += '<button class="cbot-button cbot-secondary cbot-proactive" onclick="openAndSendMessage(' + "'" + button.payload + "'" + ', true)">';
9987          }
9988          appendHtmL += button.title;
9989          appendHtmL += '</button>';
9990        } else if (button.type === "URL") {
9991          appendHtmL += '<a href="' + button.payload + '" target="_blank" class="cbot-button cbot-secondary cbot-proactive">';
9992          appendHtmL += button.title;
9993          appendHtmL += '</a>';
9994        }
9995      }
9996
9997      appendHtmL += '</div></div>';
9998    }
9999
10000    appendHtmL += "</div>";
10001
10002    handlePopupTimeouts.push(setTimeout(async () => {
10003      await displayPopup(popup);
10004
10005      if (popup.show_again) {
10006        let showAgainTime = parseInt(popup.show_again_time, 10);
10007        let showAgainLoop = parseInt(popup.show_again_loop, 10);
10008
10009        if (!isNaN(showAgainTime)) {
10010          if (isNaN(showAgainLoop)) {
10011            repeatDisplayPopup(-1, showAgainTime, popup); // Sonsuz döngü
10012          } else if (showAgainLoop > 0) {
10013            repeatDisplayPopup(showAgainLoop, showAgainTime, popup);
10014          }
10015        }
10016      }
10017    }, popup.opening_delay * 1000)
10018    )
10019  }
10020
10021  function processWelcomePopup(type, content) {
10022    if (type == "NEW_MESSAGE") {
10023      if (localStorage.getItem(getDynamicLSName("iswidgetopened")) != 'true') {
10024        trigger_messages = [content]
10025      }
10026    }
10027    else if (type == "INTENT") {
10028      trigger_messages = ["intent"]
10029      sendCategory = content
10030    }
10031  }
10032
10033  ia_display_popup_state.popups.forEach(popup => {
10034    if (popup.popup_type === "SHORT_TEXT") {
10035      processShortTextPopup(popup);
10036    } else if (popup.popup_type === "RICH_CONTENT") {
10037      processRichContentPopup(popup);
10038    } else if (popup.popup_type === "IMAGE") {
10039      processImagePopup(popup);
10040    } else if (popup.popup_type === "WELCOME_MESSAGE") {
10041      if (popup.welcome_message_type) {
10042        let context = popup.welcome_message_type === "NEW_MESSAGE" ? popup.welcome_message : popup.welcome_intent;
10043        processWelcomePopup(popup.welcome_message_type, context);
10044      }
10045    } else {
10046      processButtonPopup(popup);
10047    }
10048  });
10049
10050  return appendHtmL;
10051}
10052
10053/**
10054 * Event Data Payload
10055 * @typedef {Object} EventPayload
10056 * @property {string} actionType - The type of action being performed.
10057 * @property {string} actionName - The name of the action.
10058 * @property {Object} options - Additional options for the event.
10059 */
10060
10061window.addEventListener("cbotCustomEventListener", function (event) {
10062  let data = event.detail;
10063  if ($(".cbot-proactive-rule").length) {
10064    $(".cbot-proactive-rule").remove
10064();
10065  }
10066
10067  if (data.actionType) {
10068    let matchedAction = interactive_actions.display_popup.find(popup => popup.action_type === data.actionType);
10069    if (matchedAction) {
10070      matchedAction = {
10071        popups: [matchedAction.popup]
10072      };
10073      let popupContent = handlePopup(matchedAction, clients, cbot_config);
10074      $('.cbot-animation-holder').append(popupContent);
10075      afterAppend();
10076    } else {
10077      console.log("Eşleşen aksiyon bulunamadı.");
10078    }
10079  }
10080});
10081
10082function ChangeWelcomeMessage(message) {
10083  welcomeDoc = document.querySelector("#cbot-chat [data-message-id]").querySelector(".cbot-msg")
10084  welcomeDoc.textContent = message;
10085}
10086
10087function animateBorderAngle() {
10088  const buttons = document.querySelectorAll('.cbot-button-suggestion.cbot-animated')
10089  if (buttons.length === 0) {
10090    return;
10091  } else {
10092    let angle = 0;
10093    function frame() {
10094      angle = (angle + 2) % 360;
10095      buttons.forEach(btn => {
10096        btn.style.setProperty('--border-angle', angle + 'deg');
10097      });
10098      requestAnimationFrame(frame);
10099    }
10100    frame();
10101  }
10102}
10103
10104const particles_intensity_levels = {
10105  low: {
10106    particles: 100,
10107    speed: 1,
10108    size: 4,
10109    opacity: 0.3,
10110    name: 'Low'
10111  },
10112  medium: {
10113    particles: 150,
10114    speed: 3,
10115    size: 5,
10116    opacity: 0.5,
10117    name: 'Medium'
10118  },
10119  high: {
10120    particles: 200,
10121    speed: 5,
10122    size: 6,
10123    opacity: 0.7,
10124    name: 'High'
10125  },
10126};
10127
10128const particles_intensity_levels_enums = {
10129  low: 'low',
10130  medium: 'medium',
10131  high: 'high',
10132}
10133
10134// Initialize particles with low intensity (görünürlük iyileştirildi)
10135let particlesConfig = {
10136  "particles": {
10137    "number": {
10138      "value": 80, // Low enerji başlangıç değeri (artırıldı)
10139      "density": {
10140        "enable": true,
10141        "value_area": 800
10142      }
10143    },
10144    "color": {
10145      "value": "#fff"
10146    },
10147    "shape": {
10148      "type": "circle",
10149      "stroke": {
10150        "width": 0,
10151        "color": "#000000"
10152      }
10153    },
10154    "opacity": {
10155      "value": 0.4, // Low enerji başlangıç değeri (artırıldı)
10156      "random": true,
10157      "anim": {
10158        "enable": false,
10159        "speed": 1,
10160        "opacity_min": 0.1,
10161        "sync": false
10162      }
10163    },
10164    "size": {
10165      "value": 3, // Low enerji başlangıç değeri (artırıldı)
10166      "random": true,
10167      "anim": {
10168        "enable": false,
10169        "speed": 40,
10170        "size_min": 0.1,
10171        "sync": false
10172      }
10173    },
10174    "line_linked": {
10175      "enable": false,
10176      "distance": 500,
10177      "color": "#ffffff",
10178      "opacity": 0.4,
10179      "width": 2
10180    },
10181    "move": {
10182      "enable": true,
10183      "speed": 1, // Low enerji başlangıç değeri (artırıldı)
10184      "direction": "none",
10185      "random": true,
10186      "straight": false,
10187      "out_mode": "bounce",
10188      "bounce": true,
10189      "attract": {
10190        "enable": false,
10191        "rotateX": 600,
10192        "rotateY": 1200
10193      }
10194    }
10195  },
10196  "interactivity": {
10197    "detect_on": "canvas",
10198    "events": {
10199      "onhover": {
10200        "enable": false,
10201        "mode": "bubble"
10202      },
10203      "onclick": {
10204        "enable": false,
10205        "mode": "repulse"
10206      },
10207      "resize": false
10208    },
10209    "modes": {
10210      "bubble": {
10211        "distance": 100,
10212        "size": 4,
10213        "duration": 0.3,
10214        "opacity": 1,
10215        "speed": 3
10216      },
10217      "repulse": {
10218        "distance": 100,
10219        "duration": 0.4
10220      }
10221    }
10222  },
10223  "retina_detect": true
10224};
10225
10226let particlesCountParticles = document.querySelector('.particles-count-particles');
10227let particlesCurrentIntensity = 'low'; // Başlangıç enerji sistemi ile uyumlu
10228let particlesTargetProperties = null;
10229let particlesAnimationFrame = null;
10230let lastEnergyValue = 0;
10231let lastEnergyUpdateTime = 0;
10232let energyUpdateThreshold = 2; // Minimum enerji değişimi eşiği
10233let energyUpdateInterval = 100; // Minimum güncelleme aralığı (ms)
10234
10235function particlesUpdateStats() {
10236  requestAnimationFrame(particlesUpdateStats);
10237}
10238requestAnimationFrame(particlesUpdateStats);
10239
10240// Enerji seviyesine göre parçacık özelliklerini hesapla (0-30 arası enerji)
10241function calculateParticlePropertiesFromEnergy(energy) {
10242  // Enerji seviyesini 0-1 arasına normalize et
10243  const normalizedEnergy = Math.max(0, Math.min(energy / 30, 1));
10244
10245  // Min ve max değerleri tanımla
10246  const minProperties = {
10247    particles: 80,   // Minimum parçacık sayısı (artırıldı)
10248    speed: 1,        // Minimum hız (artırıldı)
10249    size: 3,         // Minimum boyut (artırıldı)
10250    opacity: 0.4     // Minimum opaklık (artırıldı)
10251  };
10252
10253  const maxProperties = {
10254    particles: 350,  // Maksimum parçacık sayısı (artırıldı)
10255    speed: 10,       // Maksimum hız (artırıldı)
10256    size: 9,         // Maksimum boyut (artırıldı)
10257    opacity: 0.9     // Maksimum opaklık (ideal seviyede)
10258  };
10259
10260  // Enerji seviyesine göre interpolasyon yap
10261  return {
10262    particles: Math.round(minProperties.particles + (maxProperties.particles - minProperties.particles) * normalizedEnergy),
10263    speed: minProperties.speed + (maxProperties.speed - minProperties.speed) * normalizedEnergy,
10264    size: minProperties.size + (maxProperties.size - minProperties.size) * normalizedEnergy,
10265    opacity: minProperties.opacity + (maxProperties.opacity - minProperties.opacity) * normalizedEnergy
10266  };
10267}
10268
10269// Smooth interpolasyon fonksiyonu
10270function lerp(start, end, factor) {
10271  return start + (end - start) * factor;
10272}
10273
10274// Parçacıkları enerji seviyesine göre güncelle (optimize edilmiş)
10275function particlesUpdateByEnergy(energy) {
10276  if (!isSpeechEnabled()) {
10277    return;
10278  }
10279
10280  // console.log("particlesUpdateByEnergy", energy);
10281  if (!window.pJSDom || !window.pJSDom[0] || !window.pJSDom[0].pJS) {
10282    return;
10283  }
10284
10285  const currentTime = Date.now();
10286
10287  // Throttle kontrolü: Çok sık güncelleme yapma
10288  if (currentTime - lastEnergyUpdateTime < energyUpdateInterval) {
10289    return;
10290  }
10291
10292  // Threshold kontrolü: Küçük değişimleri görmezden gel
10293  if (Math.abs(energy - lastEnergyValue) < energyUpdateThreshold) {
10294    return;
10295  }
10296
10297  // Debugging için enerji değerini logla (sadece büyük değişimlerde)
10298  if (Math.abs(energy - lastEnergyValue) > 5) {
10299    // console.log("Particles major update - Energy:", energy, "| Previous:", lastEnergyValue);
10300  }
10301
10302  lastEnergyValue = energy;
10303  lastEnergyUpdateTime = currentTime;
10304
10305  const targetProperties = calculateParticlePropertiesFromEnergy(energy);
10306  particlesTargetProperties = targetProperties;
10307
10308  // Eğer animasyon zaten çalışıyorsa, yeni hedef değerleri ayarla
10309  if (!particlesAnimationFrame) {
10310    animateParticlesToTarget();
10311  }
10312}
10313
10314// Parçacıkları hedef değerlere smooth bir şekilde animate et
10315function animateParticlesToTarget() {
10316  if (!isSpeechEnabled() || !particlesTargetProperties || !window.pJSDom || !window.pJSDom[0] || !window.pJSDom[0].pJS) {
10317    particlesAnimationFrame = null;
10318    return;
10319  }
10320
10321  const pJS = window.pJSDom[0].pJS;
10322  const animationSpeed = 0.08; // Animasyon hızı (optimize edilmiş, daha responsive)
10323  let animationComplete = true;
10324
10325  // Parçacık sayısını güncelle
10326  const currentParticleCount = pJS.particles.array.length;
10327  const targetParticleCount = particlesTargetProperties.particles;
10328
10329  if (Math.abs(currentParticleCount - targetParticleCount) > 1) {
10330    animationComplete = false;
10331
10332    if (currentParticleCount < targetParticleCount) {
10333      // Parçacık ekle (her frame'de 1-3 tane)
10334      const particlesToAdd = Math.min(3, targetParticleCount - currentParticleCount);
10335      for (let i = 0; i < particlesToAdd; i++) {
10336        pJS.particles.array.push(new pJS.fn.particle(pJS.particles.color, pJS.particles.opacity.value));
10337      }
10338    } else if (currentParticleCount > targetParticleCount) {
10339      // Parçacık çıkar (her frame'de 1-3 tane)
10340      const particlesToRemove = Math.min(3, currentParticleCount - targetParticleCount);
10341      pJS.particles.array.splice(-particlesToRemove);
10342    }
10343  }
10344
10345  // Mevcut parçacıkların özelliklerini smooth bir şekilde güncelle
10346  pJS.particles.array.forEach(particle => {
10347    // Hız güncellemesi
10348    const targetVx = (Math.random() - 0.5) * particlesTargetProperties.speed;
10349    const targetVy = (Math.random() - 0.5) * particlesTargetProperties.speed;
10350
10351    if (Math.abs(particle.vx - targetVx) > 0.1 || Math.abs(particle.vy - targetVy) > 0.1) {
10352      animationComplete = false;
10353      particle.vx = lerp(particle.vx, targetVx, animationSpeed);
10354      particle.vy = lerp(particle.vy, targetVy, animationSpeed);
10355    }
10356
10357    // Opaklık güncellemesi
10358    const targetOpacity = particlesTargetProperties.opacity * (0.5 + Math.random() * 0.5);
10359    if (Math.abs(particle.opacity.value - targetOpacity) > 0.01) {
10360      animationComplete = false;
10361      particle.opacity.value = lerp(particle.opacity.value, targetOpacity, animationSpeed);
10362    }
10363
10364    // Boyut güncellemesi
10365    const targetSize = particlesTargetProperties.size * (0.5 + Math.random() * 0.5);
10366    if (Math.abs(particle.radius - targetSize) > 0.1) {
10367      animationComplete = false;
10368      particle.radius = lerp(particle.radius, targetSize, animationSpeed);
10369    }
10370  });
10371
10372  // Global ayarları güncelle
10373  pJS.particles.move.speed = lerp(pJS.particles.move.speed, particlesTargetProperties.speed, animationSpeed);
10374  pJS.particles.opacity.value = lerp(pJS.particles.opacity.value, particlesTargetProperties.opacity, animationSpeed);
10375  pJS.particles.size.value = lerp(pJS.particles.size.value, particlesTargetProperties.size, animationSpeed);
10376
10377  // Animasyon devam etsin mi kontrol et
10378  if (!animationComplete) {
10379    particlesAnimationFrame = requestAnimationFrame(animateParticlesToTarget);
10380  } else {
10381    particlesAnimationFrame = null;
10382  }
10383}
10384
10385function particlesChangeIntensity(level) {
10386  if (!isSpeechEnabled()) {
10387    return;
10388  }
10389
10390  particlesCurrentIntensity = level;
10391
10392  const config = particles_intensity_levels[level];
10393
10394  // Update particles configuration
10395  if (window.pJSDom && window.pJSDom[0] && window.pJSDom[0].pJS) {
10396    const pJS = window.pJSDom[0].pJS;
10397
10398    // Update number of particles
10399    pJS.particles.number.value = config.particles;
10400
10401    // Update existing particles properties
10402    pJS.particles.array.forEach(particle => {
10403      particle.opacity.value = config.opacity * (0.5 + Math.random() * 0.5);
10404      particle.radius = config.size * (0.5 + Math.random() * 0.5);
10405      particle.vx = (Math.random() - 0.5) * config.speed;
10406      particle.vy = (Math.random() - 0.5) * config.speed;
10407    });
10408
10409    // Add or remove particles based on new count
10410    const currentCount = pJS.particles.array.length;
10411    if (currentCount < config.particles) {
10412      // Add particles
10413      for (let i = currentCount; i < config.particles; i++) {
10414        pJS.particles.array.push(new pJS.fn.particle(pJS.particles.color, pJS.particles.opacity.value));
10415      }
10416    } else if (currentCount > config.particles) {
10417      // Remove particles
10418      pJS.particles.array.splice(config.particles);
10419    }
10420
10421    // Update movement speed
10422    pJS.particles.move.speed = config.speed;
10423
10424    // Update opacity
10425    pJS.particles.opacity.value = config.opacity;
10426
10427    // Update size
10428    pJS.particles.size.value = config.size;
10429  }
10430}
10431function cbotUpdateSpeedMeter(config) {
10432  const {
10433    currentSpeed,
10434    speedAngleMap,
10435    speedLevels,
10436    progressOffsetMap,
10437    containerSelector,
10438    arrowSelector,
10439    progressBarSelector,
10440    colors,
10441    transformOrigin
10442  } = config;
10443
10444  let targetAngle = speedAngleMap[0] || -245;
10445  let targetOffset = progressOffsetMap[0] || 310;
10446
10447  for (let i = 0; i < speedLevels.length - 1; i++) {
10448    if (currentSpeed >= speedLevels[i] && currentSpeed <= speedLevels[i + 1]) {
10449      const ratio = (currentSpeed - speedLevels[i]) / (speedLevels[i + 1] - speedLevels[i]);
10450      targetAngle = speedAngleMap[speedLevels[i]] +
10451        (speedAngleMap[speedLevels[i + 1]] - speedAngleMap[speedLevels[i]]) * ratio;
10452      targetOffset = progressOffsetMap[speedLevels[i]] +
10453        (progressOffsetMap[speedLevels[i + 1]] - progressOffsetMap[speedLevels[i]]) * ratio;
10454      break;
10455    }
10456  }
10457
10458  const maxSpeed = speedLevels[speedLevels.length - 1];
10459  if (currentSpeed >= maxSpeed) {
10460    targetAngle = speedAngleMap[maxSpeed];
10461    targetOffset = progressOffsetMap[maxSpeed];
10462  }
10463
10464  const speedMeter = document.querySelector(containerSelector);
10465  if (!speedMeter) return;
10466
10467  const arrowElement = speedMeter.querySelector(arrowSelector);
10468  if (arrowElement) {
10469    arrowElement.style.transform = `rotate(${targetAngle}deg)`;
10470    arrowElement.style.transformOrigin = transformOrigin;
10471  }
10472
10473  const progressBar = speedMeter.querySelector(progressBarSelector);
10474  if (progressBar) {
10475    progressBar.style.strokeDashoffset = targetOffset;
10476  }
10477
10478  const speedLabels = speedMeter.querySelectorAll('path[data-speed]');
10479  speedLabels.forEach(path => {
10480    const labelSpeed = parseInt(path.getAttribute('data-speed'));
10481    if (labelSpeed <= currentSpeed) {
10482      path.setAttribute('fill', colors.activeLabel);
10483    } else {
10484      path.setAttribute('fill', colors.inactiveLabel);
10485    }
10486  });
10487}
10488
10489function cbotHelpToggleMoreSections() {
10490  const helpContainerhiddenSections = document.querySelectorAll('[id^="hidden-section"]');
10491  const helpContainermoreLink = document.querySelector('.cbot-more-link span');
10492
10493  const helpContainerfirstHiddenSection = helpContainerhiddenSections[0];
10494  if (!helpContainerfirstHiddenSection) return;
10495
10496
10497  if (helpContainerfirstHiddenSection.classList.contains('cbot-hidden-section') && !helpContainerfirstHiddenSection.classList.contains('cbot-show')) {
10498    helpContainerhiddenSections.forEach(section => {
10499      section.classList.add('cbot-show');
10500    });
10501    helpContainermoreLink.textContent = 'Daha Az';
10502  } else {
10503    helpContainerhiddenSections.forEach(section => {
10504      section.classList.remove('cbot-show');
10505    });
10506    helpContainermoreLink.textContent = 'Daha Fazla';
10507  }
10508}
10509
10510function cbotDarkModeToogle(mode) {
10511  const dialog = document.querySelector('.cbot-dialog');
10512  if (dialog) {
10513    if (mode === 'dark') {
10514      dialog.classList.add('cbot-dark');
10515    } else if (mode === 'light') {
10516      dialog.classList.remove('cbot-dark');
10517    }
10518  }
10519}
10520
10521
10522function socket_on_pass_control(data) {
10523  if (SOCKET_CONNECT_ON_START) {
10524    socket.on("cbot_pass_control", (data) => {
10525      if (data.handover_message) {
10526        appendMessageToDialogBox(data.handover_message, "cbot-other", null, { notification: data.handover_message }, function () {
10527        });
10528        isLive = setIsLive(true);
10529        setisLiveTLS(isLive);
10530      }
10531    });
10532  }
10533}
10534
10535if (SOCKET_CONNECT_ON_START) {
10536  let _socketInterval = setInterval(function () {
10537    if (window.io && cbotSessionId && cbotUserId) {
10538      clearInterval(_socketInterval);
10539      socket_connection(true);
10540    }
10541  }, 1000);
10542}
10543
10544let USER_LOGGING_OUT_FLAG = false;
10545function cbotUserLoggedOutEvent() {
10546  USER_LOGGING_OUT_FLAG = true;
10547  data_user = null;
10548  let _payload = {
10549    message: "USER_LOGGED_OUT",
10550    session_id: cbotSessionId,
10551    user_id: cbotUserId,
10552    userInfo: null,
10553    client: cbot_config.client,
10554  };
10555  let xhr = new XMLHttpRequest();
10556  xhr.onreadystatechange = function () {
10557    if (this.readyState == 4 && this.status == 200) { }
10558  };
10559  xhr.open("POST", rootAddress + "/" + CLIENT, true);
10560  xhr.setRequestHeader('Content-Type', 'application/json');
10561  xhr.setRequestHeader("Accept", "application/json");
10562  xhr.send(JSON.stringify(_payload));
10563  USER_LOGGING_OUT_FLAG = false;
10564  cbotClearUserDialog(true);
10565  cbotSessionId = null;
10566  setSessionIdTLS(cbotSessionId);
10567  isLive = setIsLive(false);
10568  setisLiveTLS(isLive);
10569  agentId = null;
10570  agent_name = null;
10571  cbotUserId = null;
10572  setUserIdTLS(cbotUserId);
10573  clearLastMessageSentDateTLS();
10574  welcomeMessageSent = false;
10575  firstLoad = false;
10576  trigger_messages_count = 0;
10577  pendingUpdateDataUserMessage = null;
10578  if (!queryStringVars.cbot_message && welcomeMessage) {
10579    appendMessageToDialogBox(welcomeMessage, "cbot-other", null, {}, function () {
10580    });
10581  }
10582
10583  newMsgCount = 0;
10584  toggleBadge(0);
10585  sendTriggerMessages(trigger_messages);
10586}
10587
10588function sendPendingUpdateDataUserMessage() {
10589  setTimeout(() => {
10590    if (pendingUpdateDataUserMessage) {
10591      appendMessageToDialogBox(pendingUpdateDataUserMessage, "cbot-other", null, {}, function () {
10592      });
10593      pendingUpdateDataUserMessage = null;
10594    }
10595  }, 1000);
10596}
10597 

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.