var MauticVars={};var mQuery=jQuery.noConflict(!0);window.jQuery=mQuery;if(!String.prototype.startsWith){String.prototype.startsWith=function(searchString,position){position=position||0;return this.substr(position,searchString.length)===searchString}}
MauticVars.activeRequests=0;mQuery.ajaxSetup({beforeSend:function(request,settings){if(settings.showLoadingBar){Mautic.startPageLoadingBar()}
if(typeof IdleTimer!='undefined'){var userLastActive=IdleTimer.getLastActive();var queryGlue=(settings.url.indexOf("?")==-1)?'?':'&';settings.url=settings.url+queryGlue+'mauticUserLastActive='+userLastActive}
if(mQuery('#mauticLastNotificationId').length){var queryGlue=(settings.url.indexOf("?")==-1)?'?':'&';settings.url=settings.url+queryGlue+'mauticLastNotificationId='+mQuery('#mauticLastNotificationId').val()}
if(settings.type=='POST'){request.setRequestHeader('X-CSRF-Token',mauticAjaxCsrf)}
return!0},cache:!1});mQuery(document).on('click',function(e){var target=mQuery(e.target);if(!target.closest('.popover').length&&!target.closest('[data-toggle="popover"]').length){mQuery('[data-toggle="popover"]').each(function(){var $this=mQuery(this);var popover=$this.data('bs.popover');if(popover&&popover.tip().hasClass('in')){$this.popover('hide');popover.inState.click=!1}})}});mQuery(document).ajaxComplete(function(event,xhr,settings){Mautic.stopPageLoadingBar();if(xhr.responseJSON&&xhr.responseJSON.flashes){Mautic.setFlashes(xhr.responseJSON.flashes)}
Mautic.attachDismissHandlers();mQuery('[data-toggle="popover"]').popover({sanitize:!1,content:function(){return mQuery(this).data('content')}});mQuery('[data-toggle="popover"]').on('shown.bs.popover',function(){mQuery('.popover-content select').chosen({allow_single_deselect:!0,disable_search_threshold:10});mQuery('.popover-content [data-toggle="tooltip"]').tooltip()})});mQuery(document).ajaxStop(function(event){MauticVars.activeRequests=0;Mautic.stopPageLoadingBar()});mQuery(document).ready(function(){if(typeof mauticContent!=='undefined'){mQuery("html").Core({console:!1})}
Mautic.initListGroupToggle('body');mQuery(document).on('keydown',function(e){if(e.which===8&&!mQuery(e.target).is("input:not([readonly]):not([type=radio]):not([type=checkbox]), textarea, [contentEditable], [contentEditable=true]")){e.preventDefault()}});setInterval(function(){if(window.location.pathname.startsWith('/s/')&&window.location.pathname!=='/s/login'){mQuery.get('/s/keep-alive').fail(function(errorThrown){console.error('Error with keep-alive:',errorThrown)})}},mauticSessionLifetime*1000/2);Mautic.attachDismissHandlers()});if(typeof history!='undefined'){window.addEventListener('popstate',function(event){window.location.reload()})}
MauticVars.iconClasses={};MauticVars.routeInProgress='';MauticVars.moderatedIntervals={};MauticVars.intervalsInProgress={};var Mautic={loadedContent:{},keyboardShortcutHtml:{},initializeDismissedElements:function(){this.dismissedElements=JSON.parse(localStorage.getItem('dismissedElements'))||[];this.dismissedStyle=null;if(this.dismissedElements.length>0){var selector=this.dismissedElements.map(function(id){return'#'+id}).join(', ');var css=selector+' { display: none !important; }';this.dismissedStyle=document.createElement('style');this.dismissedStyle.type='text/css';this.dismissedStyle.appendChild(document.createTextNode(css));var head=document.head||document.getElementsByTagName('head')[0];head.appendChild(this.dismissedStyle)}},dismissElement:function(elementId){if(this.dismissedElements.indexOf(elementId)===-1){this.dismissedElements.push(elementId);localStorage.setItem('dismissedElements',JSON.stringify(this.dismissedElements));if(this.dismissedStyle){var newSelector='#'+elementId;this.dismissedStyle.appendChild(document.createTextNode(newSelector+' { display: none !important; }'))}else{var css='#'+elementId+' { display: none !important; }';this.dismissedStyle=document.createElement('style');this.dismissedStyle.type='text/css';this.dismissedStyle.appendChild(document.createTextNode(css));var head=document.head||document.getElementsByTagName('head')[0];head.appendChild(this.dismissedStyle)}
var element=mQuery('#'+elementId);if(element.length){element.hide()}}},resetDismissedElements:function(){this.dismissedElements=[];localStorage.setItem('dismissedElements',JSON.stringify(this.dismissedElements));if(this.dismissedStyle&&this.dismissedStyle.parentNode){this.dismissedStyle.parentNode.removeChild(this.dismissedStyle);this.dismissedStyle=null}
mQuery('[user-dismiss]').each(function(){var dismissButton=mQuery(this);var dismissType=dismissButton.attr('user-dismiss');var dismissibleElement=dismissButton.closest('.'+dismissType);dismissibleElement.css('display','')});const flashMessage=Mautic.addInfoFlashMessage(Mautic.translate('mautic.user.config.title.experience_and_learning.reset_confirmation'));Mautic.setFlashes(flashMessage)},attachDismissHandlers:function(){mQuery('[user-dismiss]').each(function(){var dismissButton=mQuery(this);var dismissType=dismissButton.attr('user-dismiss');var dismissibleElement=dismissButton.closest('.'+dismissType);var elementId=dismissibleElement.attr('id');dismissButton.off('click').on('click',function(e){e.preventDefault();Mautic.dismissElement(elementId)})})},initDismiss:function(){this.initializeDismissedElements();this.attachDismissHandlers()},addKeyboardShortcut:function(sequence,description,func,section){Mousetrap.bind(sequence,func);var sectionName=section||'global';if(!Mautic.keyboardShortcutHtml.hasOwnProperty(sectionName)){Mautic.keyboardShortcutHtml[sectionName]={}}
Mautic.keyboardShortcutHtml[sectionName][sequence]='<div class="col-xs-6"><mark>'+sequence+'</mark>: '+description+'</div>'},bindGlobalKeyboardShortcuts:function(){Mautic.addKeyboardShortcut('g d','Load the Dashboard',function(e){mQuery('#mautic_dashboard_index').click()});Mautic.addKeyboardShortcut('g c','Load Contacts',function(e){mQuery('#mautic_contact_index').click()});Mautic.addKeyboardShortcut('g e','Load Emails',function(e){mQuery('#mautic_email_index').click()});Mautic.addKeyboardShortcut('g f','Load Forms',function(e){mQuery('#mautic_form_index').click()});Mautic.addKeyboardShortcut('g s','Load Segments',function(e){mQuery('#mautic_segment_index').click()});Mautic.addKeyboardShortcut('g p','Load Segments',function(e){mQuery('#mautic_page_index').click()});Mautic.addKeyboardShortcut('f m','Toggle Admin Menu',function(e){mQuery("#admin-menu").click()});Mautic.addKeyboardShortcut('f n','Show Notifications',function(e){mQuery('.dropdown-notification').click()});Mautic.addKeyboardShortcut('f /','Global Search',function(e){mQuery('.search-button').click()});Mautic.addKeyboardShortcut('/','Search current list',function(e){e.preventDefault();e.stopPropagation();mQuery('#list-search').focus()});Mautic.addKeyboardShortcut('e','Edit current resource',function(e){mQuery('#edit').click()});Mautic.addKeyboardShortcut('c','Create current resource',function(e){mQuery('#new').click()});Mautic.addKeyboardShortcut(['del','meta+backspace'],'Delete current resource',function(e){mQuery('#delete').click()});Mautic.addKeyboardShortcut('enter','Modal confirm action',function(e){mQuery('#confirm').click()});Mautic.addKeyboardShortcut('s','General send example button',function(e){mQuery('#sendEmailButton').click()});Mautic.addKeyboardShortcut('g i','Back to index (list)',function(e){mQuery('[id*="buttons_cancel"]').click();mQuery('#close').click()});Mousetrap.bind('?',function(e){var modalWindow=mQuery('#keyboardShortcutsModal');modalWindow.modal()})},initListGroupToggle:function(container){mQuery(container).on('click','.list-group[data-toggle="list-group"] .list-group-item',function(e){e.preventDefault();var $item=mQuery(this);var $input=$item.find('input');if($input.prop('disabled')||$input.prop('readonly')){return}
var type=$input.prop('type');if(type==='radio'){$item.closest('.list-group').find('.list-group-item').removeClass('active');$item.addClass('active');$input.prop('checked',!0)}else if(type==='checkbox'){$item.toggleClass('active');$input.prop('checked',$item.hasClass('active'))}
$input.trigger('change')})},translate:function(id,params){if(!mauticLang.hasOwnProperty(id)){return id}
var translated=mauticLang[id];if(params){for(var key in params){if(!params.hasOwnProperty(key))continue;var regEx=new RegExp('%'+key+'%','g');translated=translated.replace(regEx,params[key])}}
return translated},stopPageLoadingBar:function(){if(MauticVars.activeRequests<1){MauticVars.activeRequests=0}else{MauticVars.activeRequests--}
if(MauticVars.loadingBarTimeout){clearTimeout(MauticVars.loadingBarTimeout)}
if(MauticVars.activeRequests==0){mQuery('.loading-bar').removeClass('active')}},startPageLoadingBar:function(){mQuery('.loading-bar').addClass('active');MauticVars.activeRequests++},startCanvasLoadingBar:function(){mQuery('.canvas-loading-bar').addClass('active')},startModalLoadingBar:function(modalTarget){mQuery(modalTarget+' .modal-loading-bar').addClass('active')},stopCanvasLoadingBar:function(){mQuery('.canvas-loading-bar').removeClass('active')},stopModalLoadingBar:function(modalTarget){mQuery(modalTarget+' .modal-loading-bar').removeClass('active')},activateButtonLoadingIndicator:function(button){button.prop('disabled',!0);if(!button.find('.ri-loader-3-line.ri-spin').length){button.append(mQuery('<i class="ri-loader-3-line ri-spin ri-fw"></i>'))}},removeButtonLoadingIndicator:function(button){button.prop('disabled',!1);button.find('.ri-loader-3-line').remove()},activateLabelLoadingIndicator:function(el){var labelSpinner=mQuery("label[for='"+el+"']");Mautic.labelSpinner=mQuery('<i class="ri-loader-3-line ri-spin ri-fw"></i>');labelSpinner.append(Mautic.labelSpinner)},removeLabelLoadingIndicator:function(){mQuery(Mautic.labelSpinner).remove()},loadNewWindow:function(options){if(options.windowUrl){Mautic.startModalLoadingBar();var popupName='mauticpopup';if(options.popupName){popupName=options.popupName}
setTimeout(function(){var opener=window.open(options.windowUrl,popupName,'height=600,width=1100');if(!opener||opener.closed||typeof opener.closed=='undefined'){alert(mauticLang.popupBlockerMessage)}else{opener.onload=function(){Mautic.stopModalLoadingBar();Mautic.stopIconSpinPostEvent()}}},100)}},loadScript:function(url,onLoadCallback,alreadyLoadedCallback){if(typeof Mautic.headLoadedAssets=='undefined'){Mautic.headLoadedAssets={}}else if(typeof Mautic.headLoadedAssets[url]!='undefined'){if(alreadyLoadedCallback&&typeof Mautic[alreadyLoadedCallback]=='function'){Mautic[alreadyLoadedCallback]()}
return}
Mautic.headLoadedAssets[url]=1;mQuery.getScript(url,function(data,textStatus,jqxhr){if(textStatus=='success'){if(onLoadCallback&&typeof Mautic[onLoadCallback]=='function'){Mautic[onLoadCallback]()}else if(typeof Mautic[mauticContent+"OnLoad"]=='function'){if(typeof Mautic.loadedContent[mauticContent]=='undefined'){Mautic.loadedContent[mauticContent]=!0;Mautic[mauticContent+"OnLoad"]('#app-content',{})}}}})},loadStylesheet:function(url){if(typeof Mautic.headLoadedAssets=='undefined'){Mautic.headLoadedAssets={}}else if(typeof Mautic.headLoadedAssets[url]!='undefined'){return}
Mautic.headLoadedAssets[url]=1;var link=document.createElement("link");link.type="text/css";link.rel="stylesheet";link.href=url;mQuery('head').append(link)},startIconSpinOnEvent:function(target){if(MauticVars.ignoreIconSpin){MauticVars.ignoreIconSpin=!1;return}
if(typeof target=='object'&&typeof(target.target)!=='undefined'){target=target.target}
if(mQuery(target).length){var hasBtn=mQuery(target).hasClass('btn');var hasIcon=mQuery(target).attr('class')&&mQuery(target).attr('class').startsWith('ri-');var dontspin=mQuery(target).hasClass('btn-nospin');var icon=(hasBtn&&mQuery(target).find('i[class^="ri-"]').length)?mQuery(target).find('i[class^="ri-"]'):target;if(!dontspin&&((hasBtn&&mQuery(target).find('i[class^="ri-"]').length)||hasIcon)){var el=(hasIcon)?target:mQuery(target).find('i[class^="ri-"]').first();var identifierClass=(new Date).getTime();if(typeof MauticVars.iconClasses==='undefined'){MauticVars.iconClasses={}}
MauticVars.iconClasses[identifierClass]=mQuery(el).attr('class');var specialClasses=['ri-fw','ri-lg','ri-2x','ri-3x','ri-4x','ri-5x','ri-li','text-white','text-secondary'];var appendClasses="";for(var j=0;j<specialClasses.length;j++){if(mQuery(el).hasClass(specialClasses[j])){appendClasses+=" "+specialClasses[j]}}
mQuery(el).removeClass();mQuery(el).addClass('ri-loader-3-line ri-spin '+identifierClass+appendClasses)}}},stopIconSpinPostEvent:function(specificId){if(typeof specificId!='undefined'&&specificId in MauticVars.iconClasses){mQuery('.'+specificId).removeClass('ri-loader-3-line ri-spin '+specificId).addClass(MauticVars.iconClasses[specificId]);delete MauticVars.iconClasses[specificId]}else{mQuery.each(MauticVars.iconClasses,function(index,value){mQuery('.'+index).removeClass('ri-loader-3-line ri-spin '+index).addClass(value);delete MauticVars.iconClasses[index]})}},redirectWithBackdrop:function(url){Mautic.activateBackdrop();setTimeout(function(){window.location=url},50)},activateBackdrop:function(hideWait){if(!mQuery('#mautic-backdrop').length){var container=mQuery('<div />',{id:'mautic-backdrop'});mQuery('<div />',{'class':'modal-backdrop fade in'}).appendTo(container);if(typeof hideWait=='undefined'){mQuery('<div />',{"class":'mautic-pleasewait'}).html(mauticLang.pleaseWait).appendTo(container)}
container.appendTo('body')}},deactivateBackgroup:function(){if(mQuery('#mautic-backdrop').length){mQuery('#mautic-backdrop').remove()}},executeAction:function(action,callback){if(typeof Mautic.activeActions=='undefined'){Mautic.activeActions={}}else if(typeof Mautic.activeActions[action]!='undefined'){return}
Mautic.activeActions[action]=!0;Mautic.dismissConfirmation();if(action.indexOf('batchExport')>=0){delete Mautic.activeActions[action]
Mautic.initiateFileDownload(action);return}
mQuery.ajax({showLoadingBar:!0,url:action,type:"POST",dataType:"json",success:function(response){Mautic.processPageContent(response);if(typeof callback=='function'){callback(response)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){delete Mautic.activeActions[action]}})},processAjaxError:function(request,textStatus,errorThrown,mainContent,target){if(textStatus=='abort'){Mautic.stopPageLoadingBar();Mautic.stopCanvasLoadingBar();Mautic.stopIconSpinPostEvent();return}
var inDevMode=typeof mauticEnv!=='undefined'&&mauticEnv=='dev';if(inDevMode){console.log(request)}
if(typeof request.responseJSON!=='undefined'){response=request.responseJSON}else if(typeof(request.responseText)!=='undefined'){const flashMessage=Mautic.addFlashMessage(Mautic.translate('mautic.core.request.error'));Mautic.setFlashes(flashMessage);var errorStart=request.responseText.indexOf('{"newContent');var jsonString=request.responseText.slice(errorStart);if(jsonString){try{var response=JSON.parse(jsonString);if(inDevMode){console.log(response)}}catch(err){if(inDevMode){console.log(err)}}}else{response={}}}
if(response){if(response.newContent&&mainContent){mQuery('#app-content .content-body').html(response.newContent);if(response.route&&response.route.indexOf("ajax")==-1){history.pushState(null,"Mautic",response.route)}}else if(response.newContent&&mQuery('.modal.in').length){mQuery('.modal.in .modal-body-content').html(response.newContent);mQuery('.modal.in .modal-body-content').removeClass('hide');if(mQuery('.modal.in  .loading-placeholder').length){mQuery('.modal.in  .loading-placeholder').addClass('hide')}}else if(response.closeModal){if(typeof target!=="undefined"){mQuery('body').removeClass('noscroll');mQuery(target).modal('hide')}}else if(inDevMode){console.log(response);if(response.errors&&response.errors[0]&&response.errors[0].message){alert(response.errors[0].message)}}}
Mautic.stopPageLoadingBar();Mautic.stopCanvasLoadingBar();Mautic.stopIconSpinPostEvent()},setModeratedInterval:function(key,callback,timeout,params){if(typeof MauticVars.intervalsInProgress[key]!='undefined'){clearTimeout(MauticVars.moderatedIntervals[key])}else{MauticVars.intervalsInProgress[key]=!0;if(typeof params=='undefined'){params=[]}
if(typeof callback=='function'){callback(params)}else{window.Mautic[callback].apply('window',params)}}
MauticVars.moderatedIntervals[key]=setTimeout(function(){Mautic.setModeratedInterval(key,callback,timeout,params)},timeout)},moderatedIntervalCallbackIsComplete:function(key){delete MauticVars.intervalsInProgress[key]},clearModeratedInterval:function(key){Mautic.moderatedIntervalCallbackIsComplete(key);clearTimeout(MauticVars.moderatedIntervals[key]);delete MauticVars.moderatedIntervals[key]},setFlashes:function(flashes,autoClose=!0){mQuery('#flashes').append(flashes);mQuery('#flashes .alert-new').each(function(){var me=this;if(autoClose){window.setTimeout(function(){mQuery(me).fadeTo(500,0).slideUp(500,function(){mQuery(this).remove()})},4000)}
mQuery(this).removeClass('alert-new')})},addFlashMessage:function(message){const elDiv=document.createElement('div');elDiv.className='alert alert-growl alert-growl--error alert-new';const elButton=document.createElement('button');elButton.classList.add('close');elButton.type="button";elButton.dataset.dismiss="alert";elButton.ariaHidden="true";elButton.ariaLabel="Close";const elI=document.createElement('i');elI.className='ri-close-line';const elSpan=document.createElement('span');elSpan.innerHTML=message;elButton.append(elI);elDiv.append(elButton);elDiv.append(elSpan);return elDiv},addErrorFlashMessage:function(message){return this.addFlashMessage(message)},addInfoFlashMessage:function(message){const el=this.addFlashMessage(message);el.classList.remove('alert-growl--error');return el},setNotifications:function(notifications){if(notifications.lastId){mQuery('#mauticLastNotificationId').val(notifications.lastId)}
if(mQuery('#notifications .mautic-update')){mQuery('#notifications .mautic-update').remove()}
if(notifications.hasNewNotifications){if(mQuery('#newNotificationIndicator').hasClass('hide')){mQuery('#newNotificationIndicator').removeClass('hide')}}
if(notifications.content){mQuery('#notifications').prepend(notifications.content);if(!mQuery('#notificationMautibot').hasClass('hide')){mQuery('#notificationMautibot').addClass('hide')}}},showNotifications:function(){mQuery("#notificationsDropdown").off('hide.bs.dropdown');mQuery('#notificationsDropdown').on('hidden.bs.dropdown',function(){if(!mQuery('#newNotificationIndicator').hasClass('hide')){mQuery('#notifications .is-unread').remove();mQuery('#newNotificationIndicator').addClass('hide')}})},clearNotification:function(id){if(id){mQuery("#notification"+id).fadeTo("fast",0.01).slideUp("fast",function(){mQuery(this).find("*[data-toggle='tooltip']").tooltip('destroy');mQuery(this).remove();if(!mQuery('#notifications .notification').length){if(mQuery('#notificationMautibot').hasClass('hide')){mQuery('#notificationMautibot').removeClass('hide')}}})}else{mQuery("#notifications .notification").fadeOut(300,function(){mQuery(this).remove();if(mQuery('#notificationMautibot').hasClass('hide')){mQuery('#notificationMautibot').removeClass('hide')}})}
mQuery.ajax({url:mauticAjaxUrl,type:"GET",data:"action=clearNotification&id="+id})},ajaxActionRequest:function(action,data,successClosure,showLoadingBar,queue,method="POST"){if(typeof Mautic.ajaxActionXhrQueue=='undefined'){Mautic.ajaxActionXhrQueue={}}
if(typeof Mautic.ajaxActionXhr=='undefined'){Mautic.ajaxActionXhr={}}else if(typeof Mautic.ajaxActionXhr[action]!='undefined'){if(queue){if(typeof Mautic.ajaxActionXhrQueue[action]=='undefined'){Mautic.ajaxActionXhrQueue[action]=[]}
Mautic.ajaxActionXhrQueue[action].push({action:action,data:data,successClosure:successClosure,showLoadingBar:showLoadingBar,method:method});return}else{Mautic.removeLabelLoadingIndicator();Mautic.ajaxActionXhr[action].abort()}}
if(typeof showLoadingBar=='undefined'){showLoadingBar=!1}
Mautic.ajaxActionXhr[action]=mQuery.ajax({url:mauticAjaxUrl+'?action='+action,type:method,data:data,showLoadingBar:showLoadingBar,success:function(response){if(typeof successClosure=='function'){successClosure(response)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown,!0)},complete:function(){delete Mautic.ajaxActionXhr[action];if(typeof Mautic.ajaxActionXhrQueue[action]!=='undefined'&&Mautic.ajaxActionXhrQueue[action].length){var next=Mautic.ajaxActionXhrQueue[action].shift();Mautic.ajaxActionRequest(next.action,next.data,next.successClosure,next.showLoadingBar,!1,next.method)}}})},isLocalStorageSupported:function(){try{localStorage.setItem('mautic.test','mautic');localStorage.removeItem('mautic.test');return!0}catch(e){return!1}}};Mautic.initDismiss();const ckEditors=new Map();MauticVars.maxButtons=['undo','redo','|','bold','italic','underline','heading','fontfamily','fontsize','fontColor','fontBackgroundColor','alignment','numberedList','bulletedList','blockQuote','TokenPlugin','removeFormat','link','ckfinder','mediaEmbed','insertTable','sourceEditing'];Mautic.loadContent=function(route,link,method,target,showPageLoading,callback,data){if(typeof Mautic.loadContentXhr=='undefined'){Mautic.loadContentXhr={}}else if(typeof Mautic.loadContentXhr[target]!='undefined'){Mautic.loadContentXhr[target].abort()}
showPageLoading=(typeof showPageLoading=='undefined'||showPageLoading)?!0:!1;Mautic.loadContentXhr[target]=mQuery.ajax({showLoadingBar:showPageLoading,url:route,type:method,dataType:"json",data:data,success:function(response){if(response){response.stopPageLoading=showPageLoading;if(response.callback){window.Mautic[response.callback].apply('window',[response]);return}
if(response.redirect){Mautic.redirectWithBackdrop(response.redirect)}else if(target||response.target){if(target)response.target=target;Mautic.processPageContent(response)}else{MauticVars.liveCache=new Array();MauticVars.lastSearchStr='';if(typeof response.route==='undefined'){response.route=route}
if(typeof response.activeLink==='undefined'&&link){response.activeLink=link}
Mautic.processPageContent(response)}
Mautic.stopIconSpinPostEvent()}
MauticVars.routeInProgress=''},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown,!0);MauticVars.routeInProgress='';Mautic.stopIconSpinPostEvent();Mautic.stopPageLoadingBar()},complete:function(){if(typeof callback!=='undefined'){if(typeof callback=='function'){callback()}else{window.Mautic[callback].apply('window',[])}}
Mautic.generatePageTitle(route);delete Mautic.loadContentXhr[target]}});return!1};Mautic.loadAjaxColumn=function(elementName,route,callback){var className='.'+elementName;if(mQuery(className).length){var ids=[];mQuery(className).each(function(){if(!mQuery(this).text()){var id=mQuery(this).attr('data-value');ids.push(id)}});var batchIds;if(ids.length==0){Mautic.getCallback(callback)}
while(ids.length>0){batchIds=ids.splice(0,10);Mautic.ajaxActionRequest(route,{ids:batchIds,entityId:Mautic.getEntityId()},function(response){if(response.success&&response.stats){for(var i=0;i<response.stats.length;i++){var stat=response.stats[i];if(mQuery('#'+elementName+'-'+stat.id).length){mQuery('#'+elementName+'-'+stat.id).html(stat.data)}}
if(batchIds.length<10){Mautic.getCallback(callback)}}},!1,!0,"GET")}}}
Mautic.sortTableByColumn=function(tableId,sortElement,removeZero){var tbody=mQuery(tableId).find('tbody');tbody.find('tr').each(function(){if(parseInt(mQuery(this).find(sortElement).text())==0){mQuery(this).remove()}})
tbody.find('tr').sort(function(a,b){var tda=parseFloat(mQuery(a).find(sortElement).text());var tdb=parseFloat(mQuery(b).find(sortElement).text());return tda<tdb?1:tda>tdb?-1:0}).appendTo(tbody)}
Mautic.getCallback=function(callback){if(callback&&typeof callback!=='undefined'){if(typeof callback=='function'){callback()}else{window.Mautic[callback].apply('window',[])}}}
Mautic.generatePageTitle=function(route){if(-1!==route.indexOf('timeline')){return}else if(-1!==route.indexOf('/view')){var currentModule=route.split('/')[3];var titleWithHTML=mQuery('.page-header h1').find('span.span-block');var currentModuleItem='';if(1<titleWithHTML.length){currentModuleItem=titleWithHTML.eq(0).text()+' - '+titleWithHTML.eq(1).text()}else{currentModuleItem=mQuery('.page-header h1').text()}
currentModuleItem=mQuery('<div>').text(currentModuleItem).html();mQuery('title').html(currentModule[0].toUpperCase()+currentModule.slice(1)+' | '+currentModuleItem+' | Mautic')}else{mQuery('title').html(mQuery('.page-header h1').text()+' | Mautic')}};Mautic.processPageContent=function(response){if(response){Mautic.deactivateBackgroup();if(response.errors&&'dev'==mauticEnv){alert(response.errors[0].message);console.log(response.errors)}
if(!response.target){response.target='#app-content'}
Mautic.onPageUnload(response.target,response);if(response.newContent){if(response.replaceContent&&response.replaceContent=='true'){mQuery(response.target).replaceWith(response.newContent)}else{mQuery(response.target).html(response.newContent)}}
if(response.notifications){Mautic.setNotifications(response.notifications)}
if(response.route){history.pushState(null,"Mautic",response.route);Mautic.generatePageTitle(response.route)}
if(response.target=='#app-content'){if(response.mauticContent){mauticContent=response.mauticContent}
if(response.activeLink){var link=response.activeLink;if(link!==undefined&&link.charAt(0)!='#'){link="#"+link}
var parent=mQuery(link).parent();mQuery(".nav-sidebar").find(".active").removeClass("active");parent.addClass("active");var openParent=parent.closest('li.open');mQuery(".nav-sidebar").find(".open").each(function(){if(!openParent.hasClass('open')||(openParent.hasClass('open')&&openParent[0]!==mQuery(this)[0])){mQuery(this).removeClass('open')}})}
mQuery('body').animate({scrollTop:0},0)}else{var overflow=mQuery(response.target).css('overflow');var overflowY=mQuery(response.target).css('overflowY');if(overflow=='auto'||overflow=='scroll'||overflowY=='auto'||overflowY=='scroll'){mQuery(response.target).animate({scrollTop:0},0)}}
if(response.overlayEnabled){mQuery(response.overlayTarget+' .content-overlay').remove()}
Mautic.onPageLoad(response.target,response)}};Mautic.onPageLoad=function(container,response,inModal){mQuery(container).trigger('mautic:onPageLoad:before',[container,response,inModal]);Mautic.initDateRangePicker(container+' #daterange_date_from',container+' #daterange_date_to');Mautic.makeLinksAlive(mQuery(container+" a[data-toggle='ajax']"));mQuery(container+" form[data-toggle='ajax']").each(function(index){Mautic.ajaxifyForm(mQuery(this).attr('name'))});Mautic.makeModalsAlive(mQuery(container+" *[data-toggle='ajaxmodal']"))
Mautic.activateModalEmbeddedForms(container);mQuery(container+" *[data-toggle='livesearch']").each(function(index){Mautic.activateLiveSearch(mQuery(this),"lastSearchStr","liveCache")});var pageTooltips=mQuery(container+" *[data-toggle='tooltip']");pageTooltips.tooltip({html:!0,container:'body'});pageTooltips.each(function(i){var thisTooltip=mQuery(pageTooltips.get(i));var elementParent=thisTooltip.parent();if(elementParent.get(0).tagName==='LABEL'){elementParent.append('<i class="ri-question-line"></i>');elementParent.hover(function(){thisTooltip.tooltip('show')},function(){thisTooltip.tooltip('hide')})}});mQuery(container+" *[data-toggle='sortablelist']").each(function(index){Mautic.activateSortable(this)});mQuery(container+" a[data-toggle='download']").off('click.download');mQuery(container+" a[data-toggle='download']").on('click.download',function(event){event.preventDefault();Mautic.initiateFileDownload(mQuery(this).attr('href'))});Mautic.makeConfirmationsAlive(mQuery(container+" a[data-toggle='confirmation']"));mQuery(container+" *[data-toggle='datetime']").each(function(){Mautic.activateDateTimeInputs(this,'datetime')});mQuery(container+" *[data-toggle='date']").each(function(){Mautic.activateDateTimeInputs(this,'date')});mQuery(container+" *[data-toggle='time']").each(function(){Mautic.activateDateTimeInputs(this,'time')});mQuery(container+" *[data-onload-callback]").each(function(){var callback=function(el){if(typeof window.Mautic[mQuery(el).attr('data-onload-callback')]=='function'){window.Mautic[mQuery(el).attr('data-onload-callback')].apply('window',[el])}}
mQuery(document).ready(callback(this))});mQuery(container+" *[data-copy]").off('click.copy').on('click.copy',function(event){event.preventDefault();Mautic.copyToClipboard(mQuery(this).data('copy'))});mQuery(container+" input[data-toggle='color']").each(function(){Mautic.activateColorPicker(this)});mQuery(container+" select").not('.multiselect, .not-chosen').each(function(){Mautic.activateChosenSelect(this)});mQuery(container+" select.multiselect").each(function(){Mautic.activateMultiSelect(this)});Mautic.activateLookupTypeahead(mQuery(container));mQuery(container+" .table-responsive").on('shown.bs.dropdown',function(e){var table=mQuery(this),menu=mQuery(e.target).find(".dropdown-menu"),tableOffsetHeight=table.offset().top+table.height(),menuOffsetHeight=menu.offset().top+menu.outerHeight(!0);if(menuOffsetHeight>tableOffsetHeight)
table.css("padding-bottom",menuOffsetHeight-tableOffsetHeight+16)});mQuery(container+" .table-responsive").on("hide.bs.dropdown",function(){mQuery(this).css("padding-bottom",0)})
mQuery(container+" .nav-tabs[data-toggle='tab-hash']").each(function(){var hash=document.location.hash;var prefix='tab-';if(hash){var hashPieces=hash.split('?');hash=hashPieces[0].replace("#","#"+prefix);var activeTab=mQuery(this).find('a[href='+hash+']').first();if(mQuery(activeTab).length){mQuery('.nav-tabs li').removeClass('active');mQuery('.tab-pane').removeClass('in active');mQuery(activeTab).parent().addClass('active');mQuery(hash).addClass('in active')}}
mQuery(this).find('a').on('shown.bs.tab',function(e){window.location.hash=e.target.hash.replace("#"+prefix,"#")})});mQuery(container+" .nav-overflow-tabs ul").each(function(){Mautic.activateOverflowTabs(this)});mQuery(container+" .nav.sortable").each(function(){Mautic.activateSortableTabs(this)});Mautic.activateTabDeleteButtons(container);mQuery(container+' .btn:not(.btn-nospin)').on('click.spinningicons',function(event){Mautic.startIconSpinOnEvent(event)});mQuery(container+' input[class=list-checkbox]').on('change',function(){var disabled=Mautic.batchActionPrecheck(container)?!1:!0;var color=(disabled)?'btn-ghost':'btn-info';var button=container+' th.col-actions .btn.dropdown-toggle';mQuery(button).prop('disabled',disabled);mQuery(button).removeClass('btn-ghost btn-info').addClass(color)});mQuery(container+" .bottom-form-buttons").each(function(){if(inModal||mQuery(this).closest('.modal').length){var modal=(inModal)?container:mQuery(this).closest('.modal');if(mQuery(modal).find('.modal-form-buttons').length){mQuery(modal).find('.bottom-form-buttons').addClass('hide');var buttons=mQuery(modal).find('.bottom-form-buttons').html();mQuery(modal).find('.modal-form-buttons').html('');mQuery(buttons).filter("button").each(function(i,v){var id=mQuery(this).attr('id');var button=mQuery("<button type='button' />").addClass(mQuery(this).attr('class')).addClass('btn-copy').html(mQuery(this).html()).appendTo(mQuery(modal).find('.modal-form-buttons')).on('click.ajaxform',function(event){if(mQuery(this).hasClass('disabled')){return!1}
if(!mQuery(this).hasClass('btn-dnd')){mQuery(this).parent().find('button').prop('disabled',!0)}
event.preventDefault();if(!mQuery(this).hasClass('btn-nospin')){Mautic.startIconSpinOnEvent(event)}
mQuery('#'+id).click()})})}}else{mQuery('.toolbar-action-buttons').addClass('hide');if(mQuery('.toolbar-form-buttons').hasClass('hide')){mQuery(container+' .bottom-form-buttons').addClass('hide');var buttons=mQuery(container+" .bottom-form-buttons").html();mQuery(container+' .toolbar-form-buttons .toolbar-standard').html('');mQuery(container+' .toolbar-form-buttons .toolbar-dropdown .drop-menu').html('');var lastIndex=mQuery(buttons).filter("button").length-1;mQuery(buttons).filter("button").each(function(i,v){var id=mQuery(this).attr('id');var buttonClick=function(event){event.preventDefault();if(!mQuery(this).hasClass('btn-dnd')){mQuery(this).parent().find('button').prop('disabled',!0)}
Mautic.startIconSpinOnEvent(event);mQuery('#'+id).click()};mQuery("<button type='button' />").addClass(mQuery(this).attr('class')).addClass('btn-copy').attr('id',mQuery(this).attr('id')+'_toolbar').html(mQuery(this).html()).on('click.ajaxform',buttonClick).appendTo('.toolbar-form-buttons .toolbar-standard');if(i===lastIndex){mQuery(".toolbar-form-buttons .toolbar-dropdown .btn-main").off('.ajaxform').attr('id',mQuery(this).attr('id')+'_toolbar_mobile').html(mQuery(this).html()).on('click.ajaxform',buttonClick)}else{mQuery("<a />").attr('id',mQuery(this).attr('id')+'_toolbar_mobile').html(mQuery(this).html()).on('click.ajaxform',buttonClick).appendTo(mQuery('<li />').prependTo('.toolbar-form-buttons .toolbar-dropdown .dropdown-menu'))}});mQuery('.toolbar-form-buttons').removeClass('hide')}}});Mautic.getBuilderContainer=function(){return container}
if(mQuery(container+' textarea.editor:not(".editor-dynamic-content")').length){mQuery(container+' textarea.editor:not(".editor-dynamic-content")').each(function(){const textarea=mQuery(this);let minButtons=['undo','redo','|','bold','italic','underline'];if(textarea.hasClass('editor-dynamic-content')||textarea.hasClass('editor-basic')){minButtons=['undo','redo','|','bold','italic','underline','heading','fontfamily','fontsize','fontColor','fontBackgroundColor','alignment','numberedList','bulletedList','blockQuote','removeFormat','link','ckfinder','mediaEmbed','insertTable','sourceEditing']}
let ckEditorToolbar=minButtons;if(textarea.hasClass('editor-advanced')||textarea.hasClass('editor-basic-fullpage')){ckEditorToolbar=MauticVars.maxButtons}
Mautic.ConvertFieldToCkeditor(textarea,ckEditorToolbar)})}
if(mQuery(container+' .dropdown-menu-form').length){mQuery(container+' .dropdown-menu-form').on('click',function(e){e.stopPropagation()})}
if(response&&response.updateSelect&&typeof response.id!=='undefined'){Mautic.updateEntitySelect(response)}
var contentSpecific=!1;if(response&&response.mauticContent){contentSpecific=response.mauticContent}else if(container=='body'){contentSpecific=mauticContent}
if(response&&response.sidebar){var sidebarContent=mQuery('.app-sidebar.sidebar-left');var newSidebar=mQuery(response.sidebar);var nav=sidebarContent.find('li');if(nav.length){var openNavIndex;nav.each(function(i,el){var $el=mQuery(el);if($el.hasClass('open')){openNavIndex=i}});var openNav=mQuery(newSidebar.find('li')[openNavIndex]);openNav.addClass('open');openNav.find('ul').removeClass('collapse')}
sidebarContent.html(newSidebar)}
if(container=='#app-content'||container=='body'){Mautic.bindGlobalKeyboardShortcuts();mQuery(".sidebar-left a[data-toggle='ajax']").on('click.ajax',function(event){mQuery("html").removeClass('sidebar-open-ltr')})}
if(contentSpecific&&typeof Mautic[contentSpecific+"OnLoad"]=='function'){if(inModal||typeof Mautic.loadedContent[contentSpecific]=='undefined'){Mautic.loadedContent[contentSpecific]=!0;Mautic[contentSpecific+"OnLoad"](container,response)}}
if(!inModal&&container=='body'){mQuery('#notificationsDropdown').on('click',function(e){if(mQuery(e.target).hasClass('do-not-close')){e.stopPropagation()}});const $modal=mQuery('#gsearchModal'),$input=mQuery('#globalSearchInput'),$results=mQuery('.gsearch--results'),$panel=mQuery('#globalSearchPanel');$input.on('change keyup paste',function(){const hasValue=mQuery(this).val();$results.toggleClass('hide',!hasValue);if(!hasValue)$panel.empty();});Mautic.activateLiveSearch("#globalSearchInput","lastGlobalSearchStr","globalLivecache");$modal.on('shown.bs.modal',()=>setTimeout(()=>$input.focus(),100)).on('hidden.bs.modal',()=>{$input.val('');$results.addClass('hide');$panel.empty()});$results.on('click','a',()=>$modal.modal('hide'))}
Mautic.renderCharts(container);Mautic.stopIconSpinPostEvent();if((response&&typeof response.stopPageLoading!='undefined'&&response.stopPageLoading)||container=='#app-content'||container=='.page-list'){Mautic.stopPageLoadingBar()}
const maps=mQuery(container).find('[data-load="map"]');if(maps.length){maps.each((index,map)=>map.addEventListener('click',()=>{const scopeId=event.target.getAttribute('href');const scope=mQuery(scopeId);if(scope.length){if(scope.children('.map-rendered').length){return}
const mapUrl=scope.attr('data-map-url');scope.load(mapUrl,'',()=>{const map=Mautic.initMap(scope,'regions')})}},!1))}
mQuery(container).trigger('mautic:onPageLoad:after',[container,response,inModal])};Mautic.setDynamicContentEditors=function(container){if(mQuery(container+' textarea.editor-dynamic-content').length){console.log('[Builder] Using CKEditor for the Dynamic Content editor');mQuery(container+' textarea.editor-dynamic-content').each(function(){const textarea=mQuery(this);const maxButtons=['undo','redo','|','bold','italic','underline','heading','fontfamily','fontsize','fontColor','fontBackgroundColor','alignment','numberedList','bulletedList','blockQuote','removeFormat','link','ckfinder','mediaEmbed','insertTable','TokenPlugin','sourceEditing'];let minButtons=['undo','redo','|','bold','italic','underline'];if(textarea.hasClass('editor-dynamic-content')||textarea.hasClass('editor-basic')){minButtons=['undo','redo','|','bold','italic','underline','heading','fontfamily','fontsize','fontColor','fontBackgroundColor','alignment','numberedList','bulletedList','blockQuote','removeFormat','link','ckfinder','mediaEmbed','insertTable','sourceEditing']}
let ckEditorToolbar=minButtons;if(textarea.hasClass('editor-advanced')||textarea.hasClass('editor-basic-fullpage')){ckEditorToolbar=maxButtons}
Mautic.ConvertFieldToCkeditor(textarea,ckEditorToolbar)})}}
Mautic.activateLookupTypeahead=function(containerEl){containerEl.find("*[data-toggle='field-lookup']").each(function(){var lookup=mQuery(this),callback=lookup.attr('data-callback')?lookup.attr('data-callback'):'activateFieldTypeahead';Mautic[callback](lookup.attr('id'),lookup.attr('data-target'),lookup.attr('data-options'),lookup.attr('data-action'))})};Mautic.makeConfirmationsAlive=function(jQueryObject){jQueryObject.off('click.confirmation');jQueryObject.on('click.confirmation',function(event){event.preventDefault();MauticVars.ignoreIconSpin=!0;return Mautic.showConfirmation(this)})};Mautic.makeModalsAlive=function(jQueryObject){jQueryObject.off('click.ajaxmodal');jQueryObject.on('click.ajaxmodal',function(event){event.preventDefault();Mautic.ajaxifyModal(this,event)})};Mautic.makeLinksAlive=function(jQueryObject){jQueryObject.off('click.ajax');jQueryObject.on('click.ajax',function(event){event.preventDefault();return Mautic.ajaxifyLink(this,event)})};Mautic.onPageUnload=function(container,response){if(typeof container!='undefined'){mQuery(container+" *[data-toggle='tooltip']").tooltip('destroy');if(typeof MauticVars.modalsReset=='undefined'){MauticVars.modalsReset={}}
if(ckEditors.size>0){ckEditors.forEach(function(value,key,map){if(container==='#app-content'||container==='body'||mQuery(container).find(key).length>0||mQuery(key).closest(container).length>0){map.get(key).destroy();map.delete(key)}})}
mQuery(container+" input[data-toggle='color']").each(function(){mQuery(this).minicolors('destroy')})}
var contentSpecific=!1;if(container=='#app-content'){Mousetrap.reset();contentSpecific=mauticContent;if(typeof Mautic.chartObjects!=='undefined'){mQuery.each(Mautic.chartObjects,function(i,chart){chart.destroy()});Mautic.chartObjects=[]}
if(typeof Mautic.mapObjects!=='undefined'){mQuery.each(Mautic.mapObjects,(i,map)=>{map.destroyMap()});Mautic.mapObjects=[]}
if(typeof Mautic.builderTokens!=='undefined'){Mautic.builderTokens={}}}else if(response&&response.mauticContent){contentSpecific=response.mauticContent}
if(contentSpecific){if(typeof Mautic[contentSpecific+"OnUnload"]=='function'){Mautic[contentSpecific+"OnUnload"](container,response)}
if(typeof Mautic.loadedContent[contentSpecific]!=='undefined'){delete Mautic.loadedContent[contentSpecific]}}};Mautic.ajaxifyLink=function(el,event,extraData={}){if(mQuery(el).hasClass('disabled')){return!1}
var route=mQuery(el).attr('href');if(route.indexOf('javascript')>=0||MauticVars.routeInProgress===route){return!1}
if(route.indexOf('batchExport')>=0){Mautic.initiateFileDownload(route);return!0}
if(event.ctrlKey||event.metaKey){route=route.split("?")[0];window.open(route,'_blank');return}
if(mQuery(".form-exit-unlock-id").length){if(mQuery(el).attr('data-ignore-formexit')!='true'){var unlockParameter=(mQuery('.form-exit-unlock-parameter').length)?mQuery('.form-exit-unlock-parameter').val():'';Mautic.unlockEntity(mQuery('.form-exit-unlock-model').val(),mQuery('.form-exit-unlock-id').val(),unlockParameter)}}
var link=mQuery(el).attr('data-menu-link');if(link!==undefined&&link.charAt(0)!='#'){link="#"+CSS.escape(link)}
var method=mQuery(el).attr('data-method');if(!method){method='GET'}
MauticVars.routeInProgress=route;var target=mQuery(el).attr('data-target');if(!target){target=null}
var showLoadingBar=(mQuery(el).attr('data-hide-loadingbar'))?!1:!0;Mautic.loadContent(route,link,method,target,showLoadingBar,undefined,extraData)};Mautic.activateChosenSelect=function(el,ignoreGlobal,jQueryVariant){var mQuery=(typeof jQueryVariant!='undefined')?jQueryVariant:window.mQuery;const $select=mQuery(el);if($select.parents('.no-chosen').length&&!ignoreGlobal){return}
var noResultsText=$select.data('no-results-text');if(!noResultsText){noResultsText=mauticLang.chosenNoResults}
var isLookup=$select.attr('data-chosen-lookup');if(isLookup){if($select.attr('data-new-route')){$select.on('change',function(){var url=$select.attr('data-new-route');if($select.val()=='new'&&($select.attr('data-popup')=="true"||$select.closest('.modal').length>0)){var queryGlue=url.indexOf('?')>=0?'&':'?';$select.find('option[value="new"]').prop('selected',!1);$select.trigger('chosen:updated');Mautic.loadNewWindow({"windowUrl":url+queryGlue+"contentOnly=1&updateSelect="+$select.attr('id')})}else{Mautic.loadAjaxModalBySelectValue(this,'new',url,$select.attr('data-header'))}})}
var multiPlaceholder=mauticLang['mautic.core.lookup.search_options'],singlePlaceholder=mauticLang['mautic.core.lookup.search_options']}else{var multiPlaceholder=mauticLang.chosenChooseMore,singlePlaceholder=mauticLang.chosenChooseOne}
if(typeof $select.data('chosen-placeholder')!=='undefined'){multiPlaceholder=singlePlaceholder=$select.data('chosen-placeholder')}
const hideResultsOnSelect=!$select.attr('data-chosen-keep-results-on-select');$select.chosen({placeholder_text_multiple:multiPlaceholder,placeholder_text_single:singlePlaceholder,no_results_text:noResultsText,width:"100%",allow_single_deselect:!0,include_group_label_in_selected:!0,search_contains:!0,hide_results_on_select:hideResultsOnSelect,});if(isLookup){const searchTerm=$select.attr('data-model');const minTermLength=$select.attr('data-chosen-min-term-length');if(searchTerm){$select.ajaxChosen({type:'GET',url:mauticAjaxUrl+'?action='+$select.attr('data-chosen-lookup'),dataType:'json',afterTypeDelay:2,minTermLength:minTermLength?minTermLength:2,jsonTermKey:searchTerm,keepTypingMsg:"Keep typing...",lookingForMsg:"Looking for"},function(data){const results=[];mQuery.each(data,function(i,value){results.push(typeof value==='object'?value:{value:value,text:value})});return results})}}};Mautic.destroyChosen=function(el){if(el.get(0)){var eventObject=mQuery._data(el.get(0),'events')}
if(eventObject!==undefined&&eventObject['chosen:activate']!==undefined){el.chosen('destroy');el.off('chosen:activate chosen:close chosen:open chosen:updated')}};Mautic.activateFieldTypeahead=function(field,target,options,action){var fieldId='#'+field;var fieldEl=mQuery('#'+field);if(fieldEl.length&&fieldEl.parent('.twitter-typeahead').length){return}
if(options&&typeof options==='String'){var keys=values=[];options=options.split('||');if(options.length==2){keys=options[1].split('|');values=options[0].split('|')}else{values=options[0].split('|')}
var fieldTypeahead=Mautic.activateTypeahead(fieldId,{dataOptions:values,dataOptionKeys:keys,minLength:0})}else{var typeAheadOptions={prefetch:!0,remote:!0,action:action+"&field="+target};if(('undefined'!==typeof options)&&('undefined'!==typeof options.limit)){typeAheadOptions.limit=options.limit}
if(('undefined'!==typeof options)&&('undefined'!==typeof options.noRrecordMessage)){typeAheadOptions.noRrecordMessage=options.noRrecordMessage}
var fieldTypeahead=Mautic.activateTypeahead(fieldId,typeAheadOptions)}
var callback=function(event,datum){if(fieldEl.length&&datum.value){fieldEl.val(datum.value);var lookupCallback=mQuery(fieldId).data('lookup-callback');if(lookupCallback&&typeof Mautic[lookupCallback]=='function'){Mautic[lookupCallback](field,datum)}}};mQuery(fieldTypeahead).on('typeahead:selected',callback).on('typeahead:autocompleted',callback)};Mautic.activateMultiSelect=function(el){var moveOption=function(v,prev){var theOption=mQuery(el).find('option[value="'+v+'"]').first();var lastSelected=mQuery(el).find('option:not(:disabled)').filter(function(){return mQuery(this).prop('selected')}).last();if(typeof prev!=='undefined'){if(prev){var prevOption=mQuery(el).find('option[value="'+prev+'"]').first();theOption.insertAfter(prevOption);return}}else if(lastSelected.length){theOption.insertAfter(lastSelected);return}
theOption.prependTo(el)};mQuery(el).multiSelect({afterInit:function(container){var funcName=mQuery(el).data('afterInit');if(funcName){Mautic[funcName]('init',container)}
var selectThat=this,$selectableSearch=this.$selectableUl.prev(),$selectionSearch=this.$selectionUl.prev(),selectableSearchString='#'+this.$container.attr('id')+' .ms-elem-selectable:not(.ms-selected)',selectionSearchString='#'+this.$container.attr('id')+' .ms-elem-selection.ms-selected';this.qs1=$selectableSearch.quicksearch(selectableSearchString).on('keydown',function(e){if(e.which===40){selectThat.$selectableUl.focus();return!1}});this.qs2=$selectionSearch.quicksearch(selectionSearchString).on('keydown',function(e){if(e.which==40){selectThat.$selectionUl.focus();return!1}});var selectOrder=mQuery(el).data('order');if(selectOrder&&selectOrder.length>1){this.deselect_all();mQuery.each(selectOrder,function(k,v){selectThat.select(v)})}
var isSortable=mQuery(el).data('sortable');if(isSortable){mQuery(el).parent('.choice-wrapper').find('.ms-selection').first().sortable({items:'.ms-elem-selection',helper:'clone',axis:'y',scroll:!1,update:function(event,ui){var prev=ui.item.prev();var prevValue=(prev.length)?prev.data('ms-value'):'';moveOption(ui.item.data('ms-value'),prevValue)}})}},afterSelect:function(value){var funcName=mQuery(el).data('afterSelect');if(funcName){Mautic[funcName]('select',value)}
this.qs1.cache();this.qs2.cache();moveOption(value)},afterDeselect:function(value){var funcName=mQuery(el).data('afterDeselect');if(funcName){Mautic[funcName]('deselect',value)}
this.qs1.cache();this.qs2.cache()},selectableHeader:"<input type='text' class='ms-search form-control' autocomplete='off'>",selectionHeader:"<input type='text' class='ms-search form-control' autocomplete='off'>",keepOrder:!0})};Mautic.activateModalEmbeddedForms=function(container){mQuery(container+" *[data-embedded-form='cancel']").off('click.embeddedform');mQuery(container+" *[data-embedded-form='cancel']").on('click.embeddedform',function(event){event.preventDefault();var modal=mQuery(this).closest('.modal');mQuery(modal).modal('hide');if(mQuery(this).attr('data-embedded-form-clear')==='true'){Mautic.resetForm(modal)}
if(typeof mQuery(this).attr('data-embedded-form-callback')!='undefined'){if(typeof window.Mautic[mQuery(this).attr('data-embedded-form-callback')]=='function'){window.Mautic[mQuery(this).attr('data-embedded-form-callback')].apply('window',[this,modal])}}});mQuery(container+" *[data-embedded-form='add']").each(function(){var submitButton=this;var modal=mQuery(this).closest('.modal');if(typeof mQuery(modal).data('bs.modal')!=='undefined'&&typeof mQuery(modal).data('bs.modal').options!=='undefined'){mQuery(modal).data('bs.modal').options.keyboard=!1;mQuery(modal).data('bs.modal').options.backdrop='static'}else{mQuery(modal).attr('data-keyboard',!1);mQuery(modal).attr('data-backdrop','static')}
mQuery(modal).on('show.bs.modal',function(){mQuery(this).on("keydown.embeddedForm",":input:not(textarea)",function(event){if(event.keyCode==13){event.preventDefault();if(event.metaKey||event.ctrlKey){mQuery(submitButton).click()}}})});mQuery(modal).on('hidden.bs.modal',function(){mQuery(this).off("keydown.embeddedForm",":input:not(textarea)")})});mQuery(container+" *[data-embedded-form='add']").off('click.embeddedform');mQuery(container+" *[data-embedded-form='add']").on('click.embeddedform',function(event){event.preventDefault();var modal=mQuery(this).closest('.modal');mQuery(modal).modal('hide');if(typeof mQuery(this).attr('data-embedded-form-callback')!='undefined'){if(typeof window.Mautic[mQuery(this).attr('data-embedded-form-callback')]=='function'){window.Mautic[mQuery(this).attr('data-embedded-form-callback')].apply('window',[this,modal])}}})};Mautic.activateDateTimeInputs=function(el,type){if(typeof type=='undefined'){type='datetime'}
var format=mQuery(el).data('format');if(type=='datetime'){mQuery(el).datetimepicker({format:(format)?format:'Y-m-d H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(type=='date'){mQuery(el).datetimepicker({timepicker:!1,format:(format)?format:'Y-m-d',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1,closeOnDateSelect:!0})}else if(type=='time'){mQuery(el).datetimepicker({datepicker:!1,format:(format)?format:'H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}
mQuery(el).addClass('calendar-activated')};Mautic.activateSearchAutocomplete=function(elId,modelName){if(mQuery('#'+elId).length){var livesearch=(mQuery('#'+elId).attr("data-toggle=['livesearch']"))?!0:!1;var typeaheadObject=Mautic.activateTypeahead('#'+elId,{prefetch:!0,remote:!1,limit:0,action:'commandList&model='+modelName,multiple:!0});mQuery(typeaheadObject).on('typeahead:selected',function(event,datum){if(livesearch){MauticVars.lastSearchStr='';mQuery('#'+elId).keyup()}}).on('typeahead:autocompleted',function(event,datum){if(livesearch){MauticVars.lastSearchStr='';mQuery('#'+elId).keyup()}})}};Mautic.activateLiveSearch=function(el,searchStrVar,liveCacheVar){if(!mQuery(el).length){return}
var btn="button[data-livesearch-parent='"+mQuery(el).attr('id')+"']";mQuery(el).on('focus',function(){Mautic.currentSearchString=mQuery(this).val().trim()});mQuery(el).on('change keyup paste',{},function(event){var searchStr=mQuery(el).val().trim();var spaceKeyPressed=(event.which==32||event.keyCode==32);var enterKeyPressed=(event.which==13||event.keyCode==13);var deleteKeyPressed=(event.which==8||event.keyCode==8);if(!enterKeyPressed&&Mautic.currentSearchString&&Mautic.currentSearchString==searchStr){return}
var target=mQuery(el).attr('data-target');var diff=searchStr.length-MauticVars[searchStrVar].length;if(diff<0){diff=parseInt(diff)*-1}
var overlayEnabled=mQuery(el).attr('data-overlay');if(!overlayEnabled||overlayEnabled=='false'){overlayEnabled=!1}else{overlayEnabled=!0}
var overlayTarget=mQuery(el).attr('data-overlay-target');if(!overlayTarget)overlayTarget=target;if(overlayEnabled){mQuery(el).off('blur.livesearchOverlay');mQuery(el).on('blur.livesearchOverlay',function(){mQuery(overlayTarget+' .content-overlay').remove()})}
if(!deleteKeyPressed&&overlayEnabled){var overlay=mQuery('<div />',{"class":"content-overlay"}).html(mQuery(el).attr('data-overlay-text'));if(mQuery(el).attr('data-overlay-background')){overlay.css('background',mQuery(el).attr('data-overlay-background'))}
if(mQuery(el).attr('data-overlay-color')){overlay.css('color',mQuery(el).attr('data-overlay-color'))}}
if((!searchStr&&MauticVars[searchStrVar].length)||diff>=3||spaceKeyPressed||enterKeyPressed){MauticVars[searchStrVar]=searchStr;event.data.livesearch=!0;Mautic.filterList(event,mQuery(el).attr('id'),mQuery(el).attr('data-action'),target,liveCacheVar,overlayEnabled,overlayTarget)}else if(overlayEnabled){if(!mQuery(overlayTarget+' .content-overlay').length){mQuery(overlayTarget).prepend(overlay)}}});if(mQuery(btn).length){mQuery(btn).on('click',{'parent':mQuery(el).attr('id')},function(event){var searchStr=mQuery(el).val().trim();MauticVars[searchStrVar]=searchStr;Mautic.filterButtonClicked=!0;Mautic.filterList(event,event.data.parent,mQuery('#'+event.data.parent).attr('data-action'),mQuery('#'+event.data.parent).attr('data-target'),'liveCache',mQuery(this).attr('data-livesearch-action'))});if(mQuery(el).val()){mQuery(btn).attr('data-livesearch-action','clear');mQuery(btn+' i').removeClass('ri-search-line').addClass('ri-eraser-line')}else{mQuery(btn).attr('data-livesearch-action','search');mQuery(btn+' i').removeClass('ri-eraser-line').addClass('ri-search-line')}}};Mautic.activateColorPicker=function(el,options){let input=mQuery(el);var pickerOptions=input.data('color-options');if(!pickerOptions){pickerOptions={theme:'bootstrap',change:function(hex){input.trigger('change.minicolors',hex)}}}
if(typeof options=='object'){pickerOptions=mQuery.extend(pickerOptions,options)}
input.minicolors(pickerOptions);input.val(input.val().replace('#',''));input.on('blur',function(){input.val(input.val().replace('#',''))})};Mautic.activateTypeahead=function(el,options){if(typeof options=='undefined'||!mQuery(el).length){return}
if(typeof options.remote=='undefined'){options.remote=(options.action)?!0:!1}
if(typeof options.prefetch=='undefined'){options.prefetch=!1}
if(typeof options.limit=='undefined'){options.limit=5}
if(!options.displayKey){options.displayKey='value'}
if(typeof options.multiple=='undefined'){options.multiple=!1}
if(typeof options.minLength=='undefined'){options.minLength=2}
if(options.prefetch||options.remote){if(typeof options.action=='undefined'){return}
var sourceOptions={datumTokenizer:Bloodhound.tokenizers.obj.whitespace(options.displayKey),queryTokenizer:Bloodhound.tokenizers.whitespace,dupDetector:function(remoteMatch,localMatch){return(remoteMatch[options.displayKey]==localMatch[options.displayKey])},ttl:15000,limit:options.limit};var filterClosure=function(list){if(typeof list.ignore_wdt!='undefined'){delete list.ignore_wdt}
if(typeof list.success!='undefined'){delete list.success}
if(typeof list=='object'){if(typeof list[0]!='undefined'){list=mQuery.map(list,function(el){return el})}else{list=[]}}
return list};if(options.remote){sourceOptions.remote={url:mauticAjaxUrl+"?action="+options.action+"&filter=%QUERY",filter:filterClosure,wildcard:'%QUERY',}}
if(options.prefetch){sourceOptions.prefetch={url:mauticAjaxUrl+"?action="+options.action,filter:filterClosure}}
var theBloodhound=new Bloodhound(sourceOptions);theBloodhound.initialize()}else{var substringMatcher=function(strs,strKeys){return function findMatches(q,cb){var matches,substrRegex;matches=[];substrRegex=new RegExp(q,'i');mQuery.each(strs,function(i,str){if(typeof str=='object'){str=str[options.displayKey]}
if(substrRegex.test(str)){var match={};match[options.displayKey]=str;if(strKeys.length&&typeof strKeys[i]!='undefined'){match.id=strKeys[i]}
matches.push(match)}});cb(matches)}};var lookupOptions=(options.dataOptions)?options.dataOptions:mQuery(el).data('options');var lookupKeys=(options.dataOptionKeys)?options.dataOptionKeys:[];if(!lookupOptions){return}}
var noRrecordMessage=(options.noRrecordMessage)?options.noRrecordMessage:mQuery(el).data('no-record-message');var theName=el.replace(/[^a-z0-9\s]/gi,'').replace(/[-\s]/g,'_');var dataset={name:theName,displayKey:options.displayKey,source:(typeof theBloodhound!='undefined')?theBloodhound.ttAdapter():substringMatcher(lookupOptions,lookupKeys)};if(noRrecordMessage){dataset.templates={empty:"<p>"+noRrecordMessage+"<p>"}}
var theTypeahead=mQuery(el).typeahead({hint:!0,highlight:!0,minLength:options.minLength,multiple:options.multiple},dataset).on('keypress',function(event){if((event.keyCode||event.which)==13){mQuery(el).typeahead('close')}}).on('focus',function(){if(mQuery(el).typeahead('val')===''&&!options.minLength){mQuery(el).data('ttTypeahead').input.trigger('queryChanged','')}});return theTypeahead};Mautic.activateSortable=function(el){var prefix=mQuery(el).attr('data-prefix');if(mQuery('#'+prefix+'_additem').length){mQuery('#'+prefix+'_additem').click(function(){var count=mQuery('#'+prefix+'_itemcount').val();var prototype=mQuery('#'+prefix+'_additem').attr('data-prototype');prototype=prototype.replace(/__name__/g,count);mQuery(prototype).appendTo(mQuery('#'+prefix+'_list div.list-sortable'));mQuery('#'+prefix+'_list_'+count).focus();count++;mQuery('#'+prefix+'_itemcount').val(count);return!1})}
mQuery('#'+prefix+'_list div.list-sortable').sortable({items:'div.sortable',handle:'span.postaddon',axis:'y',containment:'#'+prefix+'_list',stop:function(i){var order=0;mQuery('#'+prefix+'_list div.list-sortable div.input-group input').each(function(){var name=mQuery(this).attr('name');if(mQuery(this).hasClass('sortable-label')){name=name.replace(/(\[list\]\[[0-9]+\]\[label\])$/g,'')+'[list]['+order+'][label]'}else if(mQuery(this).hasClass('sortable-value')){name=name.replace(/(\[list\]\[[0-9]+\]\[value\])$/g,'')+'[list]['+order+'][value]';order++}else{name=name.replace(/(\[list\]\[[0-9]+\])$/g,'')+'[list]['+order+']';order++}
mQuery(this).attr('name',name)})}})};Mautic.initiateFileDownload=function(link){if(mauticContactExportInBackground===1&&link.indexOf('filetype=csv')>=0){Mautic.processCsvContactExport(link);return}
const iframe=mQuery("<iframe/>").attr({src:link,style:"visibility:hidden;display:none"}).appendTo(mQuery('body'));iframe.on('load',function(){try{const iframeContent=iframe.contents().text();const response=JSON.parse(iframeContent);if(response.message){const flashMessage=Mautic.addErrorFlashMessage(response.message);Mautic.setFlashes(flashMessage)}}catch(e){}})};Mautic.processCsvContactExport=function(route){mQuery.ajax({showLoadingBar:!0,url:route,type:"POST",dataType:"json",success:function(response){Mautic.processPageContent(response);if(typeof callback=='function'){callback(response)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)}})};Mautic.copyToClipboard=function(text){const textArea=document.createElement('textarea');textArea.innerHTML=text;const decodedText=textArea.value||textArea.innerText;navigator.clipboard.writeText(decodedText).then(function(){const message=Mautic.translate('mautic.core.notice.copiedtoclipboard');const flashMessage=Mautic.addInfoFlashMessage(message);Mautic.setFlashes(flashMessage)}).catch(function(err){console.error('Clipboard write error:',err);const message=Mautic.translate('mautic.core.error.copyfailed');const flashMessage=Mautic.addErrorFlashMessage(message);Mautic.setFlashes(flashMessage)})};Mautic.initFilterCommands=function(){const filterElements=document.querySelectorAll('.label[data-filter]');Mautic.filterCommands=Array.from(filterElements).map(function(el){return el.dataset.filter});const selectFields=document.querySelectorAll('.popover-content select');selectFields.forEach(function(selectElement){const options=Array.from(selectElement.options).map(option=>option.value);Mautic.filterCommands.push(...options)})};Mautic.toggleFilter=function(element){const filterValue=element.dataset.filter;const conflictGroup=element.dataset.conflictGroup||null;if(conflictGroup){const filtersInGroup=document.querySelectorAll(`.label[data-conflict-group="${conflictGroup}"]`);filtersInGroup.forEach(function(filterElement){if(filterElement!==element){filterElement.classList.remove('active')}})}
element.classList.toggle('active')};Mautic.applyFilters=function(){const searchInput=document.getElementById('list-search');let currentSearchValue=searchInput.value||'';currentSearchValue=Mautic.removeFilterCommands(currentSearchValue);const activeFilters=document.querySelectorAll('.label.active');let filterCommands=Array.from(activeFilters).map(function(filterElement){return filterElement.dataset.filter});const selectFields=document.querySelectorAll('.popover-content select');selectFields.forEach(function(selectElement){const selectedOptions=Array.from(selectElement.selectedOptions).map(option=>option.value);filterCommands.push(...selectedOptions)});const newSearchValue=(currentSearchValue+' '+filterCommands.join(' ')).trim();searchInput.value=newSearchValue;const popoverTrigger=mQuery('[data-toggle="popover"]');popoverTrigger.popover('destroy');popoverTrigger.popover({html:!0,container:'body'});const enterKeyEvent=new KeyboardEvent('keyup',{key:'Enter',keyCode:13,which:13,bubbles:!0});searchInput.dispatchEvent(enterKeyEvent)};Mautic.resetFilters=function(){const searchInput=document.getElementById('list-search');let currentSearchValue=searchInput.value||'';currentSearchValue=Mautic.removeFilterCommands(currentSearchValue);searchInput.value=currentSearchValue.trim();const activeFilters=document.querySelectorAll('.label.active');activeFilters.forEach(function(filterElement){filterElement.classList.remove('active')});const selectFields=document.querySelectorAll('.popover-content select');selectFields.forEach(function(selectElement){selectElement.value=null;if(typeof mQuery!=='undefined'){mQuery(selectElement).trigger('chosen:updated')}});const popoverTrigger=mQuery('[data-toggle="popover"]');popoverTrigger.popover('destroy');const enterKeyEvent=new KeyboardEvent('keyup',{key:'Enter',keyCode:13,which:13,bubbles:!0});searchInput.dispatchEvent(enterKeyEvent)};Mautic.removeFilterCommands=function(searchValue){if(!Mautic.filterCommands||Mautic.filterCommands.length===0){Mautic.initFilterCommands()}
const escapedCommands=Mautic.filterCommands.map(cmd=>cmd.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&'));const regex=new RegExp('\\b('+escapedCommands.join('|')+')\\b','g');return searchValue.replace(regex,'').replace(/\s{2,}/g,' ').trim()};Mautic.getActiveFilterCommands=function(){const searchInput=document.getElementById('list-search');if(!searchInput){return[]}
const searchValue=searchInput.value||'';if(!Mautic.filterCommands||Mautic.filterCommands.length===0){Mautic.initFilterCommands()}
const escapedCommands=Mautic.filterCommands.map(cmd=>cmd.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&'));const regex=new RegExp('\\b('+escapedCommands.join('|')+')\\b','g');const matches=searchValue.match(regex);return matches?matches:[]};Mautic.initializePopoverFilters=function(popoverElement){const activeFilterCommands=Mautic.getActiveFilterCommands();activeFilterCommands.forEach(function(filterCommand){const label=popoverElement.querySelector(`.label[data-filter="${filterCommand}"]`);if(label){label.classList.add('active')}
const selectFields=popoverElement.querySelectorAll('select');selectFields.forEach(function(selectElement){Array.from(selectElement.options).forEach(function(option){const isSelected=activeFilterCommands.some(cmd=>cmd===option.value||cmd===`category:${option.value}`);option.selected=isSelected});mQuery(selectElement).chosen({width:'100%',allow_single_deselect:!0});mQuery(selectElement).trigger('chosen:updated')})})};Mautic.handlePopoverInsertion=function(){mQuery(document).on('inserted.bs.popover','[data-toggle="popover"]',function(){const popoverId=mQuery(this).attr('aria-describedby');if(!popoverId)return;const popoverElement=document.getElementById(popoverId);if(!popoverElement)return;Mautic.initializePopoverFilters(popoverElement);mQuery('.popover-content select').chosen({width:'100%',allow_single_deselect:!0})})};document.addEventListener('DOMContentLoaded',function(){Mautic.initFilterCommands();Mautic.handlePopoverInsertion()});Mautic.downloadIpLookupDataStore=function(){var ipService=mQuery('#config_coreconfig_ip_lookup_service').val();var ipAuth=mQuery('#config_coreconfig_ip_lookup_auth').val();mQuery('#iplookup_fetch_button_container .ri-loader-3-line').removeClass('hide');Mautic.ajaxActionRequest('downloadIpLookupDataStore',{service:ipService,auth:ipAuth},function(response){mQuery('#iplookup_fetch_button_container .ri-loader-3-line').addClass('hide');if(response.message){mQuery('#iplookup_fetch_button_container').parent().removeClass('has-error').addClass('has-success');mQuery('#iplookup_fetch_button_container').next('.help-block').html(response.message)}else if(response.error){mQuery('#iplookup_fetch_button_container').parent().removeClass('has-success').addClass('has-error');mQuery('#iplookup_fetch_button_container').next('.help-block').html(response.error)}},!1,!1,'GET')};Mautic.getIpLookupFormConfig=function(){var ipService=mQuery('#config_coreconfig_ip_lookup_service').val();Mautic.activateLabelLoadingIndicator('config_coreconfig_ip_lookup_service');Mautic.ajaxActionRequest('getIpLookupForm',{service:ipService},function(response){Mautic.removeLabelLoadingIndicator();mQuery('#ip_lookup_config_container').html(response.html);mQuery('#ip_lookup_attribution').html(response.attribution)},!1,!1,"GET")};Mautic.configOnLoad=function(container){document.querySelectorAll('input[type="radio"][data-attribute-toggle]').forEach(radio=>{const attributeName=radio.dataset.attributeToggle;const modifiedName=attributeName.replace('-','_');const hiddenInput=document.querySelector(`input[type="hidden"][id*="${modifiedName}"]`);if(hiddenInput&&hiddenInput.value){const correspondingRadio=document.querySelector(`input[name="${attributeName}"][data-attribute-value="${hiddenInput.value}"]`);if(correspondingRadio)correspondingRadio.checked=!0}else if(radio.checked&&hiddenInput){hiddenInput.value=radio.dataset.attributeValue}});document.querySelectorAll('input[type="radio"][data-attribute-toggle]').forEach(radio=>{radio.addEventListener('change',function(){if(this.checked){const attributeName=this.dataset.attributeToggle;const modifiedName=attributeName.replace('-','_');const hiddenInput=document.querySelector(`input[type="hidden"][id*="${modifiedName}"]`);if(hiddenInput)hiddenInput.value=this.dataset.attributeValue}})})};Mautic.launchBuilder=function(){alert('Please enable the GrapesJS builder plugin (or another builder plugin) to use this feature.')};Mautic.inBuilderSubmissionOn=function(form){const inBuilder=mQuery('<input type="hidden" name="inBuilder" value="1" />');const applyButton=mQuery('#btn-views-apply').css('pointer-events','none');form.append(inBuilder);form.one('submit:success',function(event,action,data){if(data?.newContent){const selector='#page_version, #emailform_version';const version=mQuery(data.newContent).find(selector).val();mQuery(this).find(selector).val(version)}
applyButton.css('pointer-events','auto')})}
Mautic.inBuilderSubmissionOff=function(form){Mautic.isInBuilder=!1;mQuery('input[name="inBuilder"]').remove()}
Mautic.processBuilderErrors=function(response){if(response.validationError){mQuery('.btn-apply-builder').attr('disabled',!0);mQuery('#builder-errors span').text(response.validationError);mQuery('#builder-errors').show('fast')}};Mautic.openMediaManager=function(){Mautic.openServerBrowser(mauticBasePath+'/elfinder',screen.width*0.7,screen.height*0.7)}
Mautic.sanitizeHtmlBeforeSave=function(htmlContent){htmlContent.find('[data-source="mautic"]').remove();htmlContent.find('.atwho-container').remove();htmlContent.find('.fr-image-overlay, .fr-quick-insert, .fr-tooltip, .fr-toolbar, .fr-popup, .fr-image-resizer').remove();htmlContent.find('[data-slot-focus], [data-section-focus]').remove();var customHtml=Mautic.domToString(htmlContent).replace(/url\(&quot;(.+)&quot;\)/g,'url(\'$1\')');return customHtml};Mautic.domToString=function(dom){if(typeof dom==='string'){return dom}
var xs=new XMLSerializer();return xs.serializeToString(dom.get(0))};Mautic.openServerBrowser=function(url,width,height){var iLeft=(screen.width-width)/2;var iTop=(screen.height-height)/2;var sOptions="toolbar=no,status=no,resizable=yes,dependent=yes";sOptions+=",width="+width;sOptions+=",height="+height;sOptions+=",left="+iLeft;sOptions+=",top="+iTop;var oWindow=window.open(url,"BrowseWindow",sOptions)}
Mautic.initSelectTheme=function(themeField){var customHtml=mQuery('textarea.builder-html');var isNew=Mautic.isNewEntity('#page_sessionId, #emailform_sessionId');Mautic.showChangeThemeWarning=!0;Mautic.builderTheme=themeField.val();if(isNew){Mautic.showChangeThemeWarning=!1;if(!customHtml.length||!customHtml.val().length){Mautic.setThemeHtml(Mautic.builderTheme)}}
if(customHtml.length){mQuery('[data-theme]').click(function(e){e.preventDefault();var currentLink=mQuery(this);var theme=currentLink.attr('data-theme');var isCodeMode=(theme==='mautic_code_mode');Mautic.builderTheme=theme;if(Mautic.showChangeThemeWarning&&customHtml.val().length){if(!isCodeMode){if(confirm(Mautic.translate('mautic.core.builder.theme_change_warning'))){customHtml.val('');Mautic.showChangeThemeWarning=!1}else{return}}else{if(confirm(Mautic.translate('mautic.core.builder.code_mode_warning'))){}else{return}}}
themeField.val(theme);if(isCodeMode){mQuery('.builder').addClass('code-mode');mQuery('.builder .code-editor').removeClass('hide');mQuery('.builder .code-mode-toolbar').removeClass('hide');mQuery('.builder .builder-toolbar').addClass('hide')}else{mQuery('.builder').removeClass('code-mode');mQuery('.builder .code-editor').addClass('hide');mQuery('.builder .code-mode-toolbar').addClass('hide');mQuery('.builder .builder-toolbar').removeClass('hide');Mautic.setThemeHtml(theme)}
mQuery('.theme-list .panel').removeClass('theme-selected');currentLink.closest('.panel').addClass('theme-selected');mQuery('.theme-list .select-theme-selected').addClass('hide');mQuery('.theme-list .select-theme-link').removeClass('hide');currentLink.closest('.panel').find('.select-theme-selected').removeClass('hide');currentLink.addClass('hide')})}};Mautic.setThemeHtml=function(theme){mQuery.get(mQuery('#builder_url').val()+'?template='+theme,function(themeHtml){var textarea=mQuery('textarea.builder-html');textarea.val(themeHtml)})};Mautic.toggleBuilderButton=function(hide){if(mQuery('.toolbar-form-buttons .toolbar-standard .btn-builder')){if(hide){mQuery('.toolbar-form-buttons .toolbar-standard .btn-builder').addClass('hide btn-standard-toolbar').appendTo('.toolbar-form-buttons')
mQuery('.toolbar-form-buttons .toolbar-dropdown i.ri-instance-fill').parent().addClass('hide')}else{if(!mQuery('.btn-standard-toolbar.btn-builder').length){mQuery('.toolbar-form-buttons .toolbar-standard .btn-builder').addClass('btn-standard-toolbar')}else{mQuery('.toolbar-form-buttons .btn-standard-toolbar.btn-builder').prependTo('.toolbar-form-buttons .toolbar-standard').removeClass('hide');mQuery('.toolbar-form-buttons .toolbar-dropdown i.ri-instance-fill').parent().removeClass('hide')}}}};Mautic.removeAddVariantButton=function(){parent.mQuery('#customize-slot-panel').find('.panel-heading button').remove();Mautic.reattachDEC()};Mautic.reattachDEC=function(){if(typeof Mautic.activeDEC!=='undefined'){var element=Mautic.activeDEC.detach();Mautic.activeDECParent.append(element)}};Mautic.isCodeMode=function(){return mQuery('a[data-theme=mautic_code_mode]').first().hasClass('hide')};window.document.fileManagerInsertImageCallback=function(selector,url){if(Mautic.isCodeMode()){Mautic.insertTextAtCMCursor(url)}};Mautic.getBuilderTokensMethod=function(){var method='page:getBuilderTokens';if(parent.mQuery('.builder').hasClass('email-builder')){method='email:getBuilderTokens'}
return method};Mautic.getAbTestWinnerForm=function(bundle,formName,abKey){if(abKey&&mQuery(abKey).val()&&mQuery(abKey).closest('.form-group').hasClass('has-error')){mQuery(abKey).closest('.form-group').removeClass('has-error');if(mQuery(abKey).next().hasClass('help-block')){mQuery(abKey).next().remove()}}
Mautic.activateLabelLoadingIndicator(formName+'_variantSettings_winnerCriteria');var id=mQuery('#'+formName+'_sessionId').val();var query="action="+bundle+":getAbTestForm&abKey="+mQuery(abKey).val()+"&id="+id;mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(typeof response.html!='undefined'){if(mQuery('#'+formName+'_variantSettings_properties').length){mQuery('#'+formName+'_variantSettings_properties').replaceWith(response.html)}else{mQuery('#'+formName+'_variantSettings').append(response.html)}
if(response.html!=''){Mautic.onPageLoad('#'+formName+'_variantSettings_properties',response)}}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.removeLabelLoadingIndicator()}})};mQuery(document).on({"chosen:hiding_dropdown":function(){mQuery('#app-wrapper').css('overflow','hidden')},"chosen:showing_dropdown":function(){mQuery('#app-wrapper').css('overflow','visible')}});Mautic.renameFormElements=function(container,oldIdPrefix,oldNamePrefix,newIdPrefix,newNamePrefix){mQuery('*[id^="'+oldIdPrefix+'"]',container).each(function(){var id=mQuery(this).attr('id');id=id.replace(oldIdPrefix,newIdPrefix);mQuery(this).attr('id',id);var name=mQuery(this).attr('name');if(name){name=name.replace(oldNamePrefix,newNamePrefix);mQuery(this).attr('name',name)}});mQuery('label[for^="'+oldIdPrefix+'"]',container).each(function(){var id=mQuery(this).attr('for');id=id.replace(oldIdPrefix,newIdPrefix);mQuery(this).attr('for',id)})};Mautic.ajaxifyForm=function(formName){Mautic.initializeFormFieldStateSwitcher(formName);var form='form[name="'+formName+'"]';Mautic.addKeyboardShortcut(['meta+enter','ctrl+enter'],'Submit form',function(e){if(MauticVars.formSubmitInProgress){return!1}
var saveButton=mQuery(form).find('button.btn-save');var applyButton=mQuery(form).find('button.btn-apply');var modalParent=mQuery(form).closest('.modal');var inMain=mQuery(modalParent).length>0?!1:!0;if(mQuery(saveButton).length){if(inMain){if(mQuery(form).find('button.btn-save.btn-copy').length){mQuery(mQuery(form).find('button.btn-save.btn-copy')).trigger('click');return}}else{if(mQuery(modalParent).find('button.btn-save.btn-copy').length){mQuery(mQuery(modalParent).find('button.btn-save.btn-copy')).trigger('click');return}}
mQuery(saveButton).trigger('click')}else if(mQuery(applyButton).length){if(inMain){if(mQuery(form).find('button.btn-apply.btn-copy').length){mQuery(mQuery(form).find('button.btn-apply.btn-copy')).trigger('click');return}}else{if(mQuery(modalParent).find('button.btn-apply.btn-copy').length){mQuery(mQuery(modalParent).find('button.btn-apply.btn-copy')).trigger('click');return}}
mQuery(applyButton).trigger('click')}});mQuery(form+' input, '+form+' select').off('keydown.ajaxform');mQuery(form+' input, '+form+' select').on('keydown.ajaxform',function(e){if(e.keyCode==13&&mQuery(e.target).is(':input')){var inputs=mQuery(this).parents('form').eq(0).find(':input');if(inputs[inputs.index(this)+1]!=null){inputs[inputs.index(this)+1].focus()}
e.preventDefault();return!1}});mQuery(form+' :submit').each(function(){mQuery(this).off('click.ajaxform');mQuery(this).on('click.ajaxform',function(){if(mQuery(this).attr('name')&&!mQuery('input[name="'+mQuery(this).attr('name')+'"]').length){mQuery('input.button-clicked').remove();mQuery('form[name="'+formName+'"]').append(mQuery('<input type="hidden" class="button-clicked">').attr({name:mQuery(this).attr('name'),value:mQuery(this).attr('value')}))}})});mQuery(form).off('submit.ajaxform');mQuery(form).on('submit.ajaxform',(function(e){e.preventDefault();var form=mQuery(this);if(typeof ckEditors!=='undefined'&&ckEditors.size>0){form.find('textarea.editor').each(function(){var editor=ckEditors.get(this);if(editor&&typeof editor.updateSourceElement==='function'){editor.updateSourceElement()}})}
if(MauticVars.formSubmitInProgress){return!1}else{var callbackAsync=form.data('submit-callback-async');if(callbackAsync&&typeof Mautic[callbackAsync]=='function'){Mautic[callbackAsync].apply(this,[form,function(){Mautic.postMauticForm(form)}])}else{var callback=form.data('submit-callback');if(callback&&typeof Mautic[callback]=='function'){if(!Mautic[callback]()){return!1}}
Mautic.postMauticForm(form)}}
return!1}))};Mautic.postMauticForm=function(form){MauticVars.formSubmitInProgress=!0;Mautic.postForm(form,function(response){if(response.inMain){Mautic.processPageContent(response)}else{Mautic.processModalContent(response,'#'+response.modalId)}})};Mautic.resetForm=function(form){mQuery(':input',form).not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').prop('checked',!1).removeAttr('selected').prop('selected',!1);mQuery(form).find('select:not(.not-chosen):not(.multiselect)').each(function(){mQuery(this).find('option:selected').prop('selected',!1)
mQuery(this).trigger('chosen:updated')})};Mautic.postForm=function(form,callback,extraData={}){form=mQuery(form);var modalParent=form.closest('.modal');var inMain=mQuery(modalParent).length===0;var action=form.attr('action');if(!inMain){var modalTarget='#'+mQuery(modalParent).attr('id');Mautic.startModalLoadingBar(modalTarget)}
var showLoading=(!inMain||form.attr('data-hide-loadingbar'))?!1:!0;form.ajaxSubmit({data:extraData,showLoadingBar:showLoading,success:function(data){form.trigger('submit:success',[action,data,inMain]);if(!inMain){Mautic.stopModalLoadingBar(modalTarget)}
if(data.redirect){Mautic.redirectWithBackdrop(data.redirect)}else{MauticVars.formSubmitInProgress=!1;if(!inMain){var modalId=mQuery(modalParent).attr('id')}
if(data.sessionExpired){if(!inMain){mQuery('#'+modalId).modal('hide');mQuery('.modal-backdrop').remove()}
Mautic.processPageContent(data)}else if(callback){data.inMain=inMain;if(!inMain){data.modalId=modalId}
if(typeof callback=='function'){callback(data)}else if(typeof Mautic[callback]=='function'){Mautic[callback](data)}}}},error:function(request,textStatus,errorThrown){MauticVars.formSubmitInProgress=!1;Mautic.processAjaxError(request,textStatus,errorThrown,inMain)}})};Mautic.initializeFormFieldStateSwitcher=function(formName){Mautic.switchFormFieldState(formName);mQuery('form[name="'+formName+'"]').on('change',function(){Mautic.switchFormFieldState(formName)})};Mautic.switchFormFieldState=function(formName){var form=mQuery('form[name="'+formName+'"]');var visibleFields={};var disabledFields={};var fieldsPriority={};var getFieldParts=function(fieldName){var returnObject={"name":fieldName,"attribute":''};if(fieldName.search(':')!==-1){var returnArray=fieldName.split(':');returnObject.name=returnArray[0];returnObject.attribute=returnArray[1]}
return returnObject};var checkValueCondition=function(sourceFieldVal,condition){var state=!0;if(typeof condition=='object'){state=mQuery.inArray(sourceFieldVal,condition)!==-1}else if(condition=='empty'||(condition=='notEmpty')){var isEmpty=(sourceFieldVal==''||sourceFieldVal==null||sourceFieldVal=='undefined');state=(condition=='empty')?isEmpty:!isEmpty}else if(condition!==sourceFieldVal){state=!1}
return state};var checkFieldCondition=function(fieldId,attribute,condition){var state=!0;if(attribute){if(typeof mQuery('#'+fieldId).attr(attribute)!=='undefined'){var field='#'+fieldId}else if(mQuery('#'+fieldId).is('select')){var field=mQuery('#'+fieldId+' option[value="'+mQuery('#'+fieldId).val()+'"]')}else{return state}
var attributeValue=(typeof mQuery(field).attr(attribute)!=='undefined')?mQuery(field).attr(attribute):null;return checkValueCondition(attributeValue,condition)}else if(mQuery('#'+fieldId).is(':checkbox')||mQuery('#'+fieldId).is(':radio')){return(condition=='checked'&&mQuery('#'+fieldId).is(':checked'))||(condition==''&&!mQuery('#'+fieldId).is(':checked'))}
return checkValueCondition(mQuery('#'+fieldId).val(),condition)}
var processConditions=function(attribute,checkState,shouldInvert){form.find('['+attribute+']').each(function(_,el){var field=mQuery(el);var conditions=JSON.parse(field.attr(attribute));mQuery.each(conditions,function(fieldId,condition){var fieldParts=getFieldParts(fieldId);var stateId=field.attr('id');var conditionResult=checkFieldCondition(fieldParts.name,fieldParts.attribute,condition);if(shouldInvert){conditionResult=!conditionResult}
if(typeof checkState[stateId]==='undefined'||!checkState[stateId]){checkState[stateId]=conditionResult}})})};var toggleFieldOff=function(field){if(field.attr('onchange')?.includes('Mautic.toggleYesNo(this)')&&field.val()==="1"&&field.is(':checked')){label=field.siblings('.toggle__label')
if(label.attr('aria-checked')==="true"){label.trigger('click')}}}
processConditions('data-show-on',visibleFields,!1);form.find('[data-hide-on]').each(function(index,el){var field=mQuery(el);var hideOn=JSON.parse(field.attr('data-hide-on'));if(typeof hideOn.display_priority!=='undefined'){fieldsPriority[field.attr('id')]='hide';delete hideOn.display_priority}
mQuery.each(hideOn,function(fieldId,condition){var fieldParts=getFieldParts(fieldId);if(typeof visibleFields[field.attr('id')]==='undefined'||visibleFields[field.attr('id')]){visibleFields[field.attr('id')]=!checkFieldCondition(fieldParts.name,fieldParts.attribute,condition)}})});mQuery.each(visibleFields,function(fieldId,show){var field=mQuery('#'+fieldId);var fieldContainer=field.closest('[class*="col-"]');if(show){fieldContainer.fadeIn()}else{toggleFieldOff(field);fieldContainer.fadeOut()}});processConditions('data-enable-on',disabledFields,!0);processConditions('data-disable-on',disabledFields,!1);mQuery.each(disabledFields,function(fieldId,disable){var field=mQuery('#'+fieldId)
if(disable){toggleFieldOff(field);field.addClass('disabled',disable);field.attr('disabled','disabled')}else{field.removeClass('disabled',disable);field.removeAttr('disabled')}})};Mautic.updateEntitySelect=function(response){var mQueryParent=(window.opener)?window.opener.mQuery:mQuery;if(response.id){var newOption=mQuery('<option />').val(response.id);newOption.html(response.name);var el='#'+response.updateSelect;var sortOptions=function(options){return options.sort(function(a,b){var alc=a.text?a.text.toLowerCase():mQuery(a).attr("label").toLowerCase();var blc=b.text?b.text.toLowerCase():mQuery(b).attr("label").toLowerCase();return alc>blc?1:alc<blc?-1:0})}
var emptyOption=!1,createNewOption=!1;if(mQueryParent(el).prop('disabled')){mQueryParent(el).prop('disabled',!1);var emptyOption=mQuery('<option value="">'+mauticLang.chosenChooseOne+'</option>')}else{if(mQueryParent(el+' option[value=""]').length){emptyOption=mQueryParent(el+' option[value=""]').clone();mQueryParent(el+' option[value=""]').remove()}
if(mQueryParent(el+' option[value="new"]').length){createNewOption=mQueryParent(el+' option[value="new"]').clone();mQueryParent(el+' option[value="new"]').remove()}}
if(response.group){var optgroup=el+' optgroup[label="'+response.group+'"]';if(mQueryParent(optgroup).length){var firstOptionGroups=mQueryParent(optgroup);var isUpdateOption=!1;firstOptionGroups.each(function(){var firstOptions=mQuery(this).children();for(var i=0;i<firstOptions.length;i++){if(firstOptions[i].value===response.id.toString()){firstOptions[i].text=response.name;isUpdateOption=!0;break}}});if(!isUpdateOption){mQueryParent(optgroup).append(newOption)}}else{var newOptgroup=mQuery('<optgroup label= />');newOption.appendTo(newOptgroup);mQueryParent(newOptgroup).appendTo(mQueryParent(el))}
var optionGroups=sortOptions(mQueryParent(el+' optgroup'));optionGroups.each(function(){var options=sortOptions(mQuery(this).children());mQuery(this).html(options)});var appendOptions=optionGroups}else{newOption.appendTo(mQueryParent(el));var appendOptions=sortOptions(mQueryParent(el).children())}
mQueryParent(el).html(appendOptions);if(createNewOption){mQueryParent(el).prepend(createNewOption)}
if(emptyOption){mQueryParent(el).prepend(emptyOption)}
newOption.prop('selected',!0);mQueryParent(el).trigger("chosen:updated")}
if(window.opener){window.close()}else{mQueryParent('#MauticSharedModal').modal('hide')}};Mautic.toggleYesNo=function(element){let $label=mQuery(element),$toggle=$label.closest('.toggle'),yesId=$label.data('yes-id'),noId=$label.data('no-id'),$yesInput=mQuery('#'+yesId),$noInput=mQuery('#'+noId),$switchEl=$toggle.find('.toggle__switch'),$toggleLabel=$toggle.find('.toggle__label'),$textEl=$toggle.find('.toggle__text'),isYes=$yesInput.is(':checked');if($yesInput.is(':disabled')){return}
$noInput.prop('checked',isYes);$yesInput.prop('checked',!isYes).trigger('change');$switchEl.toggleClass('toggle__switch--checked',!isYes);$textEl.text($toggle.data(isYes?'no':'yes'));$toggleLabel.attr('aria-checked',!isYes);Mautic.updatePublishingToggle(element)};Mautic.updatePublishingToggle=function(element){let $label=mQuery(element),$toggle=$label.closest('.toggle'),$form=$toggle.closest('form'),yesId=$label.data('yes-id'),$yesInput=mQuery('#'+yesId),$textEl=$toggle.find('.toggle__text'),isYes=$yesInput.is(':checked'),yesText=$toggle.data('yes'),noText=$toggle.data('no'),noneText=$toggle.data('none'),startText=$toggle.data('start'),bothText=$toggle.data('both'),endText=$toggle.data('end'),$publishUp=$form.find('input[name$="[publishUp]"]'),$publishDown=$form.find('input[name$="[publishDown]"]'),hasPublishUp=$publishUp.length&&$publishUp.val().trim()!=='',hasPublishDown=$publishDown.length&&$publishDown.val().trim()!=='';const $scheduleOptionsNotice=$form.find('#scheduleOptionsNotice');if($scheduleOptionsNotice.length){$scheduleOptionsNotice.toggle(isYes)}
function togglePublishFields(enable){[$publishUp,$publishDown].forEach($input=>{$input.prop('disabled',!enable);$input.closest('.form-group').find(`label.btn-datepicker[for="${$input.attr('id')}"]`).toggleClass('disabled',!enable).attr('aria-disabled',!enable)})}
if(typeof noneText!=='undefined'){if(isYes){$textEl.text(hasPublishUp&&hasPublishDown?bothText:hasPublishUp?startText:hasPublishDown?endText:yesText);togglePublishFields(!0)}else{$textEl.text(hasPublishUp||hasPublishDown?noneText:noText);togglePublishFields(!1)}}else{$textEl.text(isYes?yesText:noText)}};Mautic.initializePublishingToggles=function(){mQuery('.toggle[data-none]').each(function(){const $label=mQuery(this).find('.toggle__label');Mautic.updatePublishingToggle($label)});mQuery('input[name$="[publishUp]"], input[name$="[publishDown]"]').off('change').on('change',function(){const $form=mQuery(this).closest('form');$form.find('.toggle[data-none]').each(function(){const $label=mQuery(this).find('.toggle__label');Mautic.updatePublishingToggle($label)})})};mQuery(document).ready(Mautic.initializePublishingToggles);mQuery(document).ajaxComplete(Mautic.initializePublishingToggles);Mautic.handleKeyDown=function(event,element){if(event.key===' '||event.key==='Enter'){event.preventDefault();Mautic.toggleYesNo(element)}};Mautic.removeFormListOption=function(el){var sortableDiv=mQuery(el).parents('div.sortable');mQuery(sortableDiv).remove()};Mautic.createOption=function(value,label){return mQuery('<option/>').attr('value',value).text(label)}
Mautic.updateFieldOperatorValue=function(field,action,valueOnChange,valueOnChangeArguments){var fieldId=mQuery(field).attr('id');Mautic.activateLabelLoadingIndicator(fieldId);if(fieldId.indexOf('_operator')!==-1){var fieldType='operator'}else if(fieldId.indexOf('_field')!==-1){var fieldType='field'}else{return}
var fieldPrefix=fieldId.slice(0,-1*fieldType.length);var fieldAlias=mQuery('#'+fieldPrefix+'field').val();var fieldOperator=mQuery('#'+fieldPrefix+'operator').val();Mautic.ajaxActionRequest(action,{'alias':fieldAlias,'operator':fieldOperator,'changed':fieldType},function(response){if(typeof response.options!='undefined'){var valueField=mQuery('#'+fieldPrefix+'value');var valueFieldAttrs={'class':valueField.attr('class'),'id':valueField.attr('id'),'name':valueField.attr('name').replace(/\[\]$/,''),'autocomplete':valueField.attr('autocomplete'),'value':valueField.val()};if(mQuery('#'+fieldPrefix+'value_chosen').length){valueFieldAttrs.value='';Mautic.destroyChosen(valueField)}
if(!mQuery.isEmptyObject(response.options)&&response.fieldType!=='number'){var newValueField=mQuery('<select/>').attr('class',valueFieldAttrs['class']).attr('id',valueFieldAttrs.id).attr('name',valueFieldAttrs.name).attr('autocomplete',valueFieldAttrs.autocomplete).attr('value',valueFieldAttrs.value).removeAttr('multiple');var multiple=(fieldOperator==='in'||fieldOperator==='!in');if(multiple){newValueField.attr('multiple','multiple');var newName=newValueField.attr('name')+'[]';newValueField.attr('name',newName);newValueField.attr('data-placeholder',mauticLang.chosenChooseMore)}
mQuery.each(response.options,function(value,optgroup){if(typeof optgroup==='object'){var optgroupEl=mQuery('<optgroup/>').attr('label',value);mQuery.each(optgroup,function(optVal,label){var option=Mautic.createOption(optVal,label);if(response.optionsAttr&&response.optionsAttr[optVal]){mQuery.each(response.optionsAttr[optVal],function(optAttr,optVal){option.attr(optAttr,optVal)})}
optgroupEl.append(option)});newValueField.append(optgroupEl)}else{var option=Mautic.createOption(value,optgroup);if(response.optionsAttr&&response.optionsAttr[value]){mQuery.each(response.optionsAttr[value],function(optAttr,optVal){option.attr(optAttr,optVal)})}
newValueField.append(option)}});newValueField.val(valueFieldAttrs.value);valueField.replaceWith(newValueField);Mautic.activateChosenSelect(newValueField)}else{var newValueField=mQuery('<input/>').attr('type','text').attr('class',valueFieldAttrs['class']).attr('id',valueFieldAttrs.id).attr('name',valueFieldAttrs.name).attr('autocomplete',valueFieldAttrs.autocomplete).attr('value',valueFieldAttrs.value);if(response.disabled){newValueField.attr('value','');newValueField.prop('disabled',!0)}
valueField.replaceWith(newValueField);if(response.fieldType=='date'||response.fieldType=='datetime'){Mautic.activateDateTimeInputs(newValueField,response.fieldType)}}
if(valueOnChange&&typeof valueOnChange=='function'){mQuery('#'+fieldPrefix+'value').on('change',function(){if(typeof valueOnChangeArguments!='object'){valueOnChangeArguments=[]}
valueOnChangeArguments.unshift(mQuery('#'+fieldPrefix+'value'));valueOnChange.apply(null,valueOnChangeArguments)})}
if(!mQuery.isEmptyObject(response.operators)){var operatorField=mQuery('#'+fieldPrefix+'operator');Mautic.destroyChosen(operatorField);var operatorFieldAttrs={'class':operatorField.attr('class'),'id':operatorField.attr('id'),'name':operatorField.attr('name'),'autocomplete':operatorField.attr('autocomplete'),'value':operatorField.val()};var newOperatorField=mQuery('<select/>').attr('class',operatorFieldAttrs['class']).attr('id',operatorFieldAttrs.id).attr('name',operatorFieldAttrs.name).attr('autocomplete',operatorFieldAttrs.autocomplete).attr('value',operatorFieldAttrs.value).attr('onchange','Mautic.updateLeadFieldValues(this)');mQuery.each(response.operators,function(optionVal,optionKey){newOperatorField.append(Mautic.createOption(optionKey,optionVal))});newOperatorField.val(operatorField.val());operatorField.replaceWith(newOperatorField);Mautic.activateChosenSelect(newOperatorField)}}
Mautic.removeLabelLoadingIndicator()},!1,!1,"POST")};if(typeof Chart!='undefined'){Chart.defaults.global.elements.line.borderWidth=2;Chart.defaults.global.elements.point.radius=0;Chart.defaults.global.legend.labels.boxWidth=12;Chart.defaults.global.maintainAspectRatio=!1;Chart.defaults.scale.ticks.padding=10;Chart.defaults.global.elements.point.hoverRadius=6;Chart.defaults.global.elements.point.hitRadius=20;Chart.defaults.global.legend.labels.usePointStyle=!0;Chart.defaults.global.legend.labels.pointStyle='circle'}
Mautic.renderCharts=function(scope){var charts=[];if(!Mautic.chartObjects)Mautic.chartObjects=[];if(mQuery.type(scope)==='string'){charts=mQuery(scope).find('canvas.chart')}else if(scope){charts=scope.find('canvas.chart')}else{charts=mQuery('canvas.chart')}
if(charts.length){charts.each(function(index,canvas){canvas=mQuery(canvas);if(!canvas.hasClass('chart-rendered')){if(canvas.hasClass('line-chart')){Mautic.renderLineChart(canvas)}else if(canvas.hasClass('pie-chart')){Mautic.renderPieChart(canvas)}else if(canvas.hasClass('bar-chart')){Mautic.renderBarChart(canvas)}else if(canvas.hasClass('liefechart-bar-chart')){Mautic.renderLifechartBarChart(canvas)}else if(canvas.hasClass('simple-bar-chart')){Mautic.renderSimpleBarChart(canvas)}else if(canvas.hasClass('horizontal-bar-chart')){Mautic.renderHorizontalBarChart(canvas)}else if(canvas.hasClass('hour-chart')){Mautic.renderHourChart(canvas)}}
canvas.addClass('chart-rendered')})}};Mautic.renderLineChart=function(canvas){var data=JSON.parse(canvas.text());if(!data.labels.length||!data.datasets.length)return;var chart=new Chart(canvas,{type:'line',data:data,options:{lineTension:0.2,borderWidth:1,tooltips:{mode:'index',intersect:!1},scales:{xAxes:[{gridLines:{display:!1},ticks:{maxRotation:0,callback:function(value,index,values){if(index===0||index===values.length-1){return value}
return''}}}],yAxes:[{afterBuildTicks:function(scale){scale.ticks=[];scale.ticks.push(scale.min);scale.ticks.push((scale.max-scale.min)/2);scale.ticks.push(scale.max)},gridLines:{drawBorder:!1,},ticks:{beginAtZero:!0,callback:function(value,index,values){if(index===0||index===values.length-1){return value}
if(/^\d+\.5$/.test(value.toString())){return''}
if(index===Math.floor(values.length/2)){return value!==0.5?value:''}
return''}}}]}}});Mautic.chartObjects.push(chart)};Mautic.renderHourChart=function(canvas){const data=JSON.parse(canvas.text());const chart=new Chart(canvas,{type:'line',data,options:{tooltips:{mode:'index',intersect:!1},scales:{xAxes:[{gridLines:{display:!1},ticks:{autoSkip:!0,maxTicksLimit:6,maxRotation:0,callback:value=>value.split(' - ')[0]}}],yAxes:[{afterBuildTicks:scale=>{scale.ticks=[scale.min,(scale.max-scale.min)/2,scale.max]},gridLines:{drawBorder:!1},ticks:{beginAtZero:!0,callback:(value,index,values)=>{if(index===0||index===values.length-1)return value;if(/^\d+\.5$/.test(value.toString()))return'';if(index===Math.floor(values.length/2))return value!==0.5?value:'';return''}}}]}}});Mautic.chartObjects.push(chart)};Mautic.renderPieChart=function(canvas){var data=JSON.parse(canvas.text());var options={borderWidth:1};var disableLegend=canvas.attr('data-disable-legend');if(typeof disableLegend!=='undefined'&&disableLegend!==!1){options.legend={display:!1}}
var chart=new Chart(canvas,{type:'pie',data:data,options:options});Mautic.chartObjects.push(chart)};Mautic.renderBarChart=function(canvas){var data=JSON.parse(canvas.text());var chart=new Chart(canvas,{type:'bar',data:data,options:{scales:{xAxes:[{barPercentage:0.9,}]}}});Mautic.chartObjects.push(chart)};Mautic.renderLifechartBarChart=function(canvas){var canvasWidth=mQuery(canvas).parent().width();var barWidth=(canvasWidth<300)?5:25;var data=JSON.parse(canvas.text());var chart=new Chart(canvas,{type:'bar',data:data,options:{scales:{xAxes:[{barThickness:barWidth,}]}}});Mautic.chartObjects.push(chart)};Mautic.renderSimpleBarChart=function(canvas){var data=JSON.parse(canvas.text());var chart=new Chart(canvas,{type:'bar',data:data,options:{scales:{xAxes:[{stacked:!1,ticks:{fontSize:9},gridLines:{display:!1},}],yAxes:[{display:!1,stacked:!1,ticks:{beginAtZero:!0,display:!1},gridLines:{display:!1}}],display:!1},legend:{display:!1}}});Mautic.chartObjects.push(chart)};Mautic.renderHorizontalBarChart=function(canvas){var data=JSON.parse(canvas.text());var chart=new Chart(canvas,{type:'horizontalBar',data:data,options:{scales:{xAxes:[{display:!0,stacked:!1,gridLines:{display:!1},ticks:{beginAtZero:!0,display:!0,fontSize:8,stepSize:5}}],yAxes:[{stacked:!1,ticks:{beginAtZero:!0,display:!0,fontSize:9},gridLines:{display:!1},barPercentage:0.5,categorySpacing:1}],display:!1},legend:{display:!1},tooltips:{mode:'single',bodyFontSize:9,bodySpacing:0,callbacks:{title:function(tooltipItems,data){return''},label:function(tooltipItem,data){return tooltipItem.xLabel+': '+tooltipItem.yLabel}}}}});Mautic.chartObjects.push(chart)};Mautic.initDateRangePicker=function(fromId,toId){var dateFrom=mQuery(fromId);var dateTo=mQuery(toId);if(dateFrom.length&&dateTo.length){dateFrom.datetimepicker({format:'M j, Y',onShow:function(ct){this.setOptions({maxDate:dateTo.val()?new Date(dateTo.val()):!1})},timepicker:!1,scrollMonth:!1,scrollInput:!1});dateTo.datetimepicker({format:'M j, Y',onShow:function(ct){this.setOptions({maxDate:new Date(),minDate:dateFrom.val()?new Date(dateFrom.val()):!1})},timepicker:!1,scrollMonth:!1,scrollInput:!1})}};Mautic.getChartData=function(element,action,query,callback){var element=mQuery(element);var wrapper=element.closest('ul');var button=mQuery('#time-scopes .button-label');wrapper.find('a').removeClass('bg-primary');element.addClass('bg-primary');button.text(element.text());query=query+'&action='+action;mQuery.ajax({showLoadingBar:!0,url:mauticAjaxUrl,type:'POST',data:query,dataType:"json",success:function(response){if(response.success){Mautic.stopPageLoadingBar();if(typeof callback=='function'){callback(response)}else if(typeof window.Mautic[callback]!=='undefined'){window.Mautic[callback].apply('window',[response])}}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)}})};Mautic.emulateNoDataForPieChart=function(data){var dataEmpty=!0;mQuery.each(data,function(i,part){if(part.value){dataEmpty=!1}});if(dataEmpty){data=[{value:1,color:"#efeeec",highlight:"#EBEBEB",label:"No data"}]}
return data};Mautic.modalContentXhr={};Mautic.activeModal='';Mautic.backgroundedModal='';Mautic.ajaxifyModal=function(el,event){let element=mQuery(el);if(element.hasClass('disabled')){return!1}
mQuery('body').addClass('noscroll');let target=element.attr('data-target');let route=element.attr('data-href')?element.attr('data-href'):element.attr('href');if(route.indexOf('javascript')>=0){return!1}
let method=element.attr('data-method')?element.attr('data-method'):'GET';let header=element.attr('data-header');let footer=element.attr('data-footer');let modalOpenCallback=element.attr('data-modal-open-callback')?element.attr('data-modal-open-callback'):null;let modalCloseCallback=element.attr('data-modal-close-callback')?element.attr('data-modal-close-callback'):null;let preventDismissal=element.attr('data-prevent-dismiss');let formData=element.data('form-data')?element.data('form-data'):{};if(preventDismissal){element.removeAttr('data-prevent-dismiss')}
let modalOpenCallbackReal=null;if(modalOpenCallback&&window.Mautic.hasOwnProperty(modalOpenCallback)){modalOpenCallbackReal=function(){Mautic[modalOpenCallback](el)}}
let modalCloseCallbackReal=null;if(modalCloseCallback&&window.Mautic.hasOwnProperty(modalOpenCallback)){modalCloseCallbackReal=function(){Mautic[modalCloseCallback](el)}}
Mautic.loadAjaxModal(target,route,method,header,footer,preventDismissal,modalOpenCallbackReal,modalCloseCallbackReal,formData)};Mautic.loadAjaxModal=function(target,route,method,header,footer,preventDismissal,modalOpenCallback,modalCloseCallback,formData={}){let element=mQuery(target);if(element.find('.loading-placeholder').length){element.find('.loading-placeholder').removeClass('hide');element.find('.modal-body-content').addClass('hide');if(element.find('.modal-loading-bar').length){element.find('.modal-loading-bar').addClass('active')}}
if(footer=='false'){element.find(".modal-footer").addClass('hide')}
element.one('show.bs.modal',function(){if(header){element.find(".modal-title").text(header)}
if(footer&&footer!='false'){element.find(".modal-footer").html(header)}
if(modalOpenCallback){modalOpenCallback()}});element.one('hidden.bs.modal',function(){if(typeof Mautic.modalContentXhr[target]!='undefined'){Mautic.modalContentXhr[target].abort();delete Mautic.modalContentXhr[target]}
mQuery('body').removeClass('noscroll');let response={};if(Mautic.modalMauticContent){response.mauticContent=Mautic.modalMauticContent;delete Mautic.modalMauticContent}
if(modalCloseCallback){modalCloseCallback()}
Mautic.onPageUnload(target,response);Mautic.resetModal(target)});if(typeof element.data('bs.modal')!=='undefined'&&typeof element.data('bs.modal').options!=='undefined'){if(preventDismissal){element.data('bs.modal').options.keyboard=!1;element.data('bs.modal').options.backdrop='static'}else{element.data('bs.modal').options.keyboard=!0;element.data('bs.modal').options.backdrop=!0}}else{if(preventDismissal){element.modal({backdrop:'static',keyboard:!1})}else{element.modal({backdrop:!0,keyboard:!0})}}
Mautic.showModal(target);if(typeof Mautic.modalContentXhr=='undefined'){Mautic.modalContentXhr={}}else if(typeof Mautic.modalContentXhr[target]!='undefined'){Mautic.modalContentXhr[target].abort()}
Mautic.modalContentXhr[target]=mQuery.ajax({url:route,type:method,dataType:"json",data:formData,success:function(response){if(response){Mautic.processModalContent(response,target)}
Mautic.stopIconSpinPostEvent()},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown,null,target);Mautic.stopIconSpinPostEvent()},complete:function(){Mautic.stopModalLoadingBar(target);delete Mautic.modalContentXhr[target]}})};Mautic.resetModal=function(target){if(mQuery(target).hasClass('in')){return}
mQuery(target+" .modal-title").html('');mQuery(target+" .modal-body-content").html('');if(mQuery(target+" loading-placeholder").length){mQuery(target+" loading-placeholder").removeClass('hide')}
if(mQuery(target+" .modal-footer").length){var hasFooterButtons=mQuery(target+" .modal-footer .modal-form-buttons").length;mQuery(target+" .modal-footer").html('');if(hasFooterButtons){mQuery('<div class="modal-form-buttons" />').appendTo(target+" .modal-footer")}
mQuery(target+" .modal-footer").removeClass('hide')}};Mautic.processModalContent=function(response,target){Mautic.stopIconSpinPostEvent();if(response.error){if(response.errors){alert(response.errors[0].message)}else if(response.error.message){alert(response.error.message)}else{alert(response.error)}
return}
if(response.sessionExpired||(response.closeModal&&response.newContent&&!response.updateModalContent)){mQuery(target).modal('hide');mQuery('body').removeClass('modal-open');mQuery('.modal-backdrop').remove();Mautic.processPageContent(response)}else{if(response.notifications){Mautic.setNotifications(response.notifications)}
if(response.callback){window.Mautic[response.callback].apply('window',[response]);return}
if(response.target){mQuery(response.target).html(response.newContent);Mautic.onPageLoad(response.target,response,!0)}else if(response.newContent){if(mQuery(target+' .loading-placeholder').length){mQuery(target+' .loading-placeholder').addClass('hide');mQuery(target+' .modal-body-content').html(response.newContent);mQuery(target+' .modal-body-content').removeClass('hide')}else{mQuery(target+' .modal-body').html(response.newContent)}}
Mautic.onPageLoad(target,response,!0);Mautic.modalMauticContent=!1;if(response.closeModal){mQuery('body').removeClass('noscroll');mQuery(target).modal('hide');if(!response.updateModalContent){Mautic.onPageUnload(target,response)}}else{Mautic.modalMauticContent=response.mauticContent?response.mauticContent:!1}}};Mautic.showConfirmation=function(el,customMessage){var precheck=mQuery(el).data('precheck');if(precheck){if(typeof precheck=='function'){if(!precheck()){return}}else if(typeof Mautic[precheck]=='function'){if(!Mautic[precheck]()){return}}}
var message=customMessage??mQuery(el).data('message');var confirmText=mQuery(el).data('confirm-text');var confirmAction=mQuery(el).attr('href');var confirmCallback=mQuery(el).data('confirm-callback');var cancelText=mQuery(el).data('cancel-text');var cancelCallback=mQuery(el).data('cancel-callback');const confirmBtnClass=mQuery(el).data('confirm-btn-class')?mQuery(el).data('confirm-btn-class'):'btn btn-danger';var confirmContainer=mQuery("<div />").attr({"class":"modal fade confirmation-modal"});var confirmDialogDiv=mQuery("<div />").attr({"class":"modal-dialog"});var confirmContentDiv=mQuery("<div />").attr({"class":"modal-content"});var confirmFooterDiv=mQuery("<div />").attr({"class":"modal-body text-center"});var confirmHeaderDiv=mQuery("<div />").attr({"class":"modal-header"});confirmHeaderDiv.append(mQuery('<h4 />').attr({"class":"modal-title"}).text(message));var confirmButton=mQuery('<button type="button" />').attr("id","confirm").addClass(confirmBtnClass).css("marginRight","5px").css("marginLeft","5px").click(function(){if(typeof Mautic[confirmCallback]==="function"){window.Mautic[confirmCallback].apply('window',[confirmAction,el])}}).html(confirmText);if(cancelText){var cancelButton=mQuery('<button type="button" />').addClass("btn btn-primary").click(function(){if(cancelCallback&&typeof Mautic[cancelCallback]==="function"){window.Mautic[cancelCallback].apply('window',[el])}else{Mautic.dismissConfirmation()}}).html(cancelText)}
if(typeof cancelButton!='undefined'){confirmFooterDiv.append(cancelButton)}
if(confirmText){confirmFooterDiv.append(confirmButton)}
confirmContentDiv.append(confirmHeaderDiv);confirmContentDiv.append(confirmFooterDiv);confirmContainer.append(confirmDialogDiv.append(confirmContentDiv));mQuery('body').append(confirmContainer);mQuery('.confirmation-modal').on('hidden.bs.modal',function(){mQuery(this).remove()});mQuery('.confirmation-modal').modal('show')};Mautic.dismissConfirmation=function(){if(mQuery('.confirmation-modal').length){mQuery('.confirmation-modal').modal('hide')}};Mautic.closeModalAndRedirect=function(el,url){Mautic.startModalLoadingBar(el);Mautic.loadContent(url);mQuery('body').removeClass('noscroll')};Mautic.loadAjaxModalBySelectValue=function(el,value,route,header){var selectVal=mQuery(el).val();var hasValue=(selectVal==value);if(!hasValue&&mQuery.isArray(selectVal)){hasValue=(mQuery.inArray(value,selectVal)!==-1)}
if(hasValue){route=route+(route.indexOf('?')>-1?'&':'?')+'modal=1&contentOnly=1&updateSelect='+mQuery(el).attr('id');mQuery(el).find('option[value="'+value+'"]').prop('selected',!1);mQuery(el).trigger("chosen:updated");Mautic.loadAjaxModal('#MauticSharedModal',route,'get',header)}};Mautic.showModal=function(target){if(mQuery('.modal.in').length){if(mQuery(target).closest('.modal').length){mQuery('<div />').attr('data-modal-placeholder',target).insertAfter(mQuery(target));mQuery(target).attr('data-modal-moved',1);mQuery(target).appendTo('body')}
var activeModal=mQuery('.modal.in .modal-dialog:not(:has(.aside))').parents('.modal').last(),targetModal=mQuery(target);if(activeModal.length&&activeModal.attr('id')!==targetModal.attr('id')){targetModal.attr('data-previous-modal','#'+activeModal.attr('id'));activeModal.find('.modal-dialog').addClass('aside');var stackedDialogCount=mQuery('.modal.in .modal-dialog.aside').length;if(stackedDialogCount<=5){activeModal.find('.modal-dialog').addClass('aside-'+stackedDialogCount)}
mQuery(target).on('hide.bs.modal',function(){var modal=mQuery(this);var previous=modal.attr('data-previous-modal');if(previous){mQuery(previous).find('.modal-dialog').removeClass('aside');mQuery(modal).attr('data-previous-modal',undefined)}
if(mQuery(modal).attr('data-modal-moved')){mQuery('[data-modal-placeholder]').replaceWith(mQuery(modal));mQuery(modal).attr('data-modal-moved',undefined)}})}}
mQuery(target).modal('show')};MauticVars.liveCache=new Array();MauticVars.lastSearchStr="";MauticVars.globalLivecache=new Array();MauticVars.lastGlobalSearchStr="";Mautic.isNewEntity=function(idInputSelector){id=mQuery(idInputSelector);if(id.length){return id.val().match("^new_")}
return null};Mautic.getEntityId=function(){return(mQuery('input#entityId').length)?mQuery('input#entityId').val():0};Mautic.reorderTableData=function(name,orderby,tmpl,target,baseUrl){if(typeof baseUrl=='undefined'){baseUrl=window.location.pathname;baseUrl=baseUrl.replace(/\/\d+$/,'/1')}
var params=[];if(tmpl){params.push('tmpl='+tmpl)}
if(name){params.push('name='+name)}
if(orderby){params.push('orderby='+encodeURIComponent(orderby))}
var route=baseUrl+(params.length?'?'+params.join('&'):'');Mautic.loadContent(route,'','POST',target)};Mautic.filterTableData=function(name,filterby,filterValue,tmpl,target,baseUrl){if(typeof baseUrl=='undefined'){baseUrl=window.location.pathname}
if(baseUrl.indexOf('tmpl')==-1){baseUrl=baseUrl+"?tmpl="+tmpl}
var value='';if(mQuery.isArray(filterValue)){for(var i=0;i<filterValue.length;i++){value+='&value[]='+encodeURIComponent(filterValue[i])}}else{value="&value="+encodeURIComponent(filterValue)}
var route=baseUrl+"&name="+name+"&filterby="+encodeURIComponent(filterby)+value
Mautic.loadContent(route,'','POST',target)};Mautic.limitTableData=function(name,limit,tmpl,target,baseUrl){if(typeof baseUrl=='undefined'){baseUrl=window.location.pathname}
if(baseUrl.indexOf('tmpl')==-1){baseUrl=baseUrl+"?tmpl="+tmpl}
var route=baseUrl+"&name="+name+"&limit="+limit;Mautic.loadContent(route,'','POST',target)};Mautic.filterList=function(e,elId,route,target,liveCacheVar,action,overlayEnabled,overlayTarget){if(typeof liveCacheVar=='undefined'){liveCacheVar="liveCache"}
var el=mQuery('#'+elId);if(el.length&&(e.data.livesearch||mQuery(e.target).prop('tagName')=='BUTTON'||mQuery(e.target).parent().prop('tagName')=='BUTTON')){var value=el.val().trim();if(!value){action='clear'}else if(action=='clear'){el.val('');el.typeahead('val','');value=''}
if(!1&&value&&value in MauticVars[liveCacheVar]){var response={"newContent":MauticVars[liveCacheVar][value]};response.target=target;response.overlayEnabled=overlayEnabled;response.overlayTarget=overlayTarget;Mautic.processPageContent(response)}else{var searchName=el.attr('name');if(searchName=='undefined'){searchName='search'}
if(typeof Mautic.liveSearchXhr!=='undefined'){Mautic.liveSearchXhr.abort('searchCompleted')}
var btn="button[data-livesearch-parent='"+elId+"']";if(mQuery(btn).length&&!mQuery(btn).hasClass('btn-nospin')&&!Mautic.filterButtonClicked){Mautic.startIconSpinOnEvent(btn)}
var tmpl=mQuery('#'+elId).data('tmpl');if(!tmpl){tmpl='list'}
var tmplParam=(route.indexOf('tmpl')==-1)?'&tmpl='+tmpl:'';var checkInModalTarget=(overlayTarget)?overlayTarget:target;var modalParent=mQuery(checkInModalTarget).closest('.modal');var inModal=mQuery(modalParent).length>0;if(inModal){var modalTarget='#'+mQuery(modalParent).attr('id');Mautic.startModalLoadingBar(modalTarget)}
var showLoading=(inModal)?!1:!0;Mautic.liveSearchXhr=mQuery.ajax({showLoadingBar:showLoading,url:route,type:"GET",data:searchName+"="+encodeURIComponent(value)+tmplParam,dataType:"json",success:function(response){if(response.newContent){MauticVars[liveCacheVar][value]=response.newContent}
response.target=target;response.overlayEnabled=overlayEnabled;response.overlayTarget=overlayTarget;if(mQuery(btn).length){if(action=='clear'){mQuery(btn).attr('data-livesearch-action','search');mQuery(btn).children('i').first().removeClass('ri-eraser-line').addClass('ri-search-line')}else{mQuery(btn).attr('data-livesearch-action','clear');mQuery(btn).children('i').first().removeClass('ri-search-line').addClass('ri-eraser-line')}}
if(inModal){Mautic.processModalContent(response);Mautic.stopModalLoadingBar(modalTarget)}else{Mautic.processPageContent(response);Mautic.stopPageLoadingBar()}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown);if(mQuery(btn).length){if(action=='clear'){mQuery(btn).attr('data-livesearch-action','search');mQuery(btn).children('i').first().removeClass('ri-eraser-line').addClass('ri-search-line')}else{mQuery(btn).attr('data-livesearch-action','clear');mQuery(btn).children('i').first().removeClass('ri-search-line').addClass('ri-eraser-line')}}},complete:function(){delete Mautic.liveSearchXhr;delete Mautic.filterButtonClicked}})}}};Mautic.setSearchFilter=function(el,searchId,string){if(typeof searchId=='undefined')
searchId='#list-search';else searchId='#'+searchId;if(string||string===''){var current=string}else{var filter=mQuery(el).val();var current=mQuery('#list-search').typeahead('val')+" "+filter}
mQuery(searchId).typeahead('val',current);var e=mQuery.Event("keypress",{which:13});e.data={};e.data.livesearch=!0;Mautic.filterList(e,'list-search',mQuery(searchId).attr('data-action'),mQuery(searchId).attr('data-target'),'liveCache')};Mautic.unlockEntity=function(model,id,parameter){mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:"action=unlockEntity&model="+model+"&id="+id+"&parameter="+parameter,dataType:"json"})};Mautic.togglePublishStatus=function(event,el,model,id,extra,backdrop){event.preventDefault();var wasPublished=mQuery(el).hasClass('ri-toggle-fill');var element=mQuery(el);element.removeClass('ri-toggle-fill ri-toggle-line').addClass('ri-spin ri-loader-3-line');element.tooltip('destroy');MauticVars.liveCache=new Array();if(backdrop){Mautic.activateBackdrop()}
if(extra){extra='&'+extra}
element.tooltip('destroy');mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:"action=togglePublishStatus&model="+model+'&id='+id+extra,dataType:"json",success:function(response){if(response.reload){Mautic.redirectWithBackdrop(window.location)}else if(response.statusHtml){element.replaceWith(response.statusHtml);element.tooltip({html:!0,container:'body'})}},error:function(request,textStatus,errorThrown){var addClass=(wasPublished)?'ri-toggle-fill':'ri-toggle-line';element.removeClass('ri-spin ri-loader-3-line').addClass(addClass);Mautic.processAjaxError(request,textStatus,errorThrown)}})};Mautic.executeBatchAction=function(action,el){if(typeof Mautic.activeActions=='undefined'){Mautic.activeActions={}}else if(typeof Mautic.activeActions[action]!='undefined'){return}
var items=Mautic.getCheckedListIds(el,!0);var queryGlue=action.indexOf('?')>=0?'&':'?';var action=action+queryGlue+'ids='+items;Mautic.executeAction(action)};Mautic.batchActionPrecheck=function(container){if(typeof container=='undefined'){container=''}
return mQuery(container+' input[class=list-checkbox]:checked').length};Mautic.getCheckedListIds=function(el,stringify){var checkboxes='input[class=list-checkbox]:checked';if(typeof el!='undefined'&&el){var target=mQuery(el).data('target');if(target){checkboxes=target+' '+checkboxes}}
var items=mQuery(checkboxes).map(function(){return mQuery(this).val()}).get();if(stringify){items=JSON.stringify(items)}
return items};Mautic.builderTokensForCkEditor={};Mautic.builderTokens={};Mautic.dynamicContentTokens={};Mautic.builderTokensRequestInProgress=!1;Mautic.imageManagerLoadURL=mauticBaseUrl+'s/file/list';Mautic.imageUploadURL=mauticBaseUrl+'s/file/upload';Mautic.imageManagerDeleteURL=mauticBaseUrl+'s/file/delete';Mautic.elfinderURL=mauticBaseUrl+'elfinder';Mautic.initAtWho=function(element,method){if(Mautic.builderTokensRequestInProgress){var intervalID=setInterval(function(){if(!Mautic.builderTokensRequestInProgress){clearInterval(intervalID);Mautic.configureAtWho(element,method)}},500)}else{Mautic.configureAtWho(element,method)}};Mautic.configureAtWho=function(element,method){Mautic.getTokens(method,function(tokens){element.atwho('destroy');Mautic.configureDynamicContentAtWhoTokens();mQuery.extend(tokens,Mautic.dynamicContentTokens);element.atwho({at:'{',displayTpl:'<li>${name} <small>${id}</small></li>',insertTpl:"${id}",editableAtwhoQueryAttrs:{"data-fr-verified":!0},data:mQuery.map(tokens,function(value,i){return{'id':i,'name':value}}),acceptSpaceBar:!0})})};Mautic.getTokens=function(method,callback){if(!mQuery.isEmptyObject(Mautic.builderTokens)){return callback(Mautic.builderTokens)}
Mautic.builderTokensRequestInProgress=!0;mQuery.ajax({url:mauticAjaxUrl,data:'action='+method,success:function(response){if(typeof response.tokens==='object'){Mautic.builderTokens=response.tokens;callback(response.tokens)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.builderTokensRequestInProgress=!1}})};Mautic.configureDynamicContentAtWhoTokens=function(){Mautic.dynamicContentTokens={};var dynamicContentTabs=mQuery('#dynamicContentTabs');if(dynamicContentTabs.length===0&&window.parent){dynamicContentTabs=mQuery(window.parent.document.getElementById('dynamicContentTabs'))}
if(dynamicContentTabs.length){dynamicContentTabs.find('a[data-toggle="tab"]').each(function(){var tokenText=mQuery(this).text();var prototype='{dynamiccontent="__tokenName__"}';var newOption=prototype.replace(/__tokenName__/g,tokenText);Mautic.dynamicContentTokens[newOption]=tokenText})}};Mautic.insertHtmlInEditor=function(obj,html){const ckEditor=ckEditors.get(obj[0]);const viewFragment=ckEditor.data.processor.toView(html);const modelFragment=ckEditor.data.toModel(viewFragment);ckEditor.model.change(writer=>{const insertPosition=ckEditor.model.document.selection.getFirstPosition();writer.insert(modelFragment,insertPosition)})};Mautic.MentionLinks=function(editor){editor.conversion.for('upcast').elementToAttribute({view:{name:'span',key:'data-fr-verified',classes:'atwho-inserted'},model:{key:'mention',value:viewItem=>editor.plugins.get('Mention').toMentionAttribute(viewItem)},converterPriority:'high'});editor.conversion.for('downcast').attributeToElement({model:'mention',view:(modelAttributeValue,{writer})=>{if(!modelAttributeValue){return}
return writer.createAttributeElement('span',{class:'atwho-inserted','data-fr-verified':!0},{priority:20,id:modelAttributeValue.uid})},converterPriority:'high'})}
Mautic.customItemRenderer=function(item){let tokenId=item.id;let tokenName=item.name;const itemElement=document.createElement('span');const idElement=document.createElement('span');idElement.classList.add('custom-item-id');itemElement.classList.add('custom-item');if(tokenName.startsWith('a:')){tokenName=tokenName.substring(2)}
if(tokenId.match(/dwc=/i)){const tn=tokenId.substr(5,tokenId.length-6);tokenName=tokenName+' ('+tn+')'}else if(tokenId.match(/contactfield=company/i)&&!tokenName.match(/company/i)){tokenName='Company '+tokenName}
itemElement.textContent=tokenName;idElement.textContent=tokenId;itemElement.appendChild(idElement);return itemElement}
Mautic.getFeedItems=function(queryText){return new Promise(resolve=>{setTimeout(()=>{const itemsToDisplay=Mautic.builderTokensForCkEditor.filter(isItemMatching).slice(0,5);resolve(itemsToDisplay)},100)});function isItemMatching(item){const searchString=queryText.toLowerCase();return(item.name.toLowerCase().includes(searchString)||item.id.toLowerCase().includes(searchString))}}
Mautic.getTokensForPlugIn=function(method){method=typeof method!='undefined'?method:'page:getBuilderTokens';mQuery.ajax({url:mauticAjaxUrl,data:'action='+method,async:!1,success:function(response){if(typeof response.tokens==='object'){Mautic.builderTokens=response.tokens;Mautic.configureDynamicContentAtWhoTokens();mQuery.extend(Mautic.builderTokens,Mautic.dynamicContentTokens);Mautic.builderTokensForCkEditor=mQuery.map(Mautic.builderTokens,function(value,i){return{'id':i,'name':value}})}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.builderTokensRequestInProgress=!1}});return Mautic.builderTokensForCkEditor};Mautic.getCKEditorFonts=function(fonts){fonts=Array.isArray(fonts)?fonts:[];const CKEditorFonts=[];for(let i=0;i<fonts.length;i++){if('undefined'!=typeof fonts[i].font){CKEditorFonts.push(fonts[i].font)}}
return CKEditorFonts}
Mautic.ConvertFieldToCkeditor=function(textarea,ckEditorToolbarOptions){if(ckEditors.has(textarea[0])){ckEditors.get(textarea[0]).destroy();ckEditors.delete(textarea[0])}
const tokenCallback=textarea.attr('data-token-callback');Mautic.InitCkEditor(textarea,Mautic.GetCkEditorConfigOptions(ckEditorToolbarOptions,tokenCallback,textarea))}
Mautic.GetCkEditorConfigOptions=function(ckEditorToolbarOptions,tokenCallback,textarea=null){const defaultOptions=['undo','redo','|','bold','italic','underline','heading','fontfamily','fontsize','fontColor','fontBackgroundColor','alignment','numberedList','bulletedList','blockQuote','removeFormat','link','ckfinder','mediaEmbed','insertTable','sourceEditing'];const ckEditorToolbar=typeof ckEditorToolbarOptions!="undefined"&&ckEditorToolbarOptions.length>0?ckEditorToolbarOptions:defaultOptions;const ckEditorColors=[{color:'#000000',label:'Black'},{color:'#4d4d4d',label:'Dim grey'},{color:'#999999',label:'Grey'},{color:'#e6e6e6',label:'Light grey'},{color:'#ffffff',label:'White',hasBorder:!0},{color:'#e64c4c',label:'Red'},{color:'#e6994c',label:'Orange'},{color:'#e6e64c',label:'Yellow'},{color:'#99e64c',label:'Light green'},{color:'#4ce64c',label:'Green'},{color:'#4ce699',label:'Aquamarine'},{color:'#4ce6e6',label:'Turquoise'},{color:'#4c99e6',label:'Light blue'},{color:'#4c4ce6',label:'Blue'},{color:'#994ce6',label:'Purple'}];const allowFullHtml=textarea&&typeof textarea.attr('allow-full-html')!=='undefined';const ckEditorOption={toolbar:{items:ckEditorToolbar,shouldNotGroupWhenFull:!0},fontFamily:{options:Mautic.getCKEditorFonts(mauticEditorFonts),shouldNotGroupWhenFull:!0},fontSize:{options:[8,9,10,11,12,14,18,24,30,36,48,72],supportAllValues:!0},fontColor:{colorPicker:{format:'hex'},colors:ckEditorColors},fontBackgroundColor:{colorPicker:{format:'hex'},colors:ckEditorColors},link:{allowCreatingEmptyLinks:!0,decorators:{openInNewTab:{mode:'manual',label:'Open in a new tab',attributes:{target:'_blank',rel:'noopener noreferrer'}}},allowedProtocols:['https?','tel','sms','sftp','smb','slack']},htmlSupport:{fullPage:{allowRenderStylesFromHead:allowFullHtml},allow:allowFullHtml?[{name:/.*/,attributes:!0,classes:!0,styles:!0}]:[{name:/^(a|span)$/,attributes:!0,classes:!0,styles:!0}],},};mQuery.extend(ckEditorOption,{autosave:{save(editor){editor.updateSourceElement()}}});if(ckEditorToolbar.indexOf('ckfinder')>-1){mQuery.extend(ckEditorOption,{ckfinder:{uploadUrl:Mautic.imageUploadURL+'?editor=ckeditor'},image:{toolbar:['imageResize','imageTextAlternative','|','imageStyle:inline','imageStyle:block','imageStyle:side','|','linkImage'],}})}else{mQuery.extend(ckEditorOption,{removePlugins:["Image","ImageCaption","ImageInsert","ImageResize","ImageStyle","ImageToolbar","AutoImage","ImageInline"]})}
if(ckEditorToolbar.indexOf('insertTable')>-1){mQuery.extend(ckEditorOption,{table:{contentToolbar:['tableColumn','tableRow','mergeTableCells']}})}
if(ckEditorToolbar.indexOf('TokenPlugin')>-1){const tokens=Mautic.getTokensForPlugIn(tokenCallback);mQuery.extend(ckEditorOption,{extraPlugins:[Mautic.MentionLinks],dynamicTokenLabel:'Insert token',dynamicToken:tokens,mention:{feeds:[{marker:'{',feed:Mautic.getFeedItems,itemRenderer:Mautic.customItemRenderer}]}})}
return ckEditorOption}
Mautic.InitCkEditor=function(textarea,options){ClassicEditor.create(textarea[0],options).then(editor=>{ckEditors.set(textarea[0],editor);if(textarea.hasClass('editor-advanced')||textarea.hasClass('editor-basic-fullpage')){editor.editing.view.document.on('change:isFocused',(evt,data,isFocused)=>{Mautic.showChangeThemeWarning=isFocused})}
const ckf=editor.commands.get('ckfinder');if(ckf){ckf.execute=()=>{const width=screen.width*0.7;const height=screen.height*0.7;const iLeft=(screen.width-width)/2;const iTop=(screen.height-height)/2;let sOptions="toolbar=no,status=no,resizable=yes,dependent=yes";sOptions+=",width="+width;sOptions+=",height="+height;sOptions+=",left="+iLeft;sOptions+=",top="+iTop;const elPopup=window.open(Mautic.elfinderURL+'?editor=ckeditor',"BrowseWindow",sOptions);elPopup.addEventListener('load',function(){elPopup.editor=editor})}}}).catch(err=>{console.error(err.stack)})}
window.document.ckEditorInsertImages=function(editor,imageUrl){const ntf=editor.plugins.get('Notification'),i18=editor.locale.t,imgCmd=editor.commands.get('imageUpload');if(!imgCmd.isEnabled){ntf.showWarning(i18('Could not insert image at the current position.'),{title:i18('Inserting image failed'),namespace:'ckfinder'});return}
editor.execute('imageInsert',{source:imageUrl})};Mautic.overflowNavOptions={"parent":".nav-overflow-tabs","more":Mautic.translate('mautic.core.tabs.more')};Mautic.toggleTabPublished=function(el){if(mQuery(el).val()==="1"&&mQuery(el).prop('checked')){Mautic.publishTab(el)}else{Mautic.unpublishTab(el)}}
Mautic.publishTab=function(tab){mQuery('a[href="#'+Mautic.getTabId(tab)+'"]').find('.fa').removeClass('text-secondary').addClass('text-success')};Mautic.unpublishTab=function(tab){mQuery('a[href="#'+Mautic.getTabId(tab)+'"]').find('.fa').removeClass('text-success').addClass('text-secondary')};Mautic.getTabId=function(tab){if(!mQuery(tab).hasClass('tab-pane')){tab=mQuery(tab).closest('.tab-pane')}
return mQuery(tab).attr('id')};Mautic.activateOverflowTabs=function(tabs,options){if(!options){options={}}
var localOptions=Mautic.overflowNavOptions;mQuery.extend(localOptions,options);mQuery(tabs).overflowNavs(localOptions);var resizeMe=function(tabs,options){mQuery(window).on('resize',{tabs:tabs,options:options},function(event){mQuery(event.data.tabs).overflowNavs(event.data.options)})};resizeMe(tabs,localOptions)};Mautic.activateSortableTabs=function(tabs){mQuery(tabs).sortable({container:'ul.nav',axis:mQuery(tabs).hasClass('tabs-right')||mQuery(tabs).hasClass('tabs-left')?'y':'x',stop:function(e,ui){var action=mQuery(tabs).attr('data-sort-action');mQuery.ajax({type:"POST",url:action,data:mQuery(tabs).sortable("serialize",{attribute:'data-tab-id'})})}})};Mautic.activateTabDeleteButtons=function(container){mQuery(container+" .nav.nav-deletable>li a").each(function(){Mautic.activateTabDeleteButton(this)})};Mautic.activateTabDeleteButton=function(tab){var btn=mQuery('<span class="btn btn-danger btn-xs btn-delete pull-right hide"><i class="ri-close-line"></i></span>').on('click',function(){return Mautic.deleteTab(btn)}).appendTo(tab);mQuery(tab).hover(function(){mQuery(btn).removeClass('hide')},function(){mQuery(btn).addClass('hide')})};Mautic.deleteTab=function(deleteBtn){var tab=mQuery(deleteBtn).closest('li');var tabContent=mQuery(deleteBtn).closest('a').attr('href');var parent=mQuery(tab).closest('ul');var wasActive=(mQuery(tab.hasClass('active')));var action=mQuery(parent).attr('data-delete-action');if(action){var success=!1;mQuery.ajax({url:action,type:'POST',dataType:"json",data:{tab:tabContent},success:function(response){if(response&&response.success){mQuery(tab).remove();mQuery(tabContent).remove();if(wasActive){mQuery(parent).find('li:first a').click()}
if(!mQuery(parent).find('li').length){mQuery('.tab-content .placeholder').removeClass('hide')}}else{Mautic.stopIconSpinPostEvent()}}})}else{mQuery(tab).remove();mQuery(tabContent).remove();if(wasActive){mQuery(parent).find('li:first a').click()}
if(!mQuery(parent).find('li').length){mQuery('.tab-content .placeholder').removeClass('hide')}}
return!1};Mautic.initTabsScroll=function(){mQuery('.nav-tabs').each(function(){var $navTabs=mQuery(this);if($navTabs.parent().hasClass('nav-tabs-wrapper')){return}
var $navTabsWrapper=mQuery('<div class="nav-tabs-wrapper"></div>');$navTabs.wrap($navTabsWrapper);$navTabsWrapper=$navTabs.parent('.nav-tabs-wrapper');var $leftBtn=mQuery('<button type="button" class="scroll-btn left-btn"><i class="ri-arrow-left-wide-line"></i></button>');var $rightBtn=mQuery('<button type="button" class="scroll-btn right-btn"><i class="ri-arrow-right-wide-line"></i></button>');$navTabsWrapper.append($leftBtn);$navTabsWrapper.append($rightBtn);var scrollAmount=150;function updateButtons(){var scrollLeft=$navTabs.scrollLeft();var maxScrollLeft=$navTabs[0].scrollWidth-$navTabs[0].clientWidth;if(maxScrollLeft>0){$navTabsWrapper.addClass('show-scroll-buttons')}else{$navTabsWrapper.removeClass('show-scroll-buttons')}
$leftBtn.prop('disabled',scrollLeft<=0);$rightBtn.prop('disabled',scrollLeft>=(maxScrollLeft-1))}
$leftBtn.on('click',function(event){event.preventDefault();event.stopPropagation();$navTabs.animate({scrollLeft:$navTabs.scrollLeft()-scrollAmount},300,updateButtons)});$rightBtn.on('click',function(event){event.preventDefault();event.stopPropagation();$navTabs.animate({scrollLeft:$navTabs.scrollLeft()+scrollAmount},300,updateButtons)});$navTabs.on('scroll',updateButtons);mQuery(window).on('resize',debounce(updateButtons,100));updateButtons()})};function debounce(func,wait){let timeout;return function(){clearTimeout(timeout);timeout=setTimeout(func,wait)}}
mQuery(document).ready(function(){Mautic.initTabsScroll()});mQuery(document).ajaxComplete(function(event,xhr,settings){Mautic.initTabsScroll()});Mautic.contentVersions={};Mautic.versionNamespace='';Mautic.currentContentVersion=-1;Mautic.prepareVersioning=function(undoCallback,redoCallback,namespace){if(!Mautic.isLocalStorageSupported()){mQuery('.btn-undo').prop('disabled',!0);mQuery('.btn-redo').prop('disabled',!0);return}
mQuery('.btn-undo').prop('disabled',!1).on('click',function(){Mautic.undoVersion(undoCallback)});mQuery('.btn-redo').prop('disabled',!1).on('click',function(){Mautic.redoVersion(redoCallback)});Mautic.currentContentVersion=-1;if(!namespace){namespace=window.location.href}
if(typeof Mautic.contentVersions[namespace]=='undefined'){Mautic.contentVersions[namespace]=[]}
Mautic.versionNamespace=namespace;console.log(namespace)};Mautic.clearVersioning=function(){if(!Mautic.versionNamespace){throw 'Versioning not configured'}
if(typeof Mautic.contentVersions[Mautic.versionNamespace]!=='undefined'){delete Mautic.contentVersions[Mautic.versionNamespace]}
Mautic.versionNamespace='';Mautic.currentContentVersion=-1};Mautic.storeVersion=function(content){if(!Mautic.versionNamespace){throw 'Versioning not configured'}
Mautic.contentVersions[Mautic.versionNamespace].push(content);Mautic.currentContentVersion=Mautic.contentVersions[Mautic.versionNamespace].length};Mautic.undoVersion=function(callback){console.log('undo');if(!Mautic.versionNamespace){throw 'Versioning not configured'}
if(Mautic.currentContentVersion<0){return}
var version=Mautic.currentContentVersion-1;if(Mautic.getVersion(version,callback)){--Mautic.currentContentVersion}};Mautic.redoVersion=function(callback){console.log('redo');if(!Mautic.versionNamespace){throw 'Versioning not configured'}
if(Mautic.currentContentVersion<0||Mautic.contentVersions[Mautic.versionNamespace].length===Mautic.currentContentVersion){return}
var version=Mautic.currentContentVersion+1;if(Mautic.getVersion(version,callback)){++Mautic.currentContentVersion}};Mautic.getVersion=function(version,callback){var content=!1;if(typeof Mautic.contentVersions[Mautic.versionNamespace][version]!=='undefined'){content=Mautic.contentVersions[Mautic.versionNamespace][version]}
if(!1!==content&&typeof callback=='function'){callback(content);return!0}
return!1};Mautic.contentPreviewUrlGenerator={urlBase:'email/preview',lastUsedObjectId:!1,contactId:!1,init(){this.lastUsedObjectId=mQuery('#content_preview_settings_object_id').val()},getElementValue(element){const value=element.val()
if(value===undefined||value.length===0){return!1}
return value},setElementValue(elementId,value){const element=mQuery(elementId);const hasOption=mQuery(elementId+' option[value="'+value+'"]');if(hasOption.length>0){element.val(value)}else{element.val("")}
mQuery(element).trigger('chosen:updated')},regenerateUrl:function(newValue,changedElement){this.urlBase=mQuery("#content_preview_url").attr('data-route');changedElement=mQuery(changedElement);const elementId=changedElement.attr('id');const value=this.getElementValue(changedElement);if(elementId==='content_preview_settings_variant'){this.setElementValue('#content_preview_settings_translation',value)}
if(elementId==='content_preview_settings_translation'){this.setElementValue('#content_preview_settings_variant',value)}
if(elementId==='content_preview_settings_contact_id'){if(newValue===''){this.contactId=!1}else{this.contactId=value}
newValue=this.lastUsedObjectId}else if(value!==!1){this.lastUsedObjectId=newValue=value}
let previewUrl=mauticBaseUrl+this.urlBase+'/'+newValue;if(this.contactId!==!1){previewUrl=previewUrl+'?contactId='+this.contactId}
mQuery('#content_preview_url').val(previewUrl);mQuery('#content_preview_url_button').attr('onClick',"window.open('"+previewUrl+"', '_blank');")}}
Mautic.updatePreviewContactLookupListFilter=function(field,item){if(item&&item.id){mQuery('#content_preview_settings_contact_id').val(item.id);mQuery(field).val(item.value);Mautic.contentPreviewUrlGenerator.regenerateUrl(item.id,mQuery('#content_preview_settings_contact_id'))}};Mautic.activatePreviewContactLookupField=function(fieldOptions,filterId){const lookupElementId='content_preview_settings_contact';const action=mQuery('#'+lookupElementId).attr('data-chosen-lookup');const options={limit:20,'searchKey':'lead.lead',};Mautic.activateFieldTypeahead(lookupElementId,filterId,options,action);Mautic.contentPreviewUrlGenerator.init();mQuery('#content_preview_settings_contact').on('change',function(event){if(event.target.value===''){Mautic.contentPreviewUrlGenerator.regenerateUrl('',mQuery('#content_preview_settings_contact_id'));mQuery('#content_preview_settings_contact_id').val('')}})};'use strict';Mautic.Marketplace={installPackage:(vendorName,packageName,successCallback,errorCallback)=>{mQuery.ajax({showLoadingBar:!0,url:mauticAjaxUrl+`?action=marketplace:installPackage`,type:'POST',data:JSON.stringify({vendor:vendorName,package:packageName}),dataType:'json',success:successCallback,error:errorCallback})},removePackage:(vendorName,packageName,successCallback,errorCallback)=>{mQuery.ajax({showLoadingBar:!0,url:mauticAjaxUrl+`?action=marketplace:removePackage`,type:'POST',data:JSON.stringify({vendor:vendorName,package:packageName}),dataType:'json',success:successCallback,error:errorCallback})},};class MauticMap{static TYPES={'markers':0,'regions':1,};static SETTINGS={backgroundColor:'transparent',zoomOnScroll:!1,zoomAnimate:!0,markerStyle:{initial:{fill:'#40C7B5'},selected:{fill:'#40C7B5'}},regionStyle:{initial:{"fill":'#dce0e5',"fill-opacity":1,"stroke":'none',"stroke-width":0,"stroke-opacity":1},hover:{"fill-opacity":0.7,"cursor":'pointer'}},map:'world_mill_en',series:{regions:[{scale:['#b9ebe4','#40C7B5'],normalizeFunction:'polynomial',}]},onRegionOver:()=>{document.body.style.cursor='pointer'},onRegionOut:()=>{document.body.style.cursor='default'}}
constructor(wrapper,typeKey='regions'){this.type=MauticMap.TYPES[typeKey];this.scope=mQuery(wrapper);this.mapData=this.getMapData();this.settings=MauticMap.SETTINGS;this.map=this.getMapsInScope();this.legendEnabled=this.isLegendEnabled();this.statUnit=this.getStatUnitFromItem(this.map);this.settings.onRegionTipShow=(event,label,index)=>{if(this.mapData){const value=this.mapData[index];if(value>0){const tooltip=`<b>${label.html()}</b></br>${value} ${this.statUnit}${(value > 1) ? 's' : ''}`;label.html(tooltip)}}}
if(this.legendEnabled){this.settings.series.regions[0].legend={horizontal:!0,title:'<div data-map-legend="true"></div>',}}
this.mapOptions=this.scope.find('[data-map-option]')}
init(){this.initSeries(this.mapData);this.initMap()}
initSeries(data){if(this.type===MauticMap.TYPES.regions){this.settings.series.regions[0].values=data;this.settings.markers={}}
if(this.type===MauticMap.TYPES.markers){this.settings.series.regions[0].values={};this.settings.markers=data}}
isLegendEnabled(){return this.map.data('legend-enabled')}
getMapsInScope(){return this.scope.find('.vector-map')}
getStatUnitFromItem(item){return mQuery(item).data('stat-unit')}
setStatUnit(value){this.statUnit=value}
getMapData(){const map=this.getMapsInScope();let data=map.data('map-data');if(typeof data==='undefined'||!data.length){try{data=JSON.parse(map.text());map.data('map-data',data)
map.attr('data-map-data',JSON.stringify(data))}catch(error){return{}}}
return data}
renderMap(){if(this.scope.is(':visible')){this.map.text('');this.map.vectorMap(this.settings);mQuery(this.map).addClass('map-rendered')}};destroyMap(){if(this.map.length){const mapObj=this.map.vectorMap('get','mapObject');if(mapObj){mapObj.removeAllMarkers();mapObj.remove();this.map.empty();this.map.removeClass('map-rendered')}}};getOptionLegendText(option){return option.data('legend-text')}
addMapOptionsListener(){if(this.mapOptions.length){mQuery(this.mapOptions).on('click',(event)=>{const currentOption=mQuery(event.currentTarget);const newValues=currentOption.data('map-series');const legendText=this.getOptionLegendText(currentOption);const statUnit=this.getStatUnitFromItem(currentOption);this.setMapValues(newValues);this.setActiveOption(currentOption);if(this.legendEnabled){this.setLegend(legendText)}
if(statUnit){this.setStatUnit(statUnit)}});if(this.legendEnabled){const defaultOption=mQuery(this.mapOptions[0]);const legendText=this.getOptionLegendText(defaultOption);this.setLegend(legendText)}}}
setActiveOption(option){this.mapOptions.removeClass('active');option.addClass('active')}
setLegend(legendText){const mapLegend=this.scope.find('[data-map-legend]');mQuery(mapLegend).text(legendText)}
setMapValues(values){const mapObject=this.map.vectorMap('get','mapObject');const dataSeries=mapObject.series.regions[0];this.mapData=values;mapObject.reset();if(this.type===MauticMap.TYPES.regions&&dataSeries){this.unsetExtremeValues(dataSeries);dataSeries.setValues(values)}else if(this.type===MauticMap.TYPES.markers){this.settings.markers[0].setValues(values)}}
unsetExtremeValues(dataSeries){dataSeries.params.min=undefined;dataSeries.params.max=undefined}
initMap(){if(this.scope.length){if(this.scope.children('.map-rendered').length){return}
const map=this.getMapsInScope()
this.renderMap(map);this.addMapOptionsListener()}}}
Mautic.initMap=(wrapper,typeKey)=>{const map=new MauticMap(wrapper,typeKey);map.init();if(!Mautic.mapObjects)Mautic.mapObjects=[];Mautic.mapObjects.push(map);return map};Mautic.clientOnLoad=function(container){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','api.client')}};Mautic.refreshApiClientForm=function(url,modeEl){var mode=mQuery(modeEl).val();if(mQuery('#client_redirectUris').length){mQuery('#client_redirectUris').prop('disabled',!0)}else{mQuery('#client_callback').prop('disabled',!0)}
mQuery('#client_name').prop('disabled',!0);Mautic.loadContent(url+'/'+mode)};Mautic.assetOnLoad=function(container){if(typeof mauticAssetUploadEndpoint!=='undefined'&&typeof Mautic.assetDropzone=='undefined'&&mQuery('div#dropzone').length){Mautic.initializeDropzone()}};Mautic.assetOnUnload=function(id){if(id==='#app-content'){delete Mautic.assetDropzone}};Mautic.updateRemoteBrowser=function(provider,path){path=typeof path!=='undefined'?path:'';var spinner=mQuery('<i class="ri-loader-3-line ri-spin ri-fw"></i>');spinner.appendTo('#tab'+provider+' a');mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:"action=asset:fetchRemoteFiles&provider="+provider+"&path="+path,dataType:"json",success:function(response){if(response.success){mQuery('div#remoteFileBrowser').html(response.output);mQuery('.remote-file-search').quicksearch('#remoteFileBrowser .remote-file-list a')}else{const flashMessage=Mautic.addErrorFlashMessage(response.message);Mautic.setFlashes(flashMessage)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){spinner.remove()}})};Mautic.selectRemoteFile=function(url){mQuery('#asset_remotePath').val(url);mQuery('#RemoteFileModal').modal('hide')};Mautic.changeAssetStorageLocation=function(){if(mQuery('#asset_storageLocation_0').prop('checked')){mQuery('#storage-local').removeClass('hide');mQuery('#storage-remote').addClass('hide');mQuery('#remote-button').addClass('hide')}else{mQuery('#storage-local').addClass('hide');mQuery('#storage-remote').removeClass('hide');mQuery('#remote-button').removeClass('hide')}};Mautic.initializeDropzone=function(){var options={url:mauticAssetUploadEndpoint,uploadMultiple:!1,filesizeBase:1024,init:function(){this.on("addedfile",function(){if(this.files[1]!=null){this.removeFile(this.files[0])}})}};if(typeof mauticAssetUploadMaxSize!=='undefined'){options.maxFilesize=mauticAssetUploadMaxSize}
if(typeof mauticAssetUploadMaxSizeError!=='undefined'){options.dictFileTooBig=mauticAssetUploadMaxSizeError}
if(typeof mauticAssetUploadExtensions!=='undefined'){options.acceptedFiles=mauticAssetUploadExtensions}
if(typeof mauticAssetUploadExtensionError!=='undefined'){options.dictInvalidFileType=mauticAssetUploadExtensionError}
Mautic.assetDropzone=new Dropzone("div#dropzone",options);var preview=mQuery('.preview div.text-center');Mautic.assetDropzone.on("sending",function(file,request,formData){request.setRequestHeader('X-CSRF-Token',mauticAjaxCsrf);formData.append('tempId',mQuery('#asset_tempId').val())}).on("addedfile",function(file){preview.fadeOut('fast')}).on("success",function(file,response,progress){if(response.tmpFileName){mQuery('#asset_tempName').val(response.tmpFileName)}
var messageArea=mQuery('.mdropzone-error');if(response.error||!response.tmpFileName){if(!response.error){var errorText=''}else{var errorText=(typeof response.error=='object')?response.error.text:response.error}
messageArea.text(errorText);messageArea.closest('.form-group').addClass('has-error').removeClass('is-success');var node,_i,_len,_ref,_results;file.previewElement.classList.add('dz-error');_ref=file.previewElement.querySelectorAll('data-dz-errormessage');_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){node=_ref[_i];_results.push(node.textContent=errorText)}
return _results}else{messageArea.text('');messageArea.closest('.form-group').removeClass('has-error').addClass('is-success')}
var titleInput=mQuery('#asset_title');if(file.name&&!titleInput.val()){titleInput.val(file.name)}
if(file.name){mQuery('#asset_originalFileName').val(file.name)}}).on("error",function(file,response){preview.fadeIn('fast');var messageArea=mQuery('.mdropzone-error');if(typeof response=="string"){response={'error':response}}
if(response.error){if(!response.error){var errorText=''}else{var errorText=(typeof response.error=='object')?response.error.text:response.error}
messageArea.text(errorText);messageArea.closest('.form-group').addClass('has-error').removeClass('is-success');var node,_i,_len,_ref,_results;file.previewElement.classList.add('dz-error');_ref=file.previewElement.querySelectorAll('[data-dz-errormessage]');_results=[];for(_i=0,_len=_ref.length;_i<_len;_i++){node=_ref[_i];_results.push(node.textContent=errorText)}
return _results}}).on("thumbnail",function(file,url){if(file.accepted===!0){var extension=file.name.substr((file.name.lastIndexOf('.')+1)).toLowerCase();var previewContent='';if(mQuery.inArray(extension,['jpg','jpeg','gif','png'])!==-1){previewContent=mQuery('<img />').addClass('img-thumbnail').attr('src',url)}else if(extension==='pdf'){previewContent=mQuery('<iframe />').attr('src',url)}
preview.empty().html(previewContent);preview.fadeIn('fast')}})};Mautic.changeIconToSpinner=function(iconElement){if(iconElement&&iconElement.length){iconElement.removeClass('fa-times').addClass('fa-spinner fa-spin')}};Mautic.campaignEventDeleteModal={modal:null,confirmButton:null,finalConfirmButton:null,cancelButton:null,redirectSelect:null,redirectLabel:null,warningDiv:null,init:function(){this.modal=mQuery('#campaignEventDeleteModal');this.confirmButton=mQuery('#campaignEventDeleteConfirm');this.finalConfirmButton=mQuery('#campaignEventDeleteFinalConfirm');this.cancelButton=mQuery('#campaignEventDeleteCancel');this.redirectSelect=mQuery('#campaignEventDeleteRedirect');this.redirectLabel=mQuery('#campaignEventDeleteRedirectLabel');this.warningDiv=mQuery('#campaignEventDeleteWarning');this.modal.modal({show:!1,backdrop:!0,keyboard:!0});this.finalConfirmButton.off('click');this.confirmButton.off('click');this.cancelButton.off('click');this.modal.off('hidden.bs.modal');this.confirmButton.on('click',()=>{if(this.confirmButton.prop('disabled')){return}
const selectedEventId=this.redirectSelect.val();if(!selectedEventId){this.redirectSelect.addClass('error');this.warningDiv.removeClass('alert-warning').addClass('alert-danger').show();this.warningDiv.find('.warning-message').html(Mautic.translate('mautic.campaign.event.delete.select_redirect'));this.finalConfirmButton.hide();this.cancelButton.hide();return}
this.redirectSelect.removeClass('error');this.warningDiv.removeClass('alert-danger').addClass('alert-warning');this.confirmButton.prop('disabled',!0);const warningMessage=Mautic.translate('mautic.campaign.event.delete.confirmation');this.warningDiv.find('.warning-message').text(warningMessage);this.warningDiv.show()});this.cancelButton.on('click',()=>{this.warningDiv.hide();this.confirmButton.prop('disabled',!1)});this.finalConfirmButton.off('click').on('click',()=>{const eventId=mQuery('#campaignEventDeleteTarget').val();const redirectTo=this.redirectSelect.val();const deleteUrl=mQuery('#campaignEventDeleteUrl').val();this.modal.find('button').prop('disabled',!0);this.deleteEventWithRedirect(eventId,deleteUrl,redirectTo)});this.modal.on('hidden.bs.modal',()=>{this.redirectSelect.removeClass('error');this.warningDiv.hide().removeClass('alert-danger').addClass('alert-warning');this.confirmButton.removeClass('btn-default').addClass('btn-danger').prop('disabled',!1);this.modal.find('button').prop('disabled',!1);this.finalConfirmButton.show();this.cancelButton.show();this.redirectSelect.val('');mQuery('.btns-builder').find('button').prop('disabled',!1);const sourceButton=this.modal.data('sourceButton');if(sourceButton&&sourceButton.length){sourceButton.find('i').removeClass('fa-spinner fa-spin').addClass('fa-times')}else{const $deleteIcons=mQuery("#CampaignCanvas .list-campaign-event a[data-toggle='ajax-delete'] i");$deleteIcons.each(function(){const $icon=mQuery(this);if($icon.hasClass('fa-spinner')){$icon.removeClass('fa-spinner fa-spin').addClass('fa-times')}})}
mQuery('#campaignEventDeleteTarget').val('');mQuery('#campaignEventDeleteUrl').val('');mQuery('#campaignEventDeleteCampaignId').val('');this.modal.removeData('sourceButton');setTimeout(()=>{if(typeof Mautic.campaignBuilderInstance!=='undefined'){mQuery("#CampaignCanvas .list-campaign-event a[data-toggle='ajax-delete']").each(function(){mQuery(this).off('click.ajax').on('click.ajax',Mautic.handleEventDeleteClick)})}},100)})},populateEventOptions:function(currentEventId){this.redirectSelect.empty();const availableEvents=Mautic.getCampaignBuilderEventOptions(currentEventId);if(availableEvents.length===0){this.redirectLabel.html(`<span class='text-danger'>${Mautic.translate('mautic.campaign.event.delete.unable_delete_last')}</span>`);this.redirectSelect.removeClass('required');this.confirmButton.removeClass('btn-danger').addClass('btn-default').text(Mautic.translate('mautic.campaign.event.delete'));this.confirmButton.prop('disabled',!0);this.warningDiv.removeClass('alert-warning').addClass('alert-danger').show();this.warningDiv.find('.warning-message').html(Mautic.translate('mautic.campaign.event.delete.last_event'));this.finalConfirmButton.hide();this.cancelButton.hide();this.redirectSelect.closest('.form-group').addClass('hide');return}
this.finalConfirmButton.show();this.cancelButton.show();this.redirectLabel.html(`${Mautic.translate('mautic.campaign.event.delete.redirect_contacts')} <span class='text-danger'>*</span>`);this.confirmButton.removeClass('btn-default').addClass('btn-danger').text(Mautic.translate('mautic.campaign.event.delete.redirect_event'));this.confirmButton.prop('disabled',!1);this.redirectSelect.closest('.form-group').removeClass('hide');mQuery.each(availableEvents,(index,event)=>{const optionLabel='('+event.eventType.charAt(0).toUpperCase()+event.eventType.slice(1).toLowerCase()+') '+event.name;mQuery("<option />",{value:event.id,text:optionLabel}).appendTo(this.redirectSelect)});if(this.redirectSelect.find('option').length>0){this.redirectSelect.find('option').first().prop('selected',!0)}
if(this.redirectSelect.data('chosen')){this.redirectSelect.trigger('chosen:updated')}
this.warningDiv.hide()},hasDelay:function(eventId){if(typeof Mautic.campaignBuilderCanvasEvents==='undefined'||!Mautic.campaignBuilderCanvasEvents[eventId]){return!1}
const event=Mautic.campaignBuilderCanvasEvents[eventId];return!(event.triggerMode&&event.triggerMode==='immediate')},isRedirectTarget:function(eventId){if(Mautic.campaignBuilderCampaignElements.deletedEvents){for(let i=0;i<Mautic.campaignBuilderCampaignElements.deletedEvents.length;i++){if(Mautic.campaignBuilderCampaignElements.deletedEvents[i].redirectEvent===eventId){return!0}}}
if(typeof Mautic.campaignBuilderCanvasEvents!=='undefined'&&Mautic.campaignBuilderCanvasEvents[eventId]&&typeof Mautic.campaignBuilderCanvasEvents[eventId].isRedirectTarget!=='undefined'){return Mautic.campaignBuilderCanvasEvents[eventId].isRedirectTarget}
return!1},handleNewEventDeletion:function(eventId){if(typeof Mautic.campaignBuilderInstance!=='undefined'){Mautic.campaignBuilderInstance.remove(document.getElementById('CampaignEvent_'+eventId))}
if(Mautic.campaignBuilderCanvasEvents[eventId]){Mautic.campaignBuilderCanvasEvents[eventId].deleted=!0}
if(typeof Mautic.campaignBuilderCampaignElements.modifiedEvents!=='undefined'){delete Mautic.campaignBuilderCampaignElements.modifiedEvents[eventId]}
delete Mautic.campaignBuilderEventPositions['CampaignEvent_'+eventId];const deleteButton=mQuery('#CampaignEvent_'+eventId).find('a[data-toggle="ajax-delete"] i');if(deleteButton.length){deleteButton.removeClass('fa-spinner fa-spin').addClass('fa-times')}},shouldBypassModal:function(eventId){if(typeof Mautic.campaignBuilderCanvasEvents==='undefined'||!Mautic.campaignBuilderCanvasEvents[eventId]){return!1}
const event=Mautic.campaignBuilderCanvasEvents[eventId];if(event.eventType==='decision'||this.isRedirectTarget(eventId)){return!1}
return!this.hasDelay(eventId)},openForEvent:function(eventId,deleteUrl,campaignId){if(eventId.startsWith('new')){this.handleNewEventDeletion(eventId);return}
const shouldBypass=this.shouldBypassModal(eventId);if(shouldBypass){this.deleteEventDirectly(eventId,deleteUrl)}else{this.showModalForEventDelete(eventId,deleteUrl,campaignId)}},showModalForEventDelete:function(eventId,deleteUrl,campaignId){this.warningDiv.hide().removeClass('alert-danger').addClass('alert-warning');this.modal.find('button').prop('disabled',!1);mQuery('#campaignEventDeleteTarget').val(eventId);mQuery('#campaignEventDeleteUrl').val(deleteUrl);mQuery('#campaignEventDeleteCampaignId').val(campaignId);this.populateEventOptions(eventId);const modalOptions={backdrop:!0,keyboard:!0};const deleteButton=mQuery('#CampaignEvent_'+eventId).find('a[data-toggle="ajax-delete"]');this.modal.data('sourceButton',deleteButton).modal(modalOptions).modal('show')},deleteEventDirectly:function(eventId,deleteUrl){const deleteButton=mQuery('#CampaignEvent_'+eventId).find('a[data-toggle="ajax-delete"]');const iconElement=deleteButton.find('i');Mautic.startIconSpinOnEvent(deleteButton);Mautic.campaignBuilderDeleteEvent(eventId,null,deleteUrl,(response)=>{Mautic.stopIconSpinPostEvent();if(!response.success){alert(response.message||Mautic.translate('mautic.campaign.event.delete.error'));if(iconElement&&iconElement.length){iconElement.removeClass('fa-spinner fa-spin').addClass('fa-times')}}},(response)=>{Mautic.stopIconSpinPostEvent();alert(Mautic.translate('mautic.campaign.event.delete.generic_error'));if(iconElement&&iconElement.length){iconElement.removeClass('fa-spinner fa-spin').addClass('fa-times')}})},deleteEventWithRedirect:function(eventId,deleteUrl,redirectEventId){const deleteButton=mQuery('#CampaignEvent_'+eventId).find('a[data-toggle="ajax-delete"]');Mautic.startIconSpinOnEvent(deleteButton);Mautic.campaignBuilderDeleteEvent(eventId,redirectEventId,deleteUrl,(response)=>{Mautic.stopIconSpinPostEvent();if(response.success){this.modal.modal('hide')}else{this.warningDiv.removeClass('alert-warning').addClass('alert-danger');this.warningDiv.find('.warning-message').text(response.message||Mautic.translate('mautic.campaign.event.delete.error'));this.modal.find('button').prop('disabled',!1)}},(response)=>{Mautic.stopIconSpinPostEvent();this.warningDiv.removeClass('alert-warning').addClass('alert-danger');this.warningDiv.find('.warning-message').text(Mautic.translate('mautic.campaign.event.delete.generic_error'));this.modal.find('button').prop('disabled',!1)})}};Mautic.getCampaignBuilderEventOptions=function(currentEventId){const availableEvents=[];if(typeof Mautic.campaignBuilderCanvasEvents!=='undefined'){for(const eventId in Mautic.campaignBuilderCanvasEvents){const event=Mautic.campaignBuilderCanvasEvents[eventId];if(eventId!==currentEventId&&!event.deleted&&!eventId.startsWith('new')&&event.eventType!=='decision'){availableEvents.push({id:eventId,name:event.name,eventType:event.eventType})}}}
return availableEvents};Mautic.reinitializeCampaignEventDeleteHandlers=function(){if(typeof Mautic.campaignEventDeleteModal!=='undefined'){Mautic.campaignEventDeleteModal.init()}
mQuery("#CampaignCanvas .list-campaign-event a[data-toggle='ajax-delete']").each(function(){mQuery(this).off('click.ajax').on('click.ajax',Mautic.handleEventDeleteClick)})};Mautic.ensureCampaignEventHandlers=function(){if(mQuery('#CampaignCanvas').length){Mautic.reinitializeCampaignEventDeleteHandlers();if(typeof Mautic.campaignBuilderInstance!=='undefined'){Mautic.campaignBuilderInstance.repaintEverything()}}};mQuery(document).ready(function(){Mautic.campaignEventDeleteModal.init();mQuery(document).on('mauticCampaignBuilderCanvasLoaded',function(){Mautic.ensureCampaignEventHandlers()})});Mautic.handleEventDeleteClick=function(event){event.preventDefault();const $deleteLink=mQuery(this);const $iconElement=$deleteLink.find('i');Mautic.changeIconToSpinner($iconElement);const parentId=$deleteLink.closest('.list-campaign-event').attr('id');const eventId=parentId.replace('CampaignEvent_','');const deleteUrl=$deleteLink.attr('href');const campaignId=mQuery('#campaignId').val();Mautic.campaignEventDeleteModal.openForEvent(eventId,deleteUrl,campaignId)};Mautic.campaignOnLoad=function(container,response){Mautic.lazyLoadGraphStatsOnCampaignDetail();Mautic.lazyLoadContactListOnCampaignDetail();Mautic.lazyLoadEventStatsOnCampaignDetail();const $flashes=mQuery('#flashes');const $builder=mQuery('#campaign-builder');const isCampaignPreview=$builder.hasClass('preview');Mautic.campaignBuilderPostData=[];let extraData={};Mautic.reinitializeCampaignEventDeleteHandlers();if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','campaign')}
if(mQuery('#CampaignEventPanel').length){var tooltipTimeout=null;mQuery('#CampaignEventPanelGroups button').on('click',function(){var eventType=mQuery(this).data('type');Mautic.campaignBuilderUpdateEventList([eventType],!1,'lists',!0)});mQuery('#CampaignEventPanelLists button').on('click',function(){Mautic.campaignBuilderUpdateEventList(Mautic.campaignBuilderAnchorClickedAllowedEvents,!0,'groups',!0)});if(!isCampaignPreview){mQuery('#CampaignCanvas .list-campaign-event, #CampaignCanvas .list-campaign-source').off('.eventbuttons').on('mouseover.eventbuttons',function(){mQuery(this).find('.campaign-event-buttons').removeClass('hide')}).on('mouseout.eventbuttons',function(){mQuery(this).find('.campaign-event-buttons').addClass('hide')}).on('dblclick.eventbuttons',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()});mQuery("#CampaignCanvas .list-campaign-event a[data-toggle='ajax-delete']").on("click.ajax",Mautic.handleEventDeleteClick);mQuery("#CampaignCanvas .list-campaign-source a[data-toggle='ajax-delete']").on("click.ajax",function(event){event.preventDefault();mQuery('.btns-builder').find('button').prop('disabled',!0);extraData={'modifiedSources':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedSources),};return Mautic.ajaxifyLink(this,event,extraData)});mQuery("#CampaignCanvas .list-campaign-source a[data-toggle='ajaxmodal']").off('click.ajaxmodal');mQuery("#CampaignCanvas .list-campaign-source a[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();mQuery('.btns-builder').find('button').prop('disabled',!0);mQuery(this).data('form-data',{'modifiedSources':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedSources),});Mautic.ajaxifyModal(this,event)});mQuery("#CampaignCanvas .list-campaign-event a[data-toggle='ajaxmodal']").off('click.ajaxmodal');mQuery("#CampaignCanvas .list-campaign-event a[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();mQuery('.btns-builder').find('button').prop('disabled',!0);mQuery(this).data('form-data',{"modifiedEvents":JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedEvents),'deletedEvents':Mautic.campaignBuilderCampaignElements.deletedEvents?JSON.stringify(Mautic.campaignBuilderCampaignElements.deletedEvents):'',});Mautic.ajaxifyModal(this,event)})}
mQuery('.campaign-event-selector').on('chosen:showing_dropdown',function(event){mQuery('.builder-content').css('overflow','hidden');var thisSelect=mQuery(event.target).attr('id');Mautic.campaignBuilderUpdateEventListTooltips(thisSelect,!1);mQuery('#'+thisSelect+'_chosen .chosen-search input').on('keydown.tooltip',function(){Mautic.campaignBuilderUpdateEventListTooltips(thisSelect,!0)}).on('keyup.tooltip',function(){if(tooltipTimeout){clearTimeout(tooltipTimeout)}
tooltipTimeout=setTimeout(function(){Mautic.campaignBuilderUpdateEventListTooltips(thisSelect,!1)},200)})});mQuery('.campaign-event-selector').on('chosen:hiding_dropdown',function(event){mQuery('.builder-content').css('overflow','auto');var thisSelect=mQuery(event.target).attr('id');Mautic.campaignBuilderUpdateEventListTooltips(thisSelect,!0);mQuery('#'+thisSelect+'_chosen .chosen-search input').off('keyup.tooltip').off('keydown.tooltip')});mQuery('.campaign-event-selector').on('change',function(){if(!mQuery('#CampaignEvent_newsource').length){Mautic.hideCampaignEventPanel()}
var thisId=mQuery(this).attr('id');var option=mQuery('#'+thisId+' option[value="'+mQuery(this).val()+'"]');if(option.attr('data-href')&&Mautic.campaignBuilderAnchorNameClicked){var updatedUrl=option.attr('data-href').replace(/anchor=(.*?)$/,"anchor="+Mautic.campaignBuilderAnchorNameClicked+"&anchorEventType="+Mautic.campaignBuilderAnchorEventTypeClicked);option.attr('data-href',updatedUrl)}
mQuery('#'+thisId).trigger('chosen:close');Mautic.ajaxifyModal(option);mQuery(this).val('');mQuery(this).trigger('chosen:updated')});mQuery('#CampaignCanvas').on('click',function(event){if(!mQuery(event.target).parents('#CampaignCanvas').length&&!mQuery('#CampaignEvent_newsource').length){Mautic.hideCampaignEventPanel()}});$builder.on('campaign-builder:show',function(){$builder.addClass('builder-active').removeClass('hide');$flashes.addClass('alert-offset')});$builder.on('campaign-builder:hide',function(){$builder.addClass('hide').removeClass('builder-active');$flashes.removeClass('alert-offset')});if(!isCampaignPreview){Mautic.prepareCampaignCanvas()}
if(response&&response.inBuilder){Mautic.launchCampaignEditor();Mautic.processBuilderErrors(response)}
window.addEventListener('storage',function(event){if(event.key==='mautic_campaign_event_clone'){Mautic.campaignBuilderUpdateEventCloneDescription()}});mQuery(document).ajaxError(function(event,jqxhr,settings,thrownError){var path=settings.url.split('?')[0];if(path==="/s/campaigns/events/insert"){Mautic.campaignEventInsertOnError(event,jqxhr)}})}
const campaignEmailStats=mQuery(container).find('[data-load="campaign-email-stats"]').first();if(campaignEmailStats.length){mQuery(campaignEmailStats).on('click',()=>{const $campaignWeekdaysContainer=mQuery('[data-campaign-email-stats-weekdays]');const $campaignHoursContainer=mQuery('[data-campaign-email-stats-hours]');if($campaignWeekdaysContainer.find('canvas').length===0){mQuery.ajax({url:$campaignWeekdaysContainer.data('campaign-email-stats-weekdays'),success:function(response){$campaignWeekdaysContainer.html(response);Mautic.renderCharts($campaignWeekdaysContainer)}})}
if($campaignHoursContainer.find('canvas').length===0){mQuery.ajax({url:$campaignHoursContainer.data('campaign-email-stats-hours'),success:function(response){$campaignHoursContainer.html(response);Mautic.renderCharts($campaignHoursContainer)}})}})}
Mautic.campaignAuditlogOnLoad(container,response)};Mautic.lazyLoadContactListOnCampaignDetail=function(){let containerId='#leads-container';let container=mQuery(containerId);if(!container.length){return}
let campaignContactUrl=container.data('target-url');mQuery.get(campaignContactUrl,function(response){response.target=containerId;Mautic.processPageContent(response)})};Mautic.lazyLoadGraphStatsOnCampaignDetail=function(){const containerId='#campaign-graph-div';const container=mQuery(containerId);if(!container.length){return}
const campaignGraphUrl=container.data('target-url');mQuery.get(campaignGraphUrl,function(response){response.target=containerId;Mautic.processPageContent(response)})};Mautic.lazyLoadEventStatsOnCampaignDetail=function(){const containerId='#campaign-tab-content';const container=mQuery(containerId);if(!container.length){return}
const campaignEventStatUrl=container.data('event-target-url');if('undefined'==typeof campaignEventStatUrl){return}
mQuery.get(campaignEventStatUrl,function(response){if(response.errors&&'dev'==mauticEnv){alert(response.errors[0].message);console.log(response.errors)}
if(typeof response.preview!=='undefined'){mQuery('#preview-container').html(response.preview);Mautic.prepareCampaignCanvas();Mautic.previewCampaignLabels();Mautic.previewCampaignEventDetails()}else{mQuery('#decisions_li').remove();mQuery('#decisions-container').remove()}
if(typeof response.decisions!=='undefined'){mQuery('#decisions-container').html(response.decisions)}else{mQuery('#decisions_li').remove();mQuery('#decisions-container').remove()}
if(typeof response.actions!=='undefined'){mQuery('#actions-container').html(response.actions)}else{mQuery('#actions_li').remove();mQuery('#actions-container').remove()}
if(typeof response.conditions!=='undefined'){mQuery('#conditions-container').html(response.conditions)}else{mQuery('#conditions_li').remove();mQuery('#conditions-container').remove()}
mQuery('ul#campaign_nav_header_ul li').removeClass('active');mQuery('ul#campaign_nav_header_ul li').eq(0).addClass('active');mQuery('div#campaign-tab-content .tab-pane').removeClass('active in');mQuery('div#campaign-tab-content .tab-pane').eq(0).addClass('active in')})}
Mautic.campaignBuilderUpdateEventListTooltips=function(theSelect,onlyDestroy){const $select=mQuery('#'+theSelect);const dataAttribute='tooltips';if(undefined===$select.data(dataAttribute)){$select.data(dataAttribute,[])}
const tooltips=$select.data(dataAttribute);mQuery.each(tooltips,function(index,$tooltip){if(undefined===$tooltip){return}
$tooltip.tooltip('hide');$tooltip.tooltip('destroy')});$select.data(dataAttribute,[]);if(!0===onlyDestroy){return}
$select.find('option').each(function(){if(mQuery(this).attr('id')){const chosenOption='#'+theSelect+'_chosen .option_'+mQuery(this).attr('id');const $tooltip=mQuery(chosenOption).tooltip({html:!0,container:'body',placement:'left'});$select.data(dataAttribute).push($tooltip)}})}
Mautic.campaignOnUnload=function(container){delete Mautic.campaignBuilderInstance;delete Mautic.campaignBuilderLabels}
Mautic.campaignEventCloneOnLoad=function(container,response){Mautic.setCampaignEventClone({'sourceEventName':response.eventName,'sourceEventType':response.eventType,'sourceType':response.type,'sourceCampaignId':response.campaignId,'sourceCampaignName':response.campaignName,});const flashMessage=Mautic.addInfoFlashMessage(Mautic.translate('mautic.campaign.event.clone.success'));Mautic.setFlashes(flashMessage);Mautic.campaignBuilderUpdateEventCloneDescription()};Mautic.campaignEventInsertOnError=function(event,jqxhr){Mautic.clearCampaignEventClone();Mautic.hideCampaignEventPanel();if(jqxhr.responseJSON.error){const flashMessage=Mautic.addErrorFlashMessage(jqxhr.responseJSON.error);Mautic.setFlashes(flashMessage)}};Mautic.campaignEventOnLoad=function(container,response){if(mQuery('#campaignevent_triggerHour').length){Mautic.campaignEventUpdateIntervalHours();mQuery('#campaignevent_triggerHour').on('change',Mautic.campaignEventUpdateIntervalHours);mQuery('#campaignevent_triggerRestrictedStartHour').on('change',Mautic.campaignEventUpdateIntervalHours);mQuery('#campaignevent_triggerRestrictedStopHour').on('change',Mautic.campaignEventUpdateIntervalHours);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_0').on('change',Mautic.campaignEventSelectDOW);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_1').on('change',Mautic.campaignEventSelectDOW);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_2').on('change',Mautic.campaignEventSelectDOW);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_3').on('change',Mautic.campaignEventSelectDOW);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_4').on('change',Mautic.campaignEventSelectDOW);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_7').on('change',Mautic.campaignEventSelectDOW)}
if(!response.hasOwnProperty('eventId')){return}
var domEventId='CampaignEvent_'+response.eventId;var eventId='#'+domEventId;Mautic.campaignBuilderLabels[domEventId]=(response.label)?response.label:'';if(response.formSubmitted&&!response.success&&Mautic.campaignBuilderConnectionRequiresUpdate){Mautic.campaignBuilderInstance.deleteConnection(Mautic.campaignBuilderLastConnection)}
Mautic.campaignBuilderConnectionRequiresUpdate=!1;Mautic.campaignBuilderUpdateLabel(domEventId);Mautic.campaignBuilderCanvasEvents[response.event.id]=response.event;if(response.deleted){Mautic.campaignBuilderInstance.remove(document.getElementById(domEventId));if(response.deletedEvents){mQuery.each(response.deletedEvents,function(i,eventData){Mautic.addEventToDeletedEvents(eventData.id,eventData.redirectEvent)})}
delete Mautic.campaignBuilderCampaignElements.modifiedEvents[response.event.id];delete Mautic.campaignBuilderEventPositions[domEventId];delete Mautic.campaignBuilderCanvasEvents[response.event.id]}else if(response.updateHtml){mQuery(eventId+" .campaign-event-content").replaceWith(response.updateHtml)}else if(response.eventHtml){var newHtml=response.eventHtml;var x=parseInt(mQuery('#droppedX').val());var y=parseInt(mQuery('#droppedY').val());Mautic.campaignBuilderEventPositions[domEventId]={'left':x,'top':y};mQuery(newHtml).appendTo('#CampaignCanvas');mQuery(eventId).css({'left':x+'px','top':y+'px'});Mautic.campaignBuilderRegisterAnchors(Mautic.getAnchorsForEvent(response.event),eventId);Mautic.campaignBuilderInstance.draggable(domEventId,Mautic.campaignDragOptions);mQuery(eventId+" a[data-toggle='ajax']").click(function(event){event.preventDefault();mQuery('.btns-builder').find('button').prop('disabled',!0);const extraData={'modifiedEvents':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedEvents),};return Mautic.ajaxifyLink(this,event,extraData)});mQuery(eventId+" a[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();mQuery('.btns-builder').find('button').prop('disabled',!0);mQuery(this).data('form-data',{'modifiedEvents':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedEvents),});Mautic.ajaxifyModal(this,event)});mQuery(eventId+" a[data-toggle='ajax-delete']").off("click.ajax").on("click.ajax",Mautic.handleEventDeleteClick);mQuery(eventId).off('.eventbuttons').on('mouseover.eventbuttons',function(){mQuery(this).find('.campaign-event-buttons').removeClass('hide')}).on('mouseout.eventbuttons',function(){mQuery(this).find('.campaign-event-buttons').addClass('hide')}).on('dblclick.eventbuttons',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()});mQuery(eventId+" *[data-toggle='tooltip']").tooltip({html:!0});Mautic.campaignBuilderInstance.connect({uuids:[Mautic.campaignBuilderAnchorClicked,domEventId+'_top']})}
if(response.hasOwnProperty('clearCloneStorage')){Mautic.hideCampaignEventPanel();Mautic.clearCampaignEventClone()}
if(response.modifiedEvents){Mautic.campaignBuilderCampaignElements.modifiedEvents=response.modifiedEvents}
mQuery('.btns-builder').find('button').prop('disabled',!1);Mautic.campaignBuilderInstance.repaintEverything()};Mautic.campaignEventUpdateIntervalHours=function(){var hour=mQuery('#campaignevent_triggerHour').val();var start=mQuery('#campaignevent_triggerRestrictedStartHour').val();var stop=mQuery('#campaignevent_triggerRestrictedStopHour').val();if(hour){mQuery('#campaignevent_triggerRestrictedStartHour').val('');mQuery('#campaignevent_triggerRestrictedStopHour').val('');mQuery('#campaignevent_triggerRestrictedStartHour').prop('disabled',!0);mQuery('#campaignevent_triggerRestrictedStopHour').prop('disabled',!0)}else if(start||stop){mQuery('#campaignevent_triggerHour').val('');mQuery('#campaignevent_triggerHour').prop('disabled',!0)}else{mQuery('#campaignevent_triggerHour').val('');mQuery('#campaignevent_triggerRestrictedStartHour').val('');mQuery('#campaignevent_triggerRestrictedStopHour').val('');mQuery('#campaignevent_triggerHour').prop('disabled',!1);mQuery('#campaignevent_triggerRestrictedStartHour').prop('disabled',!1);mQuery('#campaignevent_triggerRestrictedStopHour').prop('disabled',!1)}};Mautic.campaignEventSelectDOW=function(){if(mQuery('#campaignevent_triggerRestrictedDaysOfWeek_7').prop('checked')){mQuery('#campaignevent_triggerRestrictedDaysOfWeek_0').prop('checked',!0);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_1').prop('checked',!0);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_2').prop('checked',!0);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_3').prop('checked',!0);mQuery('#campaignevent_triggerRestrictedDaysOfWeek_4').prop('checked',!0)}
mQuery('#campaignevent_triggerRestrictedDaysOfWeek_7').prop('checked',!1)};Mautic.getAnchorsForEvent=function(event){var eventRestrictions=Mautic.campaignBuilderConnectionRestrictions[event.type];if(!eventRestrictions||!eventRestrictions.target){console.warn(`No restrictions found for the event type: ${event.type}. Probably the plugin was disabled.`);return['top','bottom']}
var restrictions=eventRestrictions.target;if(restrictions.decision.length===1&&restrictions.decision[0]==="none"&&restrictions.action.length===1&&restrictions.action[0]==="none"&&restrictions.condition.length===1&&restrictions.condition[0]==="none"){return['top']}
if(event.eventType==='decision'||event.eventType==='condition'){return['top','yes','no']}
return['top','bottom']};Mautic.campaignSourceOnLoad=function(container,response){var domEventId='CampaignEvent_'+response.sourceType;var eventId='#'+domEventId;if(response.deleted){Mautic.campaignBuilderInstance.remove(document.getElementById(domEventId));delete Mautic.campaignBuilderEventPositions[domEventId];mQuery('#campaignLeadSource_'+response.sourceType).prop('disabled',!1);mQuery('#SourceList').trigger('chosen:updated');if(!mQuery('.list-campaign-source:not(#CampaignEvent_newsource_hide)').length){mQuery('#CampaignEvent_newsource_hide').attr('id','CampaignEvent_newsource');Mautic.campaignBuilderPrepareNewSource()}}else if(response.updateHtml){mQuery(eventId+" .campaign-event-content").html(response.updateHtml)}else if(response.sourceHtml){mQuery('#campaignLeadSource_'+response.sourceType).prop('disabled',!0);mQuery('#SourceList').trigger('chosen:updated');var newHtml=response.sourceHtml;if(mQuery('#CampaignEvent_newsource').length){var x=mQuery('#CampaignEvent_newsource').position().left;var y=mQuery('#CampaignEvent_newsource').position().top;mQuery('#CampaignEvent_newsource').attr('id','CampaignEvent_newsource_hide');Mautic.hideCampaignEventPanel();var autoConnect=!1}else{var x=parseInt(mQuery('#droppedX').val());var y=parseInt(mQuery('#droppedY').val());var autoConnect=!0}
mQuery(newHtml).appendTo('#CampaignCanvas');Mautic.campaignBuilderEventPositions[domEventId]={'left':x,'top':y};mQuery(eventId).css({'left':x+'px','top':y+'px'});Mautic.campaignBuilderRegisterAnchors(['leadSource','leadSourceLeft','leadSourceRight'],eventId);Mautic.campaignBuilderInstance.draggable(domEventId,Mautic.campaignDragOptions);mQuery(eventId+" a[data-toggle='ajax']").click(function(event){event.preventDefault();const extraData={'modifiedSources':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedSources),};return Mautic.ajaxifyLink(this,event,extraData)});mQuery(eventId+" a[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();mQuery(this).data('form-data',{'modifiedSources':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedSources),});Mautic.ajaxifyModal(this,event)});mQuery(eventId).off('.eventbuttons').on('mouseover.eventbuttons',function(){mQuery(this).find('.campaign-event-buttons').removeClass('hide')}).on('mouseout.eventbuttons',function(){mQuery(this).find('.campaign-event-buttons').addClass('hide')}).on('dblclick.eventbuttons',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()});mQuery(eventId+" *[data-toggle='tooltip']").tooltip({html:!0});if(autoConnect){if(Mautic.campaignBuilderAnchorClicked.search('left')!==-1){var source=domEventId+'_leadsourceright';var target=Mautic.campaignBuilderAnchorClicked}else{var source=Mautic.campaignBuilderAnchorClicked;var target=domEventId+'_leadsourceleft'}
Mautic.campaignBuilderInstance.connect({uuids:[source,target]})}
if(!mQuery('.list-campaign-event').length){mQuery('.jtk-endpoint_anchor_leadsource.'+domEventId).trigger('click')}}
if(response.modifiedSources){Mautic.campaignBuilderCampaignElements.modifiedSources=response.modifiedSources}
mQuery('.btns-builder').find('button').prop('disabled',!1);Mautic.campaignBuilderInstance.repaintEverything()};Mautic.campaignBuilderUpdateLabel=function(domEventId){var theLabel=typeof Mautic.campaignBuilderLabels[domEventId]=='undefined'?'':Mautic.campaignBuilderLabels[domEventId];var currentConnections=Mautic.campaignBuilderInstance.select({target:domEventId});if(currentConnections.length>0){currentConnections.each(function(conn){var overlays=conn.getOverlays();if(overlays.length>0){for(var i=0;i<=overlays.length;i++){if(typeof overlays[i]!='undefined'&&overlays[i].type=='Label'){conn.removeOverlay(overlays[i].id)}}}
if(theLabel){conn.addOverlay(["Label",{label:theLabel,location:0.65,cssClass:"jtk-label",id:conn.sourceId+"_"+conn.targetId+"_connectionLabel"}])}})}};Mautic.launchCampaignEditor=function(){Mautic.stopIconSpinPostEvent();mQuery('body').css('overflow-y','hidden');mQuery('#campaign-builder').trigger('campaign-builder:show');if(mQuery('#CampaignEvent_newsource').length){Mautic.campaignBuilderPrepareNewSource()}
if(Mautic.campaignBuilderCanvasSettings){Mautic.campaignBuilderInstance.setSuspendDrawing(!0);Mautic.campaignBuilderReconnectEndpoints();Mautic.campaignBuilderInstance.setSuspendDrawing(!1,!0)}
Mautic.campaignBuilderInstance.repaintEverything()};Mautic.launchCampaignPreview=function(){Mautic.stopIconSpinPostEvent();if(Mautic.campaignBuilderCanvasSettings){Mautic.campaignBuilderInstance.setSuspendDrawing(!0);Mautic.campaignBuilderReconnectEndpoints();Mautic.campaignBuilderInstance.setSuspendDrawing(!1,!0)}
Mautic.campaignBuilderInstance.repaintEverything()};Mautic.campaignBuilderConnectionsMap={'source':{'leadsource':{'source':[],'action':['top'],'condition':['top'],'decision':['top'],},'leadsourceleft':{'source':['leadsourceright'],'action':[],'condition':[],'decision':[]},'leadsourceright':{'source':['leadsourceleft'],'action':[],'condition':[],'decision':[]}},'action':{'top':{'source':['leadsource'],'action':['bottom'],'condition':['yes','no'],'decision':['yes','no']},'bottom':{'source':[],'action':['top'],'condition':['top'],'decision':['top']}},'condition':{'top':{'source':['leadsource'],'action':['bottom'],'condition':['yes','no'],'decision':['yes','no']},'yes':{'source':[],'action':['top'],'condition':['top'],'decision':['top']},'no':{'source':[],'action':['top'],'condition':['top'],'decision':['top']}},'decision':{'top':{'action':['bottom'],'source':['leadsource'],'condition':['yes','no'],'decision':[],},'yes':{'source':[],'action':['top'],'condition':['top'],'decision':[],},'no':{'source':[],'action':['top'],'condition':['top'],'decision':[],}}};Mautic.campaignBuilderAnchorDefaultColor='var(--border-subtle)';Mautic.campaignEndpointDefinitions={'top':{anchors:[0.5,0,0,-1,0,0],isTarget:!0},'bottom':{anchors:[0.5,1,0,1,0,0],isTarget:!1},'yes':{anchors:[0,1,0,1,30,0],connectorColor:'var(--support-success-inverse)',isTarget:!1},'no':{anchors:[1,1,0,1,-30,0],connectorColor:'var(--support-error-inverse)',isTarget:!1},'leadSource':{anchors:[0.5,1,0,1,0,0],isTarget:!1},'leadSourceLeft':{anchors:[0,0.5,-1,0,-1,0],connectorColor:'#fdb933',isTarget:!0,connectorStyle:'Straight'},'leadSourceRight':{anchors:[1,0.5,1,0,1,0],connectorColor:'#fdb933',isTarget:!1,connectorStyle:'Straight'}};Mautic.campaignConnectionCallbacks={'beforeDetach':[],'beforeDrag':[],'beforeStartDetach':[],'beforeDrop':[],'onHover':[],'beforeAnchorsRegistered':[],'afterAnchorsRegistered':[],'beforeEndpointsRegistered':[],'beforeEndpointsReconnected':[],'afterEndpointsReconnected':[]};Mautic.campaignBuilderAnchorClicked=!1;Mautic.campaignBuilderEventPositions={};Mautic.prepareCampaignCanvas=function(){if(typeof Mautic.campaignBuilderInstance=='undefined'){Mautic.campaignBuilderInstance=jsPlumb.getInstance({Container:document.querySelector("#CampaignCanvas")});Mautic.campaignEndpoints={};var startingPosition;Mautic.campaignDragOptions={start:function(params){startingPosition={top:params.el.offsetTop,left:params.el.offsetLeft,}},stop:function(params){var endingPosition={top:params.finalPos[0],left:params.finalPos[1]};if(startingPosition.left!==endingPosition.left||startingPosition.top!==endingPosition.top){Mautic.campaignBuilderEventPositions[mQuery(params.el).attr('id')]={'left':parseInt(endingPosition.left),'top':parseInt(endingPosition.top)};var campaignId=mQuery('#campaignId').val();var query="action=campaign:updateCoordinates&campaignId="+campaignId+"&droppedX="+endingPosition.top+"&droppedY="+endingPosition.left+"&eventId="+mQuery(params.el).attr('id');mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)}})}},containment:!0};Mautic.campaignBuilderEventDimensions={'width':200,'height':45,'anchor':10,'wiggleWidth':30,'wiggleHeight':50};Mautic.campaignBuilderLabels={};Mautic.campaignBuilderInstance.bind("connection",function(info,originalEvent){Mautic.campaignBuilderConnectionRequiresUpdate=!1;Mautic.campaignBuilderLastConnection=info.connection;var epDetails=Mautic.campaignBuilderGetEndpointDetails(info.sourceEndpoint);var targetElementId=info.targetEndpoint.elementId;var previousConnection=mQuery('#'+targetElementId).attr('data-connected');var editButton=mQuery('#'+targetElementId).find('a.btn-edit');var editUrl=editButton.attr('href');if(editUrl){var anchorQueryParams='anchor='+epDetails.anchorName+"&anchorEventType="+epDetails.eventType;if(editUrl.search('anchor=')!==-1){editUrl.replace(/anchor=(.*?)$/,anchorQueryParams)}else{var delimiter=(editUrl.indexOf('?')===-1)?'?':'&';editUrl=editUrl+delimiter+anchorQueryParams}
editButton.attr('data-href',editUrl);if(previousConnection&&previousConnection!=epDetails.anchorName&&(previousConnection=='no'||epDetails.anchorName=='no')){editButton.attr('data-prevent-dismiss',!0);Mautic.campaignBuilderConnectionRequiresUpdate=!0;editButton.trigger('click')}}
mQuery('#'+targetElementId).attr('data-connected',epDetails.anchorName);Mautic.campaignBuilderUpdateLabel(info.connection.targetId);info.targetEndpoint.setPaintStyle({fill:info.connection.getPaintStyle().stroke});info.sourceEndpoint.setPaintStyle({fill:info.connection.getPaintStyle().stroke})});Mautic.campaignBuilderInstance.bind("connectionDetached",function(info,originalEvent){Mautic.campaignBuilderUpdateLabel(info.connection.targetId);info.targetEndpoint.setPaintStyle({fill:"#d5d4d4"});var currentConnections=info.sourceEndpoint.connections.length;currentConnections-=1;if(!currentConnections){info.sourceEndpoint.setPaintStyle({fill:"#d5d4d4"})}});Mautic.campaignBuilderInstance.bind("connectionMoved",function(info,originalEvent){Mautic.campaignBuilderUpdateLabel(info.connection.originalTargetId);info.originalTargetEndpoint.setPaintStyle({fill:"#d5d4d4"});Mautic.campaignBuilderUpdateLabel(info.connection.newTargetId);info.newTargetEndpoint.setPaintStyle({fill:info.newSourceEndpoint.getPaintStyle().fill})});mQuery('.builder-content').scroll(function(){Mautic.campaignBuilderInstance.repaintEverything()});mQuery.each(Mautic.campaignConnectionCallbacks.beforeEndpointsRegistered,function(index,callback){callback()});mQuery.each(Mautic.campaignEndpointDefinitions,function(ep,definition){Mautic.campaignBuilderRegisterEndpoint(ep,definition)});mQuery.each(Mautic.campaignConnectionCallbacks.beforeAnchorsRegistered,function(index,callback){callback()});mQuery("#CampaignCanvas div[data-event-id]").each(function(){var event=Mautic.campaignBuilderCanvasEvents[mQuery(this).data('eventId')];Mautic.campaignBuilderRegisterAnchors(Mautic.getAnchorsForEvent(event),this)});mQuery("#CampaignCanvas div.list-campaign-event.list-campaign-source").not('#CampaignEvent_newsource').not('#CampaignEvent_newsource_hide').each(function(){Mautic.campaignBuilderRegisterAnchors(['bottom'],this)});mQuery("#CampaignCanvas div.list-campaign-leadsource").not('#CampaignEvent_newsource').not('#CampaignEvent_newsource_hide').each(function(){Mautic.campaignBuilderRegisterAnchors(['leadSource','leadSourceLeft','leadSourceRight'],this)});mQuery.each(Mautic.campaignConnectionCallbacks.afterAnchorsRegistered,function(index,callback){callback()});if(mQuery('.preview').length){Mautic.launchCampaignPreview()}else{Mautic.campaignBuilderInstance.draggable(document.querySelectorAll("#CampaignCanvas .draggable"),Mautic.campaignDragOptions)}}};Mautic.campaignBeforeDropCallback=function(params){var sourceEndpoint=Mautic.campaignBuilderGetEndpointDetails(params.connection.endpoints[0]);var targetEndpoint=Mautic.campaignBuilderGetEndpointDetails(params.dropEndpoint);var callbackAllowed=null;mQuery.each(Mautic.campaignConnectionCallbacks.beforeDrop,function(index,callback){var result=callback(sourceEndpoint,targetEndpoint,params);if(null!==result){callbackAllowed=result;return!1}});if(null!==callbackAllowed){return callbackAllowed}
if(!Mautic.campaignBuilderValidateConnection(sourceEndpoint,targetEndpoint.eventType,targetEndpoint.event)){return!1}
if(mQuery.inArray(targetEndpoint.anchorName,['top','leadsourceleft','leadsourceright'])){var sourceConnections=Mautic.campaignBuilderInstance.select({source:params.targetId});var loopDetected=!1;sourceConnections.each(function(conn){if(conn.sourceId==targetEndpoint.elementId&&conn.targetId==sourceEndpoint.elementId){loopDetected=!0;return!1}})}
if(params.sourceId==params.targetId){return!1}
var allowedConnections=Mautic.campaignBuilderConnectionsMap[sourceEndpoint.eventType][sourceEndpoint.anchorName][targetEndpoint.eventType];var allowed=mQuery.inArray(targetEndpoint.anchorName,allowedConnections)!==-1;if(allowed){if(params.dropEndpoint.connections.length>0){mQuery.each(params.dropEndpoint.connections,function(key,conn){Mautic.campaignBuilderInstance.deleteConnection(conn)})}}
return allowed};Mautic.campaignBeforeDetachCallback=function(connection){var sourceEndpoint=Mautic.campaignBuilderGetEndpointDetails(connection.sourceId);var targetEndpoint=Mautic.campaignBuilderGetEndpointDetails(connection.targetId);var callbackAllowed=null;mQuery.each(Mautic.campaignConnectionCallbacks.beforeDetach,function(index,callback){var result=callback(sourceEndpoint,targetEndpoint,connection);if(null!==result){callbackAllowed=result;return!1}});if(null!==callbackAllowed){return callbackAllowed}
return!0};Mautic.campaignBeforeDragCallback=function(endpoint,source,sourceId){var sourceEndpoint=Mautic.campaignBuilderGetEndpointDetails(sourceId);var targetEndpoint=Mautic.campaignBuilderGetEndpointDetails(endpoint);var callbackAllowed=null;mQuery.each(Mautic.campaignConnectionCallbacks.beforeDrag,function(index,callback){var result=callback(sourceEndpoint,targetEndpoint,endpoint,source,sourceId);if(null!==result){callbackAllowed=result;return!1}});if(null!==callbackAllowed){return callbackAllowed}
return!0};Mautic.campaignBeforeStartDetachCallback=function(endpoint,source,sourceId,connection){var sourceEndpoint=Mautic.campaignBuilderGetEndpointDetails(sourceId);var targetEndpoint=Mautic.campaignBuilderGetEndpointDetails(endpoint);var callbackAllowed=null;mQuery.each(Mautic.campaignConnectionCallbacks.beforeStartDetach,function(index,callback){var result=callback(sourceEndpoint,targetEndpoint,endpoint,source,sourceId,connection);if(null!==result){callbackAllowed=result;return!1}});if(null!==callbackAllowed){return callbackAllowed}
return!0};Mautic.addEventToDeletedEvents=function(eventId,redirectEventId){if(!Mautic.campaignBuilderCampaignElements.deletedEvents){Mautic.campaignBuilderCampaignElements.deletedEvents=[]}
let exists=!1;for(const event of Mautic.campaignBuilderCampaignElements.deletedEvents){if(event.id===eventId){exists=!0;break}}
if(!exists){Mautic.campaignBuilderCampaignElements.deletedEvents.push({id:eventId,redirectEvent:redirectEventId})}};Mautic.campaignHoverCallback=function(sourceEndpoint,endpoint,event){var callbackAllowed=null;mQuery.each(Mautic.campaignConnectionCallbacks.onHover,function(index,callback){var result=callback(sourceEndpoint,endpoint,event);if(null!==result){callbackAllowed=result;return!1}});if(null!==callbackAllowed){return callbackAllowed}
return!0};Mautic.campaignToggleTimeframes=function(){const triggerModes={immediate:mQuery('#campaignevent_triggerMode_0').prop('checked'),interval:mQuery('#campaignevent_triggerMode_1').prop('checked'),date:mQuery('#campaignevent_triggerMode_2').prop('checked'),optimal:mQuery('#campaignevent_triggerMode_3').prop('checked')};if(!mQuery('#campaignevent_triggerMode_2').length){triggerModes.date=triggerModes.interval;triggerModes.interval=triggerModes.immediate;triggerModes.immediate=!1}
if(mQuery('#campaignevent_triggerInterval').length){mQuery('#triggerInterval').toggleClass('hide',!triggerModes.interval);mQuery('#triggerDate').toggleClass('hide',!triggerModes.date);mQuery('#triggerOptimized').toggleClass('hide',!triggerModes.optimal)}};Mautic.closeCampaignBuilder=function(){mQuery('.btns-builder').find('button').prop('disabled',!0);var builderCss={margin:"0",padding:"0",border:"none",width:"100%",height:"100%"};var panelHeight=(mQuery('.builder-content').css('right')=='0px')?mQuery('.builder-panel').height():0,panelWidth=(mQuery('.builder-content').css('right')=='0px')?0:mQuery('.builder-panel').width(),spinnerLeft=(mQuery(window).width()-panelWidth-60)/2,spinnerTop=(mQuery(window).height()-panelHeight-60)/2;var overlay=mQuery('<div id="builder-overlay" class="modal-backdrop fade in"><div style="position: absolute; top:'+spinnerTop+'px; left:'+spinnerLeft+'px" class=".builder-spinner"><i class="ri-loader-3-line ri-spin ri-5x"></i></div></div>').css(builderCss).appendTo('.builder-content');mQuery('#builder-errors span').text('');mQuery('#builder-errors').hide('fast');Mautic.updateConnections(function(err,response){mQuery('body').css('overflow-y','');if(!err){mQuery('#builder-overlay').remove();mQuery('body').css('overflow-y','');if(response.success){mQuery('#campaign-builder').trigger('campaign-builder:hide');mQuery('.btns-builder').find('button').prop('disabled',!1)}}});mQuery('#campaign_campaignElements').val(JSON.stringify(Mautic.campaignBuilderCampaignElements))};Mautic.saveCampaignFromBuilder=function(){mQuery('.btns-builder').find('button').prop('disabled',!0);Mautic.activateButtonLoadingIndicator(mQuery('.btn-apply-builder'));Mautic.updateConnections(function(err){if(!err){var applyBtn=mQuery('.btn-apply');mQuery('#campaign_campaignElements').val(JSON.stringify(Mautic.campaignBuilderCampaignElements));Mautic.inBuilderSubmissionOn(applyBtn.closest('form'));applyBtn.trigger('click');Mautic.inBuilderSubmissionOff();mQuery(document).trigger('mauticCampaignBuilderCanvasLoaded');Mautic.ensureCampaignEventHandlers()}})};Mautic.updateConnections=function(callback){var nodes=[];mQuery("#CampaignCanvas .list-campaign-event").each(function(idx,elem){nodes.push({id:mQuery(elem).attr('id').replace('CampaignEvent_',''),positionX:parseInt(mQuery(elem).css('left'),10),positionY:parseInt(mQuery(elem).css('top'),10)})});mQuery("#CampaignCanvas .list-campaign-source").not('#CampaignEvent_newsource').not('#CampaignEvent_newsource_hide').each(function(idx,elem){nodes.push({id:mQuery(elem).attr('id').replace('CampaignEvent_',''),positionX:parseInt(mQuery(elem).css('left'),10),positionY:parseInt(mQuery(elem).css('top'),10)})});var connections=[];mQuery.each(Mautic.campaignBuilderInstance.getConnections(),function(idx,connection){connections.push({sourceId:connection.sourceId.replace('CampaignEvent_',''),targetId:connection.targetId.replace('CampaignEvent_',''),anchors:mQuery.map(connection.endpoints,function(endpoint){var anchor=Mautic.campaignBuilderGetEndpointDetails(endpoint);return{'endpoint':anchor.anchorName,'eventId':anchor.eventId}})})});var chart={};chart.nodes=nodes;chart.connections=connections;var canvasSettings={canvasSettings:chart};Mautic.campaignBuilderCampaignElements.canvasSettings=chart;var campaignId=mQuery('#campaignId').val();var query="action=campaign:updateConnections&campaignId="+campaignId;mQuery.ajax({url:mauticAjaxUrl+'?'+query,type:"POST",data:canvasSettings,dataType:"json",success:function(response){if(typeof callback==='function')callback(!1,response);},error:function(response,textStatus,errorThrown){Mautic.processAjaxError(response,textStatus,errorThrown);if(typeof callback==='function')callback(!0,response);}})};Mautic.cancelCampaignEvent=function(e){e.preventDefault();const extraData={'modifiedEvents':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedEvents),};Mautic.postForm(mQuery('form[name="campaignevent"]'),function(response){Mautic.processModalContent(response,'#'+response.modalId)},extraData)};Mautic.submitCampaignEvent=function(e){e.preventDefault();mQuery('#campaignevent_canvasSettings_droppedX').val(mQuery('#droppedX').val());mQuery('#campaignevent_canvasSettings_droppedY').val(mQuery('#droppedY').val());mQuery('.btns-builder').find('button').prop('disabled',!0);const runningAjax=mQuery.active;Mautic.refreshModifiedEvents(mQuery('form[name="campaignevent"]'),'#CampaignEventModal');const waitForElement=function(){if(mQuery.active<=runningAjax){mQuery('.btns-builder').find('button').prop('disabled',!1)}else{setTimeout(waitForElement,100)}}
waitForElement()};Mautic.refreshModifiedEvents=function(form,target){const extraData={'modifiedEvents':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedEvents),};Mautic.postForm(form,function(response){if(response.modifiedEvents){Mautic.campaignBuilderCampaignElements.modifiedEvents={...Mautic.campaignBuilderCampaignElements.modifiedEvents,...response.modifiedEvents}}
Mautic.processModalContent(response,target)},extraData)};Mautic.submitCampaignSource=function(e){e.preventDefault();mQuery('#campaign_leadsource_droppedX').val(mQuery('#droppedX').val());mQuery('#campaign_leadsource_droppedY').val(mQuery('#droppedY').val());Mautic.refreshModifiedSources(mQuery('form[name="campaign_leadsource"]'),'#CampaignEventModal')};Mautic.refreshModifiedSources=function(form,target){const extraData={'modifiedSources':JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedSources),};Mautic.postForm(form,function(response){if(response.modifiedSources){Mautic.campaignBuilderCampaignElements.modifiedSources={...Mautic.campaignBuilderCampaignElements.modifiedSources,...response.modifiedSources}}
Mautic.processModalContent(response,target)},extraData)};Mautic.campaignBuilderReconnectEndpoints=function(){mQuery.each(Mautic.campaignConnectionCallbacks.beforeEndpointsReconnected,function(index,callback){callback()});if(typeof Mautic.campaignBuilderCanvasSettings=='undefined'){return}
if(typeof Mautic.campaignBuilderCanvasSettings.nodes!=='undefined'){var sourceFound=!1;mQuery.each(Mautic.campaignBuilderCanvasSettings.nodes,function(key,node){if(typeof Mautic.campaignBuilderCanvasSources[node.id]!=='undefined'){sourceFound=!0}
mQuery('#CampaignEvent_'+node.id).css({position:'absolute',left:node.positionX+'px',top:node.positionY+'px'});Mautic.campaignBuilderEventPositions['CampaignEvent_'+node.id]={left:parseInt(node.positionX),top:parseInt(node.positionY)}})}
if(typeof Mautic.campaignBuilderCanvasSettings.connections!=='undefined'){mQuery.each(Mautic.campaignBuilderCanvasSettings.connections,function(key,connection){if(typeof Mautic.campaignBuilderCanvasEvents[connection.targetId]!=='undefined'){var targetEvent=Mautic.campaignBuilderCanvasEvents[connection.targetId]}else if(typeof Mautic.campaignBuilderCanvasSources[connection.targetId]!=='undefined'){var targetEvent=Mautic.campaignBuilderCanvasSources[connection.targetId]}
if(targetEvent&&targetEvent.label){Mautic.campaignBuilderLabels["CampaignEvent_"+connection.targetId]=targetEvent.label}
Mautic.campaignBuilderInstance.connect({uuids:["CampaignEvent_"+connection.sourceId+'_'+connection.anchors.source,"CampaignEvent_"+connection.targetId+'_'+connection.anchors.target]})})}
if(!sourceFound){var topOffset=25;mQuery.each(Mautic.campaignBuilderCanvasSources,function(type,source){mQuery('#CampaignEvent_'+type).css({position:'absolute',left:'20px',top:topOffset+'px'})});topOffset+=45}
mQuery.each(Mautic.campaignConnectionCallbacks.afterEndpointsReconnected,function(index,callback){callback()});delete Mautic.campaignBuilderCanvasSettings};Mautic.campaignBuilderRegisterEndpoint=function(name,params){var isTarget,isSource,color,connectorColor,connectorStyle;if(params.color){color=params.color}else{color=Mautic.campaignBuilderAnchorDefaultColor}
if(params.connectorColor){connectorColor=params.connectorColor}else{connectorColor=color}
if(params.connectorStyle){connectorStyle=params.connectorStyle}else{connectorStyle=["Bezier",{curviness:25}]}
isTarget=params.isTarget;isSource=!0;if(isTarget===null){isTarget=!0}else{if(typeof isTarget=='undefined'){isTarget=!1}
if(isTarget){isSource=!1}}
Mautic.campaignEndpoints[name]={endpoint:["Dot",{radius:10}],paintStyle:{fill:color},endpointStyle:{fill:color},connectorStyle:{stroke:connectorColor,strokeWidth:2},connector:connectorStyle,connectorOverlays:[],maxConnections:-1,isTarget:isTarget,isSource:isSource,beforeDrop:Mautic.campaignBeforeDropCallback,beforeDetach:Mautic.campaignBeforeDetachCallback,beforeStartDetach:Mautic.campaignBeforeStartDetachCallback,beforeDrag:Mautic.campaignBeforeDragCallback}};Mautic.campaignBuilderRegisterAnchors=function(names,el){var id=mQuery(el).attr('id');mQuery(names).each(function(key,anchorName){var theAnchor=Mautic.campaignEndpointDefinitions[anchorName].anchors;theAnchor[6]=anchorName.toLowerCase()+' '+id;var ep=Mautic.campaignBuilderInstance.addEndpoint(id,{anchor:theAnchor,uuid:id+"_"+anchorName.toLowerCase()},Mautic.campaignEndpoints[anchorName]);ep.bind("mouseover",function(endpoint,event){var epDetails=Mautic.campaignBuilderGetEndpointDetails(endpoint);if(!Mautic.campaignHoverCallback(epDetails,endpoint,event)){return}
if(epDetails.anchorName=='top'){return}
if(epDetails.anchorName=='leadsourceleft'||epDetails.anchorName=='leadsourceright'){if(mQuery('#SourceList option:enabled').length===1){return}}
endpoint.setPaintStyle({fill:endpoint.connectorStyle.stroke});var dot=mQuery(endpoint.canvas);dot.addClass('jtk-clickable_anchor');if(!dot.find('svg text').length){var svg=dot.find('svg')[0];var textElement=document.createElementNS("http://www.w3.org/2000/svg",'text');textElement.setAttributeNS(null,'x','50%');textElement.setAttributeNS(null,'y','50%');textElement.setAttributeNS(null,'text-anchor','middle');textElement.setAttributeNS(null,'stroke-width','1px');textElement.setAttributeNS(null,'stroke','#ffffff');textElement.setAttributeNS(null,'dy','.3em');var textNode=document.createTextNode('+');textElement.appendChild(textNode);svg.appendChild(textElement)}});ep.bind("mouseout",function(endpoint){var dot=mQuery(endpoint.canvas);dot.removeClass('jtk-clickable_anchor');if(!endpoint.connections.length){endpoint.setPaintStyle({fill:Mautic.campaignBuilderAnchorDefaultColor})}});ep.bind("click",function(endpoint,event){if(mQuery('#CampaignEvent_newsource').length){return}
var epDetails=Mautic.campaignBuilderGetEndpointDetails(endpoint);if(epDetails.anchorName=='top'){return}
if(epDetails.anchorName=='leadsourceleft'||epDetails.anchorName=='leadsourceright'){if(mQuery('#SourceList option:enabled').length===1){return}}
var epDetails=Mautic.campaignBuilderGetEndpointDetails(endpoint);var clickedAnchorName=epDetails.anchorName;Mautic.campaignBuilderAnchorClicked=endpoint.elementId+'_'+clickedAnchorName;Mautic.campaignBuilderAnchorNameClicked=clickedAnchorName;Mautic.campaignBuilderAnchorEventTypeClicked=epDetails.eventType;var elPos=Mautic.campaignBuilderGetEventPosition(endpoint.element);var spotFound=!1,putLeft=elPos.left,putTop=elPos.top,direction='',fullWidth=Mautic.campaignBuilderEventDimensions.width+Mautic.campaignBuilderEventDimensions.anchor,wiggleWidth=fullWidth+Mautic.campaignBuilderEventDimensions.wiggleWidth,fullHeight=Mautic.campaignBuilderEventDimensions.height+Mautic.campaignBuilderEventDimensions.anchor,wiggleHeight=fullHeight+Mautic.campaignBuilderEventDimensions.wiggleHeight,debug=!1;if(debug){console.log(Mautic.campaignBuilderEventPositions);console.log(clickedAnchorName+' - starting with: x = '+putLeft+', y = '+putTop)}
switch(clickedAnchorName){case 'leadsourceleft':direction='xl';putLeft-=wiggleWidth;break;case 'leadsourceright':direction='xr';putLeft+=wiggleWidth;break;case 'bottom':direction='yd';putTop+=wiggleHeight;break;case 'yes':case 'leadsource':putLeft-=Mautic.campaignBuilderEventDimensions.width/2;putTop+=wiggleHeight;direction='xl';break;case 'no':putLeft+=Mautic.campaignBuilderEventDimensions.width/2;putTop+=wiggleHeight;direction='xr';break;case 'top':directon='yu';putTop-=wiggleHeight;break}
if(debug){console.log('Going direction: '+direction);console.log('Start test with: x = '+putLeft+', y = '+putTop)}
var counter=0;var windowWidth=mQuery(window).width();while(!spotFound){var isOccupied=!1;mQuery.each(Mautic.campaignBuilderEventPositions,function(id,pos){var l=Math.max(putLeft,pos.left);var r=Math.min(putLeft+fullWidth,pos.left+fullWidth);var b=Math.max(putTop,pos.top);var t=Math.min(putTop+fullHeight,pos.top+fullHeight);var h=t-b;var w=r-l;if(debug){console.log('Checking '+id);console.log(putLeft,putTop,l,r,b,t,h,w)}
if(h>0&&w>0){if(debug){console.log('Slot occupied by '+id)}
isOccupied=!0;switch(direction){case 'xl':putLeft-=(w+Mautic.campaignBuilderEventDimensions.wiggleWidth);if(putLeft<=0){putLeft=0;direction='yd';putTop+=fullHeight+Mautic.campaignBuilderEventDimensions.wiggleHeight}
break;case 'xr':if(putLeft+w+Mautic.campaignBuilderEventDimensions.wiggleWidth>windowWidth){direction='yd';putLeft-=Mautic.campaignBuilderEventDimensions.wiggleWidth;putTop+=fullHeight+Mautic.campaignBuilderEventDimensions.wiggleHeight}else{putLeft+=(w+Mautic.campaignBuilderEventDimensions.wiggleWidth)}
break;case 'yu':putTop-=(h-Mautic.campaignBuilderEventDimensions.wiggleHeight);if(putTop<=0){putTop=0;direction='xr'}
break;case 'yd':putTop+=(h+Mautic.campaignBuilderEventDimensions.wiggleHeight);break}
return!1}});if(!isOccupied){if(debug){console.log('It fits!')}
spotFound=!0}
counter++;if(counter>=100){putTop=10;putLeft=10;if(debug){console.log('Too many loops')}
spotFound=!0}}
if(debug){console.log('To be placed at: x = '+putLeft+', y = '+putTop)}
if(putLeft<=0){putLeft=10}
if(putTop<=0){putTop=10}
mQuery('#droppedX').val(putLeft);mQuery('#droppedY').val(putTop);var allowedEvents=[];mQuery.each(Mautic.campaignBuilderConnectionsMap[epDetails.eventType][epDetails.anchorName],function(group,eventTypes){if(eventTypes.length){allowedEvents[allowedEvents.length]=group.charAt(0).toUpperCase()+group.substr(1)}});Mautic.campaignBuilderAnchorClickedAllowedEvents=allowedEvents;Mautic.campaignBuilderIsEventCloneAllowed=Mautic.isCampaignCloneEventAllowedForEndpoint(epDetails);if(!(mQuery('.preview').length)){var el=(mQuery(event.target).hasClass('jtk-endpoint'))?event.target:mQuery(event.target).parents('.jtk-endpoint')[0];Mautic.campaignBuilderAnchorClickedPosition=Mautic.campaignBuilderGetEventPosition(el);Mautic.campaignBuilderUpdateEventList(allowedEvents,!1,'groups');Mautic.campaignBuilderUpdateEventCloneButton(allowedEvents,epDetails.eventType,epDetails.anchorName);Mautic.campaignBuilderUpdateEventCloneDescription()}
mQuery('.campaign-event-selector:not(#SourceList) option').prop('disabled',!1);if('source'==epDetails.eventType){var checkSelects=['action','decision','condition']}else{var primaryType=(epDetails.eventType==='decision')?'action':'decision';var checkSelects=[primaryType,'condition']}
mQuery.each(checkSelects,function(key,targetType){var selectId='#'+targetType.charAt(0).toUpperCase()+targetType.slice(1)+'List';mQuery(selectId+' option').each(function(){var optionVal=mQuery(this).val();if(optionVal){if(!Mautic.campaignBuilderValidateConnection(epDetails,targetType,optionVal)){mQuery(this).prop('disabled',!0)}}});mQuery(selectId).trigger('chosen:updated')})})})};Mautic.campaignBuilderGetEventPosition=function(el){return{'left':parseInt(mQuery(el).css('left')),'top':parseInt(mQuery(el).css('top'))}};Mautic.campaignBuilderUpdateEventList=function(groups,hidden,view,active,forcePosition){var groupsEnabled=0;var inGroupsView=('groups'==view);if(groups.length===1&&mQuery.inArray('Source',groups)!==-1&&!hidden){inGroupsView=!1}
mQuery.each(['Source','Action','Decision','Condition'],function(key,theGroup){if(mQuery.inArray(theGroup,groups)!==-1){if(inGroupsView){mQuery('#'+theGroup+'GroupSelector').removeClass('hide');if('source'!=theGroup){groupsEnabled++}}else{mQuery('#'+theGroup+'GroupList').removeClass('hide')}}else{if(inGroupsView){mQuery('#'+theGroup+'GroupSelector').addClass('hide')}else{mQuery('#'+theGroup+'GroupList').addClass('hide')}}});mQuery('#CampaignEventPanelGroups').removeClass('groups-enabled-1 groups-enabled-2 groups-enabled-3')
mQuery('#CampaignEventPanelGroups').addClass('groups-enabled-'+groups.length)
if(inGroupsView){mQuery.each(groups,function(key,theGroup){mQuery('#'+theGroup+'GroupSelector').removeClass(function(index,css){return(css.match(/col-(\S+)/g)||[]).join(' ')}).addClass('col-md-'+(12/groupsEnabled))});var newWidth=(500/3)*groupsEnabled;if(newWidth>=mQuery(window).width()){newWidth=mQuery(window).width()-10}
var leftPos=(forcePosition)?forcePosition.left:Mautic.campaignBuilderAnchorClickedPosition.left-(newWidth/2-10);var topPos=(forcePosition)?forcePosition.top:Mautic.campaignBuilderAnchorClickedPosition.top+25;mQuery('#CampaignEventPanel').css({left:(leftPos>=0)?leftPos:10,top:topPos,width:newWidth,});mQuery('#CampaignEventPanel').removeClass('hide');mQuery('#CampaignEventPanelGroups').removeClass('hide');mQuery('#CampaignEventPanelLists').addClass('hide');if(Mautic.campaignBuilderIsEventCloneAllowed){mQuery('#CampaignPasteContainer').removeClass('hide')}else{mQuery('#CampaignPasteContainer').addClass('hide')}}else{var leftPos=(forcePosition)?forcePosition.left:Mautic.campaignBuilderAnchorClickedPosition.left-125;var topPos=(forcePosition)?forcePosition.top:Mautic.campaignBuilderAnchorClickedPosition.top+25;mQuery('#CampaignEventPanel').css({left:(leftPos>=0)?leftPos:10,top:topPos,width:300,});mQuery('#CampaignEventPanelGroups').addClass('hide');mQuery('#CampaignEventPanelLists').removeClass('hide');mQuery('#CampaignEventPanel').removeClass('hide');if(groups.length===1){setTimeout(function(){mQuery('#CampaignEventPanelLists #'+groups[0]+'List').trigger('chosen:open')},10)}}};Mautic.campaignBuilderUpdateEventCloneButton=function(groups,eventType,anchorName){var $insertButton=mQuery('#EventInsertButton');var updatedUrl=$insertButton.attr('href').replace(/anchor=(.*?)$/,"anchor="+anchorName+"&anchorEventType="+eventType);$insertButton.attr('href',updatedUrl)};Mautic.campaignBuilderUpdateEventCloneDescription=function(){var cloneDetails=Mautic.getCampaignEventClone();if(cloneDetails){mQuery('[data-campaign-event-clone="sourceEventName"]').html(cloneDetails.sourceEventName);mQuery('[data-campaign-event-clone="sourceCampaignName"]').html(cloneDetails.sourceCampaignName)}};Mautic.campaignBuilderGetEndpointDetails=function(endpoint){var anchorName,eventId;if(typeof endpoint==='string'){eventId=endpoint}else{var parts=endpoint.anchor.cssClass.split(' ');if(parts.length>1){anchorName=parts[0];eventId=parts[1]}else{anchorName=parts[0];eventId=endpoint.elementId}}
return{'anchorName':anchorName,'eventId':eventId.replace('CampaignEvent_',''),'elementId':eventId,'eventType':mQuery('#'+eventId).data('type'),'event':mQuery('#'+eventId).data('event')}};Mautic.campaignBuilderPrepareNewSource=function(){var newSourcePos={left:mQuery(window).width()/2-100,top:50};mQuery('#CampaignEvent_newsource').css(newSourcePos);Mautic.campaignBuilderUpdateEventList(['Source'],!1,'list',!1,{left:newSourcePos.left-50,top:newSourcePos.top+35});mQuery('#SourceList').trigger('chosen:open')};Mautic.campaignBuilderValidateConnection=function(epDetails,targetType,targetEvent){var valid=!0;var sourceType=epDetails.eventType;var sourceEvent='source'===sourceType?sourceType:epDetails.event;if(typeof Mautic.campaignBuilderConnectionRestrictions[targetEvent]!=='undefined'){if('source'===sourceEvent){mQuery.each(Mautic.campaignBuilderConnectionRestrictions[targetEvent].source,function(eventType,events){if(events.length){valid=!1;return!1}});return valid}
if(typeof Mautic.campaignBuilderConnectionRestrictions[targetEvent].source[sourceType]!=='undefined'&&Mautic.campaignBuilderConnectionRestrictions[targetEvent].source[sourceType].length&&mQuery.inArray(sourceEvent,Mautic.campaignBuilderConnectionRestrictions[targetEvent].source[sourceType])===-1){valid=!1}}
if(typeof Mautic.campaignBuilderConnectionRestrictions[sourceEvent]!=='undefined'&&typeof Mautic.campaignBuilderConnectionRestrictions[sourceEvent].target[targetType]!=='undefined'&&Mautic.campaignBuilderConnectionRestrictions[sourceEvent].target[targetType].length){valid=(mQuery.inArray(targetEvent,Mautic.campaignBuilderConnectionRestrictions[sourceEvent].target[targetType])!==-1)}
if(typeof Mautic.campaignBuilderConnectionRestrictions.anchor[sourceType]!=='undefined'&&typeof Mautic.campaignBuilderConnectionRestrictions.anchor[sourceType][targetEvent]!=='undefined'){mQuery(Mautic.campaignBuilderConnectionRestrictions.anchor[sourceType][targetEvent]).each(function(key,anchor){switch(anchor){case 'inaction':anchor='no';break;case 'action':anchor='yes';break}
if(anchor==epDetails.anchorName){valid=!1;return!1}})}
return valid};Mautic.updateScheduledCampaignEvent=function(eventId,contactId){mQuery('#timeline-campaign-event-'+eventId+' .btn-reschedule').addClass('disabled');var converting=!1;var eventWrapper='#timeline-campaign-event-'+eventId;var eventSpan='.timeline-campaign-event-date-'+eventId;var eventText='#timeline-campaign-event-text-'+eventId;var saveButton='#timeline-campaign-event-save-'+eventId;var originalDate=mQuery(eventWrapper+' '+eventSpan).first().text();var revertInput=function(input){converting=!0;mQuery(input).datetimepicker('destroy');mQuery(eventSpan).text(originalDate);mQuery(eventWrapper+' .btn-reschedule').removeClass('disabled')};var date=mQuery(eventSpan).attr('data-date');mQuery(saveButton).show();var input=mQuery('<input type="text" id="timeline-reschedule"/>').css('height','20px').css('color','#000000').val(date).on('keyup',function(e){var code=e.keyCode||e.which;if(code==13){e.preventDefault();converting=!0
mQuery(input).prop('readonly',!0);mQuery(input).datetimepicker('destroy');Mautic.ajaxActionRequest('campaign:updateScheduledCampaignEvent',{eventId:eventId,contactId:contactId,date:mQuery(this).val(),originalDate:date},function(response){mQuery(eventSpan).text(response.formattedDate);mQuery(eventSpan).attr('data-date',response.date);mQuery(eventWrapper+' .btn-reschedule').removeClass('disabled');if(response.success){mQuery(eventText).removeClass('text-warning').addClass('text-info');mQuery(eventSpan).css('textDecoration','inherit');mQuery('.fa.timeline-campaign-event-cancelled-'+eventId).remove();mQuery('.timeline-campaign-event-scheduled-'+eventId).removeClass('hide');mQuery('.timeline-campaign-event-cancelled-'+eventId).addClass('hide');mQuery(saveButton).hide()}},!1)}else if(code==27){e.preventDefault();revertInput(input);mQuery(saveButton).hide()}}).on('blur',function(e){if(!converting){revertInput(input)}
mQuery(saveButton).hide()});mQuery('#timeline-campaign-event-'+eventId+' '+eventSpan).html(input);Mautic.activateDateTimeInputs('#timeline-reschedule');mQuery('#timeline-reschedule').focus()};Mautic.saveScheduledCampaignEvent=function(eventId,contactId){var saveButton='#timeline-campaign-event-save-'+eventId;mQuery(saveButton).addClass('disabled');var eventWrapper='#timeline-campaign-event-'+eventId;var eventSpan='.timeline-campaign-event-date-'+eventId;var eventText='#timeline-campaign-event-text-'+eventId;var date=mQuery(eventSpan).attr('data-date');Mautic.ajaxActionRequest('campaign:updateScheduledCampaignEvent',{eventId:eventId,contactId:contactId,date:mQuery('#timeline-reschedule').val(),originalDate:date},function(response){mQuery(eventSpan).text(response.formattedDate);mQuery(eventSpan).attr('data-date',response.date);if(response.success){mQuery(eventText).removeClass('text-warning').addClass('text-info');mQuery(eventSpan).css('textDecoration','inherit');mQuery('.fa.timeline-campaign-event-cancelled-'+eventId).remove();mQuery('.timeline-campaign-event-scheduled-'+eventId).removeClass('hide');mQuery('.timeline-campaign-event-cancelled-'+eventId).addClass('hide')}
mQuery(saveButton).removeClass('disabled').hide();mQuery(eventWrapper+' .btn-reschedule').removeClass('disabled')},!1)};Mautic.cancelScheduledCampaignEvent=function(eventId,contactId){mQuery('#timeline-campaign-event-'+eventId+' .btn').prop('disabled',!0).addClass('disabled');var eventWrapper='#timeline-campaign-event-'+eventId;var eventSpan='.timeline-campaign-event-date-'+eventId;var eventText='#timeline-campaign-event-text-'+eventId;Mautic.ajaxActionRequest('campaign:cancelScheduledCampaignEvent',{eventId:eventId,contactId:contactId,},function(response){if(response.success){mQuery(eventText).removeClass('text-info').addClass('text-warning');mQuery(eventWrapper+' .btn-edit').prop('disabled',!1).removeClass('disabled');mQuery('.timeline-campaign-event-scheduled-'+eventId).addClass('hide');mQuery('.timeline-campaign-event-cancelled-'+eventId).removeClass('hide')}else{mQuery(eventWrapper+' .btn').prop('disabled',!1).removeClass('disabled')}},!1)};Mautic.updateJumpToEventOptions=function(){var jumpToEventSelectNode=mQuery("#campaignevent_properties_jumpToEvent");jumpToEventSelectNode.children().remove();for(var eventId in Mautic.campaignBuilderCanvasEvents){var event=Mautic.campaignBuilderCanvasEvents[eventId];if(event.type!=='campaign.jump_to_event'&&event.eventType!=='decision'){var opt=mQuery("<option />").attr("value",event.id).text(event.name)
if(event.id==jumpToEventSelectNode.data("selected")){opt.attr("selected","selected")}
jumpToEventSelectNode.append(opt)}}
jumpToEventSelectNode.trigger("chosen:updated")};Mautic.campaignBuilderDeleteEvent=function(eventId,redirectEventId,deleteUrl,successCallback,errorCallback){let ajaxUrl=deleteUrl||'';if(redirectEventId&&ajaxUrl){ajaxUrl+=(ajaxUrl.indexOf('?')!==-1?'&':'?')+'redirectTo='+redirectEventId}
if(!Mautic.campaignBuilderCampaignElements.deletedEvents){Mautic.campaignBuilderCampaignElements.deletedEvents=[]}
const data={eventId:eventId,campaignId:mQuery('#campaignId').val(),redirectTo:redirectEventId,modifiedEvents:JSON.stringify(Mautic.campaignBuilderCampaignElements.modifiedEvents||{}),deletedEvents:JSON.stringify(Mautic.campaignBuilderCampaignElements.deletedEvents)};mQuery.ajax({url:ajaxUrl,type:'POST',data:data,success:function(response){if(response.success){if(typeof Mautic.campaignBuilderInstance!=='undefined'){Mautic.campaignBuilderInstance.remove(document.getElementById('CampaignEvent_'+eventId))}
if(Mautic.campaignBuilderCanvasEvents[eventId]){Mautic.campaignBuilderCanvasEvents[eventId].deleted=!0}
Mautic.addEventToDeletedEvents(eventId,redirectEventId);mQuery('#campaign_campaignEvents').val(JSON.stringify(Mautic.campaignBuilderCampaignElements));if(typeof response.deletedEvents!=='undefined'&&response.deletedEvents.length){mQuery.each(response.deletedEvents,function(i,eventData){if(Mautic.campaignBuilderCanvasEvents[eventData.id]){Mautic.campaignBuilderCanvasEvents[eventData.id].deleted=!0}
Mautic.addEventToDeletedEvents(eventData.id,eventData.redirectEvent)})}
if(typeof successCallback==='function'){successCallback(response)}}else if(typeof errorCallback==='function'){errorCallback(response)}},error:function(response){if(typeof errorCallback==='function'){errorCallback(response)}}})};Mautic.highlightJumpTarget=function(event,el){var element=mQuery(el);var parentEventElement=element.parent().parent();var highlightedAlready=parentEventElement.data('highlighted');var jumpTargetID='#CampaignEvent_'+element.data('jumpTarget');var jumpTarget=mQuery(jumpTargetID);var overlay=mQuery('#EventJumpOverlay');if(highlightedAlready){parentEventElement.data('highlighted',!1);overlay.hide();overlay.off('click.closejump');parentEventElement.css("z-index",1010);jumpTarget.css("z-index",1010)}else{if(mQuery('[data-highlighted="true"]').length){mQuery('[data-highlighted="true"]').find('.highlight-jump-target').click()}
parentEventElement.data('highlighted',!0);overlay.show();overlay.on('click.closejump',function(){element.click()});parentEventElement.css("z-index",2010);jumpTarget.css("z-index",2010)}};Mautic.showCampaignConfirmation=function(el){let element=mQuery(el);if(element.prop('checked')&&element.val()!=="1"){Mautic.showConfirmation(element,element.data('message-unpublish'))}else{Mautic.showConfirmation(element,element.data('message-publish'))}};Mautic.setPublishedButtonToYes=function(el){Mautic.dismissConfirmation();var yesButton=mQuery(el).parent('.btn-no').siblings('.btn-yes').children('input');var yesButtonId=mQuery(yesButton).attr('id');if(yesButtonId!==undefined){mQuery('#'+yesButtonId).trigger('click');mQuery(el).parent('.btn-no').removeClass('active');mQuery(el).parent('.btn-no').siblings('.btn-yes').addClass('active')}};Mautic.confirmationCampaignPublishStatus=function(el){let element=mQuery(el);if(element.data('status')==='published'){Mautic.showConfirmation(element,element.data('message-unpublish'))}else{Mautic.showConfirmation(element,element.data('message-publish'))}}
Mautic.confirmCallbackCampaignPublishStatus=function(action,el){let element=mQuery(el);let idClass=element.data('id-class');let model=element.data('model');let itemId=element.data('item-id');let query=element.data('query');let backdrop=element.data('backdrop');Mautic.togglePublishStatus(event,idClass,model,itemId,query,backdrop);Mautic.dismissConfirmation()}
Mautic.isCampaignCloneEventAllowedForEndpoint=function(endpointDetails){const eventClone=Mautic.getCampaignEventClone();if(!eventClone){return!1}
const eventType=eventClone.sourceEventType.charAt(0).toUpperCase()+eventClone.sourceEventType.slice(1);const allowedEvents=Mautic.campaignBuilderAnchorClickedAllowedEvents||[];const isValidConnection=Mautic.campaignBuilderValidateConnection(endpointDetails,eventClone.sourceEventType,eventClone.sourceType);return allowedEvents.includes(eventType)&&isValidConnection}
Mautic.getCampaignEventClone=function(){const eventClone=localStorage.getItem("mautic_campaign_event_clone");return eventClone===null?null:JSON.parse(eventClone)}
Mautic.setCampaignEventClone=function(data){localStorage.setItem("mautic_campaign_event_clone",JSON.stringify(data))}
Mautic.clearCampaignEventClone=function(){localStorage.removeItem("mautic_campaign_event_clone")}
Mautic.hideCampaignEventPanel=function(){mQuery('#CampaignEventPanel').addClass('hide')}
Mautic.getCampaignBuilderHtmlElements=function(){const managedElements=Mautic.campaignBuilderInstance.getManagedElements();return Object.values(managedElements).map(el=>el.el)}
Mautic.previewCampaignLabels=function(){const campaignBuilder=Mautic.campaignBuilderInstance;const allElements=Mautic.getCampaignBuilderHtmlElements();allElements.forEach(function(element){const id=element.id;const connections=campaignBuilder.getConnections({source:id});connections.forEach(function(connection){const connectionAnchor=connection.target.dataset.connected??null;if(connectionAnchor==='yes'){connection.addOverlay(["Label",{label:element.dataset.eventYesPercent+'%',location:0.25,cssClass:'jtk-label jtk-label--success',id:element.id+'yes-path-label'}])}
if(connectionAnchor==='no'){connection.addOverlay(["Label",{label:element.dataset.eventNoPercent+'%',location:0.25,cssClass:'jtk-label jtk-label--error',id:element.id+'no-path-label'}])}})})}
Mautic.previewCampaignEventDetails=function(){const $allElements=mQuery(Mautic.getCampaignBuilderHtmlElements());$allElements.click(function(event){const $el=mQuery(event.currentTarget);const eventId=$el.data('eventId');if(!eventId)return;if($el.hasClass('event-details-visible')){$el.removeClass('event-details-visible');return}else{$allElements.removeClass('event-details-visible');$el.addClass('event-details-visible')}
if($el.data('event-details-loaded'))return;mQuery.ajax({url:'/s/campaign/metrics/event-details/'+eventId,success:function(response){if(response.hasOwnProperty('first_execution_date')){renderEventDetails($el,response)}else{renderEventDetailsInfo($el,Mautic.translate('mautic.campaign.event.not_executed'))}},error:function(response){if(response.responseJSON.message){renderEventDetailsError($el,response.responseJSON.message)}else{renderEventDetailsError($el,Mautic.translate('mautic.core.request.error'))}}});event.preventDefault()});const renderEventDetails=function($el,data){const $dl=mQuery('<dl class="dl-horizontal campaign-event-details-dl"/>');Object.entries(data).forEach(([key,stat])=>{const translationKey='mautic.campaign.event.'+key;const $dt=mQuery('<dt>').attr('data-event-details-key',key).text(Mautic.translate(translationKey));const $dd=mQuery('<dd>').attr('data-event-details-key',key).text(stat.value);if(stat.tooltip){$dd.attr('title',stat.tooltip)}
$dl.append($dt).append($dd)});$el.find('.campaign-event-details').html($dl);$el.data('event-details-loaded',!0)}
const renderEventDetailsError=function($el,message){$el.find('.campaign-event-details').html('<div class="alert alert-danger mb-0" role="alert">'+message+'</div>')}
const renderEventDetailsInfo=function($el,message){$el.find('.campaign-event-details').html('<div class="alert alert-info mb-0" role="alert">'+message+'</div>')}}
Mautic.autoOrganizeCampaign=function(){if(typeof Mautic.campaignBuilderInstance==='undefined')return;const nodes={};const connections=Mautic.campaignBuilderInstance.getConnections();mQuery("#CampaignCanvas .draggable").each(function(){const id=mQuery(this).attr('id');nodes[id]={id:id,el:mQuery(this),out:[],in:[],rank:-1,x:0,y:0,width:mQuery(this).outerWidth()||260}});connections.forEach(conn=>{if(nodes[conn.sourceId]&&nodes[conn.targetId]){nodes[conn.sourceId].out.push(conn.targetId);nodes[conn.targetId].in.push(conn.sourceId)}});mQuery("#CampaignCanvas .draggable").each(function(){const id=mQuery(this).attr('id');if(nodes[id]){nodes[id].isSource=mQuery(this).hasClass('list-campaign-source')}});let moved=!0;let iterations=0;while(moved&&iterations<100){moved=!1;iterations++;Object.values(nodes).forEach(node=>{if(node.isSource){if(node.rank!==0){node.rank=0;moved=!0}
return}
if(node.in.length===0){if(node.rank!==0){node.rank=0;moved=!0}}else{let maxParentRank=-1;node.in.forEach(parentId=>{if(nodes[parentId].rank!==-1){maxParentRank=Math.max(maxParentRank,nodes[parentId].rank)}});if(maxParentRank!==-1&&node.rank!==maxParentRank+1){node.rank=maxParentRank+1;moved=!0}}})}
const layers={};Object.values(nodes).forEach(node=>{if(node.rank===-1)node.rank=0;if(!layers[node.rank])layers[node.rank]=[];layers[node.rank].push(node.id)});const visited=new Set();const horizontalSpacing=20;const verticalSpacing=100;function calculateSubtreeWidth(nodeId){if(visited.has(nodeId))return nodes[nodeId].subtreeWidth||nodes[nodeId].width;visited.add(nodeId);const node=nodes[nodeId];const downstreamChildren=node.out.filter(childId=>nodes[childId].rank>0);if(downstreamChildren.length===0){node.subtreeWidth=node.width;return node.subtreeWidth}
let totalChildrenWidth=0;downstreamChildren.forEach(childId=>{totalChildrenWidth+=calculateSubtreeWidth(childId)+horizontalSpacing});totalChildrenWidth-=horizontalSpacing;node.subtreeWidth=Math.max(node.width,totalChildrenWidth);return node.subtreeWidth}
const roots=Object.values(nodes).filter(n=>n.rank===0).sort((a,b)=>{const posA=a.el.position();const posB=b.el.position();return posA.left!==posB.left?posA.left-posB.left:(a.id<b.id?-1:1)});roots.forEach(root=>calculateSubtreeWidth(root.id));const positioned=new Set();function positionNode(nodeId,xOffset,yOffset){if(positioned.has(nodeId))return;positioned.add(nodeId);const node=nodes[nodeId];node.y=yOffset;node.x=xOffset+(node.subtreeWidth/2)-(node.width/2);let currentChildX=xOffset;node.out.forEach(childId=>{if(nodes[childId].rank>0){positionNode(childId,currentChildX,yOffset+verticalSpacing);currentChildX+=nodes[childId].subtreeWidth+horizontalSpacing}})}
let currentRootX=100;roots.forEach(root=>{positionNode(root.id,currentRootX,100);currentRootX+=root.subtreeWidth+horizontalSpacing*2});Object.values(nodes).forEach(node=>{node.el.css({top:node.y+'px',left:node.x+'px'});Mautic.campaignBuilderEventPositions[node.id]={'left':Math.round(node.x),'top':Math.round(node.y)}});Mautic.campaignBuilderInstance.repaintEverything();Mautic.fitCampaignToView()};Mautic.fitCampaignToView=function(){const canvas=mQuery('#CampaignCanvas');const nodes=canvas.find('.draggable');if(nodes.length===0)return;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;nodes.each(function(){const pos=mQuery(this).position();const width=mQuery(this).outerWidth();const height=mQuery(this).outerHeight();minX=Math.min(minX,pos.left);minY=Math.min(minY,pos.top);maxX=Math.max(maxX,pos.left+width);maxY=Math.max(maxY,pos.top+height)});minX-=100;minY-=100;maxX+=100;maxY+=100;const builderContent=mQuery('.builder-content');const contentWidth=builderContent.width();const contentHeight=builderContent.height();const campaignWidth=maxX-minX;const campaignHeight=maxY-minY;const scrollLeft=minX+(campaignWidth/2)-(contentWidth/2);const scrollTop=minY+(campaignHeight/2)-(contentHeight/2);builderContent.animate({scrollLeft:Math.max(0,scrollLeft),scrollTop:Math.max(0,scrollTop)},500)};Mautic.campaignAuditlogOnLoad=function(container,response){document.querySelector("#campaign-auditlog a[data-activate-details='all']")?.addEventListener("click",function(){let icon=this.querySelector("span:first-child");let isExpanded=icon.classList.contains("ri-arrow-down-s-line");document.querySelectorAll("#campaign-auditlog a[data-activate-details]:not([data-activate-details='all'])").forEach(element=>{const detailsId=element.getAttribute("data-activate-details");const detailsElem=document.querySelector(`#auditlog-details-${detailsId}`);const elementIcon=element.querySelector("span:first-child");if(detailsElem){detailsElem.classList.toggle("hide",!isExpanded);element.classList.toggle("active",isExpanded);elementIcon.classList.replace(isExpanded?"ri-arrow-down-s-line":"ri-arrow-up-s-line",isExpanded?"ri-arrow-up-s-line":"ri-arrow-down-s-line")}});icon.classList.replace(isExpanded?"ri-arrow-down-s-line":"ri-arrow-up-s-line",isExpanded?"ri-arrow-up-s-line":"ri-arrow-down-s-line")});document.querySelectorAll("#campaign-auditlog a[data-activate-details]:not([data-activate-details='all'])").forEach(anchor=>{anchor.addEventListener("click",function(){const detailsId=this.dataset.activateDetails;const icon=this.querySelector("span");const detailsElement=document.getElementById(`auditlog-details-${detailsId}`);if(detailsId&&detailsElement){const isActive=this.classList.contains("active");if(isActive){detailsElement.classList.add("hide");this.classList.remove("active");icon.classList.replace("ri-arrow-up-s-line","ri-arrow-down-s-line")}else{detailsElement.classList.remove("hide");this.classList.add("active");icon.classList.replace("ri-arrow-down-s-line","ri-arrow-up-s-line")}}})})};Mautic.categoryOnLoad=function(container,response){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','category')}
if(response&&response.inForm){var newOption=mQuery('<option />').val(response.categoryId);newOption.html(response.categoryName);mQuery(".category-select option:last").prev().before(newOption);newOption.prop('selected',!0);mQuery('.category-select').val(response.categoryId).trigger("chosen:updated")}};Mautic.messagesOnLoad=function(container){mQuery(container+' .sortable-panel-wrapper .modal').each(function(){mQuery(this).closest('.panel').append(mQuery(this))})};Mautic.toggleChannelFormDisplay=function(el,channel){Mautic.toggleTabPublished(el);if(mQuery(el).val()==="1"&&mQuery(el).prop('checked')){mQuery(el).closest('.tab-pane').find('.message_channel_properties_'+channel).removeClass('hide')}else{mQuery(el).closest('.tab-pane').find('.message_channel_properties_'+channel).addClass('hide')}};Mautic.cancelQueuedMessageEvent=function(channelId){Mautic.ajaxActionRequest('channel:cancelQueuedMessageEvent',{channelId:channelId},function(response){if(response.success){mQuery('#queued-message-'+channelId).addClass('disabled');mQuery('#queued-status-'+channelId).html(Mautic.translate('mautic.message.queue.status.cancelled'))}},!1)};Mautic.removeConfigValue=function(action,el){Mautic.executeAction(action,function(response){if(response.success){mQuery(el).parent().addClass('hide')}})};Mautic.parseQuery=function(query){var vars=query.split('&');var queryString={};for(var i=0;i<vars.length;i++){var pair=vars[i].split('=');var key=decodeURIComponent(pair[0]);var value=decodeURIComponent(pair[1]);if(typeof queryString[key]==='undefined'){queryString[key]=decodeURIComponent(value)}else if(typeof queryString[key]==='string'){var arr=[queryString[key],decodeURIComponent(value)];queryString[key]=arr}else{queryString[key].push(decodeURIComponent(value))}}
return queryString}
Mautic.parseUrlHashParameter=function(url){var url=url.split('#');if('undefined'!=typeof url[1]){return url[1]}
return!1}
Mautic.observeConfigTabs=function(){if(!mQuery('#config_coreconfig_last_shown_tab').length){return}
var parameters=Mautic.parseQuery(window.location.search.substr(1));if('undefined'!=typeof parameters.tab){mQuery('#config_coreconfig_last_shown_tab').val(parameters.tab);mQuery('a[data-toggle="tab"]').each(function(i,tab){if(mQuery(tab).attr('href')==('#'+parameters.tab)){mQuery(tab).tab('show')}})}
mQuery('a[data-toggle="tab"]').on('show.bs.tab',function(e){var tab=Mautic.parseUrlHashParameter(e.target.href);if(tab){mQuery('#config_coreconfig_last_shown_tab').val(tab)}})}
Mautic.resetEmailsToNotification=function(obj){const send_to_owner=obj.value;if(parseInt(send_to_owner,10)===1){mQuery(obj).closest('.panel-body').find('.notification_email_addresses').val('')}};Mautic.configDsnTestExecute=function(element,action,key){const $button=mQuery(element),$container=$button.closest('.config-dsn-container');$container.find('.ri-loader-3-line').removeClass('hide');Mautic.ajaxActionRequest(action,{key:key},function(response){const theClass=(response.success)?'has-success':'has-error',theMessage=response.message;$container.find('.config-dsn-test-container').removeClass('has-success has-error').addClass(theClass);$container.find('.help-block .status-msg').html(theMessage);$container.find('.ri-loader-3-line').addClass('hide')})};Mautic.configDsnTestDisable=function(element){const $container=mQuery(element).closest('.config-dsn-container');$container.find('.help-block .status-msg').html('');$container.find('.help-block .save-config-msg').removeClass('hide');$container.find('.config-dsn-test-button').prop('disabled',!0).addClass('disabled')};Mautic.showAnonymizeWarningMessage=function(anonymize_ip){if(mQuery(anonymize_ip).siblings('.toggle__label').attr('aria-checked')==='true'){mQuery('.anonymize_ip_address').addClass('hide')}else{mQuery('.anonymize_ip_address').removeClass('hide')}};mQuery(Mautic.observeConfigTabs);Mautic.widgetUrl=mauticBasePath+'/s/dashboard/widget/';Mautic.dashboardSubmitButton=!1;Mautic.dashboardOnLoad=function(container){Mautic.loadWidgets()};Mautic.loadWidgets=function(){Mautic.dashboardFilterPreventSubmit();jQuery('.widget').each(function(){let widgetId=jQuery(this).attr('data-widget-id');let container=jQuery('.widget[data-widget-id="'+widgetId+'"]');jQuery.ajax({url:Mautic.widgetUrl+widgetId+'?ignoreAjax=true',}).done(function(response){Mautic.widgetOnLoad(container,response)})});jQuery(document).ajaxComplete(function(){Mautic.initDashboardFilter()})};Mautic.initDashboardFilter=function(){let form=jQuery('form[name="daterange"]');form.find('button').replaceWith(Mautic.dashboardSubmitButton);form.unbind('submit').on('submit',function(e){e.preventDefault();Mautic.dashboardFilterPreventSubmit();jQuery('.widget').each(function(){let widgetId=jQuery(this).attr('data-widget-id');let element=jQuery('.widget[data-widget-id="'+widgetId+'"]');jQuery.ajax({type:'POST',url:Mautic.widgetUrl+widgetId+'?ignoreAjax=true',data:form.serializeArray(),success:function(response){Mautic.widgetOnLoad(element,response)}})})})};Mautic.dashboardFilterPreventSubmit=function(){let form=jQuery('form[name="daterange"]');let button=form.find('button:first');Mautic.dashboardSubmitButton=button.clone();button.width(button.width()+'px');button.html('<i class="ri-loader-3-line ri-spin"></i>');jQuery('.widget').find('.card-body').html('<div class="spinner"><i class="ri-loader-3-line ri-spin"></i></div>');form.unbind('submit').on('submit',function(e){e.preventDefault()})};Mautic.dashboardOnUnload=function(id){mQuery('.jvectormap-tip').remove()};Mautic.widgetOnLoad=function(container,response){if(!response.widgetId)return;var widget=mQuery('.widget[data-widget-id="'+response.widgetId+'"]');var widgetHtml=mQuery(response.widgetHtml);widgetHtml.find("*[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();Mautic.ajaxifyModal(this,event)});if(!widget.length){widget=mQuery('<div/>').addClass('widget').attr('data-widget-id',response.widgetId);mQuery('#dashboard-widgets').prepend(widget)}
widget.html(widgetHtml).css('width',response.widgetWidth+'%').css('height',response.widgetHeight+'%');Mautic.renderCharts(widgetHtml);const map=widgetHtml.find('.vector-map').first();if(map.length&&!map.hasClass('map-rendered')){Mautic.initMap(widgetHtml,'regions')}
Mautic.initWidgetRemoveEvents();Mautic.initWidgetSorting();Mautic.initDashboardFilter()};Mautic.initWidgetRemoveEvents=function(){jQuery('.remove-widget').unbind('click').on('click',function(e){e.preventDefault();element=jQuery(this);let url=element.attr('href');element.closest('.widget').remove();jQuery.ajax({url:url,})})};Mautic.initWidgetSorting=function(){var widgetsWrapper=mQuery('#dashboard-widgets');var bodyOverflow={};widgetsWrapper.sortable({handle:'.card-header h4',placeholder:'sortable-placeholder',items:'.widget',opacity:0.9,scroll:!0,scrollSpeed:10,tolerance:"pointer",cursor:'move',appendTo:'#dashboard-widgets',helper:function(e,ui){ui.children().each(function(){mQuery(this).width(mQuery(this).width());mQuery(this).height(mQuery(this).height())});bodyOverflow.overflowX=mQuery('body').css('overflow-x');bodyOverflow.overflowY=mQuery('body').css('overflow-y');mQuery('body').css({overflowX:'visible',overflowY:'visible'});mQuery("#dashboard-widgets .widget").each(function(i){var item=mQuery(this);var item_clone=item.clone();var canvas=item.find('canvas').first();if(canvas.length){var destCanvas=item_clone.find('canvas').first();var destCtx=destCanvas[0].getContext('2d');destCtx.drawImage(canvas[0],0,0)}
item.data("clone",item_clone);var position=item.position();item_clone.css({left:position.left,top:position.top,width:item.width(),visibility:"visible",position:"absolute",zIndex:1});item.css('visibility','hidden');mQuery("#cloned-widgets").append(item_clone)});return ui},start:function(e,ui){ui.helper.css('visibility','visible');ui.helper.data("clone").hide()},sort:function(e,ui){var tile=ui.item.find('.tile').first();ui.placeholder.css({marginTop:"5px",marginBottom:"5px",marginLeft:0,marginRight:0})},stop:function(){mQuery('body').css(bodyOverflow);mQuery("#dashboard-widgets .widget.exclude-me").each(function(){var item=mQuery(this);var clone=item.data("clone");var position=item.position();clone.css("left",position.left);clone.css("top",position.top);clone.show();item.removeClass("exclude-me")});mQuery("#dashboard-widgets .widget").css("visibility","visible");mQuery("#cloned-widgets .widget").remove();Mautic.saveWidgetSorting()},change:function(e,ui){mQuery("#dashboard-widgets .widget:not(.exclude-me)").each(function(){var item=mQuery(this);var clone=item.data("clone");clone.stop(!0,!1);var position=item.position();clone.animate({left:position.left,top:position.top},200)})}}).disableSelection()}
Mautic.saveWidgetSorting=function(){var widgetsWrapper=mQuery('#dashboard-widgets');var widgets=widgetsWrapper.children();var ordering=[];widgets.each(function(index,value){ordering.push(mQuery(this).attr('data-widget-id'))});Mautic.ajaxActionRequest('dashboard:updateWidgetOrdering',{'ordering':ordering},function(response){})}
Mautic.updateWidgetForm=function(element){Mautic.activateLabelLoadingIndicator('widget_type');var formWrapper=mQuery(element).closest('form');var WidgetFormValues=formWrapper.serializeArray();Mautic.ajaxActionRequest('dashboard:updateWidgetForm',WidgetFormValues,function(response){if(response.formHtml){var formHtml=mQuery(response.formHtml);formHtml.find('#widget_buttons').addClass('hide hidden');formWrapper.html(formHtml.children());Mautic.onPageLoad('#widget_params')}
Mautic.removeLabelLoadingIndicator()})};Mautic.exportDashboardLayout=function(text,baseUrl){var name=prompt(text,"");if(name!==null){if(name){baseUrl=baseUrl+"?name="+encodeURIComponent(name)}
window.location=baseUrl}};Mautic.saveDashboardLayout=function(text){var name=prompt(text,"");if(name){mQuery.ajax({type:'POST',url:mauticBaseUrl+'s/dashboard/save',data:{name:name}})}};Mautic.setDateRange=function(option){var today=new Date();var fromDate,toDate;switch(option){case 'today':fromDate=today;toDate=today;break;case 'yesterday':fromDate=new Date(today.getTime()-(24*60*60*1000));toDate=fromDate;break;default:if(typeof option==='number'){fromDate=new Date(today.getTime()-(option*24*60*60*1000));toDate=today}else{console.error('Invalid option');return}}
document.getElementById('daterange_date_from').value=Mautic.formatDate(fromDate);document.getElementById('daterange_date_to').value=Mautic.formatDate(toDate);document.getElementById('daterange_apply').click()};Mautic.formatDate=function(date){var monthNames=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];return monthNames[date.getMonth()]+" "+date.getDate()+", "+date.getFullYear()};Mautic.toggleDwcFilters=function(){mQuery("#dwcFiltersTab, #slotNameDiv").toggleClass("hide");if(mQuery("#dwcFiltersTab").hasClass('hide')){mQuery('.nav-tabs a[href="#details"]').click()}else{Mautic.dynamicContentOnLoad()}};Mautic.dwcGenerator=(function(){const copyBtnSelector='#generator-copy-dynamic-content-slot';const pluginTabSelector='#dwc--generator-plugins';const htmlTabSelector='#dwc--generator-html';const codeContainerSelector='.dwc--generator-content-code';const inputSelector='.dwc--generator-content-input';const switchCodeWrapperBtnSelector='#generator-switch-code-wrapper';const switchHtmlTagBtnSelector='#generator-switch-html-tag';let isPluginBracketMode=!0;let isUsingDiv=!0;const getActiveTabType=()=>{const activePane=document.querySelector('.tab-pane.active.in')||document.querySelector('.tab-pane.active');if(!activePane)return'plugin';return activePane.id==='dwc--generator-plugins'?'plugin':'html'};const toggleState=(currentState)=>!currentState;const updateInputValue=(container,inputValue)=>{const input=container.querySelector(inputSelector);if(input&&inputValue!==null)input.value=inputValue};const switchCodeWrapper=()=>{const pluginTab=document.querySelector(pluginTabSelector);if(!pluginTab)return;const pre=pluginTab.querySelector(codeContainerSelector);if(!pre)return;const input=pluginTab.querySelector(inputSelector);const inputValue=input?input.value:'';let code=pre.innerHTML;if(isPluginBracketMode){code=code.replace(/\{mautic/g,'[mautic').replace(/slot=".*?"\}/g,match=>match.replace('}',']')).replace(/\{\/mautic\}/g,'[/mautic]')}else{code=code.replace(/\[mautic/g,'{mautic').replace(/slot=".*?"\]/g,match=>match.replace(']','}')).replace(/\[\/mautic\]/g,'{/mautic}')}
pre.innerHTML=code;updateInputValue(pluginTab,inputValue);isPluginBracketMode=toggleState(isPluginBracketMode)};const switchHtmlTag=()=>{const htmlTab=document.querySelector(htmlTabSelector);if(!htmlTab)return;const pre=htmlTab.querySelector(codeContainerSelector);if(!pre)return;const input=htmlTab.querySelector(inputSelector);const inputValue=input?input.value:'';let code=pre.innerHTML;code=isUsingDiv?code.replace(/&lt;div/g,'&lt;span').replace(/&lt;\/div&gt;/g,'&lt;/span&gt;'):code.replace(/&lt;span/g,'&lt;div').replace(/&lt;\/span&gt;/g,'&lt;/div&gt;');pre.innerHTML=code;updateInputValue(htmlTab,inputValue);isUsingDiv=toggleState(isUsingDiv)};const copyCode=()=>{const activeTab=getActiveTabType();const container=document.querySelector(`${activeTab === 'plugin' ? pluginTabSelector : htmlTabSelector} ${codeContainerSelector}`);if(!container)return;const input=container.querySelector(inputSelector);const userValue=(input?input.value:'').trim();let code;if(activeTab==='plugin'){const slotMatch=container.textContent.match(/slot="([^"]+)"/);const slotName=slotMatch?slotMatch[1]:'';const wrapper=isPluginBracketMode?{open:`{mautic type="content" slot="${slotName}"}`,close:'{/mautic}'}:{open:`[mautic type="content" slot="${slotName}"]`,close:'[/mautic]'};code=`${wrapper.open}${userValue}${wrapper.close}`.trim()}else{const tag=isUsingDiv?'div':'span';const slotMatch=container.innerHTML.match(/data-param-slot-name="([^"]+)"/);const slotName=slotMatch?slotMatch[1]:'';code=`<${tag} data-slot="dwc" data-param-slot-name="${slotName}">${userValue}</${tag}>`}
navigator.clipboard.writeText(code).then(()=>{const flashMessage=Mautic.addInfoFlashMessage(Mautic.translate('mautic.core.copied'));Mautic.setFlashes(flashMessage)})};const init=()=>{const copyBtn=document.querySelector(copyBtnSelector);if(copyBtn)copyBtn.addEventListener('click',copyCode);const switchCodeBtn=document.querySelector(switchCodeWrapperBtnSelector);if(switchCodeBtn)switchCodeBtn.addEventListener('click',switchCodeWrapper);const switchTagBtn=document.querySelector(switchHtmlTagBtnSelector);if(switchTagBtn)switchTagBtn.addEventListener('click',switchHtmlTag);};return{init}})();Mautic.toggleContentEditor=function(){const typeField=mQuery('#dwc_type').val();const contentField=mQuery('#dwc_content');if(typeField==='html'){Mautic.ConvertFieldToCkeditor(contentField,MauticVars.maxButtons)}else if(typeField==='text'){if(ckEditors.size>0){ckEditors.forEach(function(value,key,map){map.get(key).destroy()})
ckEditors.clear()}}};Mautic.dynamicContentOnLoad=function(container,response){if(typeof container!=='object'){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','dynamicContent')}}
var availableFilters=mQuery('div.dwc-filter').find('select[data-mautic="available_filters"]');Mautic.activateChosenSelect(availableFilters,!1);Mautic.dynamicFiltersOnLoad('div.dwc-filter');Mautic.dwcGenerator.init()};Mautic.dynamicFiltersOnLoad=function(container,response){mQuery('#campaign-share-tab').hover(function(){if(Mautic.shareTableLoaded!=!0){Mautic.loadAjaxColumn('campaign-share-stat','lead:getCampaignShareStats','afterStatsLoad');Mautic.shareTableLoaded=!0}})
Mautic.afterStatsLoad=function(){Mautic.sortTableByColumn('#campaign-share-table','.campaign-share-stat',!0)}
if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','lead.list')}
var prefix='leadlist';var parent=mQuery('.dynamic-content-filter, .dwc-filter');if(parent.length){prefix=parent.attr('id')}
if(mQuery('#'+prefix+'_filters').length){mQuery('#available_filters').on('change',function(){if(mQuery(this).val()){Mautic.addDwcFilter(mQuery(this).val(),mQuery('option:selected',this).data('field-object'));mQuery(this).val('');mQuery(this).trigger('chosen:updated')}});mQuery('#'+prefix+'_filters .remove-selected').each(function(index,el){mQuery(el).on('click',function(){mQuery(this).closest('.panel').animate({'opacity':0},'fast',function(){mQuery(this).remove();Mautic.reorderSegmentFilters()});if(!mQuery('#'+prefix+'_filters li:not(.placeholder)').length){mQuery('#'+prefix+'_filters li.placeholder').removeClass('hide')}else{mQuery('#'+prefix+'_filters li.placeholder').addClass('hide')}})});var bodyOverflow={};mQuery('#'+prefix+'_filters').sortable({items:'.panel',helper:function(e,ui){ui.children().each(function(){if(mQuery(this).is(":visible")){mQuery(this).width(mQuery(this).width())}});bodyOverflow.overflowX=mQuery('body').css('overflow-x');bodyOverflow.overflowY=mQuery('body').css('overflow-y');mQuery('body').css({overflowX:'visible',overflowY:'visible'});return ui},scroll:!0,axis:'y',stop:function(e,ui){mQuery('body').css(bodyOverflow);ui.item.find('select.glue-select').first().val('and');Mautic.reorderSegmentFilters()}})}
var segmentContactForm=mQuery('#segment-contact-filters');if(segmentContactForm.length){segmentContactForm.on('change',function(){segmentContactForm.submit()}).on('keyup',function(){segmentContactForm.delay(200).submit()}).on('submit',function(e){e.preventDefault();Mautic.refreshSegmentContacts(segmentContactForm)})}};Mautic.addDwcFilter=function(elId,elObj){var filterId='#available_'+elObj+'_'+elId;var filterOption=mQuery(filterId);var label=filterOption.text();var alias=filterOption.val();var filterNum=parseInt(mQuery('.available-filters').data('index'));mQuery('.available-filters').data('index',filterNum+1);var prototypeStr=mQuery('.available-filters').data('prototype');var fieldType=filterOption.data('field-type');var fieldObject=filterOption.data('field-object');var isSpecial=(mQuery.inArray(fieldType,['leadlist','campaign','device_type','device_brand','device_os','lead_email_received','lead_email_sent','tags','multiselect','boolean','select','country','timezone','region','stage','locale','globalcategory'])!=-1);prototypeStr=prototypeStr.replace(/__name__/g,filterNum);prototypeStr=prototypeStr.replace(/__label__/g,label);prototype=mQuery(prototypeStr);var prefix='leadlist';var parent=mQuery(filterId).parents('.dynamic-content-filter, .dwc-filter');if(parent.length){prefix=parent.attr('id')}
var filterBase=prefix+"[filters]["+filterNum+"]";var filterIdBase=prefix+"_filters_"+filterNum+"_";if(isSpecial){var templateField=fieldType;if(fieldType=='boolean'||fieldType=='multiselect'){templateField='select'}
var template=mQuery('#templates .'+templateField+'-template').clone();template.attr('name',mQuery(template).attr('name').replace(/__name__/g,filterNum));template.attr('id',mQuery(template).attr('id').replace(/__name__/g,filterNum));prototype.find('input[name="'+filterBase+'[filter]"]').replaceWith(template)}
if(mQuery('#'+prefix+'_filters div.panel').length==0){prototype.find(".panel-heading").addClass('hide')}
if(fieldObject=='company'){prototype.find(".object-icon").removeClass('ri-user-6-fill').addClass('ri-building-2-line')}else{prototype.find(".object-icon").removeClass('ri-building-2-line').addClass('ri-user-6-fill')}
prototype.find(".inline-spacer").append(fieldObject);prototype.find("a.remove-selected").on('click',function(){mQuery(this).closest('.panel').animate({'opacity':0},'fast',function(){mQuery(this).remove();Mautic.reorderSegmentFilters()})});prototype.find("input[name='"+filterBase+"[field]']").val(elId);prototype.find("input[name='"+filterBase+"[type]']").val(fieldType);prototype.find("input[name='"+filterBase+"[object]']").val(fieldObject);var filterEl=(isSpecial)?"select[name='"+filterBase+"[filter]']":"input[name='"+filterBase+"[filter]']";prototype.appendTo('#'+prefix+'_filters');var filter=mQuery('#'+filterIdBase+'filter');if(isSpecial){if(fieldType=='select'||fieldType=='multiselect'||fieldType=='boolean'||fieldType=='leadlist'){var fieldOptions=filterOption.data("field-list");mQuery.each(fieldOptions,function(val,index){if(mQuery.isPlainObject(index)){var optGroup=index;mQuery.each(optGroup,function(value,index){mQuery('<option class="'+optGroup+'">').val(index).text(value).appendTo(filterEl)});mQuery('.'+index).wrapAll("<optgroup label='"+index+"' />")}else{mQuery('<option>').val(index).text(val).appendTo(filterEl)}})}}else if(fieldType=='lookup'){var fieldCallback=filterOption.data("field-callback");if(fieldCallback&&typeof Mautic[fieldCallback]=='function'){var fieldOptions=filterOption.data("field-list");Mautic[fieldCallback](filterIdBase+'filter',elId,fieldOptions)}else{filter.attr('data-target',alias);Mautic.activateLookupTypeahead(filter.parent())}}else if(fieldType=='datetime'){filter.datetimepicker({format:'Y-m-d H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(fieldType=='date'){filter.datetimepicker({timepicker:!1,format:'Y-m-d',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1,closeOnDateSelect:!0})}else if(fieldType=='time'){filter.datetimepicker({datepicker:!1,format:'H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(fieldType=='lookup_id'){var oldFilter=mQuery(filterEl);var newDisplay=oldFilter.clone();newDisplay.attr('name',filterBase+'[display]').attr('id',filterIdBase+'display');var oldDisplay=prototype.find("input[name='"+filterBase+"[display]']");var newFilter=mQuery(oldDisplay).clone();newFilter.attr('name',filterBase+'[filter]');newFilter.attr('id',filterIdBase+'filter');oldFilter.replaceWith(newFilter);oldDisplay.replaceWith(newDisplay);var fieldCallback=filterOption.data("field-callback");if(fieldCallback&&typeof Mautic[fieldCallback]=='function'){var fieldOptions=filterOption.data("field-list");Mautic[fieldCallback](filterIdBase+'display',elId,fieldOptions)}}else{filter.attr('type',fieldType)}
var operators=filterOption.data('field-operators');mQuery('#'+filterIdBase+'operator').html('');mQuery.each(operators,function(label,value){var newOption=mQuery('<option/>').val(value).text(label);newOption.appendTo(mQuery('#'+filterIdBase+'operator'))});Mautic.convertDwcFilterInput('#'+filterIdBase+'operator');Mautic.updateFilterPositioning(mQuery('#'+filterIdBase+'glue'))};Mautic.convertDwcFilterInput=function(el){var prefix='leadlist';var parent=mQuery(el).parents('.dynamic-content-filter, .dwc-filter');if(parent.length){prefix=parent.attr('id')}
var operator=mQuery(el).val();var regExp=/_filters_(\d+)_operator/;var matches=regExp.exec(mQuery(el).attr('id'));var filterNum=matches[1];var filterId='#'+prefix+'_filters_'+filterNum+'_filter';if(mQuery(filterId).parent().hasClass('has-error')){mQuery(filterId).parent().find('div.help-block').hide();mQuery(filterId).parent().removeClass('has-error')}
var disabled=(operator=='empty'||operator=='!empty');mQuery(filterId+', #'+prefix+'_filters_'+filterNum+'_display').prop('disabled',disabled);if(disabled){mQuery(filterId).val('')}
var newName='';var lastPos;if(mQuery(filterId).is('select')){var isMultiple=mQuery(filterId).attr('multiple');var multiple=(operator=='in'||operator=='!in');var placeholder=mQuery(filterId).attr('data-placeholder');if(multiple&&!isMultiple){mQuery(filterId).attr('multiple','multiple');newName=mQuery(filterId).attr('name')+'[]';mQuery(filterId).attr('name',newName);placeholder=mauticLang.chosenChooseMore}else if(!multiple&&isMultiple){mQuery(filterId).removeAttr('multiple');newName=mQuery(filterId).attr('name');lastPos=newName.lastIndexOf('[]');newName=newName.substring(0,lastPos);mQuery(filterId).attr('name',newName);placeholder=mauticLang.chosenChooseOne}
if(multiple){mQuery(filterId).find('option[value=""]').remove();mQuery(filterId+' option:selected').removeAttr('selected')}else{mQuery(filterId).prepend("<option value='' selected></option>")}
Mautic.destroyChosen(mQuery(filterId));mQuery(filterId).attr('data-placeholder',placeholder);Mautic.activateChosenSelect(mQuery(filterId))}};Mautic.standardDynamicContentUrl=function(options){if(!options){return}
var url=options.windowUrl;if(url){var editDynamicContentKey='/dwc/edit/dynamicContentId';var previewDynamicContentKey='/dwc/preview/dynamicContentId';if(url.indexOf(editDynamicContentKey)>-1||url.indexOf(previewDynamicContentKey)>-1){options.windowUrl=url.replace('dynamicContentId',mQuery('#campaignevent_properties_dynamicContent').val())}}
return options};Mautic.disabledDynamicContentAction=function(opener){if(typeof opener=='undefined'){opener=window}
var dynamicContent=opener.mQuery('#campaignevent_properties_dynamicContent').val();var disabled=dynamicContent===''||dynamicContent===null;opener.mQuery('#campaignevent_properties_editDynamicContentButton').prop('disabled',disabled)};Mautic.emailBatchSubmit=function(){if(Mautic.batchActionPrecheck("")){if(mQuery('#email_batch_newCategory').val()){const $emailBatchIds=mQuery('#email_batch_ids');if($emailBatchIds.length){$emailBatchIds.val(Mautic.getCheckedListIds(!1,!0))}
return!0}}
return!1};function setCategory(id,newCategory){const tr=document.querySelector("#row_email_"+id);const div=tr.querySelector("div.d-flex.ai-center.gap-xs");const span=div.querySelector("span");div.textContent=newCategory.name;span.style="background: #"+newCategory.color+";"
div.prepend(span)}
Mautic.emailBatchSubmitCallback=function(response){mQuery('#MauticSharedModal').modal('hide');console.log("Received: "+JSON.stringify(response));response.affected.forEach(function(id){setCategory(id,response.newCategory)})};Mautic.testMonitoredEmailServerConnection=function(mailbox){var data={host:mQuery('#config_emailconfig_monitored_email_'+mailbox+'_host').val(),port:mQuery('#config_emailconfig_monitored_email_'+mailbox+'_port').val(),encryption:mQuery('#config_emailconfig_monitored_email_'+mailbox+'_encryption').val(),user:mQuery('#config_emailconfig_monitored_email_'+mailbox+'_user').val(),password:mQuery('#config_emailconfig_monitored_email_'+mailbox+'_password').val(),mailbox:mailbox};var abortCall=!1;if(!data.host){mQuery('#config_emailconfig_monitored_email_'+mailbox+'_host').parent().addClass('has-error');abortCall=!0}else{mQuery('#config_emailconfig_monitored_email_'+mailbox+'_host').parent().removeClass('has-error')}
if(!data.port){mQuery('#config_emailconfig_monitored_email_'+mailbox+'_port').parent().addClass('has-error');abortCall=!0}else{mQuery('#config_emailconfig_monitored_email_'+mailbox+'_port').parent().removeClass('has-error')}
if(abortCall){return}
mQuery('#'+mailbox+'TestButtonContainer .ri-loader-3-line').removeClass('hide');Mautic.ajaxActionRequest('email:testMonitoredEmailServerConnection',data,function(response){var theClass=(response.success)?'has-success':'has-error';var theMessage=response.message;mQuery('#'+mailbox+'TestButtonContainer').removeClass('has-success has-error').addClass(theClass);mQuery('#'+mailbox+'TestButtonContainer .help-block').html(theMessage);mQuery('#'+mailbox+'TestButtonContainer .ri-loader-3-line').addClass('hide');if(response.folders){if(mailbox=='general'){mQuery('select[data-imap-folders]').each(function(index){var thisMailbox=mQuery(this).data('imap-folders');if(mQuery('#config_emailconfig_monitored_email_'+thisMailbox+'_override_settings_0').is(':checked')){var folder='#config_emailconfig_monitored_email_'+thisMailbox+'_folder';var curVal=mQuery(folder).val();mQuery(folder).html(response.folders);mQuery(folder).val(curVal);mQuery(folder).trigger('chosen:updated')}})}else{var folder='#config_emailconfig_monitored_email_'+mailbox+'_folder';var curVal=mQuery(folder).val();mQuery(folder).html(response.folders);mQuery(folder).val(curVal);mQuery(folder).trigger('chosen:updated')}}})};Mautic.disableSendTestEmailButton=function(element){mQuery(element).closest('.tab-pane').find('.config-dsn-test-container').each(function(){Mautic.configDsnTestDisable(this)})};Mautic.emailOnLoad=function(container,response){Mautic.internalDynamicContentItemCreateListeners=[];Mautic.internalDynamicContentFilterCreateListeners=[];if(mQuery('#emailform_plainText').length){var plaintext=mQuery('#emailform_plainText');Mautic.initAtWho(plaintext,plaintext.attr('data-token-callback'));Mautic.initSelectTheme(mQuery('#emailform_template'));Mautic.initEmailDynamicContent();Mautic.prepareVersioning(function(content){console.log('undo')},function(content){console.log('redo')});if(response&&response.inBuilder){Mautic.isInBuilder=!0;Mautic.launchBuilder('emailform');Mautic.processBuilderErrors(response)}}else if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','email')}
if(mQuery('table.email-list').length){var ids=[];mQuery('td.col-stats').each(function(){var id=mQuery(this).attr('data-stats');ids.push(id)});while(ids.length>0){let batchIds=ids.splice(0,1);Mautic.ajaxActionRequest('email:getEmailCountStats',{ids:batchIds},function(response){if(response.success&&response.stats){for(var i=0;i<response.stats.length;i++){var stat=response.stats[i];if(mQuery('#sent-count-'+stat.id).length){if(stat.pending){mQuery('#pending-'+stat.id+' > a').html(stat.pending);mQuery('#pending-'+stat.id).removeClass('hide')}
if(stat.queued){mQuery('#queued-'+stat.id+' > a').html(stat.queued);mQuery('#queued-'+stat.id).removeClass('hide')}
mQuery('#sent-count-'+stat.id+' > a').html(stat.sentCount);mQuery('#read-count-'+stat.id+' > a').html(stat.readCount);mQuery('#read-percent-'+stat.id+' > a').html(stat.readPercent)}}}},!1,!0,"GET")}}
if(mQuery('#emailGraphStats').length){var graphUrl=mQuery('#emailGraphStats').attr('data-graph-url');mQuery("#emailGraphStats").load(graphUrl,function(){Mautic.renderCharts();Mautic.initDateRangePicker('#emailGraphStats #daterange_date_from','#emailGraphStats #daterange_date_to')})}
var $loadDeliveredElements=mQuery('[data-email-stat-delivered-for]');if($loadDeliveredElements.length){$loadDeliveredElements.each(function(i,el){Mautic.loadEmailDeliveredStat(mQuery(el))})}
var $loadEmailUsage=mQuery('[data-fetch-email-usages]');if($loadEmailUsage.length){$loadEmailUsage.each(function(i,el){Mautic.loadEmailUsages(mQuery(el))})}
Mautic.initMailerIsOwnerGlobalCheck()};Mautic.emailOnUnload=function(id){if(id==='#app-content'){delete Mautic.listCompareChart}
if(typeof Mautic.ajaxActionXhrQueue!=='undefined'){delete Mautic.ajaxActionXhrQueue['email:getEmailCountStats']}};Mautic.insertEmailBuilderToken=function(editorId,token){var editor=Mautic.getEmailBuilderEditorInstances();editor[instance].insertText(token)};Mautic.getEmailAbTestWinnerForm=function(abKey){if(abKey&&mQuery(abKey).val()&&mQuery(abKey).closest('.form-group').hasClass('has-error')){mQuery(abKey).closest('.form-group').removeClass('has-error');if(mQuery(abKey).next().hasClass('help-block')){mQuery(abKey).next().remove()}}
Mautic.activateLabelLoadingIndicator('emailform_variantSettings_winnerCriteria');var emailId=mQuery('#emailform_sessionId').val();var query="action=email:getAbTestForm&abKey="+mQuery(abKey).val()+"&emailId="+emailId;mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(typeof response.html!='undefined'){if(mQuery('#emailform_variantSettings_properties').length){mQuery('#emailform_variantSettings_properties').replaceWith(response.html)}else{mQuery('#emailform_variantSettings').append(response.html)}
if(response.html!=''){Mautic.onPageLoad('#emailform_variantSettings_properties',response)}}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.removeLabelLoadingIndicator()}})};Mautic.submitSendForm=function(){Mautic.dismissConfirmation();mQuery('.btn-send').prop('disabled',!0);mQuery('form[name=\'batch_send\']').submit()};Mautic.emailSendOnLoad=function(container,response){if(mQuery('.email-send-progress').length){if(!mQuery('#emailSendProgress').length){Mautic.clearModeratedInterval('emailSendProgress')}else{Mautic.setModeratedInterval('emailSendProgress','sendEmailBatch',2000)}}};Mautic.emailSendOnUnload=function(){if(mQuery('.email-send-progress').length){Mautic.clearModeratedInterval('emailSendProgress');if(typeof Mautic.sendEmailBatchXhr!='undefined'){Mautic.sendEmailBatchXhr.abort();delete Mautic.sendEmailBatchXhr}}};Mautic.sendEmailBatch=function(){var data='id='+mQuery('.progress-bar-send').data('email')+'&pending='+mQuery('.progress-bar-send').attr('aria-valuemax')+'&batchlimit='+mQuery('.progress-bar-send').data('batchlimit');Mautic.sendEmailBatchXhr=Mautic.ajaxActionRequest('email:sendBatch',data,function(response){if(response.progress){if(response.progress[0]>0){mQuery('.imported-count').html(response.progress[0]);mQuery('.progress-bar-send').attr('aria-valuenow',response.progress[0]).css('width',response.percent+'%');mQuery('.progress-bar-send span.sr-only').html(response.percent+'%')}
if(response.progress[0]>=response.progress[1]){Mautic.clearModeratedInterval('emailSendProgress');setTimeout(function(){mQuery.ajax({type:'POST',showLoadingBar:!1,url:window.location,data:'complete=1',success:function(response){if(response.newContent){Mautic.processPageContent(response)}}})},1000)}}
Mautic.moderatedIntervalCallbackIsComplete('emailSendProgress')})};Mautic.autoGeneratePlaintext=function(){mQuery('.plaintext-spinner').removeClass('hide');Mautic.ajaxActionRequest('email:generatePlaintText',{id:mQuery('#emailform_sessionId').val(),custom:mQuery('#emailform_customHtml').val()},function(response){mQuery('#emailform_plainText').val(response.text);mQuery('.plaintext-spinner').addClass('hide')})};Mautic.selectEmailType=function(emailType){if(emailType=='list'){mQuery('#leadList').removeClass('hide');mQuery('#segmentTranslationParent').removeClass('hide');mQuery('#templateTranslationParent').addClass('hide');mQuery('.page-header h3').text(mauticLang.newListEmail);mQuery('#scheduleOptions').addClass('hide')}else{mQuery('#segmentTranslationParent').addClass('hide');mQuery('#templateTranslationParent').removeClass('hide');mQuery('#leadList').addClass('hide');mQuery('.page-header h3').text(mauticLang.newTemplateEmail)}
mQuery('#emailform_emailType').val(emailType);mQuery('body').removeClass('noscroll');mQuery('.email-type-modal').remove();mQuery('.email-type-modal-backdrop').remove()};Mautic.getTotalAttachmentSize=function(){var assets=mQuery('#emailform_assetAttachments').val();if(assets){assets={'assets':assets};Mautic.ajaxActionRequest('email:getAttachmentsSize',assets,function(response){mQuery('#attachment-size').text(response.size)},!1,!1,"GET")}else{mQuery('#attachment-size').text('0')}};Mautic.standardEmailUrl=function(options){if(options&&options.windowUrl&&options.origin){var url=options.windowUrl;var editEmailKey='/emails/edit/emailId';var previewEmailKey='/email/preview/emailId';if(url.indexOf(editEmailKey)>-1||url.indexOf(previewEmailKey)>-1){options.windowUrl=url.replace('emailId',mQuery(options.origin).val())}}
return options};Mautic.disabledEmailAction=function(opener,origin){if(typeof opener=='undefined'){opener=window}
var email=opener.mQuery(origin);if(email.length==0)return;var emailId=email.val();var disabled=emailId===''||emailId===null;opener.mQuery('[id$=_editEmailButton]').prop('disabled',disabled);opener.mQuery('[id$=_previewEmailButton]').prop('disabled',disabled)};Mautic.initEmailDynamicContent=function(){if(mQuery('#dynamic-content-container').length){mQuery('#emailFilters .remove-selected').each(function(index,el){mQuery(el).on('click',function(){mQuery(this).closest('.panel').animate({'opacity':0},'fast',function(){mQuery(this).remove()});if(!mQuery('#emailFilters li:not(.placeholder)').length){mQuery('#emailFilters li.placeholder').removeClass('hide')}else{mQuery('#emailFilters li.placeholder').addClass('hide')}})});mQuery('#addNewDynamicContent').on('click',function(e){e.preventDefault();Mautic.createNewDynamicContentItem()});Mautic.initDynamicContentItem()}};Mautic.createNewDynamicContentItem=function(jQueryVariant){var mQuery=(typeof jQueryVariant!='undefined')?jQueryVariant:window.mQuery;var tabHolder=mQuery('#dynamicContentTabs');var filterHolder=mQuery('#dynamicContentContainer');var dynamicContentPrototype=mQuery('#dynamicContentPrototype').data('prototype');var dynamicContentIndex=tabHolder.find('li').length-1;while(mQuery('#emailform_dynamicContent_'+dynamicContentIndex).length>0){dynamicContentIndex++}
var tabId='#emailform_dynamicContent_'+dynamicContentIndex;var tokenName='Dynamic Content '+(dynamicContentIndex+1);var newForm=dynamicContentPrototype.replace(/__name__/g,dynamicContentIndex);var newTab=mQuery('<li><a role="tab" data-toggle="tab" href="'+tabId+'">'+tokenName+'</a></li>');tabHolder.append(newTab);filterHolder.append(newForm);var itemContainer=mQuery(tabId);var textarea=itemContainer.find('.editor');var firstInput=itemContainer.find('input[type="text"]').first();if(Mautic.internalDynamicContentItemCreateListeners){Mautic.internalDynamicContentItemCreateListeners.forEach(function(callback){callback(textarea)})}
tabHolder.find('i').first().removeClass('ri-loader-3-line ri-spin').addClass('ri-add-line text-success');newTab.find('a').tab('show');firstInput.focus();Mautic.updateDynamicContentDropdown();Mautic.initDynamicContentItem(tabId,mQuery,tokenName);return tabId};Mautic.dynamicContentAddNewItemListener=function(callback){Mautic.internalDynamicContentItemCreateListeners.push(callback)}
Mautic.createNewDynamicContentFilter=function(el,jQueryVariant){var mQuery=(typeof jQueryVariant!='undefined')?jQueryVariant:window.mQuery;var $this=mQuery(el);var parentElement=$this.parents('.panel');var tabHolder=parentElement.find('.nav');var filterHolder=parentElement.find('.tab-content');var filterBlockPrototype=mQuery('#filterBlockPrototype');var filterIndex=filterHolder.find('.tab-pane').length-1;var dynamicContentIndex=$this.parents('.tab-pane').attr('id').match(/\d+$/)[0];var filterPrototype=filterBlockPrototype.data('prototype');var filterContainerId='#emailform_dynamicContent_'+dynamicContentIndex+'_filters_'+filterIndex;while(mQuery(filterContainerId).length>0){filterIndex++;filterContainerId='#emailform_dynamicContent_'+dynamicContentIndex+'_filters_'+filterIndex}
var newTab=mQuery('<li><a role="tab" data-toggle="tab" href="'+filterContainerId+'">Variation '+(filterIndex+1)+'</a></li>');var newForm=filterPrototype.replace(/__name__/g,filterIndex).replace(/dynamicContent_0_filters/g,'dynamicContent_'+dynamicContentIndex+'_filters').replace(/dynamicContent]\[0]\[filters/g,'dynamicContent]['+dynamicContentIndex+'][filters');tabHolder.append(newTab);filterHolder.append(newForm);var filterContainer=mQuery(filterContainerId);var availableFilters=filterContainer.find('select[data-mautic="available_filters"]');var altTextarea=filterContainer.find('.editor');var removeButton=filterContainer.find('.remove-item');Mautic.activateChosenSelect(availableFilters,!1,mQuery);availableFilters.on('change',function(){var $this=mQuery(this);if($this.val()){Mautic.addDynamicContentFilter($this.val(),mQuery);$this.val('');$this.trigger('chosen:updated')}});if(Mautic.internalDynamicContentFilterCreateListeners){Mautic.internalDynamicContentFilterCreateListeners.forEach(function(callback){callback(altTextarea)})}
Mautic.initRemoveEvents(removeButton,mQuery);newTab.find('a').tab('show');return filterContainerId};Mautic.dynamicContentAddNewFilterListener=function(callback){Mautic.internalDynamicContentFilterCreateListeners.push(callback)}
Mautic.initDynamicContentItem=function(tabId,jQueryVariant,tokenName){var mQuery=(typeof jQueryVariant!='undefined')?jQueryVariant:window.mQuery;var $el=mQuery('#dynamic-content-container');if($el.length===0){mQuery=parent.mQuery;$el=mQuery('#dynamic-content-container')}
if(tabId||typeof tabId!="undefined"){$el=mQuery(tabId)}
$el.find('.addNewDynamicContentFilter').on('click',function(e){e.preventDefault();Mautic.createNewDynamicContentFilter(this)});if(typeof tokenName!='undefined'){$el.find('.dynamic-content-token-name').val(tokenName)}
if($el.find('.dynamic-content-token-name').val()===''){var dynamicContent=$el.attr('id').match(/\d+$/);if(dynamicContent){var dynamicContentIndex=dynamicContent[0];$el.find('.dynamic-content-token-name').val('Dynamic Content '+dynamicContentIndex)}}
Mautic.initRemoveEvents($el.find('button.remove-selected'),mQuery);$el.find('select[data-mautic="available_filters"]').on('change',function(){var $this=mQuery(this);if($this.val()){Mautic.addDynamicContentFilter($this.val(),mQuery);$this.val('');$this.trigger('chosen:updated')}});Mautic.initRemoveEvents($el.find('.remove-item'),mQuery)};Mautic.updateDynamicContentDropdown=function(){var options=[];mQuery('#dynamicContentTabs').find('a[data-toggle="tab"]').each(function(){var prototype='<li><a class="fr-command" data-cmd="dynamicContent" data-param1="__tokenName__">__tokenName__</a></li>';var newOption=prototype.replace(/__tokenName__/g,mQuery(this).text());options.push(newOption)});mQuery('button[data-cmd="dynamicContent"]').next().find('ul').html(options.join(''))};Mautic.initMailerIsOwnerGlobalCheck=function(){let radioSelector='.mailer-is-owner-local';Mautic.toggleMailerIsOwnerWarningMessage(radioSelector);mQuery(radioSelector).on('change',function(){Mautic.toggleMailerIsOwnerWarningMessage(radioSelector)})}
Mautic.toggleMailerIsOwnerWarningMessage=function(radioSelector){let checkedRadio=mQuery(radioSelector+':checked');let globalMailerIsOwnerValue=checkedRadio.attr('data-global-mailer-is-onwer')?'1':'0';let warningMessageId='mailer-is-owner-waring';mQuery('#'+warningMessageId).remove();if(checkedRadio.val()!==globalMailerIsOwnerValue){let warning=mQuery('<div/>');warning.attr('id',warningMessageId);warning.html(checkedRadio.attr('data-warning'));warning.addClass('alert alert-warning mt-md');checkedRadio.closest('.form-group').append(warning)}}
Mautic.initRemoveEvents=function(elements,jQueryVariant){var mQuery=(typeof jQueryVariant!='undefined')?jQueryVariant:window.mQuery;if(elements.hasClass('remove-selected')){elements.on('click',function(){mQuery(this).closest('.panel').animate({'opacity':0},'fast',function(){mQuery(this).remove()})})}else{elements.on('click',function(e){e.preventDefault();var $this=mQuery(this);var parentElement=$this.parents('.tab-pane.dynamic-content');if($this.hasClass('remove-filter')){parentElement=$this.parents('.tab-pane.dynamic-content-filter')}
var tabLink=mQuery('a[href="#'+parentElement.attr('id')+'"]').parent();var tabContainer=tabLink.parent();parentElement.remove();tabLink.remove();if(tabContainer.hasClass('tabs-left')||$this.hasClass('remove-filter')){tabContainer.find('li').first().next().find('a').tab('show')}else{tabContainer.find('li').first().find('a').tab('show')}
Mautic.updateDynamicContentDropdown()})}};Mautic.addDynamicContentFilter=function(selectedFilter,jQueryVariant){var mQuery=(typeof jQueryVariant!='undefined')?jQueryVariant:window.mQuery;var dynamicContentItems=mQuery('.tab-pane.dynamic-content');var activeDynamicContent=dynamicContentItems.filter(':visible');var dynamicContentIndex=activeDynamicContent.attr('id').match(/\d+$/)[0];var dynamicContentFilterContainers=activeDynamicContent.find('div[data-filter-container]');var activeDynamicContentFilterContainer=dynamicContentFilterContainers.filter(':visible');var dynamicContentFilterIndex=dynamicContentFilterContainers.index(activeDynamicContentFilterContainer);var selectedOption=mQuery('option[data-mautic="available_'+selectedFilter+'"]').first();var label=selectedOption.text();var filterNum=activeDynamicContentFilterContainer.children('.panel').length;var prototype=mQuery('#filterSelectPrototype').data('prototype');var fieldObject=selectedOption.data('field-object');var fieldType=selectedOption.data('field-type');var isSpecial=(mQuery.inArray(fieldType,['leadlist','assets','lead_email_received','tags','multiselect','boolean','select','country','timezone','region','stage','locale'])!=-1);prototype=prototype.replace(/__name__/g,filterNum).replace(/__label__/g,label).replace(/dynamicContent_0_filters/g,'dynamicContent_'+dynamicContentIndex+'_filters').replace(/dynamicContent]\[0]\[filters/g,'dynamicContent]['+dynamicContentIndex+'][filters').replace(/filters_0_filters/g,'filters_'+dynamicContentFilterIndex+'_filters').replace(/filters]\[0]\[filters/g,'filters]['+dynamicContentFilterIndex+'][filters');if(filterNum===0){prototype=prototype.replace(/in-group/g,'')}
prototype=mQuery(prototype);if(fieldObject=='company'){prototype.find('.object-icon').removeClass('ri-user-6-fill').addClass('ri-building-2-line')}else{prototype.find('.object-icon').removeClass('ri-building-2-line').addClass('ri-user-6-fill')}
var filterBase="emailform[dynamicContent]["+dynamicContentIndex+"][filters]["+dynamicContentFilterIndex+"][filters]["+filterNum+"]";var filterIdBase="emailform_dynamicContent_"+dynamicContentIndex+"_filters_"+dynamicContentFilterIndex+"_filters_"+filterNum;if(isSpecial){var templateField=fieldType;if(fieldType=='boolean'||fieldType=='multiselect'||fieldType=='leadlist'){templateField='select'}
var template=mQuery('#templates .'+templateField+'-template').clone();var $template=mQuery(template);var templateNameAttr=$template.attr('name').replace(/__name__/g,filterNum).replace(/__dynamicContentIndex__/g,dynamicContentIndex).replace(/__dynamicContentFilterIndex__/g,dynamicContentFilterIndex);var templateIdAttr=$template.attr('id').replace(/__name__/g,filterNum).replace(/__dynamicContentIndex__/g,dynamicContentIndex).replace(/__dynamicContentFilterIndex__/g,dynamicContentFilterIndex);$template.attr('name',templateNameAttr);$template.attr('id',templateIdAttr);prototype.find('input[name="'+filterBase+'[filter]"]').replaceWith(template)}
if(activeDynamicContentFilterContainer.find('.panel').length==0){prototype.find(".panel-footer").addClass('hide')}
prototype.find("input[name='"+filterBase+"[field]']").val(selectedFilter);prototype.find("input[name='"+filterBase+"[type]']").val(fieldType);prototype.find("input[name='"+filterBase+"[object]']").val(fieldObject);var filterEl=(isSpecial)?"select[name='"+filterBase+"[filter]']":"input[name='"+filterBase+"[filter]']";activeDynamicContentFilterContainer.append(prototype);Mautic.initRemoveEvents(activeDynamicContentFilterContainer.find("button.remove-selected"),mQuery);var filter='#'+filterIdBase+'_filter';var fieldOptions=fieldCallback='';if(isSpecial){if(fieldType=='select'||fieldType=='boolean'||fieldType=='multiselect'||fieldType=='leadlist'){fieldOptions=selectedOption.data("field-list");mQuery.each(fieldOptions,function(index,val){mQuery('<option>').val(index).text(val).appendTo(filterEl)})}}else if(fieldType=='lookup'){fieldCallback=selectedOption.data("field-callback");if(fieldCallback&&typeof Mautic[fieldCallback]=='function'){fieldOptions=selectedOption.data("field-list");Mautic[fieldCallback](filterIdBase+'_filter',selectedFilter,fieldOptions)}}else if(fieldType=='datetime'){mQuery(filter).datetimepicker({format:'Y-m-d H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(fieldType=='date'){mQuery(filter).datetimepicker({timepicker:!1,format:'Y-m-d',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1,closeOnDateSelect:!0})}else if(fieldType=='time'){mQuery(filter).datetimepicker({datepicker:!1,format:'H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(fieldType=='lookup_id'){var oldFilter=mQuery(filterEl);var newDisplay=mQuery(oldFilter).clone();mQuery(newDisplay).attr('name',filterBase+'[display]').attr('id',filterIdBase+'_display');var oldDisplay=mQuery(prototype).find("input[name='"+filterBase+"[display]']");var newFilter=mQuery(oldDisplay).clone();mQuery(newFilter).attr('name',filterBase+'[filter]').attr('id',filterIdBase+'_filter');mQuery(oldFilter).replaceWith(newFilter);mQuery(oldDisplay).replaceWith(newDisplay);var fieldCallback=selectedOption.data("field-callback");if(fieldCallback&&typeof Mautic[fieldCallback]=='function'){fieldOptions=selectedOption.data("field-list");Mautic[fieldCallback](filterIdBase+'_display',selectedFilter,fieldOptions,mQuery)}}else{mQuery(filter).attr('type',fieldType)}
var operators=mQuery(selectedOption).data('field-operators');mQuery('#'+filterIdBase+'_operator').html('');mQuery.each(operators,function(label,value){var newOption=mQuery('<option/>').val(value).text(label);newOption.appendTo(mQuery('#'+filterIdBase+'_operator'))});Mautic.convertDwcFilterInput('#'+filterIdBase+'_operator',mQuery)};Mautic.copySubjectToName=function(elemSubject){let elemName=mQuery("#emailform_name");if(elemName.val()===""){elemName.val(elemSubject.val())}};Mautic.loadEmailDeliveredStat=function($el){var emailId=$el.data('email-stat-delivered-for');Mautic.ajaxActionRequest('email:getEmailDeliveredCount',{id:emailId},function(response){if(response.success){var delivered=response.delivered;$el.html(delivered)}},!1,!0,"GET")};Mautic.loadEmailUsages=function($el){var emailId=$el.data('fetch-email-usages');Mautic.ajaxActionRequest('email:getEmailUsages',{id:emailId},function(response){var usagesHtml=response.usagesHtml;$el.html(usagesHtml)},!1,!0,"GET")};(function(window,document,Mautic,$,Math){class Heatmap{constructor(emailId){this.emailId=emailId;this.mode='total';this.content=null;this.clickStats=null;this.$modal=null;this.$iframe=null;this.$iframeBody=null;this.iframeDocument=null;this.totalClicks=null;this.totalUniqueClicks=null;this.legendTemplate=null;this.links=[];this.gradient=[[44,59,182],[10,133,255],[240,223,66],[248,195,68],[255,132,58],[248,56,52]]}
init(){this.fetchHeatmap(function(){this.render()}.bind(this))}
render(){this.renderModal();this.bindEvents();this.$modal.modal('show')}
fetchHeatmap(callback){Mautic.ajaxActionRequest('email:heatmap',{id:this.emailId},function(response){this.content=response.content;this.clickStats=response.clickStats;this.totalClicks=response.totalClicks;this.totalUniqueClicks=response.totalUniqueClicks;this.legendTemplate=response.legendTemplate;callback()}.bind(this),!1,!0,"GET")}
waitForIframeContent(callback){const self=this;const interval=setInterval(function(){const height=self.$iframeBody.height();if(height>0&&self.lastHeight===height){callback();clearInterval(interval)}else{self.lastHeight=height}},100)}
bindEvents(){const self=this;self.$iframe[0].addEventListener('load',function(){self.waitForIframeContent(function(){self.renderLabels();self.bindMouseEvents()})});$(window).on('resize',function(){self.labelPositions()});self.$modal.on('hidden.bs.modal',function(){$(this).remove()});$('[data-toggle="heatmap-total"]').click(function(e){e.preventDefault();if(self.mode==='total')return;self.mode='total';$('[data-heatmap-clicks]').html(self.totalClicks);$('[data-toggle="heatmap-unique"]').removeClass('active');$(this).addClass('active');self.removeLabels();self.renderLabels()});$('[data-toggle="heatmap-unique"]').click(function(e){e.preventDefault();if(self.mode==='unique')return;self.mode='unique';$('[data-heatmap-clicks]').html(self.totalUniqueClicks);$('[data-toggle="heatmap-total"]').removeClass('active');$(this).addClass('active');self.removeLabels();self.renderLabels()});$('div.heatmap-legend').on('scroll mousewheel touchmove',function(e){e.preventDefault()})}
bindMouseEvents(){const self=this;const moveUp=function(){const $label=$(this).hasClass('heatmap-link')?$(this).data('heatmap-label'):$(this);$label.css('z-index',2050)}
const moveDown=function(){const $label=$(this).hasClass('heatmap-link')?$(this).data('heatmap-label'):$(this);$label.css('z-index',1050)}
self.$iframeBody.on('mouseenter focus','.heatmap-label, a.heatmap-link',moveUp);self.$iframeBody.on('mouseleave blur','.heatmap-label, a.heatmap-link',moveDown)}
renderModal(){this.$modal=$("<div />").attr({"class":"modal fade heatmap-modal"});const $modalDialogDiv=$("<div />").attr({"class":"modal-dialog modal-dialog-heatmap"});const $modalContentDiv=$("<div />").attr({"class":"modal-content"});this.$iframe=$('<iframe class="heatmap-iframe">'+this.content+'</iframe>');$modalContentDiv.append(this.$iframe);this.$modal.append($modalDialogDiv.append($modalContentDiv));$('body').append(this.$modal);this.iframeDocument=this.$iframe[0].contentDocument||this.$iframe[0].contentWindow.document;this.iframeDocument.open();this.iframeDocument.write(this.content);const cssLink=document.createElement("link");const baseUrl=window.mauticBaseUrl||'/';cssLink.href=baseUrl+'app/bundles/EmailBundle/Assets/css/heatmap.css';cssLink.rel="stylesheet";cssLink.type="text/css";this.iframeDocument.head.appendChild(cssLink);this.$iframeBody=$('body',this.iframeDocument);this.$iframeBody.addClass('heatmap-iframe-body');$modalContentDiv.append(this.legendTemplate);$modalContentDiv.append('<button type="button" class="modal-heatmap-close close" data-dismiss="modal"><span aria-hidden="true">×</span></button>');this.iframeDocument.close()}
renderLabels(){const self=this;self.clickStats.forEach(function(link){const $a=$('a[href="'+link.url+'"]',self.$iframeBody);$a.addClass('heatmap-link');$a.each(function(){const $el=$(this);self.links.push($el);const rate=self.mode==='total'?link.hits_rate:link.unique_hits_rate;const percent=Math.round(rate*100);const text=(self.mode==='total'?link.hits_text:link.unique_hits_text)+' ('+percent.toString()+'%)';const $label=$('<div class="heatmap-label"><p>'+text+'</p></div>');const bgColor=self.interpolateColor(rate);const bgColorLeft=self.interpolateColor(rate-0.1);const bgColorRight=self.interpolateColor(rate+0.1);$label.css({'background-color':bgColor,'background':'linear-gradient(to right, '+bgColorLeft+', '+bgColorRight+')'});const $border=$('<div class="heatmap-label-border"></div>');$border.css({'border':'1px dashed '+bgColor,'border-bottom':'none'});$label.append($border);$label.attr('title',link.url);self.$iframeBody.append($label);$el.data('heatmap-label',$label);$el.data('heatmap-label-border',$border);$label.data('a',$a)})});self.labelPositions()}
removeLabels(){if(!this.links.length)return;$(this.links).each(function(){$(this).data('heatmap-label').remove()});this.links=[]}
labelPositions(){const self=this;$(self.links).each(function(){const $el=$(this);const $label=$el.data('heatmap-label');const $border=$el.data('heatmap-label-border');const position=$el.position();$label.css({position:'absolute',top:position.top+$el.outerHeight(),left:position.left-1,'min-width':Math.max($el.outerWidth(),60)+2});$border.css({position:'absolute',bottom:'100%',left:0,width:$el.outerWidth(),height:$el.outerHeight()})})}
interpolateColor(rate){if(rate<=0){return'rgb('+this.gradient[0].join(',')+')'}
if(rate>=1){const lastIndex=this.gradient.length-1;return'rgb('+this.gradient[lastIndex].join(',')+')'}
const segmentCount=this.gradient.length-1;const segmentWidth=1/segmentCount;const segmentIndex=Math.floor(rate/segmentWidth);const segmentPercent=(rate-segmentIndex*segmentWidth)/segmentWidth;const color1=this.gradient[segmentIndex];const color2=this.gradient[segmentIndex+1];const r=Math.round(color1[0]+(color2[0]-color1[0])*segmentPercent);const g=Math.round(color1[1]+(color2[1]-color1[1])*segmentPercent);const b=Math.round(color1[2]+(color2[2]-color1[2])*segmentPercent);return'rgb('+r+','+g+','+b+')'}}
$(document).ready(function(){$('body').on('click','[data-toggle="email-heatmap"]',function(e){const emailId=$(this).data('email');const heatmap=new Heatmap(emailId);heatmap.init();e.preventDefault()})})})(window,document,Mautic,mQuery,Math);Mautic.activateExampleContactLookupField=function(fieldOptions,filterId){const lookupElementId='example_send_contact';const action=mQuery('#'+lookupElementId).attr('data-chosen-lookup');const options={limit:20,'searchKey':'lead.lead',};Mautic.activateFieldTypeahead(lookupElementId,filterId,options,action);mQuery('#'+lookupElementId).on("change",function(event){if(event.target.value===''){mQuery('#example_send_contact_id').val('')}})};Mautic.updateExampleContactLookupListFilter=function(field,item){if(item&&item.id){mQuery('#example_send_contact_id').val(item.id);mQuery(field).val(item.value)}};Mautic.formOnLoad=function(container){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','form.form')}
Mautic.toggleThemeSelectorVisibility();mQuery('#mauticform_renderStyle_0, #mauticform_renderStyle_1').on('change',Mautic.toggleThemeSelectorVisibility);Mautic.formBuilderNewComponentInit();Mautic.iniNewConditionalField();var bodyOverflow={};if(mQuery('#mauticforms_fields')){mQuery('#mauticforms_fields').sortable({items:'.form-field-wrapper',cancel:'',helper:function(e,ui){ui.children().each(function(){mQuery(this).width(mQuery(this).width())});bodyOverflow.overflowX=mQuery('body').css('overflow-x');bodyOverflow.overflowY=mQuery('body').css('overflow-y');mQuery('body').css({overflowX:'visible',overflowY:'visible'});return ui},scroll:!0,axis:'y',containment:'#mauticforms_fields .drop-here',stop:function(e,ui){mQuery('body').css(bodyOverflow);mQuery(ui.item).attr('style','');mQuery.ajax({type:"POST",url:mauticAjaxUrl+"?action=form:reorderFields",data:mQuery('#mauticforms_fields').sortable("serialize",{attribute:'data-sortable-id'})+"&formId="+mQuery('#mauticform_sessionId').val()})}});Mautic.initFormFieldButtons()}
if(mQuery('#mauticforms_actions')){mQuery('#mauticforms_actions').sortable({items:'.panel',cancel:'',helper:function(e,ui){ui.children().each(function(){mQuery(this).width(mQuery(this).width())});bodyOverflow.overflowX=mQuery('body').css('overflow-x');bodyOverflow.overflowY=mQuery('body').css('overflow-y');mQuery('body').css({overflowX:'visible',overflowY:'visible'});return ui},scroll:!0,axis:'y',containment:'#mauticforms_actions .drop-here',stop:function(e,ui){mQuery('body').css(bodyOverflow);mQuery(ui.item).attr('style','');mQuery.ajax({type:"POST",url:mauticAjaxUrl+"?action=form:reorderActions",data:mQuery('#mauticforms_actions').sortable("serialize")+"&formId="+mQuery('#mauticform_sessionId').val()})}});mQuery('#mauticforms_actions .mauticform-row').on('dblclick.mauticformactions',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()})}
Mautic.initHideItemButton('#mauticforms_fields');Mautic.initHideItemButton('#mauticforms_actions')};Mautic.formBuilderNewComponentInit=function(){mQuery('select.form-builder-new-component:not(.initialized)').change(function(e){const select=mQuery(this);select.addClass('initialized');select.find('option:selected');Mautic.ajaxifyModal(select.find('option:selected'));select.val('');select.chosen('destroy').chosen()})};Mautic.changeSelectOptions=function(selectEl,options){selectEl.empty();mQuery.each(options,function(key,field){selectEl.append(mQuery('<option></option>').attr('value',field.value).attr('data-list-type',field.isListType?1:0).text(field.label))});selectEl.trigger('chosen:updated')};Mautic.fetchFieldsOnObjectChange=function(){var fieldSelect=mQuery('select#formfield_mappedField');fieldSelect.attr('disable',!0);mQuery.ajax({url:mauticAjaxUrl+"?action=form:getFieldsForObject",data:{mappedObject:mQuery('select#formfield_mappedObject').val(),mappedField:mQuery('input#formfield_originalMappedField').val(),formId:mQuery('input#mauticform_sessionId').val()},success:function(response){Mautic.changeSelectOptions(fieldSelect,response.fields)},error:function(response,textStatus,errorThrown){Mautic.processAjaxError(response,textStatus,errorThrown)},complete:function(){fieldSelect.removeAttr('disable')}})};Mautic.formResultBatchSubmit=function(){if(!mQuery('#lead_batch_ids').val()){return!1}
return mQuery('#lead_batch_add').val()||mQuery('#lead_batch_remove').val()};Mautic.updateFormFields=function(){Mautic.activateLabelLoadingIndicator('campaignevent_properties_field');var formId=mQuery('#campaignevent_properties_form').val();Mautic.ajaxActionRequest('form:updateFormFields',{'formId':formId},function(response){if(response.fields){var select=mQuery('#campaignevent_properties_field');select.find('option').remove();var fieldOptions={};mQuery.each(response.fields,function(key,field){var option=mQuery('<option></option>').attr('value',field.alias).text(field.label);select.append(option);fieldOptions[field.alias]=field.options});select.attr('data-field-options',JSON.stringify(fieldOptions));select.trigger('chosen:updated');Mautic.updateFormFieldValues(select)}
Mautic.removeLabelLoadingIndicator()})};Mautic.updateFormFieldValues=function(field){field=mQuery(field);var fieldValue=field.val();var options=jQuery.parseJSON(field.attr('data-field-options'));var valueField=mQuery('#campaignevent_properties_value');var valueFieldAttrs={'class':valueField.attr('class'),'id':valueField.attr('id'),'name':valueField.attr('name'),'autocomplete':valueField.attr('autocomplete'),'value':valueField.attr('value')};if(typeof options[fieldValue]!=='undefined'&&!mQuery.isEmptyObject(options[fieldValue])){var newValueField=mQuery('<select/>').attr('class',valueFieldAttrs['class']).attr('id',valueFieldAttrs.id).attr('name',valueFieldAttrs.name).attr('autocomplete',valueFieldAttrs.autocomplete).attr('value',valueFieldAttrs.value);mQuery.each(options[fieldValue],function(key,optionVal){var option=mQuery("<option></option>").attr('value',key).text(optionVal);newValueField.append(option)});valueField.replaceWith(newValueField)}else{var newValueField=mQuery('<input/>').attr('type','text').attr('class',valueFieldAttrs['class']).attr('id',valueFieldAttrs.id).attr('name',valueFieldAttrs.name).attr('autocomplete',valueFieldAttrs.autocomplete).attr('value',valueFieldAttrs.value);valueField.replaceWith(newValueField)}};Mautic.formFieldOnLoad=function(container,response){if(response.fieldHtml){var newHtml=response.fieldHtml;var fieldId='#mauticform_'+response.fieldId;var fieldContainer=mQuery(fieldId).closest('.form-field-wrapper');if(mQuery(fieldId).length){mQuery(fieldContainer).replaceWith(newHtml);var newField=!1}else{var parentContainer=mQuery('#mauticform_'+response.parent);if(parentContainer.length){(parentContainer.parents('.panel:first')).append(newHtml)}else{var panel=mQuery('#mauticforms_fields .mauticform-button-wrapper').closest('.form-field-wrapper');panel.before(newHtml)}
var newField=!0}
var fieldContainer=mQuery(fieldId).closest('.form-field-wrapper');mQuery(fieldContainer).find("[data-toggle='ajax']").click(function(event){event.preventDefault();return Mautic.ajaxifyLink(this,event)});mQuery(fieldContainer).find("*[data-toggle='tooltip']").tooltip({html:!0});mQuery(fieldContainer).find("[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();Mautic.ajaxifyModal(this,event)});Mautic.initFormFieldButtons(fieldContainer);Mautic.initHideItemButton(fieldContainer);if(!mQuery('#fields-panel').hasClass('in')){mQuery('a[href="#fields-panel"]').trigger('click')}
if(newField){mQuery('.bundle-main-inner-wrapper').scrollTop(mQuery('.bundle-main-inner-wrapper').height())}
if(mQuery('#form-field-placeholder').length){mQuery('#form-field-placeholder').remove()}
Mautic.activateChosenSelect(mQuery('.form-builder-new-component'));Mautic.formBuilderNewComponentInit();Mautic.iniNewConditionalField()}};Mautic.iniNewConditionalField=function(){mQuery('.add-new-conditional-field').click(function(e){e.preventDefault();mQuery(this).parent().next().show('normal')})
mQuery('.add-new-conditional-field').parent().next().hide()}
Mautic.initFormFieldButtons=function(container){if(typeof container=='undefined'){mQuery('#mauticforms_fields .mauticform-row').off(".mauticformfields");var container='#mauticforms_fields'}
mQuery(container).find('.mauticform-row').on('dblclick.mauticformfields',function(event){event.preventDefault();mQuery(this).closest('.form-field-wrapper').find('.btn-edit').first().click()})};Mautic.formActionOnLoad=function(container,response){if(response.actionHtml){var newHtml=response.actionHtml;var actionId='#mauticform_action_'+response.actionId;if(mQuery(actionId).length){mQuery(actionId).replaceWith(newHtml);var newField=!1}else{mQuery(newHtml).appendTo('#mauticforms_actions .drop-here');var newField=!0}
mQuery(actionId+" [data-toggle='ajax']").click(function(event){event.preventDefault();return Mautic.ajaxifyLink(this,event)});mQuery(actionId+" *[data-toggle='tooltip']").tooltip({html:!0});mQuery(actionId+" [data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();Mautic.ajaxifyModal(this,event)});Mautic.initHideItemButton(actionId);mQuery('#mauticforms_actions .mauticform-row').off(".mauticform");mQuery('#mauticforms_actions .mauticform-row').on('dblclick.mauticformactions',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()});if(!mQuery('#actions-panel').hasClass('in')){mQuery('a[href="#actions-panel"]').trigger('click')}
if(newField){mQuery('.bundle-main-inner-wrapper').scrollTop(mQuery('.bundle-main-inner-wrapper').height())}
if(mQuery('#form-action-placeholder').length){mQuery('#form-action-placeholder').remove()}}};Mautic.initHideItemButton=function(container){mQuery(container).find('[data-hide-panel]').click(function(e){e.preventDefault();mQuery(this).closest('.form-field-wrapper, .mauticform-row').hide('fast')})}
Mautic.onPostSubmitActionChange=function(value){if(value=='return'){mQuery('#mauticform_postActionProperty').prev().removeClass('required')}else{mQuery('#mauticform_postActionProperty').prev().addClass('required')}
mQuery('#mauticform_postActionProperty').next().html('');mQuery('#mauticform_postActionProperty').parent().removeClass('has-error')};Mautic.selectFormType=function(formType){mQuery('#mauticform_formType').val(formType)};Mautic.toggleThemeSelectorVisibility=function(){var selectField=mQuery('#mauticform_template');var chosenContainer=mQuery('#mauticform_template_chosen');if(mQuery('#mauticform_renderStyle_0').prop('checked')){selectField.val('').trigger('chosen:updated');chosenContainer.addClass('chosen-disabled')}else{chosenContainer.removeClass('chosen-disabled')}};Mautic.integrationsConfigOnLoad=function(){mQuery('.integration-keyword-filter').each(function(){mQuery(this).off("keyup.integration-filter").on("keyup.integration-filter",function(event){var integration=mQuery(this).attr('data-integration');var object=mQuery(this).attr('data-object');Mautic.getPaginatedIntegrationFields({'integration':integration,'object':object,'keyword':mQuery(this).val()},1,this)})});Mautic.activateIntegrationFieldUpdateActions()};Mautic.getPaginatedIntegrationFields=function(settings,page,element){var requestName=settings.integration+'-'+settings.object;var action=mauticBaseUrl+'s/integration/'+settings.integration+'/config/'+settings.object+'/'+page;if(settings.keyword){action=action+'?keyword='+settings.keyword}
if(typeof Mautic.activeActions=='undefined'){Mautic.activeActions={}}else if(typeof Mautic.activeActions[requestName]!='undefined'){Mautic.activeActions[requestName].abort()}
var object=settings.object;var fieldsTab='#field-mappings-'+object+'-container';if(element&&mQuery(element).is('input')){Mautic.activateLabelLoadingIndicator(mQuery(element).attr('id'))}
var fieldsContainer='#field-mappings-'+object;var modalId='#'+mQuery(fieldsContainer).closest('.modal').attr('id');Mautic.startModalLoadingBar(modalId);Mautic.activeActions[requestName]=mQuery.ajax({showLoadingBar:!1,url:action,type:"POST",dataType:"json",success:function(response){if(response.success){mQuery(fieldsContainer).html(response.html);Mautic.onPageLoad(fieldsContainer);Mautic.activateIntegrationFieldUpdateActions();if(mQuery(fieldsTab).length){mQuery(fieldsTab).removeClass('hide')}}else if(mQuery(fieldsTab).length){mQuery(fieldsTab).addClass('hide')}
if(element){Mautic.removeLabelLoadingIndicator()}
Mautic.stopModalLoadingBar(modalId)},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){delete Mautic.activeActions[requestName]}})};Mautic.updateIntegrationField=function(integration,object,field,fieldOption,fieldValue){var action=mauticBaseUrl+'s/integration/'+integration+'/config/'+object+'/field/'+field;var modal=mQuery('form[name=integration_config]').closest('.modal');var requestName=integration+object+field+fieldOption;mQuery(modal).find('.modal-form-buttons .btn').prop('disabled',!0);if(typeof Mautic.activeActions=='undefined'){Mautic.activeActions={}}else if(typeof Mautic.activeActions[requestName]!='undefined'){Mautic.activeActions[requestName].abort()}
Mautic.startModalLoadingBar(mQuery(modal).attr('id'));var obj={};obj[fieldOption]=fieldValue;Mautic.activeActions[requestName]=mQuery.ajax({showLoadingBar:!1,url:action,type:"POST",dataType:"json",data:obj,error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){modal.find('.modal-form-buttons .btn').prop('disabled',!1);delete Mautic.activeActions[requestName]}})};Mautic.activateIntegrationFieldUpdateActions=function(){mQuery('.integration-mapped-field').each(function(){mQuery(this).off("change.integration-mapped-field").on("change.integration-mapped-field",function(event){var integration=mQuery(this).attr('data-integration');var object=mQuery(this).attr('data-object');var field=mQuery(this).attr('data-field');Mautic.updateIntegrationField(integration,object,field,'mappedField',mQuery(this).val())})});mQuery('.integration-sync-direction').each(function(){mQuery(this).off("change.integration-sync-direction").on("change.integration-sync-direction",function(event){var integration=mQuery(this).attr('data-integration');var object=mQuery(this).attr('data-object');var field=mQuery(this).attr('data-field');Mautic.updateIntegrationField(integration,object,field,'syncDirection',mQuery(this).val())})})};Mautic.authorizeIntegration=function(){mQuery('#integration_details_in_auth').val(1);Mautic.postForm(mQuery('form[name="integration_config"]'),'loadIntegrationAuthWindow')};Mautic.companyOnLoad=function(container,response){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','lead.company')}
Mautic.loadAndProcessPageContent('#company_contact_engagement');Mautic.loadAndProcessPageContent('#contacts-table')}
Mautic.leadOnLoad=function(container,response){Mautic.addKeyboardShortcut('a','Quick add a New Contact',function(e){if(mQuery('a.quickadd').length){mQuery('a.quickadd').click()}else if(mQuery('a.btn-leadnote-add').length){mQuery('a.btn-leadnote-add').click()}},'contact pages');Mautic.addKeyboardShortcut('v','Toggle View',function(e){if(mQuery('.shuffle-grid').length){mQuery('#table-view').click()}else{mQuery('#card-view').click()}},'contact pages');Mousetrap.stopCallback=function(e,element,combo){if(element.id=='leadnote_text'&&combo!='mod+enter'){return!0}
if((' '+element.className+' ').indexOf(' mousetrap ')>-1){return!1}
return element.tagName=='INPUT'||element.tagName=='SELECT'||element.tagName=='TEXTAREA'||(element.contentEditable&&element.contentEditable=='true')};var timelineForm=mQuery(container+' #timeline-filters');if(timelineForm.length){timelineForm.on('change',function(){timelineForm.submit()}).on('keyup',function(){timelineForm.delay(200).submit()}).on('submit',function(e){e.preventDefault();Mautic.refreshLeadTimeline(timelineForm)});var toggleTimelineDetails=function(el){var activateDetailsState=mQuery(el).hasClass('active');if(activateDetailsState){mQuery('#timeline-details-'+detailsId).addClass('hide');mQuery(el).removeClass('active')}else{mQuery('#timeline-details-'+detailsId).removeClass('hide');mQuery(el).addClass('active')}};Mautic.leadTimelineOnLoad(container,response);Mautic.leadAuditlogOnLoad(container,response)}
var auditlogForm=mQuery(container+' #auditlog-filters');if(auditlogForm.length){auditlogForm.on('change',function(){auditlogForm.submit()}).on('keyup',function(){auditlogForm.delay(200).submit()}).on('submit',function(e){e.preventDefault();Mautic.refreshLeadAuditLog(auditlogForm)})}
var noteForm=mQuery(container+' #note-filters');if(noteForm.length){noteForm.on('change',function(){noteForm.submit()}).on('keyup',function(){noteForm.delay(200).submit()}).on('submit',function(e){e.preventDefault();Mautic.refreshLeadNotes(noteForm)})}
if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','lead.lead')}
if(mQuery(container+' #notes-container').length){Mautic.activateSearchAutocomplete('NoteFilter','lead.note')}
if(mQuery('#lead_preferred_profile_image').length){mQuery('#lead_preferred_profile_image').on('change',function(){if(mQuery(this).val()=='custom'){mQuery('#customAvatarContainer').slideDown('fast')}else{mQuery('#customAvatarContainer').slideUp('fast')}})}
if(mQuery('.lead-avatar-panel').length){mQuery('.lead-avatar-panel .avatar-collapser a.arrow').on('click',function(){setTimeout(function(){var status=(mQuery('#lead-avatar-block').hasClass('in')?'expanded':'collapsed');Cookies.set('mautic_lead_avatar_panel',status,{expires:30})},500)})}
if(mQuery('#anonymousLeadButton').length){var searchValue=mQuery('#list-search').typeahead('val').toLowerCase();var string=mQuery('#anonymousLeadButton').data('anonymous').toLowerCase();if(searchValue.indexOf(string)>=0&&searchValue.indexOf('!'+string)==-1){mQuery('#anonymousLeadButton').addClass('btn-primary')}else{mQuery('#anonymousLeadButton').removeClass('btn-primary')}}
var leadMap=[];mQuery(document).on('shown.bs.tab','a#load-lead-map',()=>{leadMap=Mautic.initMap('#place-container','markers')});mQuery('a[data-toggle="tab"]').not('a#load-lead-map').on('shown.bs.tab',function(e){if(leadMap.length){leadMap.destroyMap();leadMap=undefined}});Mautic.initUniqueIdentifierFields();if(mQuery(container+' .panel-companies').length){mQuery(container+' .panel-companies .ri-check-line').tooltip({html:!0})}
mQuery('#lead_tags_chosen input').keyup(function(el){const newTag=mQuery('#lead_tags_chosen input').val();if(el.key==="Escape"&&newTag!==''){const selectElement=mQuery('#lead_tags').get();const selectedValues=mQuery('#lead_tags').val();const payload=[...selectedValues,newTag];Mautic.activateLabelLoadingIndicator(mQuery(selectElement).attr('id'));Mautic.ajaxActionRequest('lead:addLeadTags',{tags:JSON.stringify(payload)},function(response){if(response.tags){mQuery('#'+mQuery(selectElement).attr('id')).html(response.tags);mQuery('#'+mQuery(selectElement).attr('id')).trigger('chosen:updated')}
Mautic.removeLabelLoadingIndicator()})}});Mautic.lazyLoadContactStatsOnLeadLoad()};Mautic.leadTimelineOnLoad=function(container,response){mQuery("#contact-timeline a[data-activate-details='all']").on('click',function(){var $icon=mQuery(this).find('span').first();if($icon.hasClass('ri-arrow-down-s-line')){mQuery("#contact-timeline a[data-activate-details!='all']").each(function(){var detailsId=mQuery(this).data('activate-details');if(detailsId&&mQuery('#timeline-details-'+detailsId).length){mQuery('#timeline-details-'+detailsId).removeClass('hide');mQuery(this).addClass('active')}});$icon.removeClass('ri-arrow-down-s-line').addClass('ri-arrow-up-s-line')}else{mQuery("#contact-timeline a[data-activate-details!='all']").each(function(){var detailsId=mQuery(this).data('activate-details');if(detailsId&&mQuery('#timeline-details-'+detailsId).length){mQuery('#timeline-details-'+detailsId).addClass('hide');mQuery(this).removeClass('active')}});$icon.removeClass('ri-arrow-up-s-line').addClass('ri-arrow-down-s-line')}});mQuery("#contact-timeline a[data-activate-details!='all']").on('click',function(){var detailsId=mQuery(this).data('activate-details');var $icon=mQuery(this).find('span').first();if(detailsId&&mQuery('#timeline-details-'+detailsId).length){var activateDetailsState=mQuery(this).hasClass('active');if(activateDetailsState){mQuery('#timeline-details-'+detailsId).addClass('hide');mQuery(this).removeClass('active');$icon.removeClass('ri-arrow-up-s-line').addClass('ri-arrow-down-s-line')}else{mQuery('#timeline-details-'+detailsId).removeClass('hide');mQuery(this).addClass('active');$icon.removeClass('ri-arrow-down-s-line').addClass('ri-arrow-up-s-line')}}});if(response&&typeof response.timelineCount!=='undefined'){mQuery('#TimelineCount').html(response.timelineCount)}};Mautic.leadAuditlogOnLoad=function(container,response){mQuery("#contact-auditlog a[data-activate-details='all']").on('click',function(){var $icon=mQuery(this).find('span').first();if($icon.hasClass('ri-arrow-down-s-line')){mQuery("#contact-auditlog a[data-activate-details!='all']").each(function(){var detailsId=mQuery(this).data('activate-details');if(detailsId&&mQuery('#auditlog-details-'+detailsId).length){mQuery('#auditlog-details-'+detailsId).removeClass('hide');mQuery(this).addClass('active')}});$icon.removeClass('ri-arrow-down-s-line').addClass('ri-arrow-up-s-line')}else{mQuery("#contact-auditlog a[data-activate-details!='all']").each(function(){var detailsId=mQuery(this).data('activate-details');if(detailsId&&mQuery('#auditlog-details-'+detailsId).length){mQuery('#auditlog-details-'+detailsId).addClass('hide');mQuery(this).removeClass('active')}});$icon.removeClass('ri-arrow-up-s-line').addClass('ri-arrow-down-s-line')}});mQuery("#contact-auditlog a[data-activate-details!='all']").on('click',function(){var detailsId=mQuery(this).data('activate-details');var $icon=mQuery(this).find('span').first();if(detailsId&&mQuery('#auditlog-details-'+detailsId).length){var activateDetailsState=mQuery(this).hasClass('active');if(activateDetailsState){mQuery('#auditlog-details-'+detailsId).addClass('hide');mQuery(this).removeClass('active');$icon.removeClass('ri-arrow-up-s-line').addClass('ri-arrow-down-s-line')}else{mQuery('#auditlog-details-'+detailsId).removeClass('hide');mQuery(this).addClass('active');$icon.removeClass('ri-arrow-down-s-line').addClass('ri-arrow-up-s-line')}}})};Mautic.leadOnUnload=function(id){if(typeof MauticVars.moderatedIntervals.leadListLiveUpdate!='undefined'){Mautic.clearModeratedInterval('leadListLiveUpdate')}
if(typeof Mautic.mapObjects!=='undefined'){delete Mautic.mapObjects}};Mautic.getLeadId=function(){return mQuery('input#leadId').val()}
Mautic.leadlistOnLoad=function(container,response){const segmentCountElem=mQuery('span.col-count');if(segmentCountElem.length){segmentCountElem.each(function(){const elem=mQuery(this);const id=elem.attr('data-id');Mautic.ajaxActionRequest('lead:getLeadCount',{id:id},function(response){elem.className=response.className;elem.children('a').html(response.html)},!1,!0,"GET")})}
mQuery('#campaign-share-tab').hover(function(){if(Mautic.shareTableLoaded!=!0){Mautic.loadAjaxColumn('campaign-share-stat','lead:getCampaignShareStats','afterStatsLoad');Mautic.shareTableLoaded=!0}})
Mautic.afterStatsLoad=function(){Mautic.sortTableByColumn('#campaign-share-table','.campaign-share-stat',!0)}
if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','lead.list')}
var prefix='leadlist';var parent=mQuery('.dynamic-content-filter, .dwc-filter');if(parent.length){prefix=parent.attr('id')}
if(mQuery('#'+prefix+'_filters').length){mQuery('#available_segment_filters').on('change',function(){if(mQuery(this).val()){Mautic.addLeadListFilter(mQuery(this).val(),mQuery('option:selected',this).data('field-object'));mQuery(this).val('');mQuery(this).trigger('chosen:updated')}});mQuery('#'+prefix+'_filters .segment-filter').each(function(index,filter){Mautic.segmentFilter().attachEvents(mQuery(filter))});var bodyOverflow={};mQuery('#'+prefix+'_filters').sortable({items:'.filter--row',helper:function(e,ui){ui.children().each(function(){if(mQuery(this).is(":visible")){mQuery(this).width(mQuery(this).width())}});bodyOverflow.overflowX=mQuery('body').css('overflow-x');bodyOverflow.overflowY=mQuery('body').css('overflow-y');mQuery('body').css({overflowX:'visible',overflowY:'visible'});return ui},scroll:!0,axis:'y',stop:function(e,ui){mQuery('body').css(bodyOverflow);Mautic.reorderSegmentFilters()}})}
var segmentContactForm=mQuery('#segment-contact-filters');if(segmentContactForm.length){segmentContactForm.on('change',function(){segmentContactForm.submit()}).on('keyup',function(){segmentContactForm.delay(200).submit()}).on('submit',function(e){e.preventDefault();Mautic.refreshSegmentContacts(segmentContactForm)})}
jQuery(document).ajaxComplete(function(){Mautic.ajaxifyForm('daterange')});Mautic.attachJsUiOnFilterForms()};Mautic.triggerOnPropertiesFormLoadedEvent=function(selector,filterValue){mQuery('#leadlist_filters').trigger('filter.properties.form.loaded',[selector,filterValue])};Mautic.attachJsUiOnFilterForms=function(){mQuery('#leadlist_filters').on('filter.properties.form.loaded',function(event,selector,filterValue){Mautic.activateChosenSelect(selector+'_properties select');var fieldType=mQuery(selector+'_type').val();var fieldAlias=mQuery(selector+'_field').val();var filterFieldEl=mQuery(selector+'_properties_filter');if(filterValue){filterFieldEl.val(filterValue);if(filterFieldEl.is('select')){filterFieldEl.trigger('chosen:updated')}}
if(fieldType==='lookup'){Mautic.activateLookupTypeahead(filterFieldEl.parent())}else if(fieldType==='datetime'){filterFieldEl.datetimepicker({format:'Y-m-d H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(fieldType==='date'){filterFieldEl.datetimepicker({timepicker:!1,format:'Y-m-d',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1,closeOnDateSelect:!0})}else if(fieldType==='time'){filterFieldEl.datetimepicker({datepicker:!1,format:'H:i',lazyInit:!0,validateOnBlur:!1,allowBlank:!0,scrollMonth:!1,scrollInput:!1})}else if(fieldType==='lookup_id'){var displayFieldEl=mQuery(selector+'_properties_display');var fieldCallback=displayFieldEl.attr('data-field-callback');if(fieldCallback&&typeof Mautic[fieldCallback]==='function'){var fieldOptions=displayFieldEl.attr('data-field-list');Mautic[fieldCallback](selector.replace('#','')+'_properties_display',fieldAlias,fieldOptions)}}
mQuery('.chosen-search-input').on('keypress',function(event){if(event.which===13)event.preventDefault();})});mQuery('#leadlist_filters .panel').each(function(){Mautic.triggerOnPropertiesFormLoadedEvent('#'+mQuery(this).attr('id'))})};Mautic.reorderSegmentFilters=function(){var counter=0;var prefix='leadlist';var parent=mQuery('.dynamic-content-filter, .dwc-filter');if(parent.length){prefix=parent.attr('id')}
const $filters=mQuery('#'+prefix+'_filters .filter--row');$filters.each(function(){const $filter=mQuery(this);$filter.attr('id',prefix+'_filters_'+counter);Mautic.updateFilterPositioning($filter.find('select.glue-select').first());$filter.find('[id^="'+prefix+'_filters_"]').each(function(){const $element=mQuery(this);var id=$element.attr('id');var name=$element.attr('name');var suffix=id.split(/[_]+/).pop();var isProperties=id.includes("_properties_");if(prefix+'_filters___name___filter'===id){return!0}
if(name){if(isProperties){const suffixIdMatch=id.match(/_properties_(.*)$/);const suffixNameMatch=name.match(/\[properties\](.*)$/);const suffixId=suffixIdMatch?suffixIdMatch[1]:suffix;const suffixName=suffixNameMatch?suffixNameMatch[1]:suffix;var newName=prefix+'[filters]['+counter+'][properties]'+suffixName;suffix='properties_'+suffixId}else{var newName=prefix+'[filters]['+counter+']['+suffix+']';if(name.slice(-2)==='[]'){newName+='[]'}}
$element.attr('name',newName)}
$element.attr('id',prefix+'_filters_'+counter+'_'+suffix);if($element.is('select')&&suffix==='properties_filter'){Mautic.destroyChosen($element);Mautic.activateChosenSelect($element)}
Mautic.segmentFilter().showCopyBasedOnGlue($filter);if(mQuery(this).is(':radio')&&id.includes("_dateTypeMode_")){if(mQuery(this).closest('label').hasClass('active')){mQuery(this).click()}}});$filter.find('.panel-heading').css('width','');++counter});const panelClass=prefix==='leadlist'?'.panel-glue':'.panel-heading';mQuery('#'+prefix+'_filters '+panelClass).removeClass('hide');const $firstPanel=$filters.first();$firstPanel.find(panelClass).addClass('hide');$firstPanel.find('.copy-filter-group').removeClass('hide');const $tooltips=$filters.find("*[data-toggle='tooltip']");$tooltips.each(function(){mQuery(this).tooltip({html:!0,container:'body'})})};Mautic.convertLeadFilterInput=function(el){var operatorSelect=mQuery(el);var regExp=/_filters_(\d+)_operator/;var matches=regExp.exec(operatorSelect.attr('id'));var filterNum=matches[1];var fieldAlias=mQuery('#leadlist_filters_'+filterNum+'_field');var fieldObject=mQuery('#leadlist_filters_'+filterNum+'_object');var filterValue=mQuery('#leadlist_filters_'+filterNum+'_properties_filter').val();var filterId='#leadlist_filters_'+filterNum+'_properties_filter';Mautic.loadFilterForm(filterNum,fieldObject.val(),fieldAlias.val(),operatorSelect.val(),function(propertiesFields){var selector='#leadlist_filters_'+filterNum;mQuery(selector+'_properties').html(propertiesFields);Mautic.ajaxifyForm('leadlist');Mautic.triggerOnPropertiesFormLoadedEvent(selector,filterValue)});Mautic.setProcessorForFilterValue(filterId,operatorSelect.val())};Mautic.setFilterValuesProcessor=function(){mQuery('.filter-operator').each(function(index){let filterId="#"+mQuery('.filter-value').eq(index).attr('id');Mautic.setProcessorForFilterValue(filterId,mQuery(this).val())})};Mautic.setProcessorForFilterValue=function(filterId,operator){let isInOperator=(operator=='in'||operator=='!in');if(isInOperator&&mQuery(filterId).attr('type')==='text'){mQuery(filterId).on('paste',function(e){let value=e.originalEvent.clipboardData.getData('text');value=value.replace(/\r?\n/g,'|');if(value.slice(-1)==='|'){value=value.slice(0,-1)}
mQuery(filterId).val(value);e.preventDefault()})}else{mQuery(filterId).off('paste')}};Mautic.updateLookupListFilter=function(field,item){if(item&&item.id){var filterField='#'+field.replace('_display','_filter');mQuery(filterField).val(item.id);mQuery(field).val(item.name)}};Mautic.activateSegmentFilterTypeahead=function(displayId,filterId,fieldOptions,mQueryObject){var mQueryBackup=mQuery;if(typeof mQueryObject==='function'){mQuery=mQueryObject}
mQuery('#'+displayId).attr('data-lookup-callback','updateLookupListFilter');Mautic.activateFieldTypeahead(displayId,filterId,[],mQuery('#'+displayId).data('action')||'lead:fieldList');mQuery=mQueryBackup};Mautic.loadFilterForm=function(filterNum,fieldObject,fieldAlias,operator,resultHtml,search=null){mQuery.ajax({showLoadingBar:!0,url:mauticAjaxUrl,type:'POST',data:{action:'lead:loadSegmentFilterForm',fieldAlias:fieldAlias,fieldObject:fieldObject,operator:operator,filterNum:filterNum,search:search,},dataType:'json',success:function(response){Mautic.stopPageLoadingBar();resultHtml(response.viewParameters.form);if(fieldAlias=='lead_asset_download'){Mautic.handleAssetDownloadSearch(filterNum,fieldObject,fieldAlias,operator,resultHtml,search)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)}})}
Mautic.addLeadListFilter=function(elId,elObj){var filterId='#available_'+elObj+'_'+elId;var filterOption=mQuery(filterId);var filterNum=Mautic.segmentFilter().getFilterCount();var prototypeStr=mQuery('.available-filters').data('prototype');var fieldType=filterOption.data('field-type');var fieldObject=filterOption.data('field-object');var label=filterOption.data('field-label');prototypeStr=prototypeStr.replace(/__name__/g,filterNum);prototypeStr=prototypeStr.replace(/__label__/g,label);prototype=mQuery(prototypeStr);var prefix='leadlist';var parent=mQuery(filterId).parents('.dynamic-content-filter, .dwc-filter');if(parent.length){prefix=parent.attr('id')}
var filterBase=prefix+"[filters]["+filterNum+"]";var filterIdBase=prefix+"_filters_"+filterNum+"_";if(Mautic.segmentFilter().getFilterCount()===0){prototype.find(".panel-glue").addClass('hide')}
const filterTypeIcon=filterOption.data('field-icon');prototype.find('.object-icon').removeClass('ri-shapes-line').addClass(filterTypeIcon);prototype.find(".inline-spacer").append(fieldObject);Mautic.segmentFilter().attachEvents(prototype);prototype.find("input[name='"+filterBase+"[field]']").val(elId);prototype.find("input[name='"+filterBase+"[type]']").val(fieldType);prototype.find("input[name='"+filterBase+"[object]']").val(fieldObject);prototype.appendTo('#'+prefix+'_filters');var operators=filterOption.data('field-operators');mQuery('#'+filterIdBase+'operator').html('');mQuery.each(operators,function(label,value){var newOption=mQuery('<option/>').val(value).text(label);newOption.appendTo(mQuery('#'+filterIdBase+'operator'))});Mautic.convertLeadFilterInput('#'+filterIdBase+'operator');Mautic.updateFilterPositioning(mQuery('#'+filterIdBase+'glue'));Mautic.segmentFilter().showCopyBasedOnGlue(prototype)};Mautic.segmentFilter=function(){const attachEvents=function($filter){_attachCopyEvents($filter);_attachRemoveEvents($filter);_attachGlueEvents($filter)};const getFilterCount=function(){return mQuery('.selected-filters').children('.filter--row').length};const showCopyBasedOnGlue=function($filter){const $glue=$filter.find('select.glue-select');const $copyButton=$filter.find('.copy-filter-group');if($glue.val()==='and'&&!_isFirstFilter($filter)){$copyButton.addClass('hide')}else{$copyButton.removeClass('hide')}};const _attachGlueEvents=function($filter){showCopyBasedOnGlue($filter);$filter.find('select.glue-select').on('change',function(){showCopyBasedOnGlue($filter)})};const _isFirstFilter=function($filter){return $filter.prev().length===0}
const _attachRemoveEvents=function($filter){$filter.find('a.remove-selected').each(function(index,el){mQuery(el).on('click',function(){$filter.animate({'opacity':0},'fast',function(){mQuery('*[role="tooltip"]').tooltip('destroy');mQuery(this).remove();Mautic.reorderSegmentFilters()})})})};const _attachCopyEvents=function($filter){$filter.find('.copy-filter-group').on('click',function(event){event.preventDefault();$copyButton=mQuery(this);$filter=$copyButton.closest('.segment-filter');_cloneFilter($filter);let groupEnded=!1;$filter.nextAll().each(function(i,element){$nextFilter=mQuery(element);if(!$nextFilter.hasClass('in-group')){groupEnded=!0}
if(groupEnded){return}
_cloneFilter($nextFilter)})})};const _setSelectedOptions=function($filter){$filter.find('select option').each(function(){const $option=mQuery(this);$option.attr('selected',$option.is(':selected')?'selected':null)})}
const _cloneFilter=function($origin){$origin.find('.properties-form .choice-wrapper select').chosen('destroy');_setSelectedOptions($origin);const $clone=$origin.clone(!1);if(!$origin.hasClass('in-group')){const $glueWrapper=$clone.find('.panel-glue');$glueWrapper.find('select').val('or');$glueWrapper.removeClass('hide')}
$clone.find('.filter--condition-when').addClass('hide');const $filters=$origin.closest('.selected-filters');$filters.append($clone);Mautic.reorderSegmentFilters();Mautic.triggerOnPropertiesFormLoadedEvent('#'+$clone.attr('id'));attachEvents($clone)}
return{attachEvents,getFilterCount,showCopyBasedOnGlue,}}
Mautic.leadfieldOnLoad=function(container){if(mQuery(container+' .leadfield-list').length){var bodyOverflow={};mQuery(container+' .leadfield-list tbody').sortable({handle:'.ri-draggable',helper:function(e,ui){ui.children().each(function(){mQuery(this).width(mQuery(this).width())});bodyOverflow.overflowX=mQuery('body').css('overflow-x');bodyOverflow.overflowY=mQuery('body').css('overflow-y');mQuery('body').css({overflowX:'visible',overflowY:'visible'});return ui},scroll:!1,axis:'y',containment:container+' .leadfield-list',stop:function(e,ui){mQuery('body').css(bodyOverflow);mQuery.ajax({type:"POST",url:mauticAjaxUrl+"?action=lead:reorder&limit="+mQuery('.pagination-limit').val()+'&page='+mQuery('.pagination li.active a span').first().text(),data:mQuery(container+' .leadfield-list tbody').sortable("serialize")})}})}
if(mQuery(container+' form[name="leadfield"]').length){Mautic.updateLeadFieldProperties(mQuery('#leadfield_type').val(),!0)}};Mautic.updateLeadFieldProperties=function(selectedVal,onload){let isMultiselect=selectedVal==='multiselect'?!0:!1;if(selectedVal==='multiselect'){selectedVal='select'}
mQuery('#leadfield_properties [data-toggle="tooltip"]').tooltip('destroy');if(mQuery('#field-templates .'+selectedVal).length){mQuery('#leadfield_properties').html(mQuery('#field-templates .'+selectedVal).html().replace(/leadfield_properties_template/g,'leadfield_properties'));mQuery("#leadfield_properties *[data-toggle='sortablelist']").each(function(index){var sortableList=mQuery(this);Mautic.activateSortable(this);var contactFieldListOptions=mQuery('#leadfield_properties').find('input').map(function(){return mQuery(this).val()}).get().join();var updateDefaultValuesetInterval=setInterval(function(){var evalListOptions=mQuery('#leadfield_properties').find('input').map(function(){return mQuery(this).val()}).get().join();if(mQuery('#leadfield_properties_itemcount').length){if(contactFieldListOptions!=evalListOptions){contactFieldListOptions=evalListOptions;var selected=mQuery('#leadfield_defaultValue').val();mQuery('#leadfield_defaultValue').html('<option value=""></option>');var labels=mQuery('#leadfield_properties').find('input.sortable-label');if(labels.length){labels.each(function(){var label=mQuery(this).val();var val=mQuery(this).closest('.row').find('input.sortable-value').first().val();mQuery('<option value="'+val+'">'+label+'</option>').appendTo(mQuery('#leadfield_defaultValue'))})}else{mQuery('#leadfield_properties .list-sortable').find('input').each(function(){var val=mQuery(this).val();mQuery('<option value="'+val+'">'+val+'</option>').appendTo(mQuery('#leadfield_defaultValue'))})}
mQuery('#leadfield_defaultValue').val(selected);mQuery('#leadfield_defaultValue').trigger('chosen:updated')}}else{clearInterval(updateDefaultValuesetInterval);delete contactFieldListOptions}},500)});mQuery('#leadfield_properties [data-toggle="tooltip"]').tooltip()}else if(!mQuery('#leadfield_properties .'+selectedVal).length){mQuery('#leadfield_properties').html('')}
if(selectedVal=='time'){mQuery('#leadfield_isListable').closest('.row').addClass('hide')}else{mQuery('#leadfield_isListable').closest('.row').removeClass('hide')}
var defaultValueField=mQuery('#leadfield_defaultValue');if(defaultValueField.hasClass('calendar-activated')){defaultValueField.datetimepicker('destroy').removeClass('calendar-activated')}else if(mQuery('#leadfield_defaultValue_chosen').length){Mautic.destroyChosen(defaultValueField)}
var defaultFieldType=mQuery('input[name="leadfield[defaultValue]"]').attr('type');var tempType=selectedVal;var html='';var isSelect=!1;var defaultVal=defaultValueField.val();switch(selectedVal){case 'boolean':if(defaultFieldType!='radio'){html='<div id="leadfield_default_template_boolean">'+mQuery('#field-templates .default_template_boolean').html()+'</div>'}
break;case 'country':case 'region':case 'locale':case 'timezone':html=mQuery('#field-templates .default_template_'+selectedVal).html();isSelect=!0;break;case 'select':case 'lookup':html=mQuery('#field-templates .default_template_select').html();tempType='select';isSelect=!0;break;case 'textarea':html=mQuery('#field-templates .default_template_textarea').html();break;default:html=mQuery('#field-templates .default_template_text').html();tempType='text';if(html!=undefined&&(selectedVal=='number'||selectedVal=='tel'||selectedVal=='url'||selectedVal=='email')){var replace='type="text"';var regex=new RegExp(replace,"g");html=html.replace(regex,'type="'+selectedVal+'"')}
break}
if(html&&!onload){var replace='default_template_'+tempType;var regex=new RegExp(replace,"g");html=html.replace(regex,'defaultValue')
defaultValueField.replaceWith(mQuery(html));mQuery('#leadfield_defaultValue').val(defaultVal);if(isMultiselect){mQuery('#leadfield_defaultValue').attr('multiple','multiple');mQuery('#leadfield_defaultValue').attr('name',mQuery('#leadfield_defaultValue').attr('name')+'[]')}}
if(selectedVal==='datetime'||selectedVal==='date'||selectedVal==='time'){Mautic.activateDateTimeInputs('#leadfield_defaultValue',selectedVal)}else if(isSelect){Mautic.activateChosenSelect('#leadfield_defaultValue')}};Mautic.updateLeadFieldBooleanLabels=function(el,label){mQuery('#leadfield_defaultValue_'+label).parent().find('span').text(mQuery(el).val())};Mautic.updateLeadFieldOrderChoiceList=function(){formData={'object':mQuery('#leadfield_object').val(),'group':mQuery('#leadfield_group').val()};Mautic.ajaxActionRequest('lead:updateLeadFieldOrderChoiceList',formData,function(response){if(response){mQuery('#leadfield_order_container').html(response);Mautic.activateChosenSelect('#leadfield_order');mQuery('label[for=leadfield_order]').tooltip({html:!0})}})}
Mautic.refreshLeadSocialProfile=function(network,leadId,event){var query="action=lead:updateSocialProfile&network="+network+"&lead="+leadId;mQuery.ajax({showLoadingBar:!0,url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(response.success){if(response.completeProfile){mQuery('#social-container').html(response.completeProfile);mQuery('#SocialCount').html(response.socialCount)}else{mQuery.each(response.profiles,function(index,value){if(mQuery('#'+index+'CompleteProfile').length){mQuery('#'+index+'CompleteProfile').html(value.newContent)}})}}
Mautic.stopPageLoadingBar();Mautic.stopIconSpinPostEvent()},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)}});Mautic.setFilterValuesProcessor()};Mautic.clearLeadSocialProfile=function(network,leadId,event){Mautic.startIconSpinOnEvent(event);var query="action=lead:clearSocialProfile&network="+network+"&lead="+leadId;mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(response.success){mQuery('.'+network+'-panelremove').click();if(response.completeProfile){mQuery('#social-container').html(response.completeProfile)}
mQuery('#SocialCount').html(response.socialCount)}
Mautic.stopIconSpinPostEvent()},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown);Mautic.stopIconSpinPostEvent()}})};Mautic.refreshLeadAuditLog=function(form){Mautic.postForm(mQuery(form),function(response){response.target='#auditlog-table';mQuery('#AuditLogCount').html(response.auditLogCount);Mautic.processPageContent(response)})};Mautic.refreshLeadTimeline=function(form){Mautic.postForm(mQuery(form),function(response){response.target='#timeline-table';mQuery('#TimelineCount').html(response.timelineCount);Mautic.processPageContent(response)})};Mautic.refreshLeadNotes=function(form){Mautic.postForm(mQuery(form),function(response){response.target='#NoteList';mQuery('#NoteCount').html(response.noteCount);Mautic.processPageContent(response)})};Mautic.refreshSegmentContacts=function(form){Mautic.postForm(mQuery(form),function(response){response.target='#contacts-container';Mautic.processPageContent(response)})};Mautic.toggleLeadList=function(toggleId,leadId,listId){var action=mQuery('#'+toggleId).hasClass('ri-toggle-fill')?'remove':'add';var query="action=lead:toggleLeadList&leadId="+leadId+"&listId="+listId+"&listAction="+action;Mautic.toggleLeadSwitch(toggleId,query,action)};Mautic.togglePreferredChannel=function(channel){if(channel==='all'){var channelsForm=mQuery('form[name="contact_channels"]');var status=channelsForm.find('#contact_channels_subscribed_channels_0:checked').length;channelsForm.find('tbody input:checkbox').each(function(){if(this.checked!=status){this.checked=status;Mautic.setPreferredChannel(this.value)}})}else{Mautic.setPreferredChannel(channel)}};Mautic.setPreferredChannel=function(channel){mQuery('#frequency_'+channel).slideToggle();mQuery('#frequency_'+channel).removeClass('hide');if(mQuery('#'+channel)[0].checked){mQuery('#is-contactable-'+channel).removeClass('text-secondary');mQuery('#lead_contact_frequency_rules_frequency_number_'+channel).prop("disabled",!1).trigger("chosen:updated");mQuery('#preferred_'+channel).prop("disabled",!1);mQuery('#lead_contact_frequency_rules_frequency_time_'+channel).prop("disabled",!1).trigger("chosen:updated");mQuery('#lead_contact_frequency_rules_contact_pause_start_date_'+channel).prop("disabled",!1);mQuery('#lead_contact_frequency_rules_contact_pause_end_date_'+channel).prop("disabled",!1)}else{mQuery('#is-contactable-'+channel).addClass('text-secondary');mQuery('#lead_contact_frequency_rules_frequency_number_'+channel).prop("disabled",!0).trigger("chosen:updated");mQuery('#preferred_'+channel).prop("disabled",!0);mQuery('#lead_contact_frequency_rules_frequency_time_'+channel).prop("disabled",!0).trigger("chosen:updated");mQuery('#lead_contact_frequency_rules_contact_pause_start_date_'+channel).prop("disabled",!0);mQuery('#lead_contact_frequency_rules_contact_pause_end_date_'+channel).prop("disabled",!0)}};Mautic.toggleCompanyLead=function(toggleId,leadId,companyId){var action=mQuery('#'+toggleId).hasClass('ri-toggle-fill')?'remove':'add';var query="action=lead:toggleCompanyLead&leadId="+leadId+"&companyId="+companyId+"&companyAction="+action;Mautic.toggleLeadSwitch(toggleId,query,action)};Mautic.toggleLeadCampaign=function(toggleId,leadId,campaignId){var action=mQuery('#'+toggleId).hasClass('ri-toggle-fill')?'remove':'add';var query="action=lead:toggleLeadCampaign&leadId="+leadId+"&campaignId="+campaignId+"&campaignAction="+action;Mautic.toggleLeadSwitch(toggleId,query,action)};Mautic.toggleLeadSwitch=function(toggleId,query,action){var toggleOn='ri-toggle-fill text-success';var toggleOff='ri-toggle-line text-danger';var spinClass='ri-spin ri-loader-3-line ';if(action=='remove'){mQuery('#'+toggleId).removeClass(toggleOn).addClass(spinClass+'text-danger')}else{mQuery('#'+toggleId).removeClass(toggleOff).addClass(spinClass+'text-success')}
mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){mQuery('#'+toggleId).removeClass(spinClass);if(!response.success){if(action=='remove'){mQuery('#'+toggleId).removeClass(toggleOff).addClass(toggleOn)}else{mQuery('#'+toggleId).removeClass(toggleOn).addClass(toggleOff)}}else{if(action=='remove'){mQuery('#'+toggleId).removeClass(toggleOn).addClass(toggleOff)}else{mQuery('#'+toggleId).removeClass(toggleOff).addClass(toggleOn)}}},error:function(request,textStatus,errorThrown){mQuery('#'+toggleId).removeClass(spinClass);if(action=='remove'){mQuery('#'+toggleId).removeClass(toggleOff).addClass(toggleOn)}else{mQuery('#'+toggleId).removeClass(toggleOn).addClass(toggleOff)}}})};Mautic.leadNoteOnLoad=function(container,response){if(response.noteHtml){var el='#LeadNote'+response.noteId;if(mQuery(el).length){mQuery(el).replaceWith(response.noteHtml)}else{mQuery('#LeadNotes').prepend(response.noteHtml)}
Mautic.makeModalsAlive(mQuery(el+" *[data-toggle='ajaxmodal']"));Mautic.makeConfirmationsAlive(mQuery(el+' a[data-toggle="confirmation"]'));Mautic.makeLinksAlive(mQuery(el+" a[data-toggle='ajax']"))}else if(response.deleteId&&mQuery('#LeadNote'+response.deleteId).length){mQuery('#LeadNote'+response.deleteId).remove()}
if(response.upNoteCount||response.noteCount||response.downNoteCount){var noteCountWrapper=mQuery('#NoteCount');var count=parseInt(noteCountWrapper.text().trim());if(response.upNoteCount){count++}else if(response.downNoteCount){count--}else{count=parseInt(response.noteCount)}
noteCountWrapper.text(count)}};Mautic.showSocialMediaImageModal=function(imgSrc){mQuery('#socialImageModal img').attr('src',imgSrc);mQuery('#socialImageModal').modal('show')};Mautic.leadImportOnLoad=function(container,response){if(!mQuery('#leadImportProgress').length){Mautic.clearModeratedInterval('leadImportProgress')}else{Mautic.setModeratedInterval('leadImportProgress','reloadLeadImportProgress',3000)}};Mautic.reloadLeadImportProgress=function(){if(!mQuery('#leadImportProgress').length){Mautic.clearModeratedInterval('leadImportProgress')}else{Mautic.ajaxActionRequest('lead:getImportProgress',{},function(response){if(response.progress){if(response.progress[0]>0){mQuery('.imported-count').html(response.progress[0]);mQuery('.progress-bar-import').attr('aria-valuenow',response.progress[0]).css('width',response.percent+'%');mQuery('.progress-bar-import span.sr-only').html(response.percent+'%')}}},!1,!1,"GET");mQuery.ajax({showLoadingBar:!1,url:window.location+'?importbatch=1',success:function(response){Mautic.moderatedIntervalCallbackIsComplete('leadImportProgress');if(response.newContent){Mautic.processPageContent(response)}}})}};Mautic.removeBounceStatus=function(el,dncId,channel){mQuery(el).removeClass('ri-close-line').addClass('ri-loader-3-line ri-spin');Mautic.ajaxActionRequest('lead:removeBounceStatus',{'id':dncId,'channel':channel},function(){mQuery('#bounceLabel'+dncId).tooltip('destroy');mQuery('#bounceLabel'+dncId).fadeOut(300,function(){mQuery(this).remove()})})};Mautic.removeTagFromLead=function(el,leadId,tagId,event){if(event){event.stopPropagation();event.preventDefault()}
mQuery(el).find('i').removeClass('ri-close-line').addClass('ri-loader-3-line ri-spin');Mautic.ajaxActionRequest('lead:removeTagFromLead',{'leadId':leadId,'tagId':tagId},function(){mQuery('#tagLabel'+tagId).fadeOut(300,function(){mQuery(this).remove()})})};Mautic.toggleLiveLeadListUpdate=function(){if(typeof MauticVars.moderatedIntervals.leadListLiveUpdate=='undefined'){Mautic.setModeratedInterval('leadListLiveUpdate','updateLeadList',5000);mQuery('#liveModeButton').addClass('active')}else{Mautic.clearModeratedInterval('leadListLiveUpdate');mQuery('#liveModeButton').removeClass('active')}};Mautic.updateLeadList=function(){var maxLeadId=mQuery('#liveModeButton').data('max-id');mQuery.ajax({url:mauticAjaxUrl,type:"get",data:"action=lead:getNewLeads&maxId="+maxLeadId,dataType:"json",success:function(response){if(response.leads){if(response.indexMode=='list'){mQuery('#leadTable tbody').prepend(response.leads)}else{if(mQuery('.shuffle-grid').length){var Shuffle=window.Shuffle,element=document.querySelector('.shuffle-grid'),shuffleOptions={itemSelector:'.shuffle-item'};window.leadsShuffleInstance=new Shuffle(element,shuffleOptions);var items=mQuery(response.leads);mQuery('.shuffle-grid').prepend(items);window.leadsShuffleInstance.shuffle('appended',items.children(shuffleOptions.itemSelector).toArray());window.leadsShuffleInstance.shuffle('update')}
mQuery('#liveModeButton').data('max-id',response.maxId)}}
if(typeof IdleTimer!='undefined'&&!IdleTimer.isIdle()){if(response.indexMode=='list'){mQuery('#leadTable tr.warning').each(function(){var that=this;setTimeout(function(){mQuery(that).removeClass('warning',1000)},5000)})}else{mQuery('.shuffle-grid .highlight').each(function(){var that=this;setTimeout(function(){mQuery(that).removeClass('highlight',1000,function(){mQuery(that).css('border-top-color',mQuery(that).data('color'))})},5000)})}}
if(response.maxId){mQuery('#liveModeButton').data('max-id',response.maxId)}
Mautic.moderatedIntervalCallbackIsComplete('leadListLiveUpdate')},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown);Mautic.moderatedIntervalCallbackIsComplete('leadListLiveUpdate')}})};Mautic.toggleAnonymousLeads=function(){var searchValue=mQuery('#list-search').typeahead('val');var string=mQuery('#anonymousLeadButton').data('anonymous').toLowerCase();if(searchValue.toLowerCase().indexOf('!'+string)==0){searchValue=searchValue.replace('!'+string,string);mQuery('#anonymousLeadButton').addClass('btn-primary')}else if(searchValue.toLowerCase().indexOf(string)==-1){if(searchValue){searchValue=searchValue+' '+string}else{searchValue=string}
mQuery('#anonymousLeadButton').addClass('btn-primary')}else{searchValue=mQuery.trim(searchValue.replace(string,''));mQuery('#anonymousLeadButton').removeClass('btn-primary')}
searchValue=searchValue.replace("  "," ");Mautic.setSearchFilter(null,'list-search',searchValue)};Mautic.getLeadEmailContent=function(el){var id=(mQuery.type(el)==="string")?el:mQuery(el).attr('id');Mautic.activateLabelLoadingIndicator(id);var inModal=mQuery('#'+id).closest('modal').length;if(inModal){mQuery('#MauticSharedModal .btn-primary').prop('disabled',!0)}
Mautic.ajaxActionRequest('lead:getEmailTemplate',{'template':mQuery(el).val()},function(response){if(inModal){mQuery('#MauticSharedModal .btn-primary').prop('disabled',!1)}
var idPrefix=id.replace('templates','');var bodyEl=(mQuery('#'+idPrefix+'message').length)?'#'+idPrefix+'message':'#'+idPrefix+'body';ckEditors.get(mQuery(bodyEl)[0]).setData(response.body);mQuery(bodyEl).val(response.body);mQuery('#'+idPrefix+'subject').val(response.subject);Mautic.removeLabelLoadingIndicator()},!1,!1,"GET")};Mautic.updateLeadTags=function(){Mautic.activateLabelLoadingIndicator('lead_tags_tags');var formData=mQuery('form[name="lead_tags"]').serialize();Mautic.ajaxActionRequest('lead:updateLeadTags',formData,function(response){if(response.tags){mQuery('#lead_tags_tags').html(response.tags);mQuery('#lead_tags_tags').trigger('chosen:updated')}
Mautic.removeLabelLoadingIndicator()})};Mautic.createLeadTag=function(el){var newFound=!1;mQuery('#'+mQuery(el).attr('id')+' :selected').each(function(i,selected){if(!mQuery.isNumeric(mQuery(selected).val())){newFound=!0}});if(!newFound){return}
Mautic.activateLabelLoadingIndicator(mQuery(el).attr('id'));var tags=JSON.stringify(mQuery(el).val());Mautic.ajaxActionRequest('lead:addLeadTags',{tags:tags},function(response){if(response.tags){mQuery('#'+mQuery(el).attr('id')).html(response.tags);mQuery('#'+mQuery(el).attr('id')).trigger('chosen:updated')}
Mautic.removeLabelLoadingIndicator()})};Mautic.createLeadUtmTag=function(el){var newFound=!1;mQuery('#'+mQuery(el).attr('id')+' :selected').each(function(i,selected){if(!mQuery.isNumeric(mQuery(selected).val())){newFound=!0}});if(!newFound){return}
Mautic.activateLabelLoadingIndicator(mQuery(el).attr('id'));var utmtags=JSON.stringify(mQuery(el).val());Mautic.ajaxActionRequest('lead:addLeadUtmTags',{utmtags:utmtags},function(response){if(response.tags){mQuery('#'+mQuery(el).attr('id')).html(response.utmtags);mQuery('#'+mQuery(el).attr('id')).trigger('chosen:updated')}
Mautic.removeLabelLoadingIndicator()})};Mautic.leadBatchSubmit=function(){if(Mautic.batchActionPrecheck()){if(mQuery('#lead_batch_remove').val()||mQuery('#lead_batch_add').val()||mQuery('#lead_batch_dnc_reason').length||mQuery('#lead_batch_stage_addstage').length||mQuery('#lead_batch_owner_addowner').length||mQuery('#contact_channels_ids').length||mQuery('#batch_tag_tags_add_tags').val()||mQuery('#batch_tag_tags_remove_tags').val()){var ids=Mautic.getCheckedListIds(!1,!0);if(mQuery('#lead_batch_ids').length){mQuery('#lead_batch_ids').val(ids)}else if(mQuery('#lead_batch_dnc_reason').length){mQuery('#lead_batch_dnc_ids').val(ids)}else if(mQuery('#lead_batch_stage_addstage').length){mQuery('#lead_batch_stage_ids').val(ids)}else if(mQuery('#lead_batch_owner_addowner').length){mQuery('#lead_batch_owner_ids').val(ids)}else if(mQuery('#contact_channels_ids').length){mQuery('#contact_channels_ids').val(ids)}else if(mQuery('#batch_tag_ids').length){mQuery('#batch_tag_ids').val(ids)}
return!0}}
mQuery('#MauticSharedModal').modal('hide');return!1};Mautic.updateLeadFieldValues=function(field){mQuery('.condition-custom-date-row').hide();Mautic.updateFieldOperatorValue(field,'lead:updateLeadFieldValues',Mautic.updateLeadFieldValueOptions,[!0])};Mautic.updateLeadFieldValueOptions=function(field,updating){var fieldId=mQuery(field).attr('id');var fieldPrefix=fieldId.slice(0,-5);if('date'===mQuery('#'+fieldPrefix+'operator').val()){var customOption=mQuery(field).find('option[data-custom=1]');var value=mQuery(field).val();var customSelected=mQuery(customOption).prop('selected');if(customSelected){if(!updating){var regex=/(\+|-)(PT?)([0-9]*)([DMHY])$/g;var match=regex.exec(value);if(match){var interval=('-'===match[1])?match[1]+match[3]:match[3];var unit=('PT'===match[2]&&'M'===match[4])?'i':match[4];mQuery('#lead-field-custom-date-interval').val(interval);mQuery('#lead-field-custom-date-unit').val(unit.toLowerCase())}}else{var interval=mQuery('#lead-field-custom-date-interval').val();var unit=mQuery('#lead-field-custom-date-unit').val();var prefix=("i"==unit||"h"==unit)?"PT":"P";if("i"===unit){unit="m"}
unit=unit.toUpperCase();var operator="+";if(parseInt(interval)<0){operator="-";interval=-1*parseInt(interval)}
var newValue=operator+prefix+interval+unit;customOption.attr('value',newValue)}
mQuery('.condition-custom-date-row').show()}else{mQuery('.condition-custom-date-row').hide()}}else{mQuery('.condition-custom-date-row').hide()}};Mautic.toggleTimelineMoreVisiblity=function(el){if(mQuery(el).is(':visible')){mQuery(el).slideUp('fast');mQuery(el).next().text(mauticLang.showMore)}else{mQuery(el).slideDown('fast');mQuery(el).next().text(mauticLang.hideMore)}};Mautic.displayUniqueIdentifierWarning=function(el){if(mQuery(el).val()==="0"){mQuery('.unique-identifier-warning').fadeOut('fast')}else{mQuery('.unique-identifier-warning').fadeIn('fast')}};Mautic.initUniqueIdentifierFields=function(){var uniqueFields=mQuery('[data-unique-identifier]');if(uniqueFields.length){uniqueFields.on('change',function(){var input=mQuery(this);var request={field:input.data('unique-identifier'),value:input.val(),ignore:mQuery('#lead_unlockId').val()};Mautic.ajaxActionRequest('lead:getLeadIdsByFieldValue',request,function(response){if(response.items!=='undefined'&&response.items.length){var warning=mQuery('<div class="exists-warning" />').text(response.existsMessage);mQuery.each(response.items,function(i,item){if(i>0){warning.append(mQuery('<span>, </span>'))}
var link=mQuery('<a/>').attr('href',item.link).attr('target','_blank').text(item.name+' ('+item.id+')');warning.append(link)});warning.appendTo(input.parent())}else{input.parent().find('div.exists-warning').remove()}},!1,!1,"GET")})}};Mautic.updateFilterPositioning=function(el){var $el=mQuery(el);var $parentEl=$el.closest('.filter--row');var list=$parentEl.parent().children('.filter--row');const isFirst=list.index($parentEl)===0;if(isFirst){$el.val('and')}
if($el.val()==='and'&&!isFirst){$parentEl.addClass('in-group')}else{$parentEl.removeClass('in-group')}};Mautic.setAsPrimaryCompany=function(companyId,leadId){Mautic.ajaxActionRequest('lead:setAsPrimaryCompany',{'companyId':companyId,'leadId':leadId},function(response){if(response.success){mQuery('.panel-companies .ri-user-star-fill').removeClass('ri-user-star-fill');mQuery('.panel-companies .contained-list-item__content[href$="/'+response.newPrimary+'"]').find('i').addClass('ri-user-star-fill')}})};Mautic.handleAssetDownloadSearch=function(filterNum,fieldObject,fieldAlias,operator,resultHtml,search){var assetDownloadFilter=mQuery('#leadlist_filters_'+filterNum+'_properties_filter');var assetDownloadInput=mQuery('#leadlist_filters_'+filterNum+'_properties input');var assetDownloadProperties=mQuery('#leadlist_filters_'+filterNum+'_properties');assetDownloadFilter.on('chosen:no_results',function(){var search=assetDownloadInput.val();mQuery('#leadlist_filters_'+filterNum+'_properties .chosen-drop').remove();clearTimeout(mQuery.data(this,'timer'));var existingOptions=mQuery('#leadlist_filters_'+filterNum+'_properties_filter option');mQuery(assetDownloadProperties).data('existing-options',existingOptions);mQuery(this).data('timer',setTimeout(function(){assetDownloadInput.width('auto').prop('disabled',!0).val(Mautic.translate('mautic.core.lookup.loading_data'));Mautic.loadFilterForm(filterNum,fieldObject,fieldAlias,operator,resultHtml,search)},1000,search))});var existingOptions=mQuery(assetDownloadProperties).data('existing-options');assetDownloadFilter.append(existingOptions);assetDownloadFilter.trigger('chosen:updated');if(mQuery('#leadlist_filters_'+filterNum+'_properties_filter option').length===0){assetDownloadInput.val(mauticLang.chosenNoResults)}else if(search!==null){assetDownloadFilter.trigger('chosen:open.chosen')}};Mautic.listOnLoad=function(container,response){Mautic.loadAndProcessPageContent('#contacts-container');const segmentDependenciesTab=mQuery('a#segment-dependencies');let segmentDependenciesLoaded=!1;let jsPlumbData=null;if(segmentDependenciesTab.length){mQuery(document).on('shown.bs.tab','a[data-toggle="tab"]',function(e){if(!mQuery(e.target).attr('id')==='segment-dependencies'){return}
if(!segmentDependenciesLoaded){segmentDependenciesLoaded=!0;mQuery.ajax({showLoadingBar:!0,url:mauticAjaxUrl,type:'GET',data:{action:'lead:getSegmentDependencyTree',id:mQuery('input#entityId').val()},dataType:'json',success:function(response){Mautic.stopPageLoadingBar();Mautic.renderSegmentTree('#segment-dependencies-container',response);jsPlumbData=response},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)}})}else if(jsPlumbData){Mautic.renderSegmentTree('#segment-dependencies-container',jsPlumbData)}});mQuery(document).on('hide.bs.tab','a[data-toggle="tab"]',function(e){if(!mQuery(e.target).attr('id')!=='segment-dependencies'){Mautic.cleanSegmentDependencies()}})}};Mautic.listOnUnload=function(){Mautic.cleanSegmentDependencies()}
Mautic.cleanSegmentDependencies=function(){mQuery('.jtk-connector').remove();mQuery('#segment-dependencies-container').empty()}
Mautic.renderSegmentTree=function(containerId,data){Mautic.cleanSegmentDependencies();const plumbInstance=jsPlumb.getInstance({elementsDraggable:!1,container:document.querySelector(containerId)});const wrapper=mQuery(containerId);const nodes={};for(let level=0;level<data.levels.length;level++){const row=mQuery('<div class="segment-level" id="segment-level-'+level+'"></div>');wrapper.append(row);for(let index=0;index<data.levels[level].nodes.length;index++){const nodeData=data.levels[level].nodes[index];const node=Mautic.buildSegmentDependencyNode(nodeData);row.append(node);nodes[nodeData.id]=node}}
for(let index=0;index<data.edges.length;index++){const edge=data.edges[index];plumbInstance.connect({source:nodes[edge.source],target:nodes[edge.target],connector:'Flowchart',anchor:['Top','Bottom'],endpoint:"Blank",})}
return plumbInstance}
Mautic.buildSegmentDependencyNode=function(nodeData){let message='';let hasMessageClass='';if(nodeData.message){message='<span class="segment-dependency-message text-danger">'+nodeData.message+'</span>';hasMessageClass=' has-message'}
const link='<a href="'+nodeData.link+'" data-toggle="ajax">'+nodeData.name+'</a>';const node=mQuery('<div class="segment-node'+hasMessageClass+'" id="segment-node'+nodeData.id+'">'+link+message+'</div>');return node}
Mautic.loadAndProcessPageContent=function(containerId){const container=mQuery(containerId);if(!container.length){return}
const segmentContactUrl=container.data('target-url');mQuery.get(segmentContactUrl,function(response){response.target=containerId;Mautic.processPageContent(response)})};Mautic.lazyLoadContactStatsOnLeadLoad=function(){const containerId='#lead-stats';const container=mQuery(containerId);if(!container.length){return}
const contactStatsUrl=container.data('target-url');mQuery.get(contactStatsUrl,function(response){response.target=containerId;Mautic.processPageContent(response)})};Mautic.notificationOnLoad=function(container,response){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','notification')}
Mautic.activatePreviewPanelUpdate()};Mautic.selectNotificationType=function(notificationType){if(notificationType=='list'){mQuery('#leadList').removeClass('hide');mQuery('#publishStatus').addClass('hide');mQuery('.page-header h3').text(mauticLang.newListNotification)}else{mQuery('#publishStatus').removeClass('hide');mQuery('#leadList').addClass('hide');mQuery('.page-header h3').text(mauticLang.newTemplateNotification)}
mQuery('#notification_notificationType').val(notificationType);mQuery('body').removeClass('noscroll');mQuery('.notification-type-modal').remove();mQuery('.notification-type-modal-backdrop').remove()};Mautic.standardNotificationUrl=function(options){if(!options){return}
var url=options.windowUrl;if(url){var editEmailKey='/notifications/edit/notificationId';var previewEmailKey='/notifications/preview/notificationId';if(url.indexOf(editEmailKey)>-1||url.indexOf(previewEmailKey)>-1){options.windowUrl=url.replace('notificationId',mQuery('#campaignevent_properties_notification').val())}}
return options};Mautic.disabledNotificationAction=function(opener){if(typeof opener=='undefined'){opener=window}
var notification=opener.mQuery('#campaignevent_properties_notification').val();var disabled=notification===''||notification===null;opener.mQuery('#campaignevent_properties_editNotificationButton').prop('disabled',disabled)};Mautic.activatePreviewPanelUpdate=function(){var notificationPreview=mQuery('#notification-preview');var notificationForm=mQuery('form[name="notification"]');if(notificationPreview.length&&notificationForm.length){var inputs=notificationForm.find('input,textarea');inputs.on('blur',function(){var $this=mQuery(this);var name=$this.attr('name');if(name==='notification[heading]'){notificationPreview.find('h4').text($this.val())}
if(name==='notification[message]'){notificationPreview.find('p').text($this.val())}
if(name==='notification[url]'){notificationPreview.find('span').not('.ri-notification-3-fill').text($this.val())}})}};Mautic.pageOnLoad=function(container,response){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','page.page')}
if(mQuery(container+' #page_template').length){Mautic.toggleBuilderButton(mQuery('#page_template').val()=='');Mautic.getTokens(Mautic.getBuilderTokensMethod(),function(){});Mautic.initSelectTheme(mQuery('#page_template'))}
if(response&&response.inBuilder){Mautic.launchBuilder('page');Mautic.processBuilderErrors(response)}};Mautic.getPageAbTestWinnerForm=function(abKey){if(abKey&&mQuery(abKey).val()&&mQuery(abKey).closest('.form-group').hasClass('has-error')){mQuery(abKey).closest('.form-group').removeClass('has-error');if(mQuery(abKey).next().hasClass('help-block')){mQuery(abKey).next().remove()}}
Mautic.activateLabelLoadingIndicator('page_variantSettings_winnerCriteria');var pageId=mQuery('#page_sessionId').val();var query="action=page:getAbTestForm&abKey="+mQuery(abKey).val()+"&pageId="+pageId;mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(typeof response.html!='undefined'){if(mQuery('#page_variantSettings_properties').length){mQuery('#page_variantSettings_properties').replaceWith(response.html)}else{mQuery('#page_variantSettings').append(response.html)}
if(response.html!=''){Mautic.onPageLoad('#page_variantSettings_properties',response)}}
Mautic.removeLabelLoadingIndicator()},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown);spinner.remove()},complete:function(){Mautic.removeLabelLoadingIndicator()}})};if(typeof MauticPrefCenterLoaded==='undefined'){var MauticPrefCenterLoaded=!0;function togglePreferredChannel(channel){var status=document.getElementById(channel).checked;const fieldsToToggle=['frequency_number','frequency_time','contact_pause_start_date','contact_pause_end_date','lead_channels_frequency_number','lead_channels_frequency_time','lead_channels_contact_pause_start_date','lead_channels_contact_pause_end_date',];fieldsToToggle.forEach(field=>{const element=document.getElementById('lead_contact_frequency_rules_'+field+'_'+channel);if(element){if(status){element.removeAttribute('disabled')}else{element.setAttribute('disabled','disabled')}
element.dispatchEvent(new CustomEvent('chosen:updated'))}})}
function saveUnsubscribePreferences(formId){var forms=document.getElementsByName(formId);for(var i=0;i<forms.length;i++){if(forms[i].tagName==='FORM'){forms[i].submit()}}}};Mautic.matchedFields=function(index,object,integration){var compoundMauticFields=['mauticContactId','mauticContactTimelineLink'];if(mQuery('#integration_details_featureSettings_updateDncByDate_0').is(':checked')){compoundMauticFields.push('mauticContactIsContactableByEmail')}
var integrationField=mQuery('#integration_details_featureSettings_'+object+'Fields_i_'+index).attr('data-value');var mauticField=mQuery('#integration_details_featureSettings_'+object+'Fields_m_'+index+' option:selected').val();if(mQuery('.btn-arrow'+index).parent().attr('data-force-direction')!=1){if(mQuery.inArray(mauticField,compoundMauticFields)>=0){mQuery('.btn-arrow'+index).removeClass('active');mQuery('#integration_details_featureSettings_'+object+'Fields_update_mautic'+index+'_0').attr('checked','checked');mQuery('input[name="integration_details[featureSettings]['+object+'Fields][update_mautic'+index+']"]').prop('disabled',!0).trigger("chosen:updated");mQuery('.btn-arrow'+index).addClass('disabled')}else{mQuery('input[name="integration_details[featureSettings]['+object+'Fields][update_mautic'+index+']"]').prop('disabled',!1).trigger("chosen:updated");mQuery('.btn-arrow'+index).removeClass('disabled')}}
if(object=='lead'){var updateMauticField=mQuery('input[name="integration_details[featureSettings]['+object+'Fields][update_mautic'+index+']"]:checked').val()}else{var updateMauticField=mQuery('input[name="integration_details[featureSettings]['+object+'Fields][update_mautic_company'+index+']"]:checked').val()}
Mautic.ajaxActionRequest('plugin:matchFields',{object:object,integration:integration,integrationField:integrationField,mauticField:mauticField,updateMautic:updateMauticField},function(response){var theMessage=(response.success)?'<i class="ri-check-line-circle text-success"></i>':'';mQuery('#matched-'+index+"-"+object).html(theMessage)})};Mautic.initiateIntegrationAuthorization=function(){mQuery('#integration_details_in_auth').val(1);Mautic.postForm(mQuery('form[name="integration_details"]'),'loadIntegrationAuthWindow')};Mautic.loadIntegrationAuthWindow=function(response){if(response.newContent){Mautic.processModalContent(response,'#IntegrationEditModal')}else{Mautic.stopPageLoadingBar();Mautic.stopIconSpinPostEvent();mQuery('#integration_details_in_auth').val(0);if(response.authUrl){var generator=window.open(response.authUrl,'integrationauth','height=500,width=500');if(!generator||generator.closed||typeof generator.closed=='undefined'){alert(mauticLang.popupBlockerMessage)}}}};Mautic.refreshIntegrationForm=function(){var opener=window.opener;if(opener){var form=opener.mQuery('form[name="integration_details"]');if(form.length){var action=form.attr('action');if(action){opener.Mautic.startModalLoadingBar('#IntegrationEditModal');opener.Mautic.loadAjaxModal('#IntegrationEditModal',action)}}}
window.close()};Mautic.integrationOnLoad=function(container,response){if(response&&response.name){var integration='.integration-'+response.name;if(response.enabled){mQuery(integration).removeClass('integration-disabled')}else{mQuery(integration).addClass('integration-disabled')}}else{Mautic.filterIntegrations()}
mQuery('[data-toggle="tooltip"]').tooltip()};Mautic.integrationConfigOnLoad=function(container){if(mQuery('.fields-container select.integration-field').length){var selects=mQuery('.fields-container select.integration-field');selects.on('change',function(){var select=mQuery(this),newValue=select.val(),previousValue=select.attr('data-value');select.attr('data-value',newValue);var groupSelects=mQuery(this).closest('.fields-container').find('select.integration-field').not(select);if(previousValue){mQuery('option[value="'+previousValue+'"]',groupSelects).each(function(){if(!mQuery(this).closest('select').prop('disabled')){mQuery(this).prop('disabled',!1);mQuery(this).removeAttr('disabled')}})}
if(newValue){mQuery('option[value="'+newValue+'"]',groupSelects).each(function(){if(!mQuery(this).closest('select').prop('disabled')){mQuery(this).prop('disabled',!0);mQuery(this).attr('disabled','disabled')}})}
groupSelects.each(function(){mQuery(this).trigger('chosen:updated')})});selects.each(function(){if(!mQuery(this).closest('.field-container').hasClass('hide')){mQuery(this).trigger('change')}})}};Mautic.filterIntegrations=function(update){var filter=mQuery('#integrationFilter').val();if(update){mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:"action=plugin:setIntegrationFilter&plugin="+filter})}
if(mQuery('.native-integrations').length){setTimeout(function(){var Shuffle=window.Shuffle,element=document.querySelector('.native-integrations'),shuffleOptions={itemSelector:'.shuffle-item'};window.nativeIntegrationsShuffleInstance=new Shuffle(element,shuffleOptions);window.nativeIntegrationsShuffleInstance.filter(function($el){if(filter){return mQuery($el).hasClass('plugin'+filter)}else{mQuery(shuffleOptions.itemSelector).first().css('transform','');return!0}});mQuery("html").on("fa.sidebar.minimize",function(){setTimeout(function(){window.nativeIntegrationsShuffleInstance.update()},1000)}).on("fa.sidebar.maximize",function(){setTimeout(function(){window.nativeIntegrationsShuffleInstance.update()},1000)});mQuery('#plugin-nav-tabs a').click(function(){setTimeout(function(){window.nativeIntegrationsShuffleInstance.update()},500)})},500)}};Mautic.getIntegrationLeadFields=function(integration,el,settings){if(typeof settings=='undefined'){settings={}}
settings.integration=integration;settings.object='lead';Mautic.getIntegrationFields(settings,1,el)};Mautic.getIntegrationCompanyFields=function(integration,el,settings){if(typeof settings=='undefined'){settings={}}
settings.integration=integration;settings.object='company';Mautic.getIntegrationFields(settings,1,el)};Mautic.getIntegrationFields=function(settings,page,el){var object=settings.object?settings.object:'lead';var fieldsTab=('lead'===object)?'#fields-tab':'#'+object+'-fields-container';if(el&&mQuery(el).is('input')){Mautic.activateLabelLoadingIndicator(mQuery(el).attr('id'));var namePrefix=mQuery(el).attr('name').split('[')[0];if('integration_details'!==namePrefix){var nameParts=mQuery(el).attr('name').match(/\[.*?\]+/g);nameParts=nameParts.slice(0,-1);settings.prefix=namePrefix+nameParts.join('')+"["+object+"Fields]"}}
var fieldsContainer='#'+object+'FieldsContainer';var inModal=mQuery(fieldsContainer).closest('.modal');if(inModal){var modalId='#'+mQuery(fieldsContainer).closest('.modal').attr('id');Mautic.startModalLoadingBar(modalId)}
Mautic.ajaxActionRequest('plugin:getIntegrationFields',{page:page,integration:(settings.integration)?settings.integration:null,settings:settings},function(response){if(response.success){mQuery(fieldsContainer).replaceWith(response.html);Mautic.onPageLoad(fieldsContainer);Mautic.integrationConfigOnLoad(fieldsContainer);if(mQuery(fieldsTab).length){mQuery(fieldsTab).removeClass('hide')}}else{if(mQuery(fieldsTab).length){mQuery(fieldsTab).addClass('hide')}}
if(el){Mautic.removeLabelLoadingIndicator()}
if(inModal){Mautic.stopModalLoadingBar(modalId)}})};Mautic.getIntegrationConfig=function(el,settings){Mautic.activateLabelLoadingIndicator(mQuery(el).attr('id'));if(typeof settings=='undefined'){settings={}}
settings.name=mQuery(el).attr('name');var data={integration:mQuery(el).val(),settings:settings};mQuery('.integration-campaigns-status').html('');mQuery('.integration-config-container').html('');Mautic.ajaxActionRequest('plugin:getIntegrationConfig',data,function(response){if(response.success){mQuery('.integration-config-container').html(response.html);Mautic.onPageLoad('.integration-config-container',response)}
Mautic.integrationConfigOnLoad('.integration-config-container');Mautic.removeLabelLoadingIndicator()},!1,!1,"GET")};Mautic.getIntegrationCampaignStatus=function(el,settings){Mautic.activateLabelLoadingIndicator(mQuery(el).attr('id'));if(typeof settings=='undefined'){settings={}}
var prefix=mQuery(el).attr('name').split("[")[0];settings.name=mQuery('#'+prefix+'_properties_integration').attr('name');var data={integration:mQuery('#'+prefix+'_properties_integration').val(),campaign:mQuery(el).val(),settings:settings};mQuery('.integration-campaigns-status').html('');mQuery('.integration-campaigns-status').removeClass('hide');Mautic.ajaxActionRequest('plugin:getIntegrationCampaignStatus',data,function(response){if(response.success){mQuery('.integration-campaigns-status').append(response.html);Mautic.onPageLoad('.integration-campaigns-status',response)}
Mautic.integrationConfigOnLoad('.integration-campaigns-status');Mautic.removeLabelLoadingIndicator()},!1,!1,"GET")};Mautic.initPluginEvents=function(){const $integrationModal=mQuery('#IntegrationEditModal');$integrationModal.off('mautic:onPageLoad:before');$integrationModal.on('mautic:onPageLoad:before',function(e,container,response){if(container==='#IntegrationEditModal'&&response&&response.pluginVersion){const $modalLabel=mQuery('#IntegrationEditModal-label');if($modalLabel.find('.plugin-version-badge').length===0){const $badge=mQuery('<span>').addClass('plugin-version-badge label label-default ml-xs').text('v'+String(response.pluginVersion));$modalLabel.append(' ').append($badge)}}})};Mautic.pointOnLoad=function(container){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','point')}};Mautic.pointTriggerOnLoad=function(container){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','point.trigger')}
if(mQuery('#triggerEvents')){mQuery('#triggerEvents').sortable({items:'.trigger-event-row',handle:'.reorder-handle',stop:function(i){mQuery.ajax({type:"POST",url:mauticAjaxUrl+"?action=point:reorderTriggerEvents",data:mQuery('#triggerEvents').sortable("serialize")+"&triggerId="+mQuery('#pointtrigger_sessionId').val()})}});mQuery('#triggerEvents .trigger-event-row').on('mouseover.triggerevents',function(){mQuery(this).find('.form-buttons').removeClass('hide')}).on('mouseout.triggerevents',function(){mQuery(this).find('.form-buttons').addClass('hide')}).on('dblclick.triggerevents',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()})}};Mautic.pointTriggerEventOnLoad=function(container,response){if(response.eventHtml){var newHtml=response.eventHtml;var eventId='#triggerEvent_'+response.eventId;if(mQuery(eventId).length){mQuery(eventId).replaceWith(newHtml);var newField=!1}else{mQuery(newHtml).appendTo('#triggerEvents');var newField=!0}
mQuery(eventId+" *[data-toggle='tooltip']").tooltip({html:!0});mQuery(eventId+" a[data-toggle='ajax']").click(function(event){event.preventDefault();return Mautic.ajaxifyLink(this,event)});mQuery(eventId+" a[data-toggle='ajaxmodal']").on('click.ajaxmodal',function(event){event.preventDefault();Mautic.ajaxifyModal(this,event)});mQuery('#triggerEvents .trigger-event-row').off(".triggerevents");mQuery('#triggerEvents .trigger-event-row').on('mouseover.triggerevents',function(){mQuery(this).find('.form-buttons').removeClass('hide')}).on('mouseout.triggerevents',function(){mQuery(this).find('.form-buttons').addClass('hide')}).on('dblclick.triggerevents',function(event){event.preventDefault();mQuery(this).find('.btn-edit').first().click()});if(!mQuery('#events-panel').hasClass('in')){mQuery('a[href="#events-panel"]').trigger('click')}
if(mQuery('#triggerEventPlaceholder').length){mQuery('#triggerEventPlaceholder').remove()}}};Mautic.getPointActionPropertiesForm=function(actionType){Mautic.activateLabelLoadingIndicator('point_type');var query="action=point:getActionForm&actionType="+actionType;mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(typeof response.html!='undefined'){mQuery('#pointActionProperties').html(response.html);Mautic.onPageLoad('#pointActionProperties',response)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.removeLabelLoadingIndicator()}})};Mautic.EnablesOption=function(urlActionProperty){if(urlActionProperty==='point_properties_returns_within'&&mQuery('#point_properties_returns_within').val()>0){mQuery('#point_properties_returns_after').val(0)}else{if(urlActionProperty==='point_properties_returns_after'&&mQuery('#point_properties_returns_after').val()>0){mQuery('#point_properties_returns_within').val(0)}}};class ProjectSelectBox{constructor(selectElement){this.$projectSelect=mQuery(selectElement);this.init()}
init(){this.$projectSelect.on('chosen:no_results',this.attachKeydownListener.bind(this))}
attachKeydownListener(event){const $input=mQuery(event.target).next('.chosen-container').find('.chosen-search-input');$input.off('keydown').on('keydown',(e)=>{if(e.key==='Enter'){e.preventDefault();const newValue=$input.val().trim();if(newValue){const $newOption=mQuery('<option>').val('project_to_create').text(newValue).prop('selected',!0);this.$projectSelect.append($newOption).trigger('chosen:updated');this.createProjects(event.target)}}})}
createProjects(el){const newProjectNames=[];const existingProjectIds=[];const $projectSelect=mQuery(el);mQuery('#'+$projectSelect.attr('id')+' :selected').each(function(i,selected){const $option=mQuery(selected);const selectedId=$option.val();if('project_to_create'===selectedId){newProjectNames.push($option.text())}else{existingProjectIds.push(selectedId)}});if(!newProjectNames.length){return}
Mautic.activateLabelLoadingIndicator($projectSelect.attr('id'));Mautic.ajaxActionRequest('project:addProjects',{newProjectNames:JSON.stringify(newProjectNames),existingProjectIds:JSON.stringify(existingProjectIds)},function(response){if(response.projects){mQuery('#'+$projectSelect.attr('id')).html(response.projects).trigger('chosen:updated')}
Mautic.removeLabelLoadingIndicator()})}}
mQuery(document).on('chosen:no_results','select',function(event){const $select=mQuery(event.target);if($select.data('action')==='createProject'){new ProjectSelectBox($select)}});mQuery(document).on('change','#project-entity-selector, #entity-type-selector',function(event){const $select=mQuery(this);const $selectedOption=$select.find('option:selected');if($selectedOption.val()&&$selectedOption.data('href')){const url=$selectedOption.data('href');const header=$selectedOption.data('header');Mautic.loadAjaxModal('#MauticSharedModal',url,'GET',header);$select.val('');if($select.hasClass('chosen-select')){$select.trigger('chosen:updated')}}});Mautic.reportOnLoad=function(container){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','report')}
if(mQuery('div[id=report_filters]').length){mQuery('div[id=report_filters]').attr('data-index',Mautic.getHighestIndex('report_filters'));mQuery('div[id=report_tableOrder]').attr('data-index',Mautic.getHighestIndex('report_tableOrder'));mQuery('div[id=report_aggregators]').attr('data-index',Mautic.getHighestIndex('report_aggregators'));if(mQuery('.filter-columns').length){mQuery('.filter-columns').each(function(){Mautic.updateReportFilterValueInput(this,!0);mQuery(this).on('change',function(){Mautic.updateReportFilterValueInput(this)})})}}else{mQuery('#report-shelves .collapse').on('show.bs.collapse',function(e){var actives=mQuery('#report-shelves').find('.in, .collapsing');actives.each(function(index,element){mQuery(element).collapse('hide');var id=mQuery(element).attr('id');mQuery('a[aria-controls="'+id+'"]').addClass('collapsed')})})}
Mautic.updateReportGlueTriggers();Mautic.checkSelectedGroupBy();Mautic.initDateRangePicker();var $isScheduled=mQuery('[data-report-schedule="isScheduled"]');var $unitTypeId=mQuery('[data-report-schedule="scheduleUnit"]');var $scheduleDay=mQuery('[data-report-schedule="scheduleDay"]');var $scheduleMonthFrequency=mQuery('[data-report-schedule="scheduleMonthFrequency"]');mQuery($isScheduled).change(function(){Mautic.scheduleDisplay($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency)});mQuery($unitTypeId).change(function(){Mautic.scheduleDisplay($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency)});mQuery($scheduleDay).change(function(){Mautic.schedulePreview($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency)});mQuery($scheduleMonthFrequency).change(function(){Mautic.schedulePreview($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency)});Mautic.scheduleDisplay($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency);jQuery(document).ajaxComplete(function(){Mautic.ajaxifyForm('daterange')})};Mautic.scheduleDisplay=function($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency){Mautic.checkIsScheduled($isScheduled);var unitVal=mQuery($unitTypeId).val();mQuery('#scheduleDay, #scheduleDay label, #scheduleMonthFrequency').hide();if(unitVal==='WEEKLY'||unitVal==='MONTHLY'){mQuery('#scheduleDay').show()}
if(unitVal==='MONTHLY'){mQuery('#scheduleMonthFrequency').show();mQuery('#scheduleDay label').hide()}else{mQuery('#scheduleDay label').show()}
if($isScheduled.length){Mautic.schedulePreview($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency)}};Mautic.schedulePreview=function($isScheduled,$unitTypeId,$scheduleDay,$scheduleMonthFrequency){var previewUrl=mQuery('#schedule_preview_url').data('url');var $schedulePreviewData=mQuery('#schedule_preview_data');var isScheduledVal=0;if(mQuery($isScheduled).prop("checked")){isScheduledVal=1}
if(!isScheduledVal){$schedulePreviewData.hide();return}
var unitVal=mQuery($unitTypeId).val();var scheduleDayVal=mQuery($scheduleDay).val();var scheduleMonthFrequencyVal=mQuery($scheduleMonthFrequency).val();mQuery.get(previewUrl+'/'+isScheduledVal+'/'+unitVal+'/'+scheduleDayVal+'/'+scheduleMonthFrequencyVal,function(data){if(!data.html){return}
mQuery("#schedule_preview_data_content").html(data.html);$schedulePreviewData.show()})};Mautic.checkIsScheduled=function($isScheduled){var $scheduleForm=mQuery('#schedule-container .schedule_form');if(mQuery($isScheduled).prop("checked")){$scheduleForm.show();return}
$scheduleForm.hide()};Mautic.addReportRow=function(elId){var prototypeHolder=mQuery('div[id="'+elId+'"]');var index=parseInt(prototypeHolder.attr('data-index'));if(!index){index=0}
index++;var prototype=prototypeHolder.data('prototype');var output=prototype.replace(/__name__/g,index);prototypeHolder.attr('data-index',index);prototypeHolder.append(output);var newColumnId='#'+elId+'_'+index+'_column';if(elId=='report_filters'){if(typeof Mautic.reportPrototypeFilterOptions!='undefined'){mQuery(newColumnId).html(Mautic.reportPrototypeFilterOptions)}
mQuery('#report_filters_'+index+'_container').addClass('in-group');mQuery(newColumnId).on('change',function(){Mautic.updateReportFilterValueInput(this)});Mautic.updateReportFilterValueInput(newColumnId);Mautic.updateReportGlueTriggers()}else if(typeof Mautic.reportPrototypeColumnOptions!='undefined'){mQuery(newColumnId).html(Mautic.reportPrototypeColumnOptions.clone())}
Mautic.activateChosenSelect(mQuery('#'+elId+'_'+index+'_column'));mQuery("#"+elId+" *[data-toggle='tooltip']").tooltip({html:!0,container:'body'})};Mautic.updateReportGlueTriggers=function(){var filterContainer=mQuery('#report_filters');var glueEl=filterContainer.find('.filter-glue');glueEl.off('change');glueEl.on('change',function(){var $this=mQuery(this);if($this.val()==='and'){$this.parents('.panel').addClass('in-group')}else{$this.parents('.panel').removeClass('in-group')}})};Mautic.updateReportFilterValueInput=function(filterColumn,setup){var definitions=(typeof Mautic.reportPrototypeFilterDefinitions!='undefined')?Mautic.reportPrototypeFilterDefinitions:mQuery('#report_filters').data('filter-definitions');var operators=(typeof Mautic.reportPrototypeFilterOperators!='undefined')?Mautic.reportPrototypeFilterOperators:mQuery('#report_filters').data('filter-operators');var newValue=mQuery(filterColumn).val();if(!newValue){return}
var filterId=mQuery(filterColumn).attr('id');var filterType=definitions[newValue].type;var valueEl=mQuery(filterColumn).parent().parent().find('.filter-value');var valueVal=valueEl.val();var idParts=filterId.split("_");var valueId='report_filters_'+idParts[2]+'_value';var valueName='report[filters]['+idParts[2]+'][value]';valueEl.data('filter-type',filterType);var currentOperator=mQuery('#report_filters_'+idParts[2]+'_condition').val();mQuery('#report_filters_'+idParts[2]+'_condition').html(operators[newValue]);if(mQuery('#report_filters_'+idParts[2]+'_condition option[value="'+currentOperator+'"]').length>0){mQuery('#report_filters_'+idParts[2]+'_condition').val(currentOperator)}
Mautic.destroyChosen(mQuery('#'+valueId));if(filterType=='bool'||filterType=='boolean'){const yesId=valueId+'_1';const noId=valueId+'_0';const isYes=valueVal=='1';const $template=mQuery('#filterValueYesNoTemplate').clone();const $label=$template.find('#report_value_template_yesno_label');const $yesOption=$template.find('#report_value_template_yesno_1');const $noOption=$template.find('#report_value_template_yesno_0');$template.removeAttr('id').addClass('toggle-container');$yesOption.attr('name',valueName).attr('id',yesId);$noOption.attr('name',valueName).attr('id',noId);$label.attr('id',valueId+'_bool-label').attr('data-yes-id',yesId).attr('data-no-id',noId);if(mQuery(valueEl).is(':radio')){mQuery(valueEl).closest('.toggle-container').replaceWith($template)}else{mQuery(valueEl).replaceWith($template)}
if(!isYes){Mautic.toggleYesNo($label)}}else if(mQuery(valueEl).attr('type')!='text'){var newValueEl=mQuery('<input type="text" />').attr({id:valueId,name:valueName,'class':"form-control filter-value"});var replaceMe=(mQuery(valueEl).attr('type')=='radio')?mQuery(valueEl).parent().parent():mQuery(valueEl);replaceMe.replaceWith(newValueEl)}
if((filterType=='multiselect'||filterType=='select')&&typeof definitions[newValue].list!='undefined'){var currentValue=mQuery(valueEl).val();var attr={id:valueId,name:valueName,"class":'form-control filter-value',};if(filterType=='multiselect'){attr.name+='[]';attr.multiple=!0;currentValue=(typeof currentValue!=='undefined')?currentValue.split(","):null}
var newSelect=mQuery('<select />',attr);mQuery.each(definitions[newValue].list,function(value,label){var newOption=mQuery('<option />').val(value).html(label);if(value==currentValue&&filterType!='multiselect'){newOption.prop('selected',!0)}
newOption.appendTo(newSelect)});if(filterType=='multiselect'){newSelect.val(currentValue)}
mQuery(valueEl).replaceWith(newSelect);Mautic.activateChosenSelect(newSelect)}
const dateTypes=['datetime','date','time'];const stringComparisonOperators=['like','notLike','startsWith','endsWith','contains'];if(dateTypes.includes(filterType)){Mautic.activateDateTimeInputs('#'+valueId,filterType)}else if(mQuery('#'+valueId).hasClass('calendar-activated')){mQuery('#'+valueId).datetimepicker('destroy')}
if(dateTypes.includes(filterType)){const inputElement=mQuery('#'+valueId);if(inputElement.data('utc-tooltip-initialized')){return}
inputElement.attr('data-bs-toggle','tooltip').attr('data-bs-placement','bottom').attr('title','...').tooltip({trigger:'manual'});inputElement.on('focus',function(){const currentOperator=mQuery('#report_filters_'+idParts[2]+'_condition').val();const currentFilterType=mQuery(this).data('filter-type');let message=null;if(dateTypes.includes(currentFilterType)){if(stringComparisonOperators.includes(currentOperator)){message=Mautic.translate('mautic.report.filter.string_comparison_utc_tooltip')}else{message=Mautic.translate('mautic.report.filter.date_comparison_timezone_tooltip')}
mQuery(this).attr('title',message).tooltip('fixTitle').tooltip('show')}}).on('blur',function(){mQuery(this).tooltip('hide')});inputElement.data('utc-tooltip-initialized',!0)}};Mautic.removeReportRow=function(container){mQuery("#"+container+" *[data-toggle='tooltip']").tooltip('destroy');mQuery('#'+container).remove()};Mautic.updateReportSourceData=function(context){Mautic.activateLabelLoadingIndicator('report_source');mQuery.ajax({url:mauticAjaxUrl,type:'post',data:"action=report:getSourceData&context="+context,success:function(response){mQuery('#report_columns').html(response.columns);mQuery('#report_columns').multiSelect('refresh');mQuery('#report_groupBy').html(response.columns);mQuery('#report_groupBy').multiSelect('refresh');mQuery('#report_filters').find('div').remove().end();mQuery('#report_filters').data('index',0);Mautic.reportPrototypeColumnOptions=mQuery(response.columns);mQuery('#report_tableOrder').find('div').remove().end();mQuery('#report_tableOrder').data('index',0);mQuery('#report_aggregators').find('div').remove().end();mQuery('#report_aggregators').data('index',0);Mautic.reportPrototypeFilterDefinitions=response.filterDefinitions;Mautic.reportPrototypeFilterOptions=response.filters;Mautic.reportPrototypeFilterOperators=response.filterOperators;mQuery('#report_graphs').html(response.graphs);mQuery('#report_graphs').multiSelect('refresh');if(!response.graphs){mQuery('#graphs-container').addClass('hide');mQuery('#graphs-tab').addClass('hide')}else{mQuery('#graphs-container').removeClass('hide');mQuery('#graphs-tab').removeClass('hide')}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.removeLabelLoadingIndicator()}})};Mautic.checkReportCondition=function(selector){var option=mQuery('#'+selector+' option:selected').val();var valueInput=selector.replace('condition','value');if(option=='empty'||option=='notEmpty'){mQuery('#'+valueInput).prop('disabled',!0).trigger('chosen:updated')}else{mQuery('#'+valueInput).prop('disabled',!1).trigger('chosen:updated')}};Mautic.checkSelectedGroupBy=function(){var selectedOption=mQuery("select[name='report[groupBy][]'] option:selected").length;var existingAggregators=mQuery("select[name*='report[aggregators]']");if(selectedOption>0){mQuery('#aggregators-button').prop('disabled',!1)}else{existingAggregators.each(function(){var containerId=mQuery(this).attr('id').replace('_column','');Mautic.removeReportRow(containerId+'_container')});mQuery('#aggregators-button').prop('disabled',!0)}};Mautic.getHighestIndex=function(selector){var highestIndex=1;var selectorChildren=mQuery('#'+selector+' > div');selectorChildren.each(function(){var index=parseInt(mQuery(this).attr('id').split('_')[2]);highestIndex=(index>highestIndex)?index:highestIndex});return parseInt(highestIndex)};Mautic.cloneReportRow=function(containerId){const container=mQuery(`#${containerId}`);const glue=container.find('.filter-glue').val();const column=container.find('.filter-columns').val();const value=container.find('.filter-value:checked, .filter-value').val();const dynamic=container.find('[name*="[dynamic]"]:checked').val();Mautic.addReportRow('report_filters');const newContainer=mQuery('#report_filters').find('> .panel.in-group').last();newContainer.find('.filter-glue').val(glue);const columnSelect=newContainer.find('.filter-columns').val(column).trigger('change');const initializeChosenWhenReady=(selectElement)=>{if(selectElement.find('option').length>0){Mautic.destroyChosen(selectElement);Mautic.activateChosenSelect(selectElement)}else{setTimeout(()=>initializeChosenWhenReady(selectElement),200)}};initializeChosenWhenReady(columnSelect);const newValueInput=newContainer.find('.filter-value');if(newValueInput.is('select')){newValueInput.val(value);initializeChosenWhenReady(newValueInput)}else{newValueInput.val(value).prop('checked',!0).parent().addClass('active')}
const dynamicLabel=newContainer.find('.toggle__label');if((dynamic==='1'&&dynamicLabel.attr('aria-checked')!=='true')||(dynamic==='0'&&dynamicLabel.attr('aria-checked')!=='false')){dynamicLabel.trigger('click')}
newContainer.find("*[data-toggle='tooltip']").tooltip({html:!0,container:'body'})};Mautic.smsOnLoad=function(container,response){const smsMessage=mQuery('#sms_message');if(smsMessage.length){Mautic.setSmsCharactersCount(smsMessage);smsMessage.on('input',()=>{Mautic.setSmsCharactersCount(smsMessage)})}
if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','sms')}
if(mQuery('table.sms-list').length){var ids=[];mQuery('td.col-stats').each(function(){var id=mQuery(this).attr('data-stats');ids.push(id)});while(ids.length>0){let batchIds=ids.splice(0,10);Mautic.ajaxActionRequest('sms:getSmsCountStats',{ids:batchIds},function(response){if(response.success&&response.stats){for(var i=0;i<response.stats.length;i++){var stat=response.stats[i];if(mQuery('#pending-'+stat.id).length){if(stat.pending){mQuery('#pending-'+stat.id+' > a').html(stat.pending);mQuery('#pending-'+stat.id).removeClass('hide')}}}}},!1,!0)}}
Mautic.initSmsAtWho()};Mautic.setSmsCharactersCount=function(smsMessage){mQuery('#sms_nb_char').text((smsMessage.val().length))};Mautic.initSmsAtWho=function(){var smsMessage=mQuery('#sms_message, #send_sms_message');smsMessage.each(function(){var obj=mQuery(this);var callbackAttr=obj.attr('data-token-callback');if(typeof callbackAttr=='undefined'){obj.attr('data-token-callback','sms:getBuilderTokens');obj.attr('data-token-activator','{');obj.attr('data-token-visual','false');Mautic.initAtWho(obj,obj.attr('data-token-callback'))}})}
Mautic.selectSmsType=function(smsType){if(smsType=='list'){mQuery('#leadList').removeClass('hide');mQuery('#publishStatus').addClass('hide');mQuery('.page-header h3').text(mauticLang.newListSms)}else{mQuery('#publishStatus').removeClass('hide');mQuery('#leadList').addClass('hide');mQuery('.page-header h3').text(mauticLang.newTemplateSms)}
mQuery('#sms_smsType').val(smsType);mQuery('body').removeClass('noscroll');mQuery('.sms-type-modal').remove();mQuery('.sms-type-modal-backdrop').remove()};Mautic.standardSmsUrl=function(options){if(!options){return}
var url=options.windowUrl;if(url){var editEmailKey='/sms/edit/smsId';if(url.indexOf(editEmailKey)>-1){options.windowUrl=url.replace('smsId',mQuery('#campaignevent_properties_sms').val())}}
return options};Mautic.disabledSmsAction=function(opener){if(typeof opener=='undefined'){opener=window}
var sms=opener.mQuery('#campaignevent_properties_sms').val();var disabled=sms===''||sms===null;opener.mQuery('#campaignevent_properties_editSmsButton').prop('disabled',disabled)};Mautic.getStageActionPropertiesForm=function(actionType){Mautic.activateLabelLoadingIndicator('stage_type');var query="action=stage:getActionForm&actionType="+actionType;mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(typeof response.html!='undefined'){mQuery('#stageActionProperties').html(response.html);Mautic.onPageLoad('#stageActionProperties',response)}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.removeLabelLoadingIndicator()}})};Mautic.userOnLoad=function(container){if(mQuery(container+' form[name="user"]').length){if(mQuery('#user_position').length){Mautic.activateTypeahead('#user_position',{displayKey:'position'})}}else{if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','user.user')}}
document.querySelectorAll('input[type="radio"][data-attribute-toggle]').forEach(radio=>{const attributeName=radio.dataset.attributeToggle;const hiddenInput=document.getElementById(`user_preferences_${attributeName.replace('-', '_')}`);if(hiddenInput&&hiddenInput.value){const correspondingRadio=document.querySelector(`input[name="${attributeName}"][data-attribute-value="${hiddenInput.value}"]`);if(correspondingRadio)correspondingRadio.checked=!0}else if(radio.checked){if(hiddenInput){hiddenInput.value=radio.dataset.attributeValue}}});document.querySelectorAll('input[type="radio"][data-attribute-toggle]').forEach(radio=>{radio.addEventListener('change',function(){if(this.checked){const attributeName=this.dataset.attributeToggle;const hiddenInput=document.getElementById(`user_preferences_${attributeName.replace('-', '_')}`);if(hiddenInput){hiddenInput.value=this.dataset.attributeValue}}})});document.querySelector('[id^="user_buttons_save_toolbar"]').addEventListener('click',function(){document.querySelectorAll('input[type="radio"][data-attribute-toggle]:checked').forEach(radio=>{const attributeToggle=radio.dataset.attributeToggle;const attributeValue=radio.dataset.attributeValue;document.documentElement.setAttribute(attributeToggle,attributeValue)})})};Mautic.roleOnLoad=function(container,response){if(mQuery(container+' #list-search').length){Mautic.activateSearchAutocomplete('list-search','user.role')}
if(response&&response.permissionList){MauticVars.permissionList=response.permissionList}
Mautic.togglePermissionVisibility()};Mautic.togglePermissionVisibility=function(){setTimeout(function(){if(mQuery('#role_isAdmin_0').prop('checked')){mQuery('#rolePermissions').removeClass('hide');mQuery('#isAdminMessage').addClass('hide');mQuery('#permissions-tab').removeClass('disabled')}else{mQuery('#rolePermissions').addClass('hide');mQuery('#isAdminMessage').removeClass('hide');mQuery('#permissions-tab').addClass('disabled')}},10)};Mautic.onPermissionChange=function(changedPermission,bundle){var granted=0;if(mQuery(changedPermission).prop('checked')){if(mQuery(changedPermission).val()=='full'){mQuery(changedPermission).closest('.choice-wrapper').find("label input:checkbox:checked").map(function(){if(mQuery(this).val()!='full'){mQuery(this).prop('checked',!1);mQuery(this).parent().toggleClass('active')}})}else{mQuery(changedPermission).closest('.choice-wrapper').find("label input:checkbox:checked").map(function(){if(mQuery(this).val()=='full'){granted=granted-1;mQuery(this).prop('checked',!1);mQuery(this).parent().toggleClass('active')}})}}
if(mQuery('.'+bundle+'_granted').length){var granted=0;var levelPerms=MauticVars.permissionList[bundle];mQuery.each(levelPerms,function(level,perms){mQuery.each(perms,function(index,perm){var isChecked=mQuery('input[data-permission="'+bundle+':'+level+':'+perm+'"]').prop('checked');if(perm=='full'){if(isChecked){if(perms.length===1){granted++}else{granted+=perms.length-1}}}else if(isChecked){granted++}})});mQuery('.'+bundle+'_granted').html(granted)}};Mautic.sendHookTest=function(){var url=mQuery('#webhook_webhookUrl').val();var secret=mQuery('#webhook_secret').val();var eventTypes=mQuery("#event-types input[type='checkbox']");var selectedTypes=[];eventTypes.each(function(){var item=mQuery(this);if(item.is(':checked')){selectedTypes.push(item.val())}});var data={action:'webhook:sendHookTest',url:url,secret:secret,types:selectedTypes};var spinner=mQuery('#spinner');spinner.removeClass('hide');mQuery.ajax({url:mauticAjaxUrl,data:data,type:'POST',dataType:"json",success:function(response){if(response.html){mQuery('#tester').html(response.html)}},error:function(response,textStatus,errorThrown){console.log(response.responseJSON);if(response.responseJSON.html){mQuery('#tester').html(response.responseJSON.html)}else{Mautic.processAjaxError(response,textStatus,errorThrown)}},complete:function(response){spinner.addClass('hide')}})};Mautic.getNetworkFormAction=function(networkType){if(networkType&&mQuery(networkType).val()&&mQuery(networkType).closest('.form-group').hasClass('has-error')){mQuery(networkType).closest('.form-group').removeClass('has-error');if(mQuery(networkType).next().hasClass('help-block')){mQuery(networkType).next().remove()}}
Mautic.activateLabelLoadingIndicator('monitoring_networkType');var query="action=plugin:mauticSocial:getNetworkForm&networkType="+mQuery(networkType).val();mQuery.ajax({url:mauticAjaxUrl,type:"POST",data:query,dataType:"json",success:function(response){if(typeof response.html!='undefined'){mQuery('#properties-container').html(response.html);if(response.html!=''){Mautic.onPageLoad('#properties-container',response)}}},error:function(request,textStatus,errorThrown){Mautic.processAjaxError(request,textStatus,errorThrown)},complete:function(){Mautic.removeLabelLoadingIndicator()}})};Mautic.composeSocialWatcher=function(){var input=mQuery('textarea.tweet-message');Mautic.updateCharacterCount();input.on('keyup',function(){Mautic.updateCharacterCount()});var pageId=mQuery('select.tweet-insert-page');var assetId=mQuery('select.tweet-insert-asset');var handle=mQuery('button.tweet-insert-handle');pageId.on('change',function(){Mautic.insertSocialLink(pageId.val(),'pagelink',!1)});assetId.on('change',function(){Mautic.insertSocialLink(assetId.val(),'assetlink',!1)});handle.on('click',function(){Mautic.insertSocialLink(!1,'twitter_handle',!0)})};Mautic.getCharacterCount=function(){var tweetLenght=280;var currentLength=mQuery('textarea#twitter_tweet_text');return(tweetLenght-currentLength.val().length)};Mautic.updateCharacterCount=function(){var tweetCount=Mautic.getCharacterCount();var countContainer=mQuery('#character-count span');countContainer.text(tweetCount)};Mautic.insertSocialLink=function(id,type,skipId){if(!id&&!skipId){return}
if(skipId){var link='{'+type+'}'}else{var link='{'+type+'='+id+'}'}
var textarea=mQuery('textarea.tweet-message');var currentVal=textarea.val();var newVal=(currentVal)?currentVal+' '+link:link;textarea.val(newVal);Mautic.updateCharacterCount()};/*
 * @copyright   2014 Mautic Contributors. All rights reserved
 * @author      Mautic
 *
 * @link        http://mautic.org
 *
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 */
Mautic.testFullContactApi=function(btn){mQuery(btn).prop('disabled',!0);var apikey=mQuery('#integration_details_apiKeys_apikey').val();var d=new Date();var month=d.getMonth()+1;var period=d.getFullYear()+'-'+((month<10)?'0'+month:month);var months=new Array();months[0]="January";months[1]="February";months[2]="March";months[3]="April";months[4]="May";months[5]="June";months[6]="July";months[7]="August";months[8]="September";months[9]="October";months[10]="November";months[11]="December";var dateString=months[month-1]+' '+d.getFullYear();var EOL=String.fromCharCode(13);mQuery.get('https://api.fullcontact.com/v2/stats.json?apiKey='+apikey+'&period='+period,function(stats){var person=null;var company=null;var free=null;mQuery.each(stats.metrics,function(i,m){if('200'===m.metricId){person=m}else if('company_200'===m.metricId){company=m}else if('200_free'===m.metricId){free=m}});var result='Plan Details: '+stats.plan+EOL+EOL+'Quick Usage Stats for '+dateString+':'+EOL;if(person){result+=' - Person API: '+person.usage+' matches used from '+person.planLevel+' ('+person.remaining+' remaining)'+EOL}
if(company){result+=' - Company API: '+company.usage+' matches used from '+company.planLevel+' ('+company.remaining+' remaining)'+EOL}
if(free){result+=' - Name/Location/Stats: '+free.usage+' matches used from '+free.planLevel+' ('+free.remaining+' remaining)'+EOL}
mQuery('#integration_details_apiKeys_stats').val(result)}).fail(function(error){mQuery('#integration_details_apiKeys_stats').val((error.responseJSON&&error.responseJSON.message)?error.responseJSON.message:'Error: '+JSON.stringify(error))});mQuery(btn).prop('disabled',!1)};Mautic.disabledFocusActions=function(opener){if(typeof opener=='undefined'){opener=window}
var email=opener.mQuery('#campaignevent_properties_focus').val();var disabled=email===''||email===null;opener.mQuery('#campaignevent_properties_editFocusButton').prop('disabled',disabled);opener.mQuery('#campaignevent_properties_previewFocusButton').prop('disabled',disabled)};Mautic.focusOnLoad=function(){if(mQuery('.builder').length){mQuery('.btn-dropper').each(function(){mQuery(this).click(function(){if(mQuery(this).hasClass('active')){mQuery(this).removeClass('active btn-primary').addClass('btn-ghost');mQuery('#websiteCanvas').css('cursor','inherit')}else{mQuery('.btn-dropper').removeClass('active btn-primary').addClass('btn-ghost');mQuery(this).removeClass('btn-ghost').addClass('active btn-primary');mQuery('#websiteCanvas').css('cursor','crosshair')}})});var activateType=function(el,thisType){mQuery('[data-focus-type]').removeClass('focus-active');mQuery(el).addClass('focus-active');mQuery('#focusFormContent').removeClass(function(index,css){return(css.match(/(^|\s)focus-type\S+/g)||[]).join(' ')}).addClass('focus-type-'+thisType);mQuery('.focus-type-header').removeClass('text-danger');mQuery('#focus_type').val(thisType);var props='.focus-'+thisType+'-properties';mQuery('#focusTypeProperties').appendTo(mQuery(props)).removeClass('hide');mQuery('#focusType .focus-properties').each(function(){if(!mQuery(this).is(':hidden')&&mQuery(this).data('focus-type')!=thisType){mQuery(this).slideUp('fast',function(){mQuery(this).hide()})}});if(mQuery(props).length){if(mQuery(props).is(':hidden')){mQuery(props).slideDown('fast')}}}
mQuery('[data-focus-type]').on({click:function(){var thisType=mQuery(this).data('focus-type');if(mQuery('#focus_type').val()==thisType){return}
activateType(this,thisType);Mautic.focusUpdatePreview()},mouseenter:function(){mQuery(this).addClass('focus-hover')},mouseleave:function(){mQuery(this).removeClass('focus-hover')}});var activateStyle=function(el,thisStyle){mQuery('[data-focus-style]').removeClass('focus-active');mQuery(el).addClass('focus-active');if(!mQuery('#focusType').hasClass('hidden-focus-style-all')){mQuery('#focusType').addClass('hidden-focus-style-all')}
mQuery('#focusFormContent').removeClass(function(index,css){return(css.match(/(^|\s)focus-style\S+/g)||[]).join(' ')}).addClass('focus-style-'+thisStyle);mQuery('.focus-style-header').removeClass('text-danger');mQuery('#focus_style').val(thisStyle);var props='.focus-'+thisStyle+'-properties';mQuery('#focusStyleProperties').appendTo(mQuery(props)).removeClass('hide');mQuery('#focusStyle .focus-properties').each(function(){if(!mQuery(this).is(':hidden')){mQuery(this).slideUp('fast',function(){mQuery(this).hide()})}});if(mQuery(props).length){if(mQuery(props).is(':hidden')){mQuery(props).slideDown('fast')}}};mQuery('[data-focus-style]').on({click:function(){var thisStyle=mQuery(this).data('focus-style');if(mQuery('#focus_style').val()==thisStyle){return}
activateStyle(this,thisStyle);Mautic.focusUpdatePreview()},mouseenter:function(){mQuery(this).addClass('focus-hover')},mouseleave:function(){mQuery(this).removeClass('focus-hover')}});var currentType=mQuery('#focus_type').val();if(currentType){activateType(mQuery('[data-focus-type="'+currentType+'"]'),currentType)}
var currentStyle=mQuery('#focus_style').val();if(currentStyle){activateStyle(mQuery('[data-focus-style="'+currentStyle+'"]'),currentStyle)}
mQuery('#focus_properties_content_font').on('chosen:showing_dropdown',function(){var arrayIndex=1;mQuery('#focus_properties_content_font option').each(function(){mQuery('#focus_properties_content_font_chosen li[data-option-array-index="'+arrayIndex+'"]').css('fontFamily',mQuery(this).attr('value'));arrayIndex++})});mQuery('.btn-fetch').on('click',function(){var url=mQuery('#websiteUrlPlaceholderInput').val();if(url){mQuery('#focus_website').val(url);Mautic.launchFocusBuilder()}else{return}});Mautic.focusInitViewportSwitcher()}else{Mautic.initDateRangePicker()}
if(mQuery('[data-conversion-rate-table]').length){Mautic.focusLoadConversionRateTable()}else{Mautic.focusLoadViewCountTable()}};Mautic.launchFocusBuilder=function(forceFetch){mQuery('body').css('overflow-y','hidden');Mautic.ignoreMauticFocusPreviewUpdate=!0;if(!mQuery('#builder-overlay').length){var builderCss={margin:"0",padding:"0",border:"none",width:"100%",height:"100%"};var spinnerLeft=(mQuery(document).width()-300)/2;var overlay=mQuery('<div id="builder-overlay" class="modal-backdrop fade in"><div style="position: absolute; top:50%; left:'+spinnerLeft+'px"><i class="ri-loader-3-line ri-spin ri-5x"></i></div></div>').css(builderCss).appendTo('.builder-content')}
mQuery('.btn-close-builder').prop('disabled',!0);mQuery('.builder').addClass('builder-active').removeClass('hide');var url=mQuery('#focus_website').val();if(!url){if(!mQuery('#focus_unlockId').val()){Mautic.setFocusDefaultColors()}
mQuery('#builder-overlay').addClass('hide');mQuery('.btn-close-builder').prop('disabled',!1);mQuery('#websiteUrlPlaceholderInput').prop('disabled',!1);mQuery('#websiteCanvas').html('');mQuery('#websiteUrlPlaceholderInput').val('');Mautic.focusUpdatePreview()}else{mQuery('#websiteUrlPlaceholderInput').val(url).prop('disabled',!1);let iframe=mQuery('#websiteCanvas iframe');if(!forceFetch&&iframe.length&&url===iframe.attr('src')){return}
mQuery('#builder-overlay').removeClass('hide');Mautic.loadedPreviewImage=url;mQuery('.preview-body').html('');mQuery('.website-placeholder').removeClass('has-error').find('.help-block').html('');mQuery('.btn-dropper').addClass('disabled');Mautic.focusCreateIframe(url);Mautic.ignoreMauticFocusPreviewUpdate=!1}};Mautic.focusUpdatePreview=function(){var data=mQuery('form[name=focus]').formToArray();Mautic.ajaxActionRequest('plugin:focus:generatePreview',data,function(response){var container=mQuery('<div />');var innerContainer=mQuery('<div />').html(response.html);if(mQuery('.btn-viewport').data('viewport')=='mobile'){innerContainer.addClass('mf-responsive')}else{innerContainer.removeClass('mf-responsive')}
container.append(innerContainer);mQuery('.preview-body').html(container);if(!mQuery('.mf-bar').length&&mQuery('.builder-content').length){mQuery('.builder-content').on('click',function(){Mautic.closeFocusModal(mQuery('#focus_style').val())});mQuery('.mautic-focus').on('click',function(e){e.stopPropagation()})}})};Mautic.setFocusDefaultColors=function(){mQuery('#focus_properties_colors_primary').minicolors('value','4e5d9d');mQuery('#focus_properties_colors_text').minicolors('value',(mQuery('#focus_style').val()=='bar')?'ffffff':'000000');mQuery('#focus_properties_colors_button').minicolors('value','fdb933');mQuery('#focus_properties_colors_button_text').minicolors('value','ffffff')};Mautic.toggleBarCollapse=function(){var svg='.mf-bar-collapser-icon svg';var currentSize=mQuery(svg).data('transform-size');var currentDirection=mQuery(svg).data('transform-direction');var currentScale=mQuery(svg).data('transform-scale');var newDirection=(parseInt(currentDirection)*-1);setTimeout(function(){mQuery(svg).find('g').first().attr('transform','scale('+currentScale+') rotate('+newDirection+' '+currentSize+' '+currentSize+')');mQuery(svg).data('transform-direction',newDirection)},500);if(mQuery('.mf-bar-collapser').hasClass('mf-bar-collapsed')){if(mQuery('.mf-bar').hasClass('mf-bar-top')){mQuery('.mf-bar').css('margin-top',0)}else{mQuery('.mf-bar').css('margin-bottom',0)}
mQuery('.mf-bar-collapser').removeClass('mf-bar-collapsed')}else{if(mQuery('.mf-bar').hasClass('mf-bar-top')){mQuery('.mf-bar').css('margin-top',-60)}else{mQuery('.mf-bar').css('margin-bottom',-60)}
mQuery('.mf-bar-collapser').addClass('mf-bar-collapsed')}}
Mautic.closeFocusModal=function(style){mQuery('.mf-'+style).remove();if(mQuery('.mf-'+style+'-overlay').length){mQuery('.mf-'+style+'-overlay').remove()}}
Mautic.closeFocusBuilder=function(el){if(typeof Mautic.ajaxActionXhr!='undefined'&&typeof Mautic.ajaxActionXhr['plugin:focus:generatePreview']!='undefined'){Mautic.ajaxActionXhr['plugin:focus:generatePreview'].abort();delete Mautic.ajaxActionXhr['plugin:focus:generatePreview']}
Mautic.stopIconSpinPostEvent();mQuery('.builder').removeClass('builder-active').addClass('hide');mQuery('body').css('overflow-y','')};Mautic.focusInitViewportSwitcher=function(){mQuery('.btn-viewport').on('click',function(){if(mQuery(this).data('viewport')=='mobile'){mQuery('.btn-viewport i').removeClass('ri-macbook-line ri-2x').addClass('ri-smartphone-line ri-2x');mQuery(this).data('viewport','desktop');Mautic.launchFocusBuilder(!0)}else{mQuery('.btn-viewport i').removeClass('ri-smartphone-line ri-2x').addClass('ri-macbook-line ri-2x');mQuery(this).data('viewport','mobile');Mautic.launchFocusBuilder(!0)}})}
Mautic.focusCreateIframe=function(url){let builderCss={"pointer-events":"none",};if(mQuery('.btn-viewport').data('viewport')==='mobile'){mQuery('#websiteScreenshot').addClass('mobile')}else{builderCss.width="100%";builderCss.height=mQuery('#websiteScreenshot').height();mQuery('#websiteScreenshot').removeClass('mobile')}
var iframe=mQuery('<iframe scrolling="no" frameBorder="0"></iframe>');iframe.css(builderCss);iframe.on('load',function(){mQuery('#builder-overlay').addClass('hide');mQuery('.btn-close-builder').prop('disabled',!1);mQuery('#websiteUrlPlaceholderInput').prop('disabled',!1);Mautic.focusUpdatePreview()});mQuery('#websiteCanvas').html('').append(iframe);iframe.attr('src',url)}
Mautic.focusLoadConversionRateTable=function(){var $conversionRateTable=mQuery('[data-conversion-rate-table]');var $conversionRateCells=mQuery('[data-conversion-rate-cell]',$conversionRateTable);var $conversionRateTotalCell=mQuery('[data-conversion-rate-total-cell]',$conversionRateTable);var $focusTotalViewsCell=mQuery('[data-focus-total-views-cell]');var $focusTotalUniqueViewsCell=mQuery('[data-focus-total-unique-views-cell]');var focusId=$conversionRateTable.data('entity-id');var views=null;var uniqueViews=null;var clickThrough=null;var updateTotalClickThroughRate=function(){if(uniqueViews===null||clickThrough===null)return;var totalConversionRate=uniqueViews>0?Math.round(clickThrough/uniqueViews*10000)/100:0;$conversionRateTotalCell.children('.spinner').remove();$conversionRateTotalCell.prepend(totalConversionRate+'%')};Mautic.ajaxActionRequest('plugin:focus:getViewsCount',{focusId:focusId},function(response){views=response.views;uniqueViews=response.uniqueViews;$conversionRateCells.each(function(i,el){var $cell=mQuery(el);var uniqueClicks=$cell.data('unique-hits');var conversionRate=views>0?Math.round(uniqueClicks/uniqueViews*10000)/100:0;$cell.html(conversionRate+'%')})
$focusTotalViewsCell.html(views);$focusTotalUniqueViewsCell.html(uniqueViews);updateTotalClickThroughRate()},!1,!0,"GET");Mautic.ajaxActionRequest('plugin:focus:getClickThroughCount',{focusId:focusId},function(response){clickThrough=response.clickThrough;updateTotalClickThroughRate()},!1,!0,"GET")}
Mautic.focusLoadViewCountTable=function(){var $viewTable=mQuery('[data-view-table]');var $focusTotalViewsCell=mQuery('[data-focus-total-views-cell]');var $focusTotalUniqueViewsCell=mQuery('[data-focus-total-unique-views-cell]');var focusId=$viewTable.data('entity-id');var views=null;var uniqueViews=null;Mautic.ajaxActionRequest('plugin:focus:getViewsCount',{focusId:focusId},function(response){views=response.views;uniqueViews=response.uniqueViews;$focusTotalViewsCell.html(views);$focusTotalUniqueViewsCell.html(uniqueViews)},!1,!0,"GET")}