/home/edulekha/chat.edulekha.com/js/min/main.min.js
"use strict";!function(e){function t(t){return!!e(t).sbLoading()||(e(t).sbLoading(!0),!1)}function i(e,t=G){return ee.storage(e,t)}function s(e){return ee.translate(e)}function a(e=-1){if(-1===e)return window.sb_current_user;window.sb_current_user=e}function n(){let e=x?SB_ADMIN_SETTINGS.sound.volume:U.sound.volume;ne.audio&&e&&(ne.audio.volume=e)}function o(e){let t=Math.floor(e/60);return e-=60*t,(t||"0")+":"+(e<10?"0"+e:e)}function r(){(l=e(".sb-admin, .sb-chat, .sb-tickets")).length&&typeof SB_AJAX_URL!=G?(h=l.find(".sb-list").eq(0),g=l.find(".sb-editor"),p=g.find("textarea"),_=l.find(x||$?".sb-list":"> div > .sb-scroll-area"),f=_.find(".sb-header"),v=g.find(".sb-emoji"),b=l.find(".sb-overlay-panel"),m=$?l.find(".sb-profile-agent .sb-status"):null,ne.enabledAutoExpand(),ne.audio=l.find("#sb-audio").get(0),ne.label_date=l.find(".sb-label-date-top"),ee.cookie("sb-check","ok",1,"set"),"ok"!=ee.cookie("sb-check")?(F=!1,console.warn("Support Board: cookies not available.")):ee.cookie("sb-check",!1,!1,!1),x?(n(),ee.event("SBReady")):ee.ajax({function:"get-front-settings",current_url:window.location.href,tickets:$,popup:!i("popup")&&!$},t=>{if(U=t,typeof SB_LOCAL_SETTINGS!=G&&e.extend(U,SB_LOCAL_SETTINGS),y=U.bot_id,w=U.dialogflow_human_takeover,q=U.agents_online,te.active=U.pusher,U.language&&(SB_LANG="auto"!=U.language?[U.language,"front"]:!(!Z||"en"==Shopify.locale)&&Shopify.locale),typeof SB_REGISTRATION_REQUIRED!=G&&(U.registration_required=SB_REGISTRATION_REQUIRED,U.tickets_registration_required=SB_REGISTRATION_REQUIRED),typeof SB_ARTICLES_PAGE!=G&&SB_ARTICLES_PAGE&&(ne.automations.runAll(),ne.initArticlesPage()),$&&U.tickets_manual_init||(!$||U.tickets_manual_init)&&(U.chat_manual_init||U.disable_offline&&!q||U.disable_office_hours&&!U.office_hours||U.chat_login_init&&!le.login())||ne.initChat(),U.cron&&setTimeout(function(){ee.ajax({function:"cron-jobs"})},1e4),U.cron_email_piping&&setTimeout(function(){ee.ajax({function:"email-piping"})},8e3),U.push_notifications_users&&ee.serviceWorker.init(),$&&(U.tickets_default_department&&(ne.default_department=U.tickets_default_department),U.dialogflow_disable_tickets&&(U.dialogflow_active=!1,U.open_ai_active=!1)),le.is("martfury")){let e=!1;setInterval(function(){if(a()){let t=ee.cookie("XSRF-TOKEN");t&&t!=e&&(ee.ajax({function:"martfury-session"}),e=t)}},3e3)}Z&&(le.shopify.startCartSynchronization(),l.addClass("sb-shopify")),n(),le.aecommerce.cart(),setTimeout(()=>{ee.event("SBReady")},500)}),e(g).on("keydown","textarea",function(e){if(13==e.which&&(!$||U.tickets_enter_button)&&!O&&!e.ctrlKey&&!e.shiftKey)return ne.submit(),e.preventDefault,!1;x&&13==e.which&&e.ctrlKey&&ne.insertText("\n")}),e(l).on("keydown",".sb-dashboard-articles input",function(t){13==t.which&&e(this).next().click()}),typeof SB_DEFAULT_DEPARTMENT!==G&&(ne.default_department=SB_DEFAULT_DEPARTMENT),typeof SB_DEFAULT_AGENT!==G&&(ne.default_agent=SB_DEFAULT_AGENT),typeof SB_DIALOGFLOW_TAGS!==G&&(ne.default_tags=SB_DEFAULT_TAGS),typeof SB_DIALOGFLOW_AGENT!==G&&(le.dialogflow.project_id=SB_DIALOGFLOW_AGENT)):ee.event("SBReady"),document.addEventListener("visibilitychange",function(){ee.visibilityChange(document.visibilityState)},!1),e(l).on("click",function(){ne.tab_active||ee.visibilityChange()}),c=l,x&&(l=l.find(".sb-conversation")),e(_).on("scroll",function(){let t=_.scrollTop(),i=L.length;if(ne.scrollHeader(),!ne.label_date_show&&i&&L[i-1].getBoundingClientRect().top>h[0].getBoundingClientRect().top+h.outerHeight()&&(ne.label_date_show=!0,i>1&&ne.label_date.html(e(L[i-2]).html())),ne.label_date_show&&(ne.label_date.sbActive(!0),clearTimeout(N[0]),N[0]=setTimeout(()=>{ne.label_date.sbActive(!1)},1500)),i)if(ne.isBottom())ne.label_date.html(e(L[i-1]).html()),ne.label_date_show=L.length&&L[L.length-1].getBoundingClientRect().top<0;else{let a=ne.label_date[0].getBoundingClientRect().top;for(var s=0;s<i;s++){let i=L[s].getBoundingClientRect().top;if(i-100<a&&i+100>a){let i=e(L[M[0]>t&&s>0?s-1:s]).html();i!=M[1]&&(ne.label_date.html(i),M[1]=i);break}}}M[0]=t}),e(h).on("click",".sb-menu-btn",function(){let t=e(this).parent().find(".sb-menu"),i=e(t).sbActive();ee.deactivateAll(),i||(e(t).sbActive(!0),ee.deselectAll(),x&&(SBAdmin.open_popup=t))}),O&&(e(g).on("click",".sb-textarea",function(){l.addClass("sb-header-hidden"),e(this).find("textarea").get(0).focus(),ne.isBottom()&&(ne.scrollBottom(),setTimeout(()=>{ne.scrollBottom()},200))}),e(g).on("focusout",".sb-textarea",function(){setTimeout(()=>{l.removeClass("sb-header-hidden")},300)}),e(g).on("click",".sb-submit",function(){p.blur()}),window.addEventListener("popstate",function(){ne.chat_open&&ne.open(!1)})),e(h).on("click",".sb-menu li",function(){e(this).parent().sbActive(!1)}),e(g).on("click",".sb-submit",function(){ne.submit()}),e("body").on("click",".sb-chat-btn,.sb-responsive-close-btn, #sb-open-chat, .sb-open-chat",function(){ne.open(!ne.chat_open)}),e(l).on("click",".sb-dashboard-btn",function(){ne.showDashboard(),_.find(" > .sb-panel-articles > .sb-article").length&&ne.showArticles(),i("open-conversation",0),P=!1}),e(l).on("click",".sb-user-conversations li",function(){ne.openConversation(e(this).attr("data-conversation-id"))}),e(l).on("click",".sb-btn-new-conversation, .sb-departments-list > div, .sb-agents-list > div",function(){let t=e(this).data("id"),i=!1;if(!ee.null(t)){let n=e(this).parent().hasClass("sb-departments-list");if(n?ne.default_department=parseInt(t):ne.default_agent=parseInt(t),e(this).parent().data("force-one")){let e=a()?a().conversations:[];for(var s=0;s<e.length;s++)if(n&&e[s].get("department")==t||!n&&e[s].get("agent_id")==t){i=!0,ne.openConversation(e[s].id);break}}}i||(P="new-conversation",ne.clear(),ne.hideDashboard())}),e(l).on("click",".sb-btn-all-conversations",function(){l.find(".sb-dashboard-conversations").removeClass("sb-conversations-hidden")}),e(g).on("click",".sb-btn-attachment",function(){ne.is_busy||g.find(".sb-upload-files").val("").click()}),e(g).on("click",".sb-attachments > div > i",function(t){return e(this).parent().remove(),p.val()||0!=g.find(".sb-attachments > div").length||g.sbActive(!1),t.preventDefault(),!1}),e(g).on("change",".sb-upload-files",function(t){ne.busy(!0),e(this).sbUploadFiles(function(e){ne.uploadResponse(e)}),ee.event("SBAttachments")}),e(g).on("dragover",function(t){e(this).addClass("sb-drag"),clearTimeout(E),t.preventDefault(),t.stopPropagation()}),e(g).on("dragleave",function(t){E=setTimeout(()=>{e(this).removeClass("sb-drag")},200),t.preventDefault(),t.stopPropagation()}),e(g).on("drop",function(t){let i=t.originalEvent.dataTransfer.files;if(t.preventDefault(),t.stopPropagation(),i.length>0)for(var s=0;s<i.length;++s){let e=new FormData;e.append("file",i[s]),ee.upload(e,function(e){ne.uploadResponse(e)})}return e(this).removeClass("sb-drag"),!1}),e(l).on("click",".sb-btn-all-articles:not([onclick])",function(){ne.showArticles()}),e(l).on("click",".sb-articles > div",function(){ne.showArticles(e(this).attr("data-id"),e(this).attr("data-is-category"))}),e(l).on("click",".sb-dashboard-articles .sb-input-btn .sb-submit-articles",function(){ne.searchArticles(e(this).parent().find("input").val(),this,e(this).parent().next())}),e(c).on("click",".sb-article [data-rating]",function(){ne.articleRatingOnClick(this)}),e(h).on("click",".sb-rich-button a",function(t){let i=e(this).attr("href");if(0===i.indexOf("#")&&0===i.indexOf("#article-"))return ne.showArticles(i.replace("#article-","")),t.preventDefault(),!1}),e(b).on("click","[data-rating]",function(){let i=b.find("> div:last-child"),s=e(this).attr("data-rating"),n=ne.conversation?ne.conversation:a().getLastConversation(),o=n.getLastUserMessage(!1,!0);t(i),ee.ajax({function:"set-rating",conversation_id:n.id,agent_id:!!o&&o.get("user_id"),user_id:a().id,message:i.find("textarea").val(),rating:"positive"==s?1:-1},e=>{b.attr("data-close-chat")&&ne.closeChat(),ne.update(),b.sbActive(!1),i.sbLoading(!1)})}),e(c).on("click",".sb-lightbox-media > i",function(){return c.find(".sb-lightbox-media").sbActive(!1),x&&(SBAdmin.open_popup=!1),!1}),e(l).on("click",".sb-image",function(){ee.lightbox(e(this).html())}),e(l).on("click",".sb-slider-images .sb-card-img",function(){ee.lightbox(`<img loading="lazy" src="${e(this).attr("data-value")}" />`)}),e(document).on("SBConversationLoaded",function(){i("queue")&&ne.queue(i("queue"))}),e(g).on("click",".sb-btn-emoji",function(){ne.showEmoji(this)}),e(v).on("click",".sb-emoji-list li",function(t){ne.insertEmoji(e(this).html()),O&&clearTimeout(E)}),e(v).find(".sb-emoji-list").on("touchend",function(e){E=setTimeout(()=>{ne.mouseWheelEmoji(e)},50)}),e(v).find(".sb-emoji-list").on("mousewheel DOMMouseScroll",function(e){ne.mouseWheelEmoji(e)}),e(v).find(".sb-emoji-list").on("touchstart",function(e){ne.emoji_options.touch=e.originalEvent.touches[0].clientY}),e(v).on("click",".sb-emoji-bar > div",function(){ne.clickEmojiBar(this)}),e(v).on("click",".sb-select li",function(){ne.categoryEmoji(e(this).data("value"))}),e(v).find(".sb-search-btn input").on("change keyup paste",function(){ne.searchEmoji(e(this).val())}),e(p).on("keyup",function(){ne.textareaChange(this)}),e(l).on("click",".sb-privacy .sb-approve",function(){i("privacy-approved",!0),e(this).closest(".sb-privacy").remove(),l.removeClass("sb-init-form-active"),f.find(" > div").css({opacity:1,top:0}),ne.initChat(),$?SBTickets.showPanel(ee.setting("tickets_disable_first")?"":"new-ticket"):ne.isInitDashboard()||ne.hideDashboard()}),e(l).on("click",".sb-privacy .sb-decline",function(){let t=e(this).closest(".sb-privacy");e(t).find(".sb-text").html(e(t).attr("data-decline")),e(t).find(".sb-decline").remove(),ne.scrollBottom(!0)}),e(l).on("click",".sb-popup-message .sb-icon-close",function(){ne.popup(!0)}),e(l).on("click",".sb-rich-message .sb-submit,.sb-rich-message:not(.sb-rich-registration) .sb-select ul li",function(){let t=e(this).closest(".sb-rich-message");t[0].hasAttribute("disabled")||oe.submit(t,t.attr("data-type"),this)}),e(l).on("click",".sb-rich-message .sb-input > span",function(){e(this).sbActive(!0),e(this).siblings().focus()}),e(l).on("focus focusout click",".sb-rich-message .sb-input input,.sb-rich-message .sb-input select",function(t){switch(t.type){case"focusin":case"focus":e(this).siblings().sbActive(!0);break;case"focusout":e(this).val()?e(this).siblings().addClass("sb-filled sb-active"):setTimeout(()=>{X||e(this).siblings().sbActive(!1)},100);break;case"click":e(this).siblings().removeClass("sb-filled")}}),e(l).on("click",".sb-input-select-input > div",function(){X=!0,setTimeout(()=>{X=!1},250)}),e(l).on("click",".sb-slider-arrow",function(){oe.sliderChange(e(this).closest("[id]").attr("id"),e(this).hasClass("sb-icon-arrow-right")?"right":"left")}),e(l).on("change",'.sb-rich-message [data-type="select"] select',function(){e(this).siblings().sbActive(!0)}),e(l).on("click",'[data-type="select-input"] > div',function(){e(this).prev().sbActive(!0),e(this).next().addClass("sb-focus")}),e(l).on("focusout",'[data-type="select-input"] input,[data-type="select-input"] select',function(){let t=e(this).closest(".sb-input");t.find("> input").val()+t.find("select").val()==""&&t.find("span").sbActive(!1),t.find(".sb-focus").removeClass("sb-focus")}),e(l).on("click",".sb-rich-registration .sb-login-area",function(){let t=l.hasClass("sb-init-form-active");e(this).closest(".sb-rich-registration").replaceWith(oe.generate({},"login",t?"sb-init-form":"")),ne.scrollBottom(t)}),e(l).on("click",".sb-rich-login .sb-registration-area",function(){if(U.registration_link)document.location=U.registration_link;else{let t=l.hasClass("sb-init-form-active");e(this).closest(".sb-rich-login").replaceWith(oe.generate({},"registration",t?"sb-init-form":"")),ne.scrollBottom(t)}}),e(l).on("click",".sb-rich-login .sb-submit-login",function(){ee.loginForm(this,!1,t=>{let i=e(this).closest(".sb-rich-login");if(a(new ie(t[0])),i.hasClass("sb-init-form"))P="open-conversation",ne.initChat(),te.start(),ne.isInitDashboard()||ne.hideDashboard(),e(document).on("SBPopulateConversations",function(){l.removeClass("sb-init-form-active"),i.remove(),e(document).off("SBPopulateConversations")});else{i=i.closest("[data-id]");let e=ne.conversation.getMessage(i.attr("data-id")),t=`${s("Logged in as")} *${a().name}*`;e.set("message",t),ne.updateMessage(e.id,t),i.replaceWith(e.getCode()),te.started=!1,te.start()}})}),e(h).on("click",".sb-social-buttons div",function(){ee.openWindow(e(this).attr("data-link"))}),e(l).on("click",".sb-close-chat",function(){ne.closeChat()}),e(h).on("click",'.sb-rich-woocommerce_button a, [href="#"].sb-card-btn',function(i){let s=ee.settingsStringToArray(e(this).closest(".sb-rich-message").attr("data-settings")),a="checkout"==s["link-type"]||s.checkout,n=e(this)[0].hasAttribute("data-ids")?e(this).attr("data-ids").split(","):[s.id.split("|")[e(this).parent().index()]];if(n.length){if(t(this))return;le.wordpress.ajax("button-purchase",{product_ids:n,checkout:a,coupon:s.coupon},t=>{a?document.location=t:e(this).addClass("sb-icon-check").sbLoading(!1)})}return i.preventDefault(),!1}),e(h).on("click","#sb-waiting-list .sb-submit",function(){0==e(this).index()&&setTimeout(()=>{le.woocommerce.waitingList("submit")},1e3)}),e(document).on("SBNewEmailAddress",function(e,t){"sb-waiting-list-email"==t.id&&le.woocommerce.waitingList("submit")}),e(h).on("click",".sb-player-btn",function(){let t=e(this).parent().find("audio").get(0),i=e(this).hasClass("sb-icon-play");h.find("audio").each(function(){e(this).get(0).pause(),e(this).unbind("ended"),e(this).parent().find(".sb-player-btn").removeClass("sb-icon-pause").addClass("sb-icon-play")}),i?(t.play(),e(this).removeClass("sb-icon-play")):t.pause(),e(t).unbind("ended"),e(t).bind("ended",()=>{e(this).removeClass("sb-icon-pause").addClass("sb-icon-play")}),e(this).addClass("sb-icon-"+(i?"pause":"play"))}),e(h).on("click",".sb-player-speed",function(){let t=e(this).parent();if(t.find(".sb-player-btn").hasClass("sb-icon-pause")){let i=e(this).find(".sb-player-speed-number"),s=parseFloat(i.html());(s+=.5)>2&&(s=1),t.find("audio").get(0).playbackRate=s,i.html(s)}}),e(h).on("click",".sb-player-download",function(){window.open(e(this).parent().find("audio source").attr("src"))}),e(g).on("click",".sb-btn-audio-clip",function(){if((A=ne.conversation&&"wa"==ne.conversation.get("source"))&&typeof SBAudioRecorder===G)return e.getScript(SB_URL+"/vendor/lame.min.js",()=>{this.click()},!0);navigator.mediaDevices.getUserMedia({audio:!0}).then(t=>{A?SBAudioRecorder.init(t):(typeof SBAudioRecorder!=G&&SBAudioRecorder.close(),H=[],(T=new MediaRecorder(t)).addEventListener("dataavailable",e=>{H.push(e.data)})),k||(k=g.find("#sb-audio-clip"),C=k.find(".sb-audio-clip-time"),k.on("click",".sb-btn-mic",function(){let t=e(this).hasClass("sb-icon-pause");if(t)A?SBAudioRecorder.pause():T.stop();else{let e=k.find(".sb-btn-clip-player");e.hasClass("sb-icon-pause")&&e.click(),A?SBAudioRecorder.resume():T.start()}J[2]=!t,k.find(".sb-icon-play").sbActive(t),e(this).removeClass("sb-icon-"+(t?"pause":"mic")).addClass("sb-icon-"+(t?"mic":"pause"))}),k.on("click",".sb-btn-clip-player",function(){let t=e(this).hasClass("sb-icon-pause");if(t)Y[3].pause(),Y[2]=!1;else if(Y[3])Y[3].play(),Y[2]=!0;else{let t=new Audio(URL.createObjectURL(A?SBAudioRecorder.blob(!1):new Blob(H,{type:"audio/webm"})));C.html("0:00"),t.play(),t.onended=(()=>{Y[0]=0,Y[2]=!1,Y[3]=!1,C.html("0:00"),e(this).removeClass("sb-icon-pause").addClass("sb-icon-play")}),Y[0]=0,Y[2]=!0,Y[3]=t}e(this).removeClass("sb-icon-"+(t?"pause":"play")).addClass("sb-icon-"+(t?"play":"pause"))}),k.on("click",".sb-icon-close",function(){H=[],clearInterval(J[1]),clearInterval(Y[1]),k.sbActive(!1),g.sbActive(!1).removeClass("sb-audio-message-active"),A?SBAudioRecorder.pause():T.stop(),B.getTracks()[0].stop()})),C.html("0:00"),B=t,clearInterval(J[1]),clearInterval(Y[1]),J=[0,setInterval(()=>{J[2]&&(J[0]++,C.html(o(J[0])))},1e3),!0],Y=[0,setInterval(()=>{Y[2]&&(Y[0]++,C.html(o(Y[0])))},1e3),!1,!1],A||T.start(),k.find(".sb-btn-clip-player").removeClass("sb-icon-pause").addClass("sb-icon-play").sbActive(!1),k.find(".sb-icon-mic").removeClass("sb-icon-mic").addClass("sb-icon-pause"),k.sbActive(!0),p.val("").css("height",""),g.sbActive(!0).addClass("sb-audio-message-active")}).catch(e=>{alert(e)})}),e(h).on("click","[data-action].sb-rich-btn",function(t){return oe.calendly.load(e(this).attr("data-extra"),e(this).html(),e(this).closest("[data-id]").attr("data-id")),t.preventDefault(),!1}),e(b).on("click","> div:first-child i",function(){l.find(".sb-overlay-panel").sbActive(!1),b.attr("data-close-chat")&&ne.closeChat()}),e(l).on("change input","#phone > input",function(){let t=e(this).val().trim();if(/^[0-9+]+$/.test(t)||(t=t.replace(/[^0-9+]/g,""),e(this).val(t)),t.length>1&&0===t.indexOf("+")){let i=!1;"+1"==t.substring(0,2)&&(i=t.substring(0,2)),t.length>3&&(i=t.substring(0,3)),i&&(e(this).parent().find(`[data-value="${i}"]`).click(),e(this).parent().find(".sb-select").click(),e(this).val(t.replace(i,"")))}}),e(c).on("click",".sb-search-btn > i",function(){let t=e(this).parent(),i=e(t).sbActive();i&&(setTimeout(()=>{e(t).find("input").val("")},50),setTimeout(()=>{e(t).find("input").trigger("change")},550)),e(t).sbActive(!i),e(t).find("input").get(0).focus(),c.find(".sb-select ul").sbActive(!1)}),e(c).on("click",".sb-select",function(t){if(!t.target||!e(t.target).is("input")){let t=e(this).find("ul"),i=t.hasClass("sb-active");e(c).find(".sb-select ul").sbActive(!1),t.setClass("sb-active",!i),e(this).find(".sb-select-search").setClass("sb-active",!i),x&&(SBAdmin.open_popup=!i&&this)}}),e(c).on("click",".sb-select li",function(){let t=e(this).closest(".sb-select"),i=e(this).data("value"),s=e(t).find(`[data-value="${i}"]`);t.find("li").sbActive(!1),t.find("p").attr("data-value",i).html(e(s).html()),s.sbActive(!0)}),e(c).on("input",".sb-select-search input",function(t){let i=e(this).val();ee.search(i,()=>{let t=e(this).parent().parent().find("li");t.setClass("sb-hide",i.length),i.length&&(i=i.toLowerCase(),t.each(function(){(e(this).attr("data-value").includes(i)||e(this).attr("data-country").includes(i))&&e(this).removeClass("sb-hide")}))})}),e(c).on("click",".sb-input-image .image",function(){d=e(this).parent(),g.find(".sb-upload-files").click()}),e(c).on("click",".sb-input-image .image > .sb-icon-close",function(t){return ee.ajax({function:"delete-file",path:e(this).parent().attr("data-value")}),e(this).parent().removeAttr("data-value").css("background-image",""),t.preventDefault(),!1})}var l,c,d,u,h,g,p,f,m,v,_,b,y,w,S,A,k,C,T,B,x=!1,$=!1,E=!1,I=!1,R=!1,j=[],L=!1,M=[9999999,""],N=[!1,!1],D=document.title,U={},O=e(window).width()<465,P="",q=!1,G="undefined",F=!0,z=6e4*(new Date).getTimezoneOffset(),W=!1,V=!1,H=[],J=[0,!1],Y=[0,!1],X=!1,Q=!1,K=0,Z=typeof Shopify!==G;e.fn.extend({manualExpandTextarea:function(){var t=this[0];t.style.height="auto",t.style.maxHeight="25px",window.getComputedStyle(t),t.style.height=(t.scrollHeight>350?350:t.scrollHeight)+"px",t.style.maxHeight="",e(t).trigger("textareaChanged")},autoExpandTextarea:function(){var t=this[0];t.addEventListener("input",function(i){e(t).manualExpandTextarea()},!1)}}),function(){var e=[].slice;String.prototype.autoLink=function(){var t,i,s,a,n,o,r;return o=/(^||[\s\n]|<[A-Za-z]*\/?>)((?:https?|ftp):\/\/[\-A-Z0-9+\u0026\u2019@#\/%?=()~_|!:,.;]*[\-A-Z0-9+\u0026@#\/%=~_|])/gi,0<(n=1<=arguments.length?e.call(arguments,0):[]).length?(a=n[0],t=a.callback,s=function(){var e;for(i in e=[],a)r=a[i],"callback"!==i&&e.push(" "+i+"='"+r+"'");return e}().join(""),this.replace(o,function(e,i,a){return""+i+(("function"==typeof t?t(a):void 0)||"<a href='"+a+"'"+s+">"+a+"</a>")})):this.replace(o,"$1<a href='$2'>$2</a>")}}.call(this);var ee={visibility_status:"visible",loop_prevention:!1,ajax:function(t,i=!1){S?(S[0].push(t),S[1].push(i)):(S=[[t],[i]],setTimeout(()=>{let s=S[1],n={"login-cookie":ee.loginCookie()};a()&&(n.user_id=a().id),typeof SB_LANG!=G&&(n.language=SB_LANG),W&&(n.cloud=W),location.search.includes("debug")&&(n.debug=!0),e.ajax({method:"POST",url:SB_AJAX_URL,data:e.extend({function:"ajax_calls",calls:S[0]},n)}).done(e=>{let a;if(Array.isArray(e))a=e;else if("invalid-session"===e)setTimeout(()=>{ee.reset()},1e3);else{if(x&&SB_ADMIN_SETTINGS.cloud&&e.includes("no-credits")&&!e.includes('"value":"no-credits'))return SBCloud.creditsAlertQuota();try{a="string"==typeof e||e instanceof String?JSON.parse(e):e}catch(i){return void this.ajax_error(e,t)}}for(var n=0;n<a.length;n++){let e=a[n];if(Array.isArray(e)||(e=a),"success"==e[0])(i=s[n])&&i(e[1]);else if(ee.errorValidation(e))i&&i(e);else{if(x&&("security-error"==e[1]&&setTimeout(()=>{ee.reset()},1e3),SBAdmin.conversations.busy=!1),ne.is_busy_update=!1,ne.busy(!1),"login-data-error"==e[1]&&!this.loop_prevention)return;let i=JSON.parse(e);Array.isArray(i)&&"error"==i[0]&&i[2]&&i[3]?ee.error(i[3],i[2]):ee.error(JSON.stringify(e).replace(/\\/g,"").replace(/\"/g,"").replace(/\[/g,"").replace(/\]/g,"").replace("error,",""),t.function)}}}).fail((e,t,i)=>{i&&(this.ajax_error("HTTP CURL ERROR"),console.log(i))}),S=!1},100))},ajax_error:function(e,t=!1){x&&(SBAdmin.conversations.busy=!1,le.dialogflow.smart_reply_busy=!1),le.dialogflow.busy&&(le.dialogflow.busy=!1,!x&&ne.conversation&&(ee.ajax({function:"open-ai-send-fallback-message",conversation_id:ne.conversation.id}),ne.typing(-1,"stop"))),ne.is_busy_update=!1,ne.busy(!1),console.log(e),ee.error(e.length>500?e.substr(0,500)+"... Check the console for more details.":e,`SBF.ajax.${t?t.function:""}`)},cors:function(e="GET",t,i){let s=new XMLHttpRequest;if("withCredentials"in s)s.open(e,t,!0);else{if(typeof XDomainRequest==G)return!1;(s=new XDomainRequest).open(e,t)}s.onload=function(){i(s.responseText)},s.onerror=function(){return!1},s.send()},upload:function(e,t){W&&e.append("cloud",W),jQuery.ajax({url:SB_URL+"/include/upload.php",cache:!1,contentType:!1,processData:!1,data:e,type:"POST",success:function(e){t(e)}})},getFileType:function(e){return/.jpg|.jpeg|.png|.gif|.webp/.test(e)?"image":/.mp3|.ogg|.wav|.aac/.test(e)?"audio":/.mp4|.mkv|.vob|.3gp|.webm/.test(e)?"video":"file"},UTC:function(e){return new Date(e).getTime()-z},null:function(e){return typeof e===G||null===e||"null"===e||!1===e||!(e.length>0||"number"==typeof e||typeof e.length==G)||e===G},deactivateAll:function(){c.find(".sb-popup, .sb-tooltip, .sb-list .sb-menu, .sb-select ul").sbActive(!1)},deselectAll:function(){window.getSelection?window.getSelection().removeAllRanges():document.selection&&document.selection.empty()},getURL:function(e=!1,t=!1){if(t||(t=location.search),0==e){for(var i=t.split("?").pop().split("&"),s={},a=0;a<i.length;a++){var n=i[a].split("=");s[n[0]]=ee.escape(n[1])}return s}return t.indexOf("?")>0&&(t=t.substr(0,t.indexOf("?"))),ee.escape(decodeURIComponent((new RegExp("[?|&]"+e+"=([^&;]+?)(&|#|;|$)").exec(t)||[,""])[1].replace(/\+/g,"%20")||""))},URL:function(){return window.location.href.substr(0,window.location.href.indexOf("?"))},stringToSlug:function(e){let t={"ก":"k","ข":"kh","ฃ":"kh","ค":"kh","ฅ":"kh","ฆ":"kh","ง":"ng","จ":"ch","ฉ":"ch","ช":"ch","ซ":"s","ฌ":"ch","ญ":"y","ฎ":"d","ฏ":"t","ฐ":"th","ฑ":"th","ฒ":"th","ณ":"n","ด":"d","ต":"t","ถ":"th","ท":"th","ธ":"th","น":"n","บ":"b","ป":"p","ผ":"ph","ฝ":"f","พ":"ph","ฟ":"f","ภ":"ph","ม":"m","ย":"y","ร":"r","ล":"l","ว":"w","ศ":"s","ษ":"s","ส":"s","ห":"h","ฬ":"l","อ":"o","ฮ":"h","ะ":"a","ั":"a","า":"a","ำ":"am","ิ":"i","ี":"i","ึ":"ue","ื":"ue","ุ":"u","ู":"u","เ":"e","แ":"ae","โ":"o","ใ":"ai","ไ":"ai","ا":"a","ب":"b","ت":"t","ث":"th","ج":"j","ح":"h","خ":"kh","د":"d","ذ":"dh","ر":"r","ز":"z","س":"s","ش":"sh","ص":"s","ض":"d","ط":"t","ظ":"z","ع":"a","غ":"gh","ف":"f","ق":"q","ك":"k","ل":"l","م":"m","ن":"n","ه":"h","و":"w","ي":"y","你":"ni","好":"hao","世":"shi","界":"jie","我":"wo","是":"shi","中":"zhong","国":"guo","人":"ren","谢":"xie","再":"zai","见":"jian"},i="åàáãäâèéëêìíïîòóöôùúüûñç·/_,:;";e=e.trim().toLowerCase().split("").map(e=>t[e]||e).join("");for(var s=0,a=i.length;s<a;s++)e=e.replace(new RegExp(i.charAt(s),"g"),"aaaaaaeeeeiiiioooouuuunc------".charAt(s));return e.replace(/[^a-z0-9 -]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"").replace(/ /g,"")},slugToString:function(e){return(e=e.replace(/_/g," ").replace(/-/g," ")).charAt(0).toUpperCase()+e.slice(1)},random:function(){let e="";for(var t=5;t>0;--t)e+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return e},isAgent:function(e){return"agent"==e||"admin"==e||"bot"==e},beautifyTime:function(e,t=!1,i=!1){let a;if("0000-00-00 00:00:00"==e)return"";if(e.indexOf("-")>0){let t=e.split(/[- :]/);a=new Date(t[0],t[1]-1,t[2],t[3],t[4],t[5])}else{let t=e.split(/[. :]/);a=new Date(t[2],t[1]-1,t[0],t[3],t[4],t[5])}let n=new Date,o=new Date(Date.UTC(a.getFullYear(),a.getMonth(),a.getDate(),a.getHours(),a.getMinutes(),a.getSeconds())),r=(n-o)/864e5*(i?-1:1),l=[s("Sunday"),s("Monday"),s("Tuesday"),s("Wednesday"),s("Thursday"),s("Friday"),s("Saturday")],c=o.toLocaleTimeString(navigator.language,{hour:"2-digit",minute:"2-digit"});return"0"===c.charAt(0)&&(c.includes("PM")||c.includes("AM"))&&(c=c.substring(1)),r<1&&n.getDate()==o.getDate()?t?`<span>${s("Today")}</span> <span>${c}</span>`:`<span data-today>${c}</span>`:r<6?`<span>${l[o.getDay()]}</span>${t?` <span>${c}</span>`:""}`:`<span>${o.toLocaleDateString(void 0,{year:"2-digit",month:"2-digit",day:"2-digit"})}</span>${t?` <span>${c}</span>`:""}`},unix:function(e){let t=e.split(/[- :]/);return Date.UTC(t[0],t[1]-1,t[2],t[3],t[4],t[5])},getLocationTimeString:function(e,t){if(e.timezone){let i={};i.timezone=e.timezone.value,i.country=e.country?e.country.value:i.timezone.split("/")[0].replace(/_/g," "),i.city=e.city?e.city.value:i.timezone.split("/")[1].replace(/_/g," "),t(`${new Intl.DateTimeFormat(void 0,{timeZone:i.timezone,hour:"2-digit",minute:"2-digit"}).format(new Date)} ${s("in")} ${i.city?i.city:""}${i.country?", "+i.country:""}`)}},dateDB:function(e){return"now"==e?((e=(new Date).toISOString().replace("T"," ")).indexOf(".")>0&&(e=e.substr(0,e.indexOf("."))),e):`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()} ${e.getHours()}:${e.getMinutes()}:${e.getSeconds()}`},updateUsersActivity:function(e,t,i){te.active?i(x&&SB_ADMIN_SETTINGS.bot_id==t||!x&&U.bot_id==t?"online":te.online_ids.includes(t)?"online":"offline"):ee.ajax({function:"update-users-last-activity",user_id:e,return_user_id:t,check_slack:!x&&U.slack_active},e=>{i("online"===e?"online":"offline")})},search:function(e,t){(e=e.toLowerCase())!=u?(clearTimeout(E),E=setTimeout(function(){u=e,t()},1e3)):c.find(".sb-search-btn i").sbLoading(!1)},searchClear:function(t,i){e(t).next().val()&&(e(t).next().val(""),i())},error:function(e,t){let i=e.includes(t);if(!x||!SBAdmin.is_logout)throw e instanceof Error&&(e=e.message),"."==e[e.length-1]&&(e=e.slice(0,-1)),x&&(!e||t.includes("update-users-last-activity")||t.startsWith("security-error")||SBAdmin.infoPanel(`<pre>${i?"":`[Error] [${t}] `}${e}. Check the console for more details.</pre>`,"info",!1,"error"),le.dialogflow.smart_reply_busy=!1),c.find(".sb-loading").sbLoading(!1),ne.busy(!1),ee.event("SBError",{message:e,function_name:t}),new Error(i?e:`Support Board Error [${t}]: ${e}.`)},errorValidation:function(e,t=!0){return Array.isArray(e)&&"validation-error"===e[0]&&(!0===t||e[1]==t)},loginForm:function(t,i=!1,a=!1,n=!0){if(!(t=e(t)).sbLoading()){i=!1===i?t.closest(".sb-rich-login"):e(i);let o=e.trim(i.find("#email input").val()),r=e.trim(i.find("#password input").val());o&&r?(ee.ajax({function:"login",email:o,password:r},e=>{if(e&&Array.isArray(e)){if(!x&&this.isAgent(e[0].user_type))re.showErrorMessage(i,"You cannot sign in as an agent."),ne.scrollBottom();else{let t=new ie(e[0]);t.set("conversation_id",!!ne.conversation&&ne.conversation.id),this.loginCookie(e[1]),this.event("SBLoginForm",t),a&&a(e)}"wp"==ee.setting("wp-users-system")&&le.wordpress.ajax("wp-login",{user:o,password:r})}else{if(x&&le.is("wordpress"))return le.wordpress.ajax("wp-login-admin",{user:o,password:r},()=>{t.sbLoading(!1),n?this.loginForm(t,i,a,!1):i.find(".sb-info").html(s("ip-ban"===e?"Too many login attempts. Please retry again in a few hours.":"Invalid email or password.")).sbActive(!0)});i.find(".sb-info").html(s("ip-ban"===e?"Too many login attempts. Please retry again in a few hours.":"Invalid email or password.")).sbActive(!0),x||ne.scrollBottom()}t.sbLoading(!1)}),i.find(".sb-info").html("").sbActive(!1),t.sbLoading(!0)):(i.find(".sb-info").html(s("Please insert email and password.")).sbActive(!0),ne.scrollBottom())}},loginCookie:function(e=!1){if(!1===e)return this.cookie("sb-login")?this.cookie("sb-login"):i("login");U.cloud?i("login",e):this.cookie("sb-login",e,3650,"set")},login:function(e="",t="",i="",s="",a=!1){ee.ajax({function:"login",email:e,password:t,user_id:i,token:s},e=>!(0==e||!Array.isArray(e))&&(this.loginCookie(e[1]),a&&a(e),!0))},logout:function(e=!0){ne.stopRealTime(),this.cookie("sb-login","","",!1),this.cookie("sb-cloud","","",!1),i("open-conversation",""),i("login",""),ne.conversations=!1,a(!1),typeof sb_beams_client!==G&&sb_beams_client.stop(),typeof SB_AJAX_URL!==G&&ee.ajax({function:"logout"},()=>{ee.event("SBLogout"),e&&setTimeout(()=>{location.reload()},500)})},activeUser:function(){return a()},getActiveUser:function(e=!1,t){let s=le.login();!s&&(i("wp-login")||i("whmcs-login")||i("perfex-login")||i("aecommerce-login"))&&(this.cookie("sb-login","","","delete"),a(!1),i("login",""),i("wp-login",""),i("whmcs-login",""),i("perfex-login",""),i("aecommerce-login","")),ee.ajax({function:"get-active-user",db:e,login_app:JSON.stringify(s),user_token:ee.getURL("token")},e=>{if(!e)return t(),!1;if(e.cookie&&ee.loginCookie(e.cookie),e.user_type)if(!x&&ee.isAgent(e.user_type)){let e="You are logged in as both agent and user. Logout or use another browser, Incognito or Private mode, to login as user. Force a logout by running the function SBF.reset() in the console.";i("double-login-alert")||(i("double-login-alert",!0),alert(e)),console.warn("Support Board: "+e),ee.event("SBDoubleLoginError")}else a(new ie(e,e.phone?{phone:e.phone}:{})),te.start(),s&&i(s[1]+"-login",!0),t(),ee.event("SBActiveUserLoaded",e)})},reset:function(){let e=["sb-login","sb-cloud","sb-dialogflow-disabled"];for(var t=0;t<e.length;t++)this.cookie(e[t],"",0,!1);try{localStorage.removeItem("support-board")}catch(e){}this.logout()},lightbox:function(t){let i=e(x?c:l).find(".sb-lightbox-media");i.sbActive(!0).find(" > div").html(t),x&&(SBAdmin.open_popup=i)},storage:function(e,t=G){try{if(typeof localStorage==G)return!1}catch(e){return!1}let i=localStorage.getItem("support-board");if(i=null===i?{}:JSON.parse(i),t===G)return e in i&&i[e];t?i[e]=t:delete i[e],localStorage.setItem("support-board",JSON.stringify(i))},storageTime:function(e,t=!1){let s=new Date;if(!1!==t)return 0==i(e)||s.getTime()-i(e)>36e5*t&&(i(e,!1),!0);i(e,s.getTime())},cookie:function(e,t=!1,i=!1,s="get",a=!1){let n="https:"==location.protocol?"SameSite=None;Secure;":"",o=window[x?"SB_ADMIN_SETTINGS":"CHAT_SETTINGS"],r=o&&o.cookie_domain?"domain="+o.cookie_domain+";":"";if("get"==s){if(!F)return this.storage(e);let t=document.cookie.split(";");for(var l=0;l<t.length;l++){for(var c=t[l];" "==c.charAt(0);)c=c.substring(1);if(0==c.indexOf(e)){let t=c.substring(e.length+1,c.length);return!this.null(t)&&t}}return!1}if("set"==s)if(F){let s=new Date;s.setTime(s.getTime()+i*(a?1:86400)*1e3),document.cookie=e+"="+t+";expires="+s.toUTCString()+";path=/;"+n+r}else this.storage(e,t);else this.cookie(e)&&(F?document.cookie=e+"="+t+";expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;"+n+r:this.storage(e,""))},setting:function(e,t=-1){if(-1===t)return typeof U!==G&&e in U&&U[e];typeof U!==G&&(U[e]=t)},shortcode:function(e){return oe.shortcode(e)},event:function(t,i){e(document).trigger(t,i);let s=x?typeof SB_ADMIN_SETTINGS!==G&&SB_ADMIN_SETTINGS.webhooks:U.webhooks,a={SBGetUser:"get-user",SBSMSSent:"sms-sent",SBLoginForm:"login",SBRegistrationForm:"registration",SBUserDeleted:"user-deleted",SBNewMessagesReceived:"new-messages",SBNewConversationReceived:"new-conversation",SBSlackMessageSent:"slack-message-sent",SBMessageDeleted:"message-deleted",SBRichMessageSubmit:"rich-message",SBNewEmailAddress:"new-email-address"};if(s&&t in a){if(!0!==s&&(Array.isArray(s)||(s=s.replace(/ /g,"").split(",")),!s.includes(a[t])))return;ee.ajax({function:"webhooks",function_name:t,parameters:i})}},translate:function(e){if(!x&&ee.null(U)||x&&typeof SB_TRANSLATIONS===G)return e;let t=x?SB_TRANSLATIONS:U.translations;return t&&t[e]&&t[e]?t[e]:e},escape:function(e){return e?e.replace(/</gi,"<").replace(/javascript:|onclick|onerror|ontoggle|onmouseover|onload|oncontextmenu|ondblclick|onmousedown|onmouseenter|onmouseleave|onmousemove|onmouseout|onmouseup/gi,""):""},strip:function(e){e=e.replace("```","");let t=[/\*([^\**]+)\*/,/\__([^\____]+)\__/,/\~([^\~~]+)\~/,/\`([^\``]+)\`/];for(var i=0;i<2;i++)t.forEach(t=>{e=e.replace(t,e=>e.replace(/[\*\_\~\`]/g,""))});return e.replace(/\\,/g,",").replace(/\\:/g,":")},visibilityChange:function(e=""){this.visibility_status=e;let t=x&&typeof SBAdmin!==G;"hidden"==e?(x||ne.stopRealTime(),ne.tab_active=!1,this.visibility_was_hidden=!0):(a()&&!x&&ne.startRealTime(),ne.tab_active=!0,clearInterval(R),clearInterval(ne.audio_interval),ne.conversation&&(ne.conversation.updateMessagesStatus(),(ne.chat_open||x)&&ne.updateNotifications(ne.conversation.id),t&&setTimeout(()=>{SBAdmin.conversations.notificationsCounterReset(ne.conversation.id)},2e3)),t&&(Date.now()-(O?6e4:18e4)>K&&(SBAdmin.conversations.update(),K=Date.now()),O&&ne.update()),document.title=D,this.serviceWorker.closeNotifications())},settingsStringToArray:function(e){if(this.null(e))return[];let t=[];e=e.split(",");for(var i=0;i<e.length;i++){let s=e[i].split(":");t[s[0]]="false"!=s[1]&&("true"==s[1]||s[1])}return t},openWindow:function(e,t=550,i=350){let s=screen.width/2-t/2,a=screen.height/2-i/2;return window.open(e,"targetWindow","toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width="+t+",height="+i+", top="+a+", left="+s),!1},convertUTCDateToLocalDate:function(e,t=0){return e=new Date(e),e=new Date(e.getTime()+36e5*t),new Date(e.getTime()+-1*z)},loadResource:function(e,t=!1,i=!1,s=!1){let a=document.createElement(t?"script":"link");e?(t?a.src=e:a.href=e,a.type=t?"text/javascript":"text/css"):a.innerHTML=s,i&&(a.onload=function(){i()}),t||(a.rel="stylesheet"),document.head.appendChild(a)},debounce:function(e,t,i=500){t in j||(j[t]=!0,e(),setTimeout(()=>{delete j[t]},i))},serviceWorker:{sw:!1,timeout:!1,init:function(){navigator.serviceWorker&&navigator.serviceWorker.register(x||"undefined"!=typeof SB_CLOUD_SW?SB_URL.replace("/script","")+"/sw.js?v=3.8.3":U.push_notifications_url+"?v=3.8.3").then(e=>{e.update(),this.sw=e}).catch(function(e){console.warn(e)})},initPushNotifications:function(){x&&("pusher"==SB_ADMIN_SETTINGS.push_notifications_provider||"onesignal"!=SB_ADMIN_SETTINGS.push_notifications_provider)||!x&&("pusher"==U.push_notifications_provider||"pushalert"!=U.push_notifications_provider)?te.initPushNotifications():e.getScript("https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js",()=>{window.OneSignalDeferred=window.OneSignalDeferred||[],OneSignalDeferred.push(e=>{e.init({appId:SB_ADMIN_SETTINGS.push_notifications_id})}),OneSignalDeferred.push(e=>{e.User.PushSubscription.addEventListener("change",t=>{if(t.current.optedIn){let t=(x&&SB_ADMIN_SETTINGS.cloud?SB_ADMIN_SETTINGS.cloud.cloud_user_id+"-":!x&&U.cloud?U.cloud.cloud_user_id+"-":"")+(x?SB_ACTIVE_AGENT.id:a().id);1==t&&(t="SB-1"),e.User.addTag("user_type",x?"agents":"users"),e.login(t)}ee.event("SBPushNotificationSubscription",t.current)})}),Q=!1})},closeNotifications:function(e=0){this.sw&&this.sw.getNotifications().then(t=>{if(t.length)for(let e=0;e<t.length;e+=1)t[e].close();else e<300&&"visible"==ee.visibility_status&&setTimeout(()=>{this.closeNotifications(e+1)},10)})},pushNotification:function(e,t=!1){let i=x?SB_ACTIVE_AGENT.profile_image:a().image;ee.ajax({function:"push-notification",title:x?SB_ACTIVE_AGENT.full_name:a().name,message:ee.strip(e),icon:i.indexOf("user.svg")>0?U.notifications_icon:i,interests:t||ne.getRecipientUserID(),conversation_id:!!ne.conversation&&ne.conversation.id},e=>e)}},beautifyAttachmentName:function(e){let t=e.indexOf("_");return-1!==t?e.substring(t+1):e}},te={channels:{},channels_presence:[],active:!1,pusher:!1,started:!1,pusher_beams:!1,initialized:!1,online_ids:[],beams_loaded:!1,init:function(t=!1){if(te.active){if(this.pusher)return!t||t();if(!t)return;e(window).one("SBPusherInit",()=>{t()}),this.initialized=!0,typeof Pusher===G?e.getScript("https://js.pusher.com/8.2.0/pusher.min.js",()=>{window.Pusher=Pusher,this.init_2()},!0):this.init_2()}},init_2:function(){this.pusher=new Pusher(x?SB_ADMIN_SETTINGS.pusher_key:U.pusher_key,{cluster:x?SB_ADMIN_SETTINGS.pusher_cluster:U.pusher_cluster,channelAuthorization:{endpoint:SB_URL+"/include/pusher.php",params:{login:ee.loginCookie(),cloud_user_id:!!U.cloud&&U.cloud.cloud_user_id}}}),ee.event("SBPusherInit")},initPushNotifications:function(){(a()||x)&&(this.beams_loaded?this.initPushNotifications_2():e.getScript("https://js.pusher.com/beams/2.0.0-beta.0/push-notifications-cdn.js",()=>{this.initPushNotifications_2()},!0))},initPushNotifications_2:function(){window.navigator.serviceWorker.ready.then(e=>{this.pusher_beams=new PusherPushNotifications.Client({instanceId:x?SB_ADMIN_SETTINGS.push_notifications_id:U.push_notifications_id,serviceWorkerRegistration:e}),ee.serviceWorker.closeNotifications(),this.pusher_beams.start().then(()=>this.pusher_beams.setDeviceInterests(x?[SB_ACTIVE_AGENT.id,"agents"]:[a().id,"users"])).catch(console.error),Q=!1})},start:function(){x||this.started||!a()||(this.active&&this.init(()=>{this.event("client-typing",e=>{e.user_id==ne.agent_id&&ne.conversation&&e.conversation_id==ne.conversation.id&&(ne.typing(-1,"start"),clearTimeout(I),I=setTimeout(()=>{ne.typing(-1,"stop")},1e3))}),this.event("new-message",e=>{!(e&&a()&&e.conversation_id)||a().getConversationByID(e.conversation_id)&&ne.conversation&&ne.conversation.id==e.conversation_id?ne.update():ne.updateConversations()}),this.presence(1,()=>{this.started=!0,ne.automations.runAll()})}),U.push_notifications_users&&("pusher"!=U.push_notifications_provider&&"onesignal"==U.push_notifications_provider||(typeof Notification!=G&&"granted"==Notification.permission?this.initPushNotifications():Q=!0)))},subscribe:function(e,t=!1){if(!this.pusher)return this.init(()=>{this.subscribe(e,t)});e=this.cloudChannelRename(e);let i=this.pusher.subscribe(e);i.bind("pusher:subscription_error",e=>console.log(e)),i.bind("pusher:subscription_succeeded",()=>{this.channels[e]=i,t&&t()})},event:function(e,t,i="private-user-"+a().id){if(!this.pusher)return this.init(()=>{this.event(e,t,i)});let s=i;(i=this.cloudChannelRename(i))in this.channels?(this.channels[i].unbind(e),this.channels[i].bind(e,e=>{t(e)})):this.subscribe(s,()=>{this.event(e,t,s)})},trigger:function(e,t={},i="private-user-"+a().id){if(0==e.indexOf("client-"))return this.channels[this.cloudChannelRename(i)].trigger(e,t);ee.ajax({function:"pusher-trigger",channel:i,event:e,data:t},e=>e)},presence:function(e=1,t){if(!this.pusher)return this.init(()=>{this.presence()});let i=this.pusher.subscribe(this.cloudChannelRename("presence-"+e));i.bind("pusher:subscription_succeeded",i=>{if(i.count>98)return this.subscribe(e+1);i.each(e=>{this.presenceCheck(e)&&this.online_ids.push(e.id)}),ne.updateUsersActivity(),t&&t()}),i.bind("pusher:subscription_error",e=>console.log(e)),i.bind("pusher:member_added",e=>{this.presenceCheck(e)&&this.presenceAdd(e.id),x&&ee.storageTime("online-user-notification-"+e.id,24)&&(SBAdmin.users.onlineUserNotification(e),ee.storageTime("online-user-notification-"+e.id))}),i.bind("pusher:member_removed",e=>{this.presenceRemove(e.id)}),this.channels_presence.push(i),!x&&U.slack_active&&(this.event("add-user-presence",e=>{this.presenceAdd(e.agent_id)}),ee.ajax({function:"slack-presence",list:!0},e=>{for(var t=0;t<e.length;t++)this.presenceAdd(e[t]);ne.updateUsersActivity()}))},presenceCheck:function(e){let t=ee.isAgent(e.info.user_type);return(x&&!t||!x&&t)&&!this.online_ids.includes(e.id)},presenceAdd:function(e){typeof e==G||this.online_ids.includes(e)||(this.online_ids.push(e),this.presenceUpdateAdmin(e),ne.updateUsersActivity())},presenceRemove:function(e){if(typeof e==G)return;let t=this.online_ids.indexOf(e);-1!==t?(this.online_ids.splice(t,1),this.presenceUpdateAdmin(e),ne.updateUsersActivity()):x&&c.find(`.sb-conversation-busy[data-agent="${e}"]`).remove()},presenceUnsubscribe:function(){for(var e=0;e<this.channels_presence.length;e++)this.channels_presence[e].unsubscribe(this.cloudChannelRename("presence-"+(e+1)))},presenceUpdateAdmin:function(e){x&&(c.find(".sb-area-users.sb-active").length&&SBAdmin.users.update(),a()&&a().id==e&&SBAdmin.users.updateUsersActivity())},cloudChannelRename:function(e){return U.cloud||x&&SB_ADMIN_SETTINGS.cloud?e+"-"+(x?SB_ADMIN_SETTINGS.cloud.cloud_user_id:U.cloud.cloud_user_id):e}};window.SBF=ee,window.SBPusher=te,window.sb_current_user=!1,e.fn.sbActive=function(t=-1){return-1===t?e(this).hasClass("sb-active"):(e(this).setClass("sb-active",t),this)},e.fn.sbLoading=function(t="check"){return"check"==t?e(this).hasClass("sb-loading"):(e(this).setClass("sb-loading",t),this)},e.fn.sbTogglePopup=function(t=!1){let i=!0;return x&&(SBAdmin.open_popup=!1),e(this).sbActive()?(e(this).sbActive(!1),c.removeClass("sb-popup-active"),i=!1):(c.addClass("sb-popup-active"),c.find(".sb-popup").sbActive(!1),t&&e(this).css("left",e(t).offset().left+15).sbActive(!0),x&&setTimeout(()=>{SBAdmin.open_popup=this},500),ee.deselectAll()),i},e.fn.sbUploadFiles=function(t,i=!1){let a=e(this).prop("files");for(var n=!1===i?0:i;n<(!1===i?a.length:i+1);n++){let e=a[n],i=e.size/1048576,o=x?SB_ADMIN_SETTINGS.max_file_size:U.max_file_size;if(i>o){let e=s("Maximum upload size is {R}MB. File size: {R2}MB.").replace("{R}",o).replace("{R2}",i.toFixed(2));x?SBAdmin.infoPanel(e,"info"):alert(e)}let r=new FormData;r.append("file",e),ee.upload(r,t)}e(this).value=""},e.fn.setProfile=function(t=!1,i=!1){return ee.null(t)&&(t=a()?a().name:""),ee.null(i)&&(i=a()?a().image:SB_URL+"/media/user.svg"),t&&e(this).removeClass("sb-profile-empty"),e(this).find("img").attr("src",i),e(this).find(".sb-name").html(t),this},e.fn.setClass=function(t,i=!0){return i?e(this).addClass(t):e(this).removeClass(t),this};class ie{constructor(e={},t={}){this.details=e,this.extra=t,this.conversations=[],this.processArray(e)}get id(){return this.get("id")?this.get("id"):this.get("user_id")}get type(){return this.get("user_type")}get email(){return this.get("email")}get name(){return this.details.first_name?this.details.first_name+(this.details.last_name?" "+this.details.last_name:""):""}get nameBeautified(){let e=x?SB_ADMIN_SETTINGS.visitor_default_name:U.visitor_default_name;return!e||this.details.last_name&&"#"!=this.details.last_name.charAt(0)?this.name:e}get image(){return this.get("profile_image")}get language(){let e=this.getExtra("language");return e||(e=this.getExtra("browser_language")),e?e.value.toLowerCase():""}get(e){return e in this.details&&!ee.null(this.details[e])?this.details[e]:""}getExtra(e){return e in this.extra&&!ee.null(this.extra[e])?this.extra[e]:""}set(e,t){this.details[e]=t}setExtra(e,t){this.extra[e]=t}processArray(e){if(e&&e.details){for(var t=0;t<e.details.length;t++)this.setExtra(e.details[t].slug,e.details[t]);delete e.details,this.details=e}}update(e){this.id?ee.ajax({function:"get-user",user_id:this.id,extra:!0},t=>{this.processArray(t),e(),ee.event("SBGetUser",this)}):ee.error("Missing user ID","SBUser.update")}getConversations(e=!1,t){this.id?ee.ajax({function:"get-user-conversations",user_id:this.id,exclude_id:t,agent:ee.isAgent(this.type)},t=>{if(!ee.errorValidation(t)){let s=[];for(var i=0;i<t.length;i++)ne.isConversationAllowed(t[i].source,t[i].conversation_status_code)&&s.push(new ae([new se(t[i])],t[i]));this.conversations=s,e&&e(s)}}):ee.error("Missing user ID","SBUser.getConversations")}getConversationsCode(e=!1){let t="",i=ne.conversation?ne.conversation.id:-1;e||(e=this.conversations);for(var s=0;s<e.length;s++)if(e[s]instanceof ae){if(!x&&!ne.isConversationAllowed(e[s].get("source"),e[s].status_code))continue;let n=0,o=i==e[s].id;if(!x&&!o)for(var a=0;a<ne.notifications.length;a++)ne.notifications[a][0]==e[s].id&&n++;t+=`<li ${o?'class="sb-active" ':""}data-conversation-status="${o?0:e[s].status_code}" data-conversation-id="${e[s].id}" data-department="${e[s].get("department")}">${e[s].getCode()}${n?'<span data-count="'+n+'">'+n+"</span>":""}</li>`}else ee.error("Conversation not of type SBConversation","SBUser.getConversationsCode");return t}getFullConversation(e=!1,t=!1){!1!==e?ee.ajax({function:"get-conversation",conversation_id:e},e=>{let i=[];if(e){if("agent-not-authorized"===e)return void(window.location.href=ee.URL());for(var s=0;s<e.messages.length;s++)i.push(new se(e.messages[s]))}t&&t(new ae(i,!!e&&e.details))}):ee.error("Missing conversation ID","SBUser.getFullConversation")}getConversationByID(e,t=!1){for(var i=0;i<this.conversations.length;i++)if(this.conversations[i].id==e)return t?i:this.conversations[i];return!1}addConversation(e){if(e instanceof ae){let i=e.id,s=!0;for(var t=0;t<this.conversations.length;t++)if(this.conversations[t].id==i){this.conversations[t]=e,s=!1;break}return s&&this.conversations.unshift(e),s}ee.error("Conversation not of type SBConversation","SBUser.addConversation")}removeConversation(e){let t=this.getConversationByID(e,!0);!1!==t&&this.conversations.splice(t,1)}getLastConversation(){return!this.isConversationsEmpty()&&this.conversations[this.conversations.length-1]}isConversationsEmpty(){return 0==this.conversations.length}isExtraEmpty(){return 0===Object.keys(this.extra).length&&this.extra.constructor===Object}delete(e){this.id?ee.ajax({function:"delete-user",user_id:this.id},()=>(ee.event("SBUserDeleted",this.id),e(),!0)):ee.error("Missing user ID","SBUser.delete")}}window.SBUser=ie;class se{constructor(e={}){this.details=Object.assign({},e);let t=["message_status_code","message_id","message_profile_image","message_first_name","message_last_name","message_user_id","message_user_type"],i=["source","extra","title","tags","agent_id","department","last_update_time","conversation_creation_time","conversation_id","conversation_status_code","conversation_user_id"];for(s=0;s<t.length;s++)e[t[s]]&&(this.details[t[s].replace("message_","")]=e[t[s]]),delete this.details[t[s]];this.details.first_name&&(this.details.full_name=this.details.first_name+(this.details.last_name?" "+this.details.last_name:"")),e.last_update_time&&(this.details.creation_time=e.last_update_time);for(var s=0;s<i.length;s++)delete this.details[i[s]];let a=this.get("payload");if(a)try{var n=JSON.parse(this.get("payload").replace("\\'","'"));a=n&&"object"==typeof n?n:{}}catch(e){a={}}else a={};this.set("payload",a)}get id(){return this.get("id")}get attachments(){return ee.null(this.details.attachments)?[]:JSON.parse(this.details.attachments)}get message(){return x?this.payload("translation")&&this.payload("translation-language")==SB_ADMIN_SETTINGS.active_agent_language?this.payload("translation"):this.payload("original-message-language")==SB_ADMIN_SETTINGS.active_agent_language?this.payload("original-message"):this.get("message"):this.get("message")}get(e){return e in this.details&&!ee.null(this.details[e])?this.details[e]:""}set(e,t){this.details[e]=t}payload(e=!1,t=!1){let i=this.get("payload");if(!1!==e&&!1!==t)i[e]=t,this.set("payload",i);else if(!1!==e)return e in i?i[e]:!(!i.id||i.id!=e)&&i;return["boolean","string"].includes(typeof i)?[]:i}getCode(){let e=ee.isAgent(this.details.user_type),t=this.message,i=this.attachments,a=this.payload("reply"),n=x?SBAdmin.conversations.messageMenu(e,t,!a&&!e):"",o="",r="",l=x&&SB_ADMIN_SETTINGS.show_profile_images||!x&&(e&&!U.hide_agents_thumb||!e&&U.display_users_thumb)?`<div class="sb-thumb"><img loading="lazy" src="${this.details.profile_image}"><div class="sb-tooltip"><div>${this.details.full_name}</div></div></div>`:"",c=(x&&e||!x&&!e?"sb-right":"")+(l?" sb-thumb-active":""),d="",u=!x&&e&&U.sender_name||x&&"chat-admin"==SB_ADMIN_SETTINGS.sender_name?`<span class="sb-agent-name">${this.get("full_name")}</span>`:"",h=!!x&&this.payload().delivery_failed;if(!t&&!i.length)return"";if(a&&ne.conversation&&ne.conversation.getMessage(a)){a=ne.conversation.getMessage(a);let e=ee.isAgent(a.get("user_type")),t=a.message;t||(t='<div class="sb-message-attachments">',i.forEach(e=>{t+=`<a>${e[0]}</a>`}),t+="</div>"),a=`<div class="sb-reply-message${e?" sb-reply-agent":""}"><span>${e&&x||!e&&!x?s("You"):a.get("full_name")}</span> ${t}</div>`}else a="";if(e){let e=(t=(t=t.replace(/\n/g,"<br>")).replace(/`([\s\S]*?)`/g,e=>e.replace(/\[/g,"["))).match(/\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)\]/g)||[],i=!1,s=e.length;for(p=0;p<s;p++){let s=oe.shortcode(e[p]);if(s[0])if("action"==s[0])t=t.replace(e[p],"");else{let a=oe.generate(s[1],s[0]);a&&(t=t.replace(e[p],a),i=!0,d=`data-type="${s[0]}"`)}}i&&(c+=" sb-rich-cnt",s>1&&(d='data-type="multiple"'))}else if(t.includes("[rating ")){let e=oe.shortcode(t);t=oe.generate(e[1],e[0])}let g=t.includes("data-success")?[...t.matchAll(/data-success="([^"]*)"/g)].map(e=>e[1]):[];for(p=0;p<g.length;p++)t=t.replace(g[p],"{R"+p+"}");t=this.render(t);for(p=0;p<g.length;p++)t=t.replace("{R"+p+"}",g[p]);if(i.length){o='<div class="sb-message-attachments">';for(var p=0;p<i.length;p++){let e=i[p][1],s=e+i[p][0];if("image"==ee.getFileType(s)){let t="";i[p].length>2&&(t=`width="${(t=i[p][2].split("|"))[0]}" style="aspect-ratio: ${t[0]} / ${t[1]}"`),r+=`<div class="sb-image${s.includes(".png")?" sb-image-png":e.includes("sticker_")?" sb-image-sticker":""}"><img loading="lazy" src="${e}" ${t}/></div>`}else"audio"==ee.getFileType(s)||e.includes("voice_message")||e.includes("audioclip")?((x&&!SB_ADMIN_SETTINGS.speech_recognition||!x&&!U.speech_recognition)&&(t=""),o+=`<div class="sb-player"><div class="sb-player-btn sb-icon-play"></div><div class="sb-player-speed"><div class="sb-player-speed-number">1</div><div class="sb-icon-close"></div></div><div class="sb-player-download sb-icon-arrow-down"></div><audio><source src="${e}" type="audio/mpeg"></audio></div>`):o+=`<a rel="noopener" target="_blank" href="${e}">${ee.beautifyAttachmentName(i[p][0])}</a>`}o+="</div>"}return`<div data-id="${this.details.id}" class="${c}" ${d}>${l}${a}<div class="sb-cnt"><div class="sb-message${r&&!t?" sb-message-media":""}"${h?' style="opacity:.7"':""}>${h?SBAdmin.conversations.getDeliveryFailedMessage(h):""}${(u+t+r).trim()}</div>${o}<div class="sb-time">${ee.beautifyTime(this.details.creation_time,!0)}${x&&e&&2==this.details.status_code?'<i class="sb-icon-check"></i>':""}</div></div>${n}</div>`}render(t=!1){!1===t&&(t=""+this.details.message);let i=t.length,s=t.match(/```([\s\S]*?)```/g)||[];for(n=0;n<s.length;n++)t=t.replace(s[n],"[code-"+n+"]");if(t=t.replace(/(?:\r\n|\r|\n)/g,"<br>"),t=t.replace(/\*([^\**]+)\*/g,"<b>$1</b>"),t=t.replace(/__(.+?)__/g,"<i>$1</i>"),t=t.replace(/\~([^\~~]+)\~/g,"<del>$1</del>"),t=t.replace(/\`([^\``]+)\`/g,"<code>$1</code>"),((6==i||5==i)&&t.startsWith("&#x")||i<3&&t.match(/(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff]|[\u0023-\u0039]\ufe0f?\u20e3|\u3299|\u3297|\u303d|\u3030|\u24c2|\ud83c[\udd70-\udd71]|\ud83c[\udd7e-\udd7f]|\ud83c\udd8e|\ud83c[\udd91-\udd9a]|\ud83c[\udde6-\uddff]|\ud83c[\ude01-\ude02]|\ud83c\ude1a|\ud83c\ude2f|\ud83c[\ude32-\ude3a]|\ud83c[\ude50-\ude51]|\u203c|\u2049|[\u25aa-\u25ab]|\u25b6|\u25c0|[\u25fb-\u25fe]|\u00a9|\u00ae|\u2122|\u2139|\ud83c\udc04|[\u2600-\u26FF]|\u2b05|\u2b06|\u2b07|\u2b1b|\u2b1c|\u2b50|\u2b55|\u231a|\u231b|\u2328|\u23cf|[\u23e9-\u23f3]|[\u23f8-\u23fa]|\ud83c\udccf|\u2934|\u2935|[\u2190-\u21ff])/))&&(t=`<span class="emoji-large">${t}</span>`),t.includes("](http")){let e=t.split("[");t="";for(n=0;n<e.length;n++)e[n].includes("](http")&&(e[n]=e[n].substring(e[n].indexOf("](")+2,e[n].length-1)),t+=e[n]}t.includes("www.")&&(t=t.replaceAll("www.","https://www.").replaceAll("https://https:","https:").replaceAll("http://https:","http:"));let a=[['href="http',"[L1]"],['src="http',"[L2]"],['url("http',"[L3]"],["url('http","[L4]"],['extra="http',"[L5]"],['data-link="http',"[L6]"],['data-value="http',"[L7]"]];for(n=0;n<a.length;n++)t=t.replaceAll(a[n][0],a[n][1]);t.includes("http")&&(t=t.autoLink({target:"_blank",callback:function(e){return e.includes("#sb-")?`<a href="${e.split("#sb-")[0]}" target="_blank">${e.split("#sb-")[1].replaceAll("--"," ")}</a>`:null}}));for(n=0;n<a.length;n++)t=t.replaceAll(a[n][1],a[n][0]);for(var n=0;n<s.length;n++)t=t.replace("[code-"+n+"]","<pre>"+e.trim(e.trim(s[n].replace(/```<br>/g,"```").replace(/<br>```/g,"```")).replace(/```/g,"").replace(/(?:\r\n|\r|\n)/g,"<br>"))+"</pre>");return t.replace(/&lt;/g,"<")}strip(e=!1){return ee.strip(!1===e?""+this.details.message:e)}}window.SBMessage=se;class ae{constructor(e,t){this.details=ee.null(t)?{}:t,Array.isArray(e)?(this.messages=[],e.length&&(e[0]instanceof se?this.messages=e:ee.error("Messages not of type SBMessage","SBConversation.constructor"))):ee.error("Message array not of type Array","SBConversation.constructor");let i=["conversation_id","conversation_user_id","conversation_first_name","conversation_last_name","conversation_profile_image","conversation_user_type","conversation_creation_time","conversation_status_code"],s=["payload"];for(a=0;a<i.length;a++)t[i[a]]&&(this.details[i[a].replace("conversation_","")]=t[i[a]]),delete this.details[i[a]];for(var a=0;a<s.length;a++)delete this.details[s[a]];t&&(this.details.tags="tags"in t?"string"==typeof t.tags?t.tags.split(","):t.tags:[])}get id(){return this.get("id")}get status_code(){return this.get("status_code")}get(e){if(e in this.details&&!ee.null(this.details[e]))return this.details[e];if("title"==e){if(this.details.title)return this.details.title;if(this.details.first_name)return this.details.first_name+" "+this.details.last_name;if(this.messages.length)return this.messages[0].get("full_name")}return""}set(e,t){this.details[e]=t}getMessage(e){for(var t=0;t<this.messages.length;t++)if(this.messages[t].id==e)return this.messages[t].set("index",t),this.messages[t];return!1}getLastMessage(){for(var e=this.messages.length-1;e>-1;e--)if(this.messages[e].message||this.messages[e].attachments.length||this.messages[e].payload("preview"))return this.messages[e];return!1}getLastUserMessage(e=!1,t=!1){!1===e&&(e=this.messages.length-1);for(var i=e;i>-1;i--){let e=this.messages[i],s=e.get("user_type");if((e.message||e.attachments.length)&&(!t&&!ee.isAgent(s)||!0===t&&("agent"==s||"admin"==s)||"bot"==t&&"bot"==s||"no-bot"==t&&"bot"!=s||"all"==t&&ee.isAgent(s)))return this.messages[i].set("index",i-1),this.messages[i]}return!1}getNextMessage(e,t=!1){let i=this.messages.length;for(var s=0;s<i;s++)if(this.messages[s].id==e&&s<i-1){for(var a=s+1;a<i;a++){let e=this.messages[a].get("user_type"),i=this.messages[s+1];if(!t||"agent"==t&&ee.isAgent(e)||"user"==t&&!ee.isAgent(e))return i}break}return!1}getUserMessages(e="user"){let t=[],i="user"==e?["visitor","lead","user"]:"agents"==e?["agent","admin"]:["bot"];for(var s=0;s<this.messages.length;s++)i.includes(this.messages[s].get("user_type"))&&(this.messages[s].set("index",s),t.push(this.messages[s]));return t}updateMessage(e,t){if(t instanceof se){for(var i=0;i<this.messages.length;i++)if(this.messages[i].id==e)return this.messages[i]=t,!0}else ee.error("Message not of type SBMessage","SBConversation.updateMessage");return!1}addMessages(e){if(Array.isArray(e))for(var t=0;t<e.length;t++)e[t]instanceof se&&this.messages.push(e[t]);else e instanceof se?this.messages.push(e):ee.error("Messages not of type SBMessage","SBConversation.addMessages()");return this}getCode(e=!1){let t=this.getLastMessage();if(t){let n=t.message;if(!n&&t.payload("preview")&&(n=t.payload("preview")),x&&(n=t.payload().preview?t.payload().preview:n),!1!==(n=n.replace(/(\r\n|\n|\r)/gm," ")).indexOf("[")){let e=n.match(/\[.+?\]/g)||[];if(e.length){let t=oe.shortcode(e[0]);t[0]&&(n=n.replace(e[0],"action"==t[0]?"":s(t[1].message?t[1].message:t[1].title?t[1].title:t[1].name&&"false"!=t[1].name&&"true"!=t[1].name?t[1].name:t[1].link?t[1].link:t[1].values?t[1].values.replaceAll(",",", ").replaceAll(" "," "):t[1].options?t[1].options.replaceAll(",",", ").replaceAll(" "," "):s(ee.slugToString(t[0])))))}}if(!n&&t.attachments.length)for(var i=0;i<t.attachments.length;i++)n+=t.attachments[i][0]+" ";if((n=ee.strip(n)).length>114&&(n=n.substr(0,114)+" ..."),e)return n;let o=this.get("title");return(!o||a()&&a().name==o||$&&U.tickets_conversations_title_user)&&(o=a()&&t.get("user_id")==a().id?s("You"):t.get("full_name")),`<div class="sb-conversation-item" data-user-id="${this.get("user_id")}"><img loading="lazy" src="${t.get("profile_image")}"><div><span class="sb-name">${o}</span><span class="sb-time">${ee.beautifyTime(t.get("creation_time"))}</span></div><div class="sb-message">${n}</div></div>`}return""}deleteMessage(e){for(var t=0;t<this.messages.length;t++)if(this.messages[t].id==e)return this.messages.splice(t,1),!0;return!1}searchMessages(e,t=!1){let i=[];for(var s=0;s<this.messages.length;s++){let a=this.messages[s].message;(t&&a==e||!t&&a.includes(e))&&(this.messages[s].set("index",s),i.push(this.messages[s]))}return i}getAttachments(){let e=[];for(var t=0;t<this.messages.length;t++){let s=this.messages[t].attachments;for(var i=0;i<s.length;i++){let a=s[i][1];e.push([s[i][0],a,a.substr(a.lastIndexOf(".")+1),this.messages[t].id])}}return e}updateMessagesStatus(e=!1){if(e)for(t=0;t<this.messages.length;t++){let i=this.messages[t].id;if(e.includes(i)){let e=h.find(`[data-id="${i}"] .sb-time`);e.find("i").length||e.append('<i class="sb-icon-check"></i>')}}else if(!x&&"visible"==ee.visibility_status){e=[];for(var t=0;t<this.messages.length;t++){let i=this.messages[t];ee.isAgent(i.get("user_type"))&&2!=i.get("status_code")&&(e.push(i.id),i.set("status_code",2))}e.length&&ee.ajax({function:"update-messages-status",message_ids:e})}}}window.SBConversation=ae;var ne={emoji_options:{range:0,range_limit:47,list:[],list_now:[],touch:!1},initialized:!1,editor_listening:!1,conversation:!1,is_busy:!1,is_busy_update:!1,is_busy_populate:!1,chat_open:!1,real_time:!1,agent_id:-1,agent_online:!1,user_online:!1,expanded:!1,main_header:!0,start_header:!1,desktop_notifications:!1,flash_notifications:!1,id_last_message:0,id_last_message_conversation:0,datetime_last_message_conversation:"2000-01-01 00:00:00",audio:!1,audio_interval:!1,tab_active:!0,notifications:i("notifications")?i("notifications"):[],typing_settings:{typing:!1,sent:!1,timeout:!1},email_sent:!1,dashboard:!1,articles:!1,articles_allowed_ids:!1,articles_category:!1,slack_channel:[-1,-1],skip:!1,queue_interval:!1,departments:!1,default_department:null,default_agent:null,default_tags:null,offline_message_set:!1,label_date:!1,label_date_show:!1,sendMessage:function(t=-1,i="",n=[],o=!1,r=!1,l=!1){let c=w&&le.dialogflow.active(),d=!1,u=this.conversation,f=g.find("> [data-reply]").attr("data-reply");if(!a()&&!x)return this.addUserAndLogin(()=>this.sendMessage(t,i,n,o,r),!0),void this.busy(!0);if(!u){let e=!x&&a().getLastConversation();if(!e||"new-conversation"==P||ne.default_department&&ne.default_department!=e.get("department")||ne.default_agent&&ne.default_agent!=e.get("agent_id"))return this.newConversation(l,t,"",[],x&&SB_ACTIVE_AGENT.department?SB_ACTIVE_AGENT.department:null,null,()=>this.sendMessage(t,i,n,o,r)),void this.busy(!0);this.openConversation(e.id),this.setConversation(e),P=!1}this.calculateLabelDateFirst(),-1==t&&(t=x?SB_ACTIVE_AGENT.id:a().id);let m=t!=y;if(i||n.length||(i=p.val().trim(),g.find(".sb-attachments > div").each(function(){let t=[e(this).attr("data-name"),e(this).attr("data-value")];e(this).attr("data-size")&&t.push(e(this).attr("data-size")),n.push(t)}),x&&SBAdmin.must_translate&&i&&(le.dialogflow.translate([i],a().language,e=>{if(e.length){let t=x?SB_ADMIN_SETTINGS.active_agent_language:a().language;r?(r["original-message"]=i,r["original-message-language"]=t):r={"original-message":i,"original-message-language":t},e[0]&&(i=e[0])}this.sendMessage(t,i,n,o,r,l)}),d=!0)),this.busy(!0),m&&(p.val("").css("height",""),g.find(".sb-attachments").html("")),g.sbActive(!1),!d)if(!1===l&&t==y&&(l="skip"),x||!m||c||(l=2),f&&(r?r.reply=i:r={reply:f}),i||n.length||r){let e={user_id:t,user:a(),conversation_id:u.id,conversation:u,conversation_status_code:l,attachments:n,payload:r};ee.ajax({function:"send-message",user_id:t,conversation_id:u.id,message:i,attachments:n,conversation_status_code:l,queue:!x&&U.queue&&m,payload:r,recipient_id:!!x&&a().id},s=>{let l=x||!c||s.human_takeover_active;x||t!=y||(this.dashboard?this.updateConversations():this.chat_open||this.updateNotifications(u.id,s.id)),(x&&!this.user_online||!x&&!this.agent_online)&&this.update(),x||!m||w||(this.followUp(),this.offlineMessage()),!x&&m&&(!r||"sb-human-takeover"!=r.id&&ee.null(r["skip-dialogflow"]))&&le.dialogflow.message(i,n),!x&&m&&"visitor"==a().type?ee.ajax({function:"update-user-to-lead",user_id:t},()=>{a().set("user_type","lead"),U.slack_active&&l&&this.slackMessage(t,a().name,a().image,i,n)}):l&&!this.skip&&(x&&SB_ADMIN_SETTINGS.slack_active?this.slackMessage(a().id,SB_ACTIVE_AGENT.full_name,SB_ACTIVE_AGENT.profile_image,i,n):U.slack_active&&this.slackMessage(a().id,m?a().name:U.bot_name,m?a().image:U.bot_image,i,n)),m&&U.language_detection&&u&&i.split(" ").length&&i.length>3&&!ee.storage("language-detection-completed")&&(ee.ajax({function:"google-language-detection-update-user",user_id:t,string:i,token:le.dialogflow.token},e=>{e&&(U.translations=e)}),ee.storage("language-detection-completed",!0)),!this.articles||x||!U.articles||U.office_hours||this.isInitDashboard()||setTimeout(()=>{this.conversation&&u.id==this.conversation.id&&(this.sendMessage(y,"[articles]"),this.scrollBottom(),this.articles=!1)},5e3),s.queue&&this.queue(this.conversation.id),e.message=s.message,e.message_id=s.id,ee.event("SBMessageSent",e),$&&SBTickets.onMessageSent(),o&&o(e),s.notifications.length&&ee.event("SBNotificationsSent",s.notifications),this.skip&&(this.skip=!1),this.busy(!1)}),m&&(i=ee.escape(i),h.append(new se({id:"sending",profile_image:x?SB_ACTIVE_AGENT.profile_image:a().image,full_name:x?SB_ACTIVE_AGENT.full_name:a().name,creation_time:"0000-00-00 00:00:00",message:i.replaceAll("<","<"),user_type:x?"agent":"user"}).getCode().replace('<div class="sb-time"></div>',`<div class="sb-time">${s("Sending")}<i></i></div>`))),this.dashboard||!m&&!this.isBottom()||this.scrollBottom()}else this.busy(!1)},updateMessage:function(e,t=""){ee.ajax({function:"update-message",message_id:e,message:t})},sendEmail:function(e,t,i=!1,s=!1){let n=i?!0===i?a().id:i:this.getRecipientUserID();if(!x&&!isNaN(n)&&this.agent_online)return!1;ee.ajax({function:"create-email",recipient_id:n,sender_name:x?i?SB_ACTIVE_AGENT.full_name:a().name:i?U.bot_name:a().name,sender_profile_image:x?i?SB_ACTIVE_AGENT.profile_image:a().name:i?U.bot_image:a().image,message:e,attachments:t,department:!!this.conversation&&this.conversation.get("department"),conversation_id:!!this.conversation&&this.conversation.id},e=>{s&&s(e)})},sendSMS:function(e){let t=this.getRecipientUserID();if(!x&&!isNaN(t)&&this.agent_online)return!1;ee.ajax({function:"send-sms",to:t,message:e,conversation_id:!!this.conversation&&this.conversation.id},t=>{"sent"==t.status||"queued"==t.status?ee.event("SBSMSSent",{recipient_id:this.getRecipientUserID(),message:e,response:t}):t.message&&ee.error(t.message,"SBChat.sendSMS")})},desktopNotification:function(e,t,i,s=!1,n=!1){if("granted"!==Notification.permission)Notification.requestPermission();else{ee.serviceWorker.sw.showNotification(e,{body:ee.strip(t),icon:i.indexOf("user.svg")>0?U.notifications_icon:i}).onclick=(()=>{x?s?(SBAdmin.conversations.openConversation(s,0==n?a().id:n),SBAdmin.conversations.update()):n&&SBAdmin.profile.show(n):this.start(),window.focus()})}},getRecipientUserID:function(){return x?a().id:this.lastAgent(!1)?this.lastAgent(!1).user_id:ee.null(this.conversation.get("agent_id"))?ee.null(this.conversation.get("department"))?"agents":"department-"+this.conversation.get("department"):this.conversation.get("agent_id")},submit:function(){if(!this.is_busy){if(k&&k.sbActive()){let e=k.find(".sb-btn-mic");return k.sbActive(!1),e.hasClass("sb-icon-pause")&&e.click(),void setTimeout(()=>{let e=new FormData,t=!!this.conversation&&this.conversation.get("source");"wa"==t||H.length?(e.append("file",new File(["wa"==t?SBAudioRecorder.blob():new Blob(H,{type:"ig"==t?"audio/wav":"audio/mp3"})],"voice_message."+("ig"==t?"wav":"mp3"))),ee.upload(e,e=>{ne.uploadResponse(e),this.submit()})):this.submit(),k.find(".sb-icon-close").click()},100)}this.sendMessage(),U.cron_email_piping_active&&(setTimeout(()=>{ee.ajax({function:"email-piping"}),U.cron_email_piping_active=!0},6e4),U.cron_email_piping_active=!1),Q&&ee.serviceWorker.initPushNotifications(),x&&SBAdmin.conversations.setStatus(1,!1,!0),ne.cancelReply()}},initChat:function(){x||ee.getActiveUser(!0,()=>{let e=!1!==a(),t=!!e&&a().type;if($||!U.popup||i("popup")||O&&U.popup_mobile_hidden||this.popup(),ne.automations.runAll(),$||!U.privacy||U.registration_required||i("privacy-approved")){if(typeof Notification!==G&&!U.push_notifications_users&&(["all","users"].includes(U.desktop_notifications)||x&&"agents"==U.desktop_notifications)&&(this.desktop_notifications=!0),(["all","users"].includes(U.flash_notifications)||x&&"agents"==U.flash_notifications)&&(this.flash_notifications=!0),this.registration(!0)&&!$)return this.registration(),void(!e&&U.visitors_registration&&this.addUserAndLogin());e||!(typeof SB_WP_WAITING_LIST!==G||U.visitors_registration||U.welcome||$||U.flow_on_load)||$&&U.tickets_registration_required?!this.conversation&&e?this.populateConversations():this.finalizeInit():this.addUserAndLogin(()=>{this.welcome(),le.dialogflow.flowOnLoad(),le.woocommerce.waitingList(),this.finalizeInit()}),U.header_name&&e&&"user"==t&&!$&&f.find(".sb-title").html(`${s("Hello")} ${a().nameBeautified}!`),this.welcome(),te.active||setInterval(()=>{this.updateConversations(),this.updateUsersActivity()},10200),le.dialogflow.flowOnLoad(),le.woocommerce.waitingList(),this.scrollBottom(!0)}else this.privacy()})},finalizeInit:function(){this.initialized||(l.attr("style",""),x||$||(this.isInitDashboard()&&this.showDashboard(),!O&&window.innerHeight<760&&l.find(" > .sb-body").css("max-height",window.innerHeight-130+"px")),this.initialized=!0,x||(a()&&!this.registration(!0)&&(i("open-conversation")&&this.openConversation(i("open-conversation")),ee.getURL("conversation")&&this.openConversation(ee.getURL("conversation"))),(!this.chat_open&&(!O&&i("chat-open")||"open"==ee.getURL("chat"))||ee.getURL("conversation"))&&setTimeout(()=>{this.start()},500),U.woocommerce_returning_visitor&&(!1===i("returning-visitor")?ee.storageTime("returning-visitor"):ee.storageTime("returning-visitor",24)&&!i("returning-visitor-processed")&&setTimeout(()=>{ee.ajax({function:"woocommerce-returning-visitor"},()=>{i("returning-visitor-processed",!0)})},15e3)),U.timetable_type&&ne.offlineMessage(),U.queue_human_takeover&&le.dialogflow.humanTakeoverActive()&&(U.queue=!0),e(window).on("resize",function(){!O&&window.innerHeight<760&&l.find(" > .sb-body").css("max-height",window.innerHeight-130+"px")}),le.dialogflow.flowOnLoad()),$&&SBTickets.init(),ee.event("SBInit"))},start:function(){this.initialized&&(this.populate(),this.headerAgent(),this.updateUsersActivity(),this.startRealTime(),this.popup(!0),this.conversation&&this.updateNotifications(this.conversation.id),l.sbActive(!0),e("body").addClass("sb-chat-open"),this.chat_open=!0,"open"!=U.welcome_trigger||this.registration(!0)||this.welcome(),le.martfury.privateChat(),this.calculateLabelDates())},open:function(t=!0){t&&!this.chat_open?(this.start(),this.chat_open=!0,this.startRealTime(),l.sbActive(!0),e("body").addClass("sb-chat-open"),i("chat-open",!0),this.conversation&&i("last-open-message",this.conversation.getLastMessage().id),O&&history.pushState({"chat-open":!0},"",""),ee.event("SBChatOpen")):!t&&this.chat_open&&(l.sbActive(!1),this.stopRealTime(),this.chat_open=!1,i("chat-open",!1),e("body").removeClass("sb-chat-open"),ee.event("SBChatClose"))},openConversation:function(e){a().getFullConversation(e,t=>{if(!t.id||!ne.isConversationAllowed(t.get("source"),t.status_code))return i("open-conversation",""),!1;this.setConversation(t),this.hideDashboard(),this.populate(),this.main_header=!1,i("chat-open")&&!O&&ne.open(),i("queue")==e&&this.queue(e),(this.chat_open||$)&&this.updateNotifications(e),$&&SBTickets.activateConversation(t),i("open-conversation",e),ee.event("SBConversationOpen",t)})},update:function(){if(this.conversation){if(this.is_busy_update)return;let e=this.conversation.getLastMessage(),t=!1;ee.ajax({function:"get-new-messages",conversation_id:this.conversation.id,datetime:this.datetime_last_message_conversation,last_id:this.id_last_message_conversation},s=>{let n=s.length;if(this.is_busy_update=!1,this.conversation&&Array.isArray(s)&&n>0&&(!e||e.id!=s[n-1].id||e.message!=s[n-1].message||e.payload!=s[n-1].payload||e.attachments!=s[n-1].attachments)){let e="",r=[],l=[],c=!1;this.calculateLabelDateFirst();for(var o=0;o<n;o++)if(!(l.includes(s[o].id)||x&&this.conversation.id!=s[o].conversation_id)){let n=new se(s[o]),d=n.payload();if(this.id_last_message_conversation=n.id,this.datetime_last_message_conversation=n.get("creation_time"),d.event){let e=d.event;("delete-message"!=e||!1===this.conversation.getMessage(n.id))&&(x||n.message||n.attachments.length||d)||this.deleteMessage(n.id),"woocommerce-update-cart"!=e||x||le.woocommerce.updateCart(d.action,d.id),"woocommerce-checkout"!=e||x||le.wordpress.ajax("url",{url_name:"checkout"},e=>{setTimeout(()=>document.location=e,500)}),le.dialogflow.active()||"conversation-status-update-3"!=e&&"conversation-status-update-4"!=e&&"activate-bot"!=e||(le.dialogflow.active("activate"),c=!0),"conversation-status-update-3"==e&&this.conversationArchived()}d["human-takeover"]&&U.queue_human_takeover&&(U.queue=!0,ne.queue(ne.conversation.id)),d["human-takeover-fallback"]&&(le.dialogflow.typing_enabled=!1),this.conversation.getMessage(s[o].id)?(this.conversation.updateMessage(n.id,n),h.find(`[data-id="${n.id}"]`).replaceWith(n.getCode()),t=!0):((n.message||n.attachments.length)&&h.find('[data-id="sending"]').remove(),this.conversation.id==s[o].conversation_id&&(this.conversation.addMessages(n),e+=n.getCode(),t=!1)),this.conversation.updateMessagesStatus(),r.push(n),l.push(n.id),this.chat_open&&i("last-open-message",n.id),x||!this.dashboard&&this.chat_open&&this.tab_active||n.get("user_id")==a().id||!n.message&&!n.attachments.length||this.updateNotifications(this.conversation.id,n.id)}h.append(e);let d=this.conversation.getLastMessage(),u=!!d&&d.get("user_type"),g=ee.isAgent(u),p=g&&"bot"!=u;!x&&p&&(this.chat_open&&(!d||d.message.includes("sb-rich-success")||s[0].payload&&s[0].payload.includes("conversation-status-update")||this.setConversationStatus(0),U.follow&&clearTimeout(E)),c||le.dialogflow.active(!1)),i("queue")==this.conversation.id&&p&&this.queue("clear"),!r.length||ee.null(r[0].message)&&ee.null(r[0].attachments)&&1==n||(x||this.tab_active||this.flashNotification(),this.audio&&(!x&&g||x&&!g)&&this.playSound()),this.headerAgent(),t||this.dashboard||(this.scrollBottom(),setTimeout(()=>{this.scrollBottom()},300)),!U.auto_open||!this.dashboard&&this.chat_open||this.open(),p&&this.typing(-1,"stop"),this.busy(!1),ee.event("SBNewMessagesReceived",{messages:r,conversation_id:this.conversation.id}),$&&SBTickets.onNewMessageReceived(r[0],this.conversation.id)}}),this.is_busy_update=!0,setTimeout(()=>{this.is_busy_update=!1},5e3)}else this.updateConversations()},updateConversations:function(){a()&&ee.ajax({function:"get-new-user-conversations",datetime:this.id_last_message},e=>{if(e.length){this.id_last_message=e[0].message_id,this.chat_open&&i("last-open-message",this.id_last_message);for(var t=0;t<e.length;t++){let i=e[t].conversation_status_code;if(!ne.isConversationAllowed(e[t].source,i))continue;let s=e[t].conversation_id,n=new se(e[t]),o=new ae([n],e[t]),r=a().addConversation(o);e[t].message_user_id==a().id||this.conversation.id==s&&this.chat_open||!n.message&&!n.attachments.length||(this.updateNotifications(s,n.id),U.auto_open&&this.open());let l=n.payload();if("boolean"!=typeof l&&l.event){if("open-chat"==l.event&&((this.conversation.id!=s||this.dashboard)&&this.openConversation(s),O||setTimeout(()=>{this.open()},500)),!n.message&&!n.attachments.length)continue}this.tab_active||(this.desktop_notifications&&ne.desktopNotification(n.get("full_name"),n.message,n.get("profile_image")),this.flash_notifications&&this.flashNotification(),x||!this.audio||!U.sound||this.chat_open&&!this.dashboard&&this.conversation.id==s||ee.null(n.message)&&ee.null(n.attachments)||this.playSound()),r&&ee.event("SBNewConversationReceived",o),$&&SBTickets.onConversationReceived(o),!this.conversation&&r&&this.openConversation(o.id)}this.conversation&&this.conversation.updateMessagesStatus(),l.find(".sb-user-conversations").html(a().getConversationsCode()),l.find(".sb-dashboard-conversations").setClass("sb-conversations-hidden",l.find(".sb-user-conversations > li").length>3)}})},populate:function(){if(this.conversation){let t="",a=h.find(" > .sb-notify-message"),n=!1,o=this.conversation.id;for(var e=0;e<this.conversation.messages.length;e++){let i=this.conversation.messages[e],a=ee.beautifyTime(i.get("creation_time"));a.includes("today")&&(a=`<span>${s("Today")}</span>`),a!=n&&(i.message||i.attachments.length)&&(t+=`<div class="sb-label-date">${a}</div>`,n=a),t+=i.getCode()}if(h.html((a.length?a[0].outerHTML:"")+t),!this.dashboard&&(this.scrollBottom(),this.calculateLabelDates(),x&&SB_ADMIN_SETTINGS.notify_email_cron||!x&&U.notify_email_cron)){let e=this.conversation.getLastUserMessage(!1,!x);e&&e.id!=i("email-cron-"+o)&&(ee.ajax({function:"remove-email-cron",conversation_id:o}),i("email-cron-"+o,e.id))}}else a()&&!a().isConversationsEmpty()&&(U.disable_dashboard?this.openConversation(a().conversations[0].id):this.showDashboard())},populateConversations:function(e=!1){!this.is_busy_populate&&a()&&(this.is_busy_populate=!0,setTimeout(()=>{this.is_busy_populate=!1},5e3),a().getConversations(t=>{let s=t.length,n=[];if(s){let e=Date.now(),r=t[0].messages[0];this.id_last_message=r.id;for(o=0;o<s;o++)n.push(t[o].id),$||1!=t[o].status_code||!(i("last-open-message")<r.id)||this.conversation&&this.conversation.id==t[o].id||this.updateNotifications(t[o].id,r.id),!O&&e-ee.UTC(t[o].messages[0].get("creation_time"))<6e3&&this.open();l.find(".sb-user-conversations").html(a().getConversationsCode()),l.find(".sb-dashboard-conversations").setClass("sb-conversations-hidden",l.find(".sb-user-conversations > li").length>3)}l.setClass("sb-no-conversations",!s),this.initialized&&"open-conversation"!=P||1!=s||this.isInitDashboard()||i("open-conversation")||(this.openConversation(a().getLastConversation().id),"open-conversation"==P&&(P=""));for(var o=0;o<ne.notifications.length;o++)this.updateNotifications(ne.notifications[o][0],!!n.includes(ne.notifications[o][0])&&ne.notifications[o][1]);e&&e(t),this.finalizeInit(),ee.event("SBPopulateConversations",{conversations:t})}))},newConversation:function(e,t=-1,i="",s=[],n=null,o=null,r=!1){a()?ee.ajax({function:"new-conversation",status_code:e,title:$?l.find(".sb-ticket-title input").val():null,department:ee.null(n)?this.default_department:n,agent_id:ee.null(o)?this.default_agent:o,tags:this.default_tags,source:$?"tk":""},a=>{if(ee.errorValidation(a,"user-not-found"))return void this.addUserAndLogin(()=>{this.newConversation(e,t,i,s,n,o,r)});let l=new ae([],a.details);this.setConversation(l),(i||s.length)&&this.sendMessage(t,i,s),t!=y&&setTimeout(()=>{this.queue(l.id)},1e3),r&&r(l)}):ee.error("activeUser() not setted","SBChat.newConversation")},setConversation:function(e){if(e instanceof ae){let s=a().conversations,n=!0;this.conversation=e,this.id_last_message_conversation=this.conversation.getLastMessage()?this.conversation.getLastMessage().id:0,this.datetime_last_message_conversation=0==this.conversation.getLastMessage()?"2000-01-01 00:00:00":this.conversation.getLastMessage().get("creation_time"),e.id!=this.conversation.id&&this.queue(e.id);for(var t=0;t<s.length;t++)if(s[t].id==e.id){s[t]=e,n=!1;break}n&&s.push(e),i("open-conversation",e.id),le.dialogflow.typing_enabled=!0,this.headerAgent(),ee.event("SBActiveConversationChanged",e)}else ee.error("Value not of type SBConversation","SBChat.setConversation")},queue:function(e){if("clear"==e)return l.removeClass("sb-notify-active sb-queue-active"),h.find(" > .sb-notify-message").remove(),clearInterval(this.queue_interval),this.queue_interval=!1,i("queue",""),void(U.queue_sound&&!ne.tab_active&&ne.playSound(999));!x&&U.queue&&ee.ajax({function:"queue",conversation_id:e,department:this.conversation.get("department")},t=>{h.find(" > .sb-notify-message").remove();let a=t[0];if(0==a)this.queue("clear");else{let n=(U.queue_response_time?parseInt(U.queue_response_time):5)*a,o=s(U.queue_message?U.queue_message:"Please wait for an agent. You are number {position} in the queue. Your waiting time is approximately {minutes} minutes.").replace("{position}","<b>"+a+"</b>").replace("{minutes}","<b>"+n+"</b>");t[1]&&h.prepend(`<div class="sb-notify-message sb-rich-cnt"><div class="sb-cnt"><div class="sb-message">${o}</div></div></div>`),!1===this.queue_interval&&(this.queue_interval=setInterval(()=>{this.queue(e)},10100),t[1]&&l.addClass("sb-notify-active sb-queue-active"),i("queue",e))}ee.event("SBQueueUpdate",a)})},getDepartmentCode(e,t){if(this.departments)if("all"==e){let e="";for(var i in this.departments)this.getDepartmentCode(this.departments[i].id,t=>{e+=t});t(e)}else t(`<div data-color="${this.departments[e].color}">${this.departments[e].image?`<img loading="lazy" src="${this.departments[e].image}" />`:""}<div>${this.departments[e].name}<div></div>`);else ee.ajax({function:"get-departments"},i=>{i&&(this.departments=i,this.getDepartmentCode(e,t))})},startRealTime:function(){te.active||(this.stopRealTime(),this.real_time=setInterval(()=>{this.update(),this.typing(x?a()?a().id:-1:this.agent_id,"check")},1e3))},stopRealTime:function(){clearInterval(this.real_time)},updateUsersActivity:function(){a()&&ee.updateUsersActivity(a().id,this.agent_id,t=>{this.typing_settings.typing||("online"==t||this.agent_id==y?(e(m).addClass("sb-status-online").html(s("Online")),this.agent_online=this.agent_id!=y):(e(m).removeClass("sb-status-online").html(s("Away")),this.agent_online=!1))})},busy:function(e){g&&g.find(".sb-loader").sbActive(e),this.is_busy=e,ee.event("SBBusy",e)},headerAgent:function(e=!1){if(!x&&!$&&!this.dashboard&&this.conversation&&(-1==this.agent_id||this.conversation.getLastMessage()&&ee.isAgent(this.conversation.getLastMessage().get("user_type"))&&this.conversation.getLastMessage().get("user_id")!=this.agent_id)){let t=this.lastAgent(!1);!(t=t&&le.dialogflow.humanTakeoverActive()&&te.active&&!te.presenceCheck({info:{user_type:"agent"},id:t.user_id})?t:this.lastAgent())&&e&&(t={user_id:U.bot_id,full_name:U.bot_name,profile_image:U.bot_image}),this.headerReset(),t?(this.agent_id=t.user_id,f.addClass("sb-header-agent").attr("data-agent-id",this.agent_id).html(`<div class="sb-dashboard-btn sb-icon-arrow-left"></div><div class="sb-profile"><img loading="lazy" src="${t.profile_image}" /><div><span class="sb-name">${t.full_name}</span><span class="sb-status">${s("Away")}</span></div><i class="sb-icon sb-icon-close ${U.close_chat?"sb-close-chat":"sb-responsive-close-btn"}"></i></div><div class="sb-label-date-top"></div>`),m=f.find(".sb-status"),this.updateUsersActivity(),this.label_date=f.find(".sb-label-date-top"),ee.storageTime("header-animation",1)&&this.headerAnimation()):f.html(this.start_header[0]).addClass(this.start_header[1])}},headerReset:function(){0==this.start_header&&(this.start_header=[f.html(),f.attr("class")]),f.removeClass("sb-header-main sb-header-brand sb-header-agent sb-header-minimal"),this.main_header=!1},headerAnimation:function(){f.addClass("sb-header-animation"),setTimeout(()=>{f.removeClass("sb-header-animation")},8e3),ee.storageTime("header-animation")},lastAgent:function(e=!0){let t=!1;if(this.conversation){let i=this.conversation.getLastUserMessage(!1,!e||"all");i&&(t={user_id:i.get("user_id"),full_name:i.get("full_name"),profile_image:i.get("profile_image")})}return t},scrollBottom:function(e=!1){setTimeout(()=>{_.scrollTop(e?0:_[0].scrollHeight),this.scrollHeader()},20)},isBottom:function(){return _[0].scrollTop===_[0].scrollHeight-_[0].offsetHeight},scrollHeader:function(){if(this.main_header&&this.dashboard){let e=_.scrollTop();e>-1&&e<1e3&&f.find(".sb-content").css({opacity:1-e/500,top:e/10*-1+"px"})}},showDashboard:function(){x||$||(l.addClass("sb-dashboard-active"),f.removeClass("sb-header-agent"),this.hidePanel(),this.start_header&&f.html(this.start_header[0]).addClass(this.start_header[1]),_.find(" > div").sbActive(!1),l.find(".sb-dashboard").sbActive(!0),this.populateConversations(),this.conversation=!1,this.agent_id=-1,this.stopRealTime(),this.dashboard=!0,this.main_header=!0,this.scrollBottom(!0),ee.event("SBDashboard"))},hideDashboard:function(){x||$||(h.sbActive(!0),l.removeClass("sb-dashboard-active").find(".sb-dashboard").sbActive(!1),this.dashboard=!1,this.headerAgent(),this.scrollHeader(0),this.chat_open&&this.startRealTime(),ee.event("SBDashboardClosed"))},showPanel:function(e,t){if($)return SBTickets.showPanel(e,t);let i=_.find(" > .sb-panel-"+e);i.length&&(_.find(" > div").sbActive(!1),i.sbActive(!0),this.start_header||(this.start_header=[f.html(),f.attr("class")]),f.attr("class","sb-header sb-header-panel").html(`<span>${s(t)}</span><div class="sb-dashboard-btn sb-icon-close"></div>`),l.addClass("sb-panel-active"),this.dashboard=!0),ee.event("SBPanelActive",e)},hidePanel:function(){l.removeClass("sb-panel-active"),f.removeClass("sb-header-panel")},clear:function(){this.conversation=!1,h.html("")},updateNotifications:function(e,t=!1){let s=!1;if(t){for(a=0;a<this.notifications.length;a++)this.notifications[a][0]==e&&t==this.notifications[a][1]&&(s=!0);s||(this.notifications.push([e,t]),!this.dashboard&&this.conversation&&this.conversation.id!=e&&this.headerAnimation())}else{let t=[];for(var a=0;a<this.notifications.length;a++)this.notifications[a][0]==e?s=!0:t.push(this.notifications[a]);!x&&s&&["0",0].includes(this.conversation.status_code)&&this.setConversationStatus(1),this.notifications=t}let n=this.notifications.length;i("notifications",this.notifications),l.find(".sb-chat-btn span").attr("data-count",n).html(n>-1?n:0),ee.event("SBNotificationsUpdate",{conversation_id:e,message_id:t})},setConversationStatus:function(e){return!!this.conversation&&(ee.ajax({function:"update-conversation-status",conversation_id:this.conversation.id,status_code:e},()=>{this.conversation.set("status_code",e),ee.event("SBActiveConversationStatusUpdated",{conversation_id:this.conversation.id,status_code:e})}),!0)},typing:function(t=-1,i="check"){if(this.conversation){let n=this.agent_online||x&&this.user_online;if("check"==i&&!te.active&&-1!=t&&t!=y&&n)ee.ajax({function:"is-typing",user_id:t,conversation_id:this.conversation.id},e=>{e&&!this.typing_settings.typing?this.typing(-1,"start"):!e&&this.typing_settings.typing&&this.typing(-1,"stop")});else if("set"==i&&n){let e=this.conversation.get("source");clearTimeout(I),e&&(e="fb"==e?[e,a().getExtra("facebook-id").value,this.conversation.get("extra")]:"tw"==e&&[e,a().getExtra("twitter-id").value]),te.active?ee.debounce(()=>{te.trigger("client-typing",{user_id:x?SB_ACTIVE_AGENT.id:a().id,conversation_id:this.conversation.id}),e&&ee.ajax({function:"set-typing",source:e})},"#2"):this.typing_settings.sent?(clearTimeout(this.typing_settings.timeout),this.typing_settings.timeout=setTimeout(()=>{ee.ajax({function:"set-typing",user_id:t,conversation_id:-1},()=>{this.typing_settings.sent=!1})},2e3)):(this.typing_settings.sent=!0,ee.ajax({function:"set-typing",user_id:t,conversation_id:this.conversation.id,source:e}),this.typing(t,"set"))}else if("start"==i||"stop"==i){let t="start"==i;if(!x&&m)if(t)e(m).addClass("sb-status-typing").html(s("Typing"));else{let t=this.agent_online||this.agent_id==y;clearTimeout(I),e(m).removeClass("sb-status-typing").html(s(t?"Online":"Away")),t&&e(m).addClass("sb-status-online")}this.typing_settings.typing=t,ee.event("SBTyping",t)}}},showArticles:function(e=!1,t=!1){let i=$?l.find(".sb-panel-main .sb-panel"):_.find(" > .sb-panel-articles");i.html("").sbLoading(!0),this.showPanel("articles",U.articles_title?U.articles_title:"Help Center"),!e&&U.articles_categories?this.getArticleCategories(e=>{this.showArticles_(e,i,{categories:e})},"parent"):this.getArticles(!t&&e,s=>{e&&!t?(i.html(this.getArticleCode(s[0])),i.sbLoading(!1),ee.event("SBArticles",{id:e,articles:s})):this.showArticles_(s,i,{id:e,articles:s})},!!t&&e)},showArticles_:function(e,t,i){let s="",a=typeof SB_LANG!=G&&SB_LANG[0];for(var n=0;n<e.length;n++){let t="content"in e[n];s+=`<div data-id="${e[n].id}"${t?"":' data-is-category="true"'}><div>${t?e[n].title:a&&e[n].languages&&e[n].languages[a]?e[n].languages[a].title:e[n].title}</div><span>${t?e[n].content:a&&e[n].languages&&e[n].languages[a]?e[n].languages[a].description:e[n].description?e[n].description:""}</span></div>`}t.html(`<div class="sb-articles">${s}</div>`),t.sbLoading(!1),ee.event("SBArticles",i)},getArticles:function(e=!1,t=!1,i=!1,s=!1){ee.ajax({function:"get-articles",categories:this.articles_category?this.articles_category:i,id:e||this.articles_allowed_ids,count:s,return_categories:!!this.articles_category,full:e,skip_language:!0},e=>{t(e)})},getArticleCategories:function(e=!1,t=!1){ee.ajax({function:"get-articles-categories",category_type:t},t=>{e(t)})},searchArticles:function(t,i,a){t&&(e(i).sbLoading(!0),ee.ajax({function:"search-articles",search:t},t=>{let n="";if(0==t.length)n+=`<p class="sb-no-results">${s("No articles found.")}</p>`;else for(var o=0;o<t.length;o++)n+=`<div data-id="${t[o].id}"><div>${t[o].title}</div><span>${t[o].content}</span></div>`;e(a).html(n),e(i).sbLoading(!1)}))},setArticleRating:function(e,t,i=!1){ee.ajax({function:"article-ratings",article_id:e,rating:t},e=>{i&&i(e)})},articleRatingOnClick:function(t){let i=e(t).closest(".sb-article");if(!i[0].hasAttribute("data-user-rating")){e(t).parent().sbLoading();let s="positive"==e(t).attr("data-rating")?1:-1,a=e(t).closest(".sb-article").attr("data-id");ne.setArticleRating(a,s,()=>{ee.storage("article-rating-"+a,s),i.attr("data-user-rating",s),e(t).parent().sbLoading(!1)})}},getArticleCode:function(e){let t=ee.storage("article-rating-"+e.id),i="";if(this.articles_categories&&!ee.null(e.categories))for(var a=0;a<this.articles_categories.length;a++){let t=this.articles_categories[a].id;(e.categories.includes(t)||e.parent_category==t)&&(i+=`<span data-id="${t}">${s(this.articles_categories[a].title)}</span>`)}return`<div data-id="${e.id}"${t?` data-user-rating="${t}"`:""} class="sb-article"><div class="sb-title">${e.title}<div class="sb-close sb-icon-close"></div></div><div class="sb-content">${e.content.replace(/(?:\r\n|\r|\n)/g,"<br>")}</div>${e.link?`<a href="${e.link}" target="_blank" class="sb-btn-text"><i class="sb-icon-plane"></i>${s("Read more")}</a>`:""}${i?`<div class="sb-article-category-links">${i}</div>`:""}<div class="sb-rating"><span>${s("Rate and review")}</span><div><i data-rating="positive" class="sb-submit sb-icon-like"><span>${s("Helpful")}</span></i><i data-rating="negative" class="sb-submit sb-icon-dislike"><span>${s("Not helpful")}</span></i></div></div></div>`},initArticlesPage:function(){let i=ee.getURL("article_id"),a=ee.getURL("category"),n=ee.getURL("search");if(U.articles_url_rewrite){let e=location.href.replace(U.articles_url_rewrite,"").split("/");"category"==e[e.length-2]&&(a=e[e.length-1]),(2==e.length&&!e[0]&&e[1]||1==e.length&&e[0])&&(i=e[e.length-1]),U.articles_page_url}if((V=e("body").find("#sb-articles")).length||(V=e("body")),V.sbLoading()){let e=SB_URL+"/include/articles.php"+(a?"?category="+a:i?"?article_id="+i:n?"?search="+n:"");W&&(e+=(e.includes("?")?"&":"?")+"cloud="+W),ee.loadResource(SB_URL+"/css/articles.css"),ee.cors("GET",e,e=>{V.html(e),V.sbLoading(!1)})}V.on("keydown",".sb-panel-side input",function(t){13==t.which&&e(this).next().click()}),V.on("click",".sb-articles > [data-id]",function(){cache=panel_main.html(),panel_main.sbLoading(!0),ne.getArticles(e(this).attr("data-id"),e=>{panel_main.removeClass("sb-articles").html(ne.getArticleCode(e)),panel_main.sbLoading(!1)})}),V.on("click",".sb-article [data-rating]",function(){ne.articleRatingOnClick(this)}),V.on("click",".sb-article .sb-title .sb-close",function(){V.find(".sb-panel-main").addClass("sb-articles").html(cache)}),V.on("click",".sb-submit-articles",function(){let t=e(this).parent().find("input").val();t?(cache=panel_main.html(),panel_main.html(""),ne.searchArticles(t,this,panel_main)):panel_main.html(cache),panel_main.addClass("sb-articles")}),V.on("click",".sb-article-categories [data-id]",function(){if(t(panel_main))return;let i="";cache=panel_main.html(),V.find(".sb-article-categories [data-id]").sbActive(!1),e(this).sbActive(!0),ne.getArticles(-1,e=>{for(var t=0;t<e.length;t++)i+=`<div data-id="${e[t].id}"><div>${e[t].title}</div><span>${e[t].content}</span></div>`;panel_main.addClass("sb-articles").html(i||`<p class="sb-no-results">${s("No articles found.")}</p>`),panel_main.sbLoading(!1)},e(this).attr("data-id"))})},categoryEmoji:function(e){let t=this.emoji_options.list;if("all"==e)this.emoji_options.list_now=t;else{this.emoji_options.list_now=[];for(var i=0;i<t.length;i++)t[i].category.startsWith(e)&&this.emoji_options.list_now.push(t[i])}this.emoji_options.range=0,this.populateEmoji(0),this.populateEmojiBar()},mouseWheelEmoji:function(e){let t=this.emoji_options.range;(function(e){let t=e.originalEvent.wheelDelta;return typeof t==G&&(t=e.originalEvent.deltaY),typeof t==G&&(t=-1*e.originalEvent.detail),t})(e)>0||O&&typeof e.originalEvent.changedTouches!==G&&this.emoji_options.touch<e.originalEvent.changedTouches[0].clientY?t-=t<1?0:1:t+=t>this.emoji_options.range_limit?0:1,v.find(".sb-emoji-bar > div").sbActive(!1).eq(t).sbActive(!0),this.emoji_options.range=t,this.populateEmoji(t),e.preventDefault()},insertEmoji:function(t){t.indexOf(".svg")>0&&(t=e.parseHTML(t)[0].alt),this.insertText(t),v.sbTogglePopup()},showEmoji:function(e){v.sbTogglePopup(e)&&(x||v.css({left:g.offset().left+($?68:20),top:g.offset().top-window.scrollY-($?g.height()-330:304)}),v.find(".sb-emoji-list > ul").html()||jQuery.ajax({method:"POST",url:SB_AJAX_URL,data:{function:"emoji","login-cookie":ee.loginCookie()}}).done(e=>{this.emoji_options.list=JSON.parse(e),this.emoji_options.list_now=this.emoji_options.list,this.populateEmoji(0),this.populateEmojiBar()}),ee.deselectAll())},populateEmoji:function(e){let t="",i=O?42:48,s=e*i+i,a=this.emoji_options.list_now;s>a.length&&(s=a.length),this.emoji_options.range_limit=a.length/i-1,this.emoji_options.range=e;for(var n=e*i;n<s;n++)t+=`<li>${a[n].char}</li>`;v.find(".sb-emoji-list").html(`<ul>${t}</ul>`)},populateEmojiBar:function(){let e='<div class="sb-active"></div>',t=O?42:49;for(var i=0;i<this.emoji_options.list_now.length/t-1;i++)e+="<div></div>";this.emoji_options.range=0,v.find(".sb-emoji-bar").html(e)},clickEmojiBar:function(t){let i=e(t).index();this.populateEmoji(i),this.emoji_options.range=i,v.find(".sb-emoji-bar > div").sbActive(!1).eq(i).sbActive(!0)},searchEmoji:function(e){ee.search(e,()=>{if(e.length>1){let i=this.emoji_options.list,s=[];for(var t=0;t<i.length;t++)(i[t].category.toLowerCase().includes(e)||i[t].name.toLowerCase().includes(e))&&s.push(i[t]);this.emoji_options.list_now=s}else this.emoji_options.list_now=this.emoji_options.list;this.emoji_options.range=0,this.populateEmoji(0),this.populateEmojiBar()})},textareaChange:function(t){let i=e(t).val();x&&(SBAdmin.conversations.savedReplies(t,i),SBAdmin.apps.openAI.rewriteButton(i)),i&&this.typing(x&&!te.active?SB_ACTIVE_AGENT.id:a().id,"set"),g.sbActive(i)},insertText:function(t){let i=e(p.get(0)),s=0;if(this.dashboard)return!1;if(i.get(0).selectionStart)s=i.get(0).selectionStart;else if(document.selection){i.focus();let e=document.selection.createRange();var a=document.selection.createRange().text.length;e.moveStart("character",-i.value.length),s=e.text.length-a}i.val(i.val().substr(0,s)+t+i.val().substr(s)),i.focus(),i.manualExpandTextarea(),g.sbActive(!0)},enabledAutoExpand:function(){p.length&&p.autoExpandTextarea()},cancelReply:function(){g.find("[data-reply]").remove(),h.removeClass("sb-reply-active")},privacy:function(){ee.ajax({function:"get-block-setting",value:"privacy"},e=>{_.append(`<div class="sb-privacy sb-init-form" data-decline="${e.decline}"><div class="sb-title">${e.title}</div><div class="sb-text">${e.message.replace(/\n/g,"<br>")}</div>`+(e.link?`<a target="_blank" href="${e.link}">${e["link-name"]}</a>`:"")+`<div class="sb-buttons"><a class="sb-btn sb-approve">${e["btn-approve"]}</a><a class="sb-btn sb-decline">${e["btn-decline"]}</a></div></div>`),this.finalizeInit(),ee.event("SBPrivacy")}),this.dashboard||this.showDashboard(),this.dashboard=!0,l.addClass("sb-init-form-active")},popup:function(e=!1,t=!1){if(e){let e=l.find(".sb-popup-message"),t=e.attr("data-id");return i("popup"+(ee.null(t)?"":t),!0),void e.remove()}setTimeout(()=>{this.chat_open||(0==t&&(t=U.popup),l.find(".sb-popup-message").remove(),l.append(`<div data-id="${t.id?t.id:""}" class="sb-popup-message">`+(t.image?`<img loading="lazy" src="${t.image}" />`:"")+(t.title?`<div class="sb-top">${t.title}</div>`:"")+`<div class="sb-text">${t.message}</div><div class="sb-icon-close"></div></div>`),ee.event("SBPopup",t))},1e3)},followUp:function(){this.followUpCheck()&&(E=setTimeout(()=>{this.followUpCheck()&&ee.ajax({function:"execute-bot-message",conversation_id:this.conversation.id,name:"follow_up",check:!1},e=>{e.settings.sound&&this.audio&&this.audio.play(),this.skip=!0,ee.storageTime("email"),ee.event("SBFollowUp")})},!0===U.follow?U.office_hours||q?15e3:5e3:parseInt(U.follow)))},followUpCheck:function(){return!x&&this.conversation&&U.follow&&a()&&!a().email&&ee.storageTime("email",24)},welcome:function(){$||"open"==U.welcome_trigger&&!this.chat_open||!U.office_hours&&U.welcome_disable_office_hours||!U.welcome||i("welcome")||!a()||ee.ajax({function:"get-block-setting",value:"welcome"},e=>{setTimeout(()=>{U.dialogflow_welcome?!1===this.conversation?this.newConversation(3,-1,"",[],null,null,function(){le.dialogflow.welcome(e.open,e.sound)}):le.dialogflow.welcome(e.open,e.sound):(this.sendMessage(y,e.message,[],!1,!1,3),e.open&&!O&&this.start(),e.sound&&this.audio.play()),this.skip=!0,ee.event("SBWelcomeMessage")},parseInt($?0:U.welcome_delay)),i("welcome",!0)})},offlineMessage:function(){if(!x&&U.timetable&&(!U.office_hours||!q&&!U.timetable_disable_agents)){let e=U.timetable_message;switch(U.timetable_type){case"header":this.offline_message_set||(e[0]&&f.find(".sb-title").html(e[0]),f.find(".sb-text").html(e[1]),this.offline_message_set=!0);break;case"info":this.offline_message_set||(h.prepend(`<div class="sb-notify-message sb-rich-cnt"><div class="sb-cnt"><div class="sb-message">${e[0]?`<b>${e[0]}</b> `:""}${e[1]}</div></div></div>`),l.addClass("sb-notify-active"),this.offline_message_set=!0);break;default:setTimeout(()=>{if(this.conversation){let t=U.timetable_hide?`${e[0]?`*${e[0]}*\n`:""}${e[1]}`:"[timetable]",i=this.conversation.searchMessages(t,!0);if(i=!!i.length&&i){let e=this.conversation.getLastUserMessage(!1,!0);i=!e||(e.get("index")<i[i.length-1].get("index")&&Date.now()-36e5)<ee.unix(i[0].get("creation_time"))}i||this.sendMessage(y,t)}},5e3)}}},slackMessage:function(e,t,i,s,n=[]){if(!this.conversation||!s&&!n.length)return!1;let o=this.conversation.id;ee.ajax({function:"send-slack-message",user_id:e,full_name:t,profile_image:i,conversation_id:o,message:s,attachments:n,channel:this.slack_channel[0]==a().id&&this.slack_channel[1]},e=>{this.slack_channel=[a().id,e[1]],ee.event("SBSlackMessageSent",{message:s,conversation_id:o,slack_channel:e[1]})})},deleteMessage:function(e){ee.ajax({function:"delete-message",message_id:e},()=>{this.conversation&&this.conversation.deleteMessage(e),h.find(`[data-id="${e}"]`).remove(),ee.event("SBMessageDeleted",e)})},registration:function(e=!1,t=U.registration_required){if(e)return U.registration_required&&(!U.registration_offline||!q)&&(typeof SB_DEFAULT_USER==G||!SB_DEFAULT_USER.email)&&(!U.registration_timetable||!U.office_hours)&&(!1===a()||["visitor","lead"].includes(a().type));_.append(oe.generate({},U.registration_link||"registration-login"==U.registration_required?"login":t,"sb-init-form")),this.dashboard||this.showDashboard(),this.dashboard=!0,this.finalizeInit(),l.addClass("sb-init-form-active")},addUserAndLogin:function(e=!1,t=!1){let i=typeof SB_DEFAULT_USER!=G&&SB_DEFAULT_USER?SB_DEFAULT_USER:{};i.user_type=t?"lead":"visitor",ee.ajax({function:"add-user-and-login",settings:i,settings_extra:i.extra},i=>{if(ee.errorValidation(i)){if("duplicate-email"==i[1]||"duplicate-phone"==i[1])return delete SB_DEFAULT_USER.email,delete SB_DEFAULT_USER.extra.phone,this.addUserAndLogin(e,t)}else ee.loginCookie(i[1]),a(new ie(i[0])),te.start(),te.active||ne.automations.runAll(),e&&e(i)})},isInitDashboard:function(){return U.init_dashboard||a()&&a().conversations.length>1},uploadResponse:function(t){if("success"==(t=JSON.parse(t))[0])if("extension_error"==t[1]){let e="The file you are trying to upload has an extension that is not allowed.";x?SBAdmin.infoPanel(e,"info"):alert(e)}else if(e(d).hasClass("sb-input-image")){let i=e(d).find(".image"),s=i.attr("data-value");s&&!s.includes("media/user.svg")&&ee.ajax({function:"delete-file",path:s}),i.attr("data-value","").css("background-image",""),setTimeout(()=>{i.attr("data-value",t[1]).css("background-image",`url("${t[1]}?v=${ee.random()}")`).append('<i class="sb-icon-close"></i>'),d=!1},500)}else{let e=ee.beautifyAttachmentName(t[1].substr(t[1].lastIndexOf("/")+1));g.find(".sb-attachments").append(`<div data-name="${e}" data-value="${t[1]}"${t.length>2?' data-size="'+t[2][0]+"|"+t[2][1]+'"':""}>${e}<i class="sb-icon-close"></i></div>`),g.sbActive(!0)}else ee.error(t[1],"sb-upload-files.change");this.busy(!1)},closeChat:function(e=!0){let t=this.conversation.id;ne.clear(),e?ee.ajax({function:"update-conversation-status",conversation_id:t,status_code:3},()=>{this.closeChat_(t)}):this.closeChat_(t)},closeChat_(e){l.find(`li[data-conversation-id="${e}"]`).remove(),P="new-conversation",ne.clear(),i("open-conversation",""),i("welcome",""),i("flow_on_load",""),a().removeConversation(e),U.disable_dashboard||ne.showDashboard()},conversationArchived:function(){let e=!$&&U.close_chat||$&&U.tickets_close;if(e&&!U.rating)return this.closeChat(!1);U.rating&&oe.rating(e)},automations:{history:[],busy:[],scroll_position_intervals:{},timeout_queue:[],runAll:function(){let t=U.automations;for(var i=0;i<t.length;i++){let o=t[i],r=o.conditions,l=0==r.length,c=!1,d=!1,u=!1;for(var s=0;s<r.length;s++){let t=r[s][1];switch(l=!1,r[s][0]){case"browsing_time":l=!0,c=t;break;case"scroll_position":l=!0,d=t;break;case"referring":case"url":let i="referring"==r[s][0]?document.referrer:window.location.href,o=r[s][2].replace(/https?:\/\/|www\./g,"").split(",");i=i.replace(/https?:\/\/|www\./g,"");for(n=0;n<o.length;n++)if(i.includes(o[n])){l="contains"==t;break}break;case"include_urls":case"exclude_urls":let h="referring"==r[s][0]?document.referrer:window.location.href,g=r[s][2].replace(/https?:\/\/|www\./g,"").split(","),p="exclude_urls"!=r[s][0];p||(l=!0),h=h.replace(/https?:\/\/|www\./g,"");for(var n=0;n<g.length;n++)if(g[n]=e.trim(g[n].replace("https://","").replace("http://","").replace("www.","")),"contains"==t&&-1!=h.indexOf(g[n])||"does-not-contain"==t&&-1==h.indexOf(g[n])||"is-exactly"==t&&g[n]==h||"is-not"==t&&g[n]!=h){l=p;break}break;case"custom_variable":let f=t.split("=");f[0]in window&&window[f[0]]==f[1]&&(l=!0);break;case"returning_visitor":case"user_type":case"cities":case"languages":case"countries":case"postal_code":case"website":case"company":case"creation_time":case"last_activity":l=a(),u=!0;break;case"phone":l=a()&&a().getExtra("phone");break;case"email":l=a()&&a().email;break;default:l=a()&&a().getExtra(r[s][0])}if(!l)break}["messages","emails","sms"].includes(o.type)&&!a()&&(l=!1),l&&(u?o.id in this.busy||(ee.ajax({function:"automations-validate",automation:o},e=>{!1!==e&&this.runAll_final(o,d,c),delete this.busy[o.id]}),this.busy[o.id]=!0):"messages"==o.type&&ne.registration(!0)||this.runAll_final(o,d,c))}},runAll_final:function(t,i,s){i?this.scroll_position_intervals[t.id]=setInterval(()=>{e(window).scrollTop()>parseInt(i)&&(s?setTimeout(()=>{this.run(t)},1e3*parseInt(s)):this.run(t),clearInterval(this.scroll_position_intervals[t.id]))},1e3):s?this.timeout_queue.includes(t.id)||(setTimeout(()=>{this.run(t)},1e3*parseInt(s)),this.timeout_queue.push(t.id)):this.run(t)},run:function(e){if(!this.history.includes(e.id))switch(e.type){case"messages":case"emails":case"sms":if((!te.active||te.started)&&!(e.id in this.busy)){if("messages"==e.type&&ne.chat_open){let e=!!ne.conversation&&ne.conversation.getLastUserMessage(!1,"no-bot");if(e&&Date.now()-6e5<ee.unix(e.get("creation_time")))return}ee.ajax({function:"automations-run",automation:e},t=>{!1!==t&&(this.history.push(e.id),"messages"!=e.type||te.active||ne.updateConversations()),delete this.busy[e.id]}),this.busy[e.id]=!0}break;case"popups":if(!i("popup"+e.id))if(ne.chat_open){if(e.fallback){let t=!!ne.conversation&&ne.conversation.getLastUserMessage(!1,"no-bot");(!t||Date.now()-6e5>ee.unix(t.get("creation_time")))&&(ne.sendMessage(y,(ee.null(e.title)?"":`*${e.title}*\n`)+e.message,[],!1,!1,0),i("popup"+e.id,!0),this.history.push(e.id))}}else setTimeout(()=>{ne.popup(!1,{id:e.id,image:e.profile_image,title:e.title,message:e.message})},1e3),this.history.push(e.id);break;case"design":e.background&&f.css("background-image",`url("${e.background}")`),e.brand&&f.find(".sb-brand img").attr("src",e.brand),e.title&&f.find(".sb-title").html(e.title),e.message&&f.find(".sb-text").html(e.message),e.icon&&l.find(".sb-chat-btn .sb-icon").attr("src",e.icon),(e.color_1||e.color_2||e.color_3)&&ee.ajax({function:"chat-css",color_1:e.color_1,color_2:e.color_2,color_3:e.color_3},e=>{c.append(`<style>${e}</style>`)}),this.history.push(e.id);break;case"more":let t={};if(e.department&&(ne.default_department=e.department,t={function:"update-conversation-department",department:e.department}),e.agent&&(ne.default_agent=e.agent,t={function:"update-conversation-agent",agent_id:e.agent}),e.tags&&(e.tags=e.tags.split(","),ne.default_tags=e.tags,t={function:"update-tags",tags:e.tags,add:!0}),ne.conversation.id&&(e.tags||e.agent||e.department)&&(t.conversation_id=ne.conversation.id,ee.ajax(t)),e.articles||e.articles_category){let t=l.find(".sb-dashboard-articles > .sb-articles");ne.articles_allowed_ids=e.articles,ne.articles_category=e.articles_category,t&&ne.getArticles(e.articles,e=>{let i="";for(var s=0;s<2;s++)i+=`<div data-id="${e[s].id}"><div>${e[s].title}</div><span>${e[s].content}</span></div>`;t.html(i)},e.articles_category,2)}this.history.push(e.id)}}},flashNotification:function(){clearInterval(R),R=setInterval(function(){ne.notifications.length&&(document.title=document.title==D?"("+ne.notifications.length+") "+s("New message"+(ne.notifications.length>1?"s":"")):D)},2e3)},calculateLabelDates:function(){(x||this.chat_open)&&(L=h.find(".sb-label-date"))},calculateLabelDateFirst:function(){this.conversation.messages.length||h.append(`<div class="sb-label-date"><span>${s("Today")}</span></div>`)},playSound:function(e=!1){this.audio.play();let t=e||(x?SB_ADMIN_SETTINGS.sound.repeat:U.sound.repeat);t&&!this.tab_active&&(clearInterval(this.audio_interval),this.audio_interval=setInterval(()=>{this.audio.play(),--t||clearInterval(this.audio_interval)},1e3*this.audio.duration+1500))},isConversationAllowed:function(e,t){return(!U.tickets_hide||$&&"tk"==e||!$&&"tk"!=e)&&(![3,4,"3","4"].includes(t)||!$&&!U.close_chat||$&&!U.tickets_close)}};window.SBChat=ne;var oe={rich_messsages:{email:"",button:"",video:"",image:"",woocommerce_button:"",rating:"",chips:'<div class="sb-buttons">[options]</div>',buttons:'<div class="sb-buttons">[options]</div>',select:'<div class="sb-select"><p></p><ul>[options]</ul></div>',list:'<div class="sb-text-list">[values]</div>',"list-image":'<div class="sb-image-list">[values]</div>',table:"<table><tbody>[header][values]</tbody></table>",inputs:'<div class="sb-form">[values]</div>',card:'<div class="sb-card">[settings]</div>',share:'<div class="sb-social-buttons">[settings]</div>',slider:'<div class="sb-slider"><div>[items]</div></div><div class="sb-slider-arrow sb-icon-arrow-left[class]"></div><div class="sb-slider-arrow sb-icon-arrow-right sb-active[class]"></div>',"slider-images":'<div class="sb-slider sb-slider-images"><div>[items]</div></div><div class="sb-slider-arrow sb-icon-arrow-left[class]"></div><div class="sb-slider-arrow sb-icon-arrow-right sb-active[class]"></div>'},cache:{},duplicated_email:!1,generate:function(t,i,n=""){let o,r=!0,c=t.id?t.id:ee.random(),d=new se({});if(i in this.rich_messsages)o=this.rich_messsages[i];else if(i in this.cache)o=this.cache[i];else{if(!this.isShortcode(i))return!1;t.id||(c=i),o='<div class="sb-rich-loading sb-loading"></div>',ee.ajax({function:"get-rich-message",name:i,settings:t},s=>{s=this.initInputs(s),"timetable"==i&&(s=this.timetable(s)),e(x&&"chatbot"==SBAdmin.active_admin_area?".sb-playground":l).find(`.sb-rich-message[id="${c}"]`).html(`<div class="sb-content">${s}</div>`),this.cache[i]=s,ne.scrollBottom(ne.dashboard),ee.event("SBRichMessageShown",{name:i,settings:t,response:s})}),r=!1}let u=t.disabled;if(r){let n,r="";switch(i){case"email":let l=[],c=a().email,d="#"==a().get("last_name").charAt(0);"true"==t.name&&l.push(["first_name","true"==t["last-name"]?"First name":"Name",d?"":"true"==t["last-name"]?a().get("first_name"):a().name,"text",!0]),"true"==t["last-name"]&&l.push(["last_name","Last name",d?"":a().get("last_name"),"text",!0]);for(p=0;p<l.length;p++)o+=`<div id="${l[p][0]}" data-type="text" class="sb-input sb-input-text"><span class="${l[p][2]?"sb-active sb-filled":""}">${s(l[p][1])}</span><input value="${l[p][2]}" autocomplete="false" type="${l[p][3]}" ${l[p][4]?"required":""}></div>`;if("true"==t.phone){let e=a().getExtra("phone");this.cache.phone||(this.cache.phone=!0,ee.ajax({function:"get-select-phone"},e=>{this.cache.phone=e,h.find("#phone .sb-select-phone").html(e)})),o+=`<div id="phone" data-type="select-input" class="sb-input sb-input-select-input"><span class="${e?"sb-active sb-filled":""}">${s("Phone")}</span><div class="sb-select-phone">${this.cache.phone?this.cache.phone:""}</div><input autocomplete="false" type="text" data-phone="true"${"false"!=t["phone-required"]?" required":""}></div>`}o+=`<div id="email" data-type="email" class="sb-input sb-input-btn"><span class="${c?"sb-active sb-filled":""}">${s(ee.null(t.placeholder)?"Email":t.placeholder)}</span><input value="${c}" autocomplete="off" type="email" required><div class="sb-submit sb-icon-arrow-right"></div></div>`;break;case"image":o=`<div class="sb-image"><img loading="lazy" src="${t.url}"></div>`;break;case"video":o=`<iframe loading="lazy"${t.height?` height="${t.height}"`:""} src="https://${"youtube"==t.type?"www.youtube.com/embed/":"player.vimeo.com/video/"}${t.id}" allowfullscreen></iframe>`;break;case"select":n=t&&t.options?t.options.replace(/\\,/g,"{R}").split(","):[];for(p=0;p<n.length;p++){let e=n[p].replace(/{R}/g,",");r+=`<li data-value="${ee.stringToSlug(e)}">${s(e)}</li>`}o=o.replace("[options]",r);break;case"chips":case"buttons":n=t&&t.options?t.options.replace(/\\,/g,"{R}").split(","):[];for(p=0;p<n.length;p++)r+=`<div class="sb-btn sb-submit">${s(n[p].replace(/{R}/g,","))}</div>`;o=o.replace("[options]",r);break;case"button":if(t&&t.link){let e=t.link.includes("calendly.com");o=`<a ${e?'data-action="calendly" data-extra="'+t.link+"|"+(t.success?t.success.replaceAll('"',"'"):"")+'" ':""}href="${e?"#":t.link.replace(/<i>/g,"_").replace(/<\/i>/g,"_")}"${t.target&&!e?' target="_blank"':""} class="sb-rich-btn sb-btn${"link"==t.style?"-text":""}">${s(t.name)}</a>`}break;case"list":if(t.values){n=t.values.replace(/\\,/g,"{R}").replace(/\\:/g,"{R2}").replace(/:\/\//g,"{R3}").split(",");let a="list"==i,l=a&&n.length&&n[0].indexOf(":")>0;a&&!l&&(o=o.replace("sb-text-list","sb-text-list sb-text-list-single")),t.numeric&&(o=o.replace("sb-text-list","sb-text-list sb-text-list-numeric"));for(p=0;p<n.length;p++){let t=n[p].replace(/{R}/g,","),i="-"===t.substr(0,1);r+=l&&t.includes(":")?`<div><div>${s(t.split(":")[0].replace(/{R2}/g,":").replace(/{R3}/g,"://"))}</div><div>${s(t.split(":")[1].replace(/{R2}/g,":").replace(/{R3}/g,"://"))}</div></div>`:`<div${i?' data-inner="true"':""}>${e.trim(s((i?t.substr(1):t).replace(/{R2}/g,":").replace(/{R3}/g,"://")))}</div>`}o=o.replace("[values]",r)}break;case"list-image":if(t.values){n=t.values.split(",");for(p=0;p<n.length;p++){let e=n[p].replace("://","///").split(":");r+=`<div><div class="sb-thumb" style="background-image:url('${e[0].replace("///","://")}')"></div><div class="sb-list-title">${e[1]}</div><div>${e[2]}</div></div>`}o=o.replace("[values]",r)}break;case"table":if(t.values){n=t.header.split(","),r+="<tr>";for(p=0;p<n.length;p++)r+=`<th>${n[p]}</th>`;r+="</tr>",o=o.replace("[header]",r),r="",n=t.values.split(",");for(p=0;p<n.length;p++){let e=n[p].split(":");r+="<tr>";for(var g=0;g<e.length;g++)r+=`<td>${e[g]}</td>`;r+="</tr>"}o=o.replace("[values]",r)}break;case"inputs":if(t.values){n=t.values.split(",");for(p=0;p<n.length;p++)u&&!n[p]||(r+=`<div id="${ee.stringToSlug(n[p])}" data-type="text" class="sb-input sb-input-text"><span>${s(n[p])}</span><input autocomplete="false" type="text" required></div>`);r+='<div class="sb-btn sb-submit">'+s(t.button?t.button:"Send now")+"</div>",o=o.replace("[values]",r)}break;case"card":r=`${t.image?`<div class="sb-card-img" style="background-image:url('${t.image}')"></div>`:""}<div class="sb-card-header">${t.header}</div>${t.extra?`<div class="sb-card-extra">${t.extra}</div>`:""}${t.description?`<div class="sb-card-description">${t.description}</div>`:""}${t.link?`<a class="sb-card-btn" href="${t.link}"${t.target?' target="_blank"':""}>${s(t["link-text"])}</a>`:""}`,o=o.replace("[settings]",r);break;case"share":let f=t.channels?t.channels.replace(/ /g,"").split(","):["fb","tw","li","wa","pi"],m="";for(p=0;p<f.length;p++){switch(f[p]){case"fb":m="www.facebook.com/sharer.php?u=";break;case"tw":m="twitter.com/intent/tweet?url=";break;case"li":m="www.linkedin.com/sharing/share-offsite/?url=";break;case"wa":m="web.whatsapp.com/send?text=";break;case"pi":m="www.pinterest.com/pin/create/button/?url="}r+=`<div class="sb-${f[p]} sb-icon-social-${f[p]}" data-link="https://${m}${encodeURIComponent(t[f[p]])}"></div>`}o=o.replace("[settings]",r);break;case"slider":let v=0;for(p=1;p<16&&"header-"+p in t;p++)r+=`<div>${"image-"+p in t?`<div class="sb-card-img" style="background-image:url('${t["image-"+p]}')"></div>`:""}<div class="sb-card-header">${t["header-"+p]}</div>${"extra-"+p in t?`<div class="sb-card-extra">${t["extra-"+p]}</div>`:""}${"description-"+p in t?`<div class="sb-card-description">${t["description-"+p]}</div>`:""}${"link-"+p in t?`<a class="sb-card-btn" href="${t["link-"+p]}"${t.target?' target="_blank"':""}>${s(t["link-text-"+p])}</a>`:""}</div>`,v++;o=o.replace("[items]",r).replace(/\[class\]/g,1==v?" sb-hide":"");break;case"slider-images":if(t.images){let e=t.images.split(",");for(var p=0;p<e.length;p++)r+=`<div class="sb-card-img" data-value="${e[p]}" style="background-image:url('${e[p]}')"></div>`;o=o.replace(/\[class\]/g,1==e.length?" sb-hide":"")}o=o.replace("[items]",r);break;case"woocommerce_button":t.settings=`checkout:${t.checkout},coupon:${t.coupon}`,o=`<a href="#" data-ids="${t.ids}" class="sb-rich-btn sb-btn">${t.name}</a>`;break;case"rating":o=`<div class="sb-rating-message sb-rating-${1==t.value?"positive":"negative"}"><div><i class="sb-icon-${1==t.value?"like":"dislike"}"></i> ${s(1==t.value?"Helpful":"Not helpful")}</div>${t.message?"<div>"+t.message+"</div>":""}</div>`,t.message=!1}}return`<div id="${c}" data-type="${i}"${u?'disabled="true"':""}${t.settings?` data-settings="${t.settings}"`:""}class="sb-rich-message sb-rich-${i} ${n}">`+(t.title?`<div class="sb-top">${d.render(s(t.title))}</div>`:"")+(t.message?`<div class="sb-text">${d.render(s(t.message))}</div>`:"")+`<div class="sb-content">${o}</div>${"email"==i?`<div data-success="${t.success?t.success.replace(/"/g,""):""}" class="sb-info"></div>`:""}</div>`},submit:function(i,n,o){if(!x&&!t(o)&&!this.is_busy){let t="",c="",d={},u=e(i).find("[data-success]").length?e(i).find("[data-success]").attr("data-success"):"",h=e(i).closest(".sb-rich-message").attr("id"),g=e(i).closest("[data-id]").attr("data-id"),p="",f={"rich-messages":{}},m=0==a()?{profile_image:"",first_name:"",last_name:"",email:"",password:"",user_type:""}:{profile_image:a().image,first_name:a().get("first_name"),last_name:a().get("last_name"),email:a().email,password:"",user_type:""},v={},_=e(o),b="",S=!1,A=!1!==ne.conversation,k={},C={},T=i.find("#otp");if(ee.null(g))g=-1;else{let e=ne.conversation.getMessage(g);p=e.message,(f=e.payload())["rich-messages"]||(f["rich-messages"]={})}switch(e(o).hasClass("sb-btn")||e(o).hasClass("sb-select")||e(o).hasClass("sb-submit")||(_=e(o).closest(".sb-btn,.sb-select")),e(i).find(".sb-info").html("").sbActive(!1),n){case"email":if(v=re.getAll(i),e.each(v,function(e,t){v[e]=t[0]}),v.first_name&&(m.user_type="user",v.last_name||(m.last_name="")),v.phone&&(k={phone:[v.phone,"Phone"]}),e.extend(m,v),t="Please fill in all required fields and make sure the email is valid.",u&&(u=s(u).replace("{user_email}",m.email).replace("{user_name_}",m.first_name+(v.last_name?" "+m.last_name:""))),T.sbActive()){let e=T.attr("data-otp");v.otp=!!e&&[e,i.find("#otp input").val()]}f["rich-messages"][h]={type:n,result:v},f.event="update-user",d={function:"update-user-and-message",settings:m,settings_extra:k,payload:f,skip_otp:!0},S={settings:m,settings_extra:k};break;case"registration":if(v=re.getAll(i.find(".sb-form-main")),k=re.getAll(i.find(".sb-form-extra")),e.each(v,function(e,t){v[e]=t[0]}),e.extend(m,v),C=e.extend({},m),u&&(u=s(u)),U.registration_details){u+='[list values="';for(var r in m){let e=m[r].replace(/:|,/g,"");e&&("profile_image"==r&&(e=e.substr(e.lastIndexOf("/")+1)),["password","password-check","envato-purchase-code","otp"].includes(r)?(e="********",C[r]="********"):u+=m[r]?`${s(ee.slugToString(r.replace("first_name","name")))}:${e},`:"")}for(var r in k)k[r][0]&&(u+=`${s(k[r][1].replace(/:|,/g,""))}:${k[r][0].replace(/:|,/g,"")},`);u=u.slice(0,-1)+'"]'}if(T.sbActive()){let e=T.attr("data-otp");m.otp=!!e&&[e,i.find("#otp input").val()]}m.user_type="user",f["rich-messages"][h]={type:n,result:{user:C,extra:k}},f.event="update-user",d=U.registration_otp&&m.email&&!m.otp?{function:"otp",email:m.email}:{function:a()?"update-user-and-message":"add-user-and-login",settings:m,settings_extra:k,payload:f},t=re.getRegistrationErrorMessage(i),S={settings:m,settings_extra:k};break;case"chips":case"select":case"buttons":v=ee.escape(e(o).html()),u&&(u=s(u)+` *${v}*`),f["rich-messages"][h]={type:n,result:v},d={function:"update-message",payload:f},b=v,"chips"==n&&(ne.sendMessage(a().id,v,[],!1,{id:h,event:"chips-click",result:v},"sb-human-takeover"==h&&0==_.index()&&2),"sb-human-takeover"==h&&0==e(o).index()&&le.dialogflow.humanTakeover(),e(o).closest(".sb-content").remove());break;case"inputs":if(v=re.getAll(i),t="All fields are required.",u){u=s(u)+' [list values="';for(var r in v)u+=`${s(v[r][1].replace(/:|,/g,""))}:${v[r][0].replace(/:|,/g,"")},`;u=u.slice(0,-1)+'"]'}f["rich-messages"][h]={type:n,result:v},d={function:"update-message",payload:f},S={settings:v}}if(c=p.substr(p.indexOf("["+n)),c=c.substr(0,c.indexOf("]")+1),t&&re.errors(i))return re.showErrorMessage(i,t),_.sbLoading(!1),(ne.dashboard||A&&ne.conversation.getLastMessage().id==g)&&ne.scrollBottom(),!1;if(!u&&"registration"!=n){let e=this.shortcode(c),t=e[1].id?`id="${e[1].id}"`:"",i=e[1].title?`title="${e[1].title}"`:"",s=e[1].message?`message="${e[1].message}"`:"",a="";if(["inputs","email"].includes(n)){for(var r in v)a+=v[r]+",";a=`values="${a.slice(0,-1)}"`}else a=`options="${v}"`;u=`[${"email"==n?"inputs":n} ${t} ${i} ${s} ${a} disabled="true"]`}-1!=g&&(u=u.replace(/<br>/g,"\n"),e.extend(d,{message_id:g,message:p?"chips"==n?p.replace("]",' disabled="true"]'):p.replace(c,u):u,payload:f})),ee.ajax(d,t=>{if(t&&!ee.errorValidation(t)){switch(n){case"email":for(var r in m)a().set(r,m[r]);for(var r in k)a().setExtra(r,k[r][0]);ee.loginCookie(t[1]),"sb-follow-up"==h&&ee.ajax({function:"subscribe-email",email:a().email}),ne.automations.runAll(),ee.event("SBNewEmailAddress",{id:h,name:a().name,email:a().email});break;case"registration":let o=i.find("#otp");if(U.registration_otp&&!o.sbActive())return o.attr("data-otp",t).sbActive(!0),o.find("input").attr("required",!0).addClass("sb-error"),re.showErrorMessage(i,s("Please check your email for the one-time code.")),ne.scrollBottom(),void _.sbLoading(!1);if(ee.loginCookie(t[1]),m.id=t[0].id,a()){for(var r in m)a().set(r,m[r]);for(var r in k)a().setExtra(r,k[r][0]);ne.automations.runAll(),ne.welcome()}else{a(new ie(t[0]));for(var r in k)a().setExtra(r,k[r][0]);this.duplicated_email&&!U.init_dashboard&&(P="open-conversation"),te.start(),ne.initChat(),this.duplicated_email||U.init_dashboard&&l.find(".sb-departments-list").length||!u||ne.sendMessage(y,u,[],!1,!1,3)}ne.dashboard&&(l.removeClass("sb-init-form-active"),e(i).remove(),ne.isInitDashboard()||U.init_dashboard&&this.duplicated_email||ne.hideDashboard()),U.wp_registration&&m.email&&m.password?le.wordpress.ajax("wp-registration",{user_id:t[0].id,first_name:t[0].first_name,last_name:t[0].last_name,password:m.password,email:m.email}):"wp"==U.wp_users_system&&le.wordpress.ajax("wp-login",{user:m.email,password:m.password}),delete this.cache.registration,setTimeout(()=>{ee.event("SBRegistrationForm",{id:h,conversation_id:!!ne.conversation&&ne.conversation.id,user:m,extra:f["rich-messages"][h].result.extra})},5e3);break;case"buttons":ne.scrollBottom()}-1==g?e(o).closest(".sb-rich-message").html(u):(_.sbLoading(!1),f.type&&"close-message"==f.type||w||ne.setConversationStatus(2)),["login","chips"].includes(n)||!U.dialogflow_send_user_details&&["email","registration"].includes(n)||le.dialogflow.message(`${h}${b?"|"+b:""}`,[],!1,S),!U.slack_active||w&&!le.dialogflow.humanTakeoverActive()||ne.slackMessage(a().id,a().name,a().image,u),te.active&&ne.update(),"registration"!=n&&"email"!=n&&ee.event("SBRichMessageSubmit",{result:t,data:f["rich-messages"][h],id:h})}else"registration"==n&&ee.errorValidation(t,"duplicate-email")?(ee.ajax({function:"otp",email:m.email},e=>{let t=i.find("#otp");t.attr("data-otp",e).sbActive(!0),t.find("input").attr("required",!0).addClass("sb-error"),re.showErrorMessage(i,s("This email is already in use. Please check your email for the one-time code.")),i.find(".sb-submit").html(s("Sign in")),ne.scrollBottom()}),this.duplicated_email=!0):(this.duplicated_email=!1,re.showErrorMessage(i,re.getRegistrationErrorMessage(t,"response"))),ne.dashboard&&ne.scrollBottom(),_.sbLoading(!1)})}},shortcode:function(t){let i={},s=t.includes(" ")?t.substr(1,t.indexOf(" ")-1):t.slice(1,-1);if(/\?|"|'|`|\*/gi.test(s))return[!1,!1];let a=(t=t.slice(1,-1).substr(s.length+1)).split('" ');for(var n=0;n<a.length;n++)if(a[n].includes("=")){let t=[a[n].substr(0,a[n].indexOf("=")),a[n].substr(a[n].indexOf("=")+2)];i[e.trim(t[0])]=t[1].replace(/"/g,"")}return[s,i]},initInputs:function(t){return(t=e(e.parseHTML("<div>"+t+"</div>"))).find(".sb-input input").each(function(){e(this).val()&&e(this).siblings().addClass("sb-active sb-filled")}),t.html()},timetable:function(t){let i=e(e.parseHTML(`<div>${t}</div>`)),a=i.find("[data-offset]").attr("data-offset");return a=ee.null(a)?0:parseFloat(a),i.find("[data-time]").each(function(){let n=e(this).attr("data-time").split("|");t="";for(var o=0;o<n.length;o++){if("closed"==n[o]){t+=s("Closed");break}if(n[o]){let e=n[o].split(":"),i=ee.convertUTCDateToLocalDate(`01/01/2000 ${e[0]}:${e[1]}`,a);t+=i.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})+(0==o||2==o?`<span>${s("to")}</span>`:1==o&&n[o+1]?"<br />":"")}}i.find(" > div > span").html(`<i class="sb-icon-clock"></i> ${s("Time zone")} ${Intl.DateTimeFormat().resolvedOptions().timeZone}`),e(this).html(t)}),i.html()},sliderChange:function(e,t="left"){let i=h.find(`#${e}`);if(i.length&&!i.hasClass("sb-moving")){let e=i.find(".sb-slider > div > div"),s=e.eq(0),a=Math.ceil(s.closest(".sb-slider").width()),n="right"==t?-1:1,o=parseFloat(parseFloat(parseFloat(s.css("margin-left"))+a*n)),r=a*(e.length-1)*-1;o<1&&o>=r&&(s.css("margin-left",o+"px"),i.addClass("sb-moving"),setTimeout(()=>{i.removeClass("sb-moving")},1200)),i.find(".sb-icon-arrow-right").sbActive(!(r>o-15&&r<o+15)),i.find(".sb-icon-arrow-left").sbActive(o<-10)}},calendly:{script_loaded:!1,load:function(t,i,a){t=t.split("|"),this.script_loaded?this.load_(t[0],i):e.getScript("https://assets.calendly.com/assets/external/widget.js",()=>{this.script_loaded=!0,window.addEventListener("message",function(e){"https://calendly.com"===e.origin&&"calendly.event_scheduled"==e.data.event&&(ne.updateMessage(a,s(t[1]?t[1]:"Booking completed.")),b.sbActive(!1))}),this.load_(t[0],i)},!0)},load_:function(e,t){Calendly.initInlineWidget({url:(e.includes("http")?"":"https://")+e+"?hide_landing_page_details=1&hide_event_type_details=1&hide_gdpr_banner=1",parentElement:b.find("> div").eq(1),prefil:"user"==a().type?{name:a().name,email:a().email}:{}}),b.find("> div:first-child > div").html(s(t)),b.sbActive(!0).attr("data-id","calendly")}},rating:function(e=!1){b.find("> div:first-child > div").html(s("Rate your experience")),b.find("> div:last-child").html(`${U.rating_message?`<div class="sb-input sb-input-textarea"><textarea placeholder="${s("Add a message here...")}"></textarea></div>`:""}<div class="sb-rating"><div><i data-rating="positive" class="sb-submit sb-icon-like"><span>${s("Helpful")}</span></i><i data-rating="negative" class="sb-submit sb-icon-dislike"><span>${s("Not helpful")}</span></i></div></div>`),b.sbActive(!0).attr("data-id","rating").attr("data-close-chat",e?"true":"").css("max-height",(U.rating_message?167:80)+"px")},isShortcode:function(e){return e in this.rich_messsages||x&&SB_ADMIN_SETTINGS.rich_messages.includes(e)||!x&&U.rich_messages.includes(e)}};window.SBRichMessages=oe;var re={getAll:function(t){let i={};return e(t).find(".sb-input[id]").each((t,s)=>{i[e(s).attr("id")]=this.get(s)}),i},get:function(t){let i=(t=e(t)).data("type"),a=s(ee.escape(t.find(" > span").html()));switch(i){case"image":let e=t.find(".image").attr("data-value");return[ee.null(e)?"":e,a];case"select":return[ee.escape(t.find("select").val()),a];case"select-input":let s=t.find("select,input[disabled]");return[ee.escape((s.is("select")||s.is("input")?s.val():t.find(".sb-select").length?t.find(".sb-select > p").attr("data-value"):t.find("> div").html())+t.find("> input").val()),a];default:let n=t.find("input");return[ee.escape(n.length?n.val():t.find("[data-value]").attr("data-value")),a]}},set:function(t,i){if((t=e(t)).length){switch(t.data("type")){case"image":i?t.find(".image").attr("data-value",i).css("background-image",`url("${i}")`):t.find(".image").removeAttr("data-value").removeAttr("style");break;case"select":t.find("select").val(i);break;default:t.find("input,textarea").val(i)}return!0}return!1},clear:function(t){e(t).find(".sb-input,.sb-setting").each((t,i)=>{this.set(i,""),e(i).find("input, select, textarea").removeClass("sb-error")}),this.set(e(t).find("#user_type"),"user")},errors:function(t){let i=!1,s=e(t).find("input, select, textarea").removeClass("sb-error");return s.each(function(t){let a=e.trim(e(this).val()),n=e(this).attr("type"),o=e(this).prop("required");(o&&!a||(o||a)&&("password"==n&&(a.length<8||s.length>t+1&&"password"==s.eq(t+1).attr("type")&&s.eq(t+1).val()!=a)||"email"==n&&(a.indexOf("@")<0||a.indexOf(".")<0||/;|:|\/|\\|,|#|"|!|=|\*|{|}|[|]|£|\$|€|~|'|>|<|\^|&/.test(a))||e(this).attr("data-phone")&&a&&(!e(this).parent().find("select").val()&&!e(this).prev().find("> div > p").attr("data-value")&&!e(this).parent().find("div").html().trim().startsWith("+")||isNaN(a)||a.includes("+")||a.length<5)))&&(i=!0,e(this).addClass("sb-error"))}),(s=e(t).find("[data-required]").removeClass("sb-error")).each(function(){ee.null(e(this).attr("data-value"))&&(e(this).addClass("sb-error"),i=!0)}),i},showErrorMessage:function(t,i){e(t).find(".sb-info").html(s(i)).sbActive(!0),clearTimeout(E),E=setTimeout(function(){e(t).find(".sb-info").sbActive(!1)},7e3)},showSuccessMessage:function(t,i){e(t).find(".sb-info").remove(),e(t).addClass("sb-success").find(".sb-content").html(`<div class="sb-text">${i}</div>`)},getRegistrationErrorMessage(t,i="validation"){let a="";return"response"==i?ee.errorValidation(t,"duplicate-email")?"This email is already in use. Please use another email.":ee.errorValidation(t,"duplicate-phone")?"This phone number is already in use. Please use another number.":ee.errorValidation(t,"invalid-envato-purchase-code")?"Invalid Envato purchase code.":ee.errorValidation(t,"invalid-otp")?"Invalid one-time code.":"Error. Please check your information and try again.":(e(t).find(".sb-input:not(#password-check) [required]").each(function(){a+=", "+e(this).closest(".sb-input").find("span").html()+("password"==e(this).attr("type")?" ("+s("8 characters minimum")+")":"")}),`${a.substring(2)} ${s((a.includes(",")?"are":"is")+" required.")}`)}};window.SBForm=re;var le={login:function(){return typeof SB_DEFAULT_USER!=G&&SB_DEFAULT_USER?[SB_DEFAULT_USER,"default"]:this.is("wp")&&typeof SB_WP_ACTIVE_USER!=G&&"wp"==U.wp_users_system?[[SB_WP_ACTIVE_USER,typeof SB_WP_AVATAR!=G?SB_WP_AVATAR:""],"wp"]:typeof SB_SHOPIFY_ACTIVE_USER!=G?[SB_SHOPIFY_ACTIVE_USER,"shopify"]:typeof SB_PERFEX_ACTIVE_USER!=G?[[SB_PERFEX_ACTIVE_USER,SB_PERFEX_CONTACT_ID],"perfex"]:typeof SB_WHMCS_ACTIVE_USER!=G?[SB_WHMCS_ACTIVE_USER,"whmcs"]:typeof SB_AECOMMERCE_ACTIVE_USER!=G&&[SB_AECOMMERCE_ACTIVE_USER,"aecommerce"]},is:function(e){return x?SBAdmin.apps.is(e):"wordpress"==e||"wp"==e?U.wp:e in U&&U[e]},shopify:{startCartSynchronization:function(){setInterval(()=>{a()&&fetch("/cart.js").then(e=>e.json()).then(e=>{e={total:e.total_price,currency:e.currency,items:e.items.map(e=>({id:e.product_id,price:e.price,handle:e.handle,title:e.title,quantity:e.quantity}))};let t=JSON.stringify(e);i("shopify-cart")!=t&&(i("shopify-cart",t),ee.ajax({function:"shopify-cart-sync",cart:e}))})},1e4)}},wordpress:{ajax:function(t,i,s=!1){if(typeof SB_WP_AJAX_URL==G)return!!s&&s(!1);e.ajax({method:"POST",url:SB_WP_AJAX_URL,data:e.extend({action:"sb_wp_ajax",type:t},i)}).done(e=>{s&&s(e)})}},woocommerce:{updateCart:function(e,t,i=!1){le.wordpress.ajax(e,{product_id:t},i)},waitingList:function(e="request",t=!1){typeof SB_WP_WAITING_LIST!==G&&("request"!=e||SB_WP_WAITING_LIST&&ee.storageTime("waiting-list-"+SB_WP_PAGE_ID,24))&&a()&&ee.ajax({function:"woocommerce-waiting-list",product_id:!1===t?SB_WP_PAGE_ID:t,conversation_id:ne.conversation.id,action:e,token:this.token},t=>{t&&(ee.storageTime("waiting-list-"+SB_WP_PAGE_ID),"request"!=e||ne.chat_open&&!ne.dashboard||ne.updateConversations())})}},dialogflow:{token:i("dialogflow-token"),typing_enabled:!0,project_id:!1,busy:!1,message:function(t="",s=[],n=!1,o=!1,r=!1){if(!(t.length<2)||s.length){if(!r)for(var l=0;l<s.length;l++)s[l][0].includes("voice_message")&&(r=s[l][1]);if(this.active(!0,!0,!1)){let e=le.dialogflow.humanTakeoverActive();if(e&&!this.typing_enabled||this.typing(),this.chatbotLimit())return ne.sendMessage(y,this.chatbotLimit());ne.headerAgent(!0),setTimeout(()=>{let n=ne.conversation;ee.ajax({function:"dialogflow-message",conversation_id:!!n&&n.id,message:t,attachments:s,parameters:o,token:this.token,dialogflow_language:i("dialogflow-language")?i("dialogflow-language"):SB_LANG,project_id:this.project_id,session_id:a().id+"-"+n.id,audio:r},s=>{if(ne.typing(-1,"stop"),!1!==s){if(s.response&&s.response.error)return console.error(s.response);if(s.human_takeover)return ne.offlineMessage(),ne.followUp(),this.active(!1);if(s.language_detection&&!i("dialogflow-language")&&i("dialogflow-language",[s.language_detection]),s.user_language&&!i("dialogflow-language")&&a().setExtra("language",s.user_language),s.translations&&(U.translations=s.translations),!ee.errorValidation(s)){let r=!!s.response.queryResult&&s.response.queryResult,l=r&&("input.unknown"==r.action||r.match&&"NO_MATCH"==r.match.matchType),c=s.messages&&Array.isArray(s.messages)?s.messages:[];if(clearTimeout(E),this.token!=s.token&&(this.token=s.token,i("dialogflow-token",s.token)),l?e&&(this.typing_enabled=!1):this.typing_enabled=!0,r){if(r.action){let e=r.action;"end"==e&&this.active(!1),ee.event("SBBotAction",e)}for(o=0;o<c.length;o++){if(c[o].payload){let e=["human-takeover","redirect","woocommerce-update-cart","woocommerce-checkout","open-article","transcript","department","agent","send-email","rich-message","tags"],t=c[o].payload;if(ee.null(t)&&(t=[]),e[0]in t&&!0===t[e[0]]&&this.humanTakeover(),e[1]in t&&setTimeout(function(){t["new-window"]?window.open(t[e[1]]):document.location=t[e[1]]},500),e[2]in t){let i=t[e[2]];le.woocommerce.updateCart(i[0],i[1],e=>{e&&ee.event("SBWoocommerceCartUpdated",{action:i[0],product:i[1]})})}if(e[3]in t&&!0===t[e[3]]&&le.wordpress.ajax("url",{url_name:"checkout"},e=>{setTimeout(()=>document.location=e,500)}),e[4]in t&&ne.showArticles(t[e[4]]),e[5]in t&&t[e[5]]&&ee.ajax({function:"transcript",conversation_id:n.id,type:"txt"},i=>{"email"==t[e[5]]&&a().email?ne.sendEmail(t.message?t.message:"",[[i,i]],n.id):window.open(i)}),e[6]in t&&ee.ajax({function:"update-conversation-department",conversation_id:n.id,department:t[e[6]],message:n.getLastUserMessage().message}),e[7]in t&&ee.ajax({function:"update-conversation-agent",conversation_id:n.id,agent_id:t[e[7]],message:n.getLastUserMessage().message}),e[8]in t){let i=t[e[8]];ne.sendEmail(i.message,i.attachments,"active_user"==i.recipient)}e[9]in t&&ne.sendMessage(y,t[e[10]]),e[10]in t&&ee.ajax({function:"update-tags",conversation_id:n.id,tags:t[e[11]]}),ee.event("SBBotPayload",t)}this.chatbotLimit(!1),i("dialogflow-language")||!r.languageCode||SB_LANG&&r.languageCode==SB_LANG[0]||i("dialogflow-language",[r.languageCode])}if(r.diagnosticInfo){r.diagnosticInfo.end_conversation&&this.active(!1)}}if(U.slack_active&&c&&(!w||e))for(var o=0;o<c.length;o++)ne.slackMessage(a().id,U.bot_name,U.bot_image,c[o].message,c[o].attachments);ee.event("SBBotMessage",{response:s,message:t})}}}),this.busy=!0},!1!==n?n:0==U.bot_delay?2e3:parseInt(U.bot_delay))}else this.active(!0,!1,!0)&&!e(".sb-emoji-list").html().includes("<li>"+t+"</li>")&&this.openAI(t,!1,r,s)}},openAI:function(t,s=!1,n=!1,o=[]){if(U.open_ai_active){if(ne.headerAgent(!0),ne.agent_id!=y||le.dialogflow.humanTakeoverActive()&&!this.typing_enabled||this.typing(),this.chatbotLimit())return ne.sendMessage(y,this.chatbotLimit());setTimeout(()=>{ee.ajax({function:"open-ai-message",message:t,conversation_id:!!ne.conversation&&ne.conversation.id,audio:n,extra:{token:le.dialogflow.token},attachments:o,context:!!U.open_ai_context_awareness&&(document.title.toUpperCase()+"\n\n\n"+e('meta[name="description"]').attr("content")||"")},e=>{this.busy=!1,ne.typing(-1,"stop"),ee.event("SBOpenAIMessage",{response:e,message:t}),e&&(e[0]||e[5])?(U.chatbot_limit&&this.chatbot_limit++,U.slack_active&&t&&(!w||le.dialogflow.humanTakeoverActive())&&ne.slackMessage(a().id,U.bot_name,U.bot_image,e[1]),e[2]&&le.dialogflow.token!=e[2]&&(le.dialogflow.token=e.token,i("dialogflow-token",e.token)),e[3]&&(ne.offlineMessage(),ne.followUp()),e[5]&&(e[5].redirect&&setTimeout(()=>{document.location=e[5].redirect},500),e[5].open_article&&ne.showArticles(e[5].open_article),"conversation-status-update-3"==e[5].event&&ne.conversationArchived()),this.chatbotLimit(!1)):!1!==e[1]&&ee.error(e[1].error?e[1].error.message:e[1],"SBApps.dialogflow.openAI"),s&&s(e)}),this.busy=!0},0==U.bot_delay?2e3:parseInt(U.bot_delay))}},flowOnLoad(){U.flow_on_load&&!i("flow-on-load")&&a()&&(ne.conversation?ee.ajax({function:"run-flow-on-load",message:U.flow_on_load,conversation_id:ne.conversation.id}):ne.newConversation(3,a().id,"",[],null,null,()=>{ee.ajax({function:"run-flow-on-load",message:U.flow_on_load,conversation_id:ne.conversation.id})}),i("flow-on-load",!0))},typing:function(){clearTimeout(I),I=setTimeout(()=>{ne.typing(-1,"start")},1e3)},active:function(e=!0,t=!0,i=!0){if(!1===e)return ne.conversation.set("is_human_takeover",!0),!1;if("activate"==e&&ne.conversation.set("is_human_takeover",!1),!x&&le.dialogflow.humanTakeoverActive()&&U.dialogflow_human_takeover_disable_chatbot)return!1;let s=!(x||ne.conversation&&le.dialogflow.humanTakeoverActive()&&ne.agent_online||U.dialogflow_office_hours&&U.office_hours);return t&&i?(U.dialogflow_active||U.open_ai_active)&&s:(!t||U.dialogflow_active)&&(!i||U.open_ai_active)&&s},welcome:function(e=!1,t=!1){ee.ajax({function:"dialogflow-message",message:"",conversation_id:ne.conversation.id,token:this.token,event:"Welcome",dialogflow_language:i("dialogflow-language")?i("dialogflow-language"):SB_LANG},()=>{e&&ne.start(),t&&ne.audio.play()})},humanTakeover:function(){ee.ajax({function:"dialogflow-human-takeover",conversation_id:ne.conversation.id},()=>{ne.offlineMessage(),ne.followUp(),this.active(!1),U.queue_human_takeover&&(U.queue=!0,ne.queue(ne.conversation.id))})},humanTakeoverActive:function(){return!!ne.conversation&&ne.conversation.get("is_human_takeover")},translate:function(e,t,i,s,a){ee.ajax({function:"google-translate",strings:e,language_code:t,token:this.token,message_ids:s,conversation_id:a},e=>{this.token=e[1],i(e[0])})},chatbotLimit:function(e=!0){if(U.chatbot_limit){let s=i("chatbot_limit"),a=(new Date).getTime()/1e3;if(s||(s=[]),e){let e=a-U.chatbot_limit.interval,n=[];for(var t=0;t<s.length;t++)s[t]>e&&n.push(s[t]);if(i("chatbot_limit",n),n.length>=U.chatbot_limit.quota)return U.chatbot_limit.message}else s.push(a),i("chatbot_limit",s)}return!1}},aecommerce:{cart:function(){le.is("aecommerce")&&typeof SB_AECOMMERCE_CART!=G&&typeof SB_AECOMMERCE_ACTIVE_USER!=G&&i("aecommerce")!=JSON.stringify(SB_AECOMMERCE_CART)&&ee.ajax({function:"aecommerce-cart",cart:SB_AECOMMERCE_CART},()=>{i("aecommerce",JSON.stringify(SB_AECOMMERCE_CART))})}},martfury:{privateChat:function(){let t=e("#tab-vendor > h4,.ps-product__vendor > a");if(t.length){t=t.html().toLowerCase();for(var i=0;i<U.martfury.length;i++)if(t==U.martfury[i]["martfury-linking-store"].toLowerCase()){let e=U.martfury[i]["martfury-linking-agent"],t=ee.activeUser()?ee.activeUser().conversations:[];ne.default_agent=e;for(var s=0;s<t.length;s++)if(t[s].get("agent_id")==e)return void ne.openConversation(t[s].id);ne.clear(),ne.hideDashboard()}}}}};window.SBApps=le,e(document).ready(function(){if((l=e(".sb-admin, .sb-admin-start")).length)return x=!0,void r();let t,i,s=!1;if(typeof SB_INIT_URL!=G)SB_INIT_URL.indexOf(".js")<0&&(SB_INIT_URL+="/js/main.js?v=3.8.3"),t=SB_INIT_URL;else{let e=document.getElementsByTagName("script"),i=["init.js","main.js","min/init.min.js","min/main.min.js"];for(var a=0;a<e.length;a++){let o=e[a].src;if("sbinit"==e[a].id){t=o,s=s||t.includes("init.");break}for(var n=0;n<i.length;n++)if(o&&o.includes("/supportboard/js/"+i[n])){t=o,s=s||t.includes("init.");break}}}let o=ee.getURL(!1,t);if(o.url&&(t=o.url),typeof SB_DISABLED!=G&&SB_DISABLED)return;if(s)return void r();typeof SB_TICKETS==G&&"tickets"!=o.mode||($=!0,o.mode="tickets"),o.cloud&&(W=o.cloud);let c=!(!Z||"en"==Shopify.locale)&&Shopify.locale,d=t.lastIndexOf("main.min.js"),u=(i=t.substr(0,t.lastIndexOf("main.js")>0?t.lastIndexOf("main.js")-4:d-8))+"/include/init.php"+(o.lang?"?lang="+o.lang:"")+(c?"?lang_optional="+c:"")+(o.mode?"&mode="+o.mode:"")+(W?"&cloud="+W:"");ee.cors("GET",u.replace(".php&",".php?"),t=>{let s="body";$&&e("#sb-tickets").length&&(s="#sb-tickets"),e(s).append(t),ee.loadResource(i+"/css/"+($?"tickets":"main")+".css"),$?ee.loadResource(i+"/apps/tickets/tickets"+(d>0?".min":"")+".js?v=3.8.3",!0,()=>{r()}):r(),o.lang&&(SB_LANG=[o.lang,x?"admin":"front"])})})}(jQuery);