public_html/layouts/resources/Fields.min.js
'use strict';
/* {[The file is published on the basis of YetiForce Public License 6.5 that can be found in the following directory: licenses/LicenseEN.txt or yetiforce.com]} */"use strict";var _class;function _createForOfIteratorHelper(o,allowArrayLike){var it="undefined"!=typeof Symbol&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&"number"==typeof o.length){it&&(o=it);var i=0,F=function(){};return {s:F,n:function n(){return i>=o.length?{done:!0}:{done:!1,value:o[i++]}},e:function e(_e2){throw _e2},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var err,normalCompletion=!0,didErr=!1;return {s:function s(){it=it.call(o);},n:function n(){var step=it.next();return normalCompletion=step.done,step},e:function e(_e3){didErr=!0,err=_e3;},f:function f(){try{normalCompletion||null==it.return||it.return();}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(o){if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);return "Object"===n&&o.constructor&&(n=o.constructor.name),"Map"===n||"Set"===n?Array.from(o):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?_arrayLikeToArray(o,minLen):void 0}}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function _typeof(o){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&"function"==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},_typeof(o)}function ownKeys(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);r&&(o=o.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,o);}return t}function _objectSpread(e){for(var t,r=1;r<arguments.length;r++)t=null==arguments[r]?{}:arguments[r],r%2?ownKeys(Object(t),!0).forEach(function(r){_defineProperty(e,r,t[r]);}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):ownKeys(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r));});return e}function _defineProperty(obj,key,value){return key=_toPropertyKey(key),key in obj?Object.defineProperty(obj,key,{value:value,enumerable:!0,configurable:!0,writable:!0}):obj[key]=value,obj}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var descriptor,i=0;i<props.length;i++)descriptor=props[i],descriptor.enumerable=descriptor.enumerable||!1,descriptor.configurable=!0,"value"in descriptor&&(descriptor.writable=!0),Object.defineProperty(target,_toPropertyKey(descriptor.key),descriptor);}function _createClass(Constructor,protoProps,staticProps){return protoProps&&_defineProperties(Constructor.prototype,protoProps),staticProps&&_defineProperties(Constructor,staticProps),Object.defineProperty(Constructor,"prototype",{writable:!1}),Constructor}function _toPropertyKey(arg){var key=_toPrimitive(arg,"string");return "symbol"===_typeof(key)?key:String(key)}function _toPrimitive(input,hint){if("object"!==_typeof(input)||null===input)return input;var prim=input[Symbol.toPrimitive];if(prim!==void 0){var res=prim.call(input,hint||"default");if("object"!==_typeof(res))return res;throw new TypeError("@@toPrimitive must return a primitive value.")}return ("string"===hint?String:Number)(input)}window.App.Fields={Date:{months:["JS_JAN","JS_FEB","JS_MAR","JS_APR","JS_MAY_SHORT","JS_JUN","JS_JUL","JS_AUG","JS_SEP","JS_OCT","JS_NOV","JS_DEC"],monthsTranslated:["JS_JAN","JS_FEB","JS_MAR","JS_APR","JS_MAY_SHORT","JS_JUN","JS_JUL","JS_AUG","JS_SEP","JS_OCT","JS_NOV","JS_DEC"].map(function(monthName){return app.vtranslate(monthName)}),fullMonths:["JS_JANUARY","JS_FEBRUARY","JS_MARCH","JS_APRIL","JS_MAY","JS_JUNE","JS_JULY","JS_AUGUST","JS_SEPTEMBER","JS_OCTOBER","JS_NOVEMBER","JS_DECEMBER"],fullMonthsTranslated:["JS_JANUARY","JS_FEBRUARY","JS_MARCH","JS_APRIL","JS_MAY","JS_JUNE","JS_JULY","JS_AUGUST","JS_SEPTEMBER","JS_OCTOBER","JS_NOVEMBER","JS_DECEMBER"].map(function(monthName){return app.vtranslate(monthName)}),days:["JS_SUN","JS_MON","JS_TUE","JS_WED","JS_THU","JS_FRI","JS_SAT"],daysTranslated:["JS_SUN","JS_MON","JS_TUE","JS_WED","JS_THU","JS_FRI","JS_SAT"].map(function(monthName){return app.vtranslate(monthName)}),fullDays:["JS_SUNDAY","JS_MONDAY","JS_TUESDAY","JS_WEDNESDAY","JS_THURSDAY","JS_FRIDAY","JS_SATURDAY"],fullDaysTranslated:["JS_SUNDAY","JS_MONDAY","JS_TUESDAY","JS_WEDNESDAY","JS_THURSDAY","JS_FRIDAY","JS_SATURDAY"].map(function(monthName){return app.vtranslate(monthName)}),/**
* Register DatePicker
* @param {$} parentElement
* @param {boolean} registerForAddon
* @param {object} customParams
*/register:function register(parentElement,registerForAddon,customParams){var className=3<arguments.length&&void 0!==arguments[3]?arguments[3]:"dateField";parentElement="undefined"==typeof parentElement?$("body"):$(parentElement),"undefined"==typeof registerForAddon&&(registerForAddon=!0);var elements=$("."+className,parentElement);if(parentElement.hasClass(className)&&(elements=parentElement),0!==elements.length){if(!0===registerForAddon){var parentDateElem=elements.closest(".date");$(".js-date__btn",parentDateElem).on("click",function(e){$(e.currentTarget).closest(".date").find("input."+className).get(0).focus();});}var format=CONFIG.dateFormat,elementDateFormat=elements.data("dateFormat");"undefined"!=typeof elementDateFormat&&(format=elementDateFormat),"undefined"==typeof $.fn.datepicker.dates[CONFIG.langKey]&&($.fn.datepicker.dates[CONFIG.langKey]={days:App.Fields.Date.fullDaysTranslated,daysShort:App.Fields.Date.daysTranslated,daysMin:App.Fields.Date.daysTranslated,months:App.Fields.Date.fullMonthsTranslated,monthsShort:App.Fields.Date.monthsTranslated,today:app.vtranslate("JS_TODAY"),clear:app.vtranslate("JS_CLEAR"),format:format,titleFormat:"MM yyyy"/* Leverages same syntax as 'format' */,weekStart:CONFIG.firstDayOfWeekNo});var params={todayBtn:"linked",clearBtn:!0,language:CONFIG.langKey,weekStart:CONFIG.firstDayOfWeekNo,autoclose:!0,todayHighlight:!0,format:format};return "undefined"!=typeof customParams&&(params=$.extend(params,customParams)),elements.each(function(_index,element){$(element).datepicker($.extend(!0,Object.assign(params,{enableOnReadonly:!element.hasAttribute("readonly")}),$(element).data("params")));}),App.Fields.Utils.hideMobileKeyboard(elements),elements}},/**
* Register dateRangePicker
* @param {jQuery} parentElement
* @param {object} customParams
*/registerRange:function registerRange(parentElement){var customParams=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};parentElement="undefined"==typeof parentElement?$("body"):$(parentElement);var elements=$(".dateRangeField",parentElement);if(parentElement.hasClass("dateRangeField")&&(elements=parentElement),0!==elements.length){var format=CONFIG.dateFormat.toUpperCase(),elementDateFormat=elements.data("dateFormat");"undefined"!=typeof elementDateFormat&&(format=elementDateFormat.toUpperCase());var ranges={};ranges[app.vtranslate("JS_TODAY")]=[moment(),moment()],ranges[app.vtranslate("JS_TOMORROW")]=[moment().add(1,"days"),moment().add(1,"days")],ranges[app.vtranslate("JS_YESTERDAY")]=[moment().subtract(1,"days"),moment().subtract(1,"days")],ranges[app.vtranslate("JS_LAST_7_DAYS")]=[moment().subtract(6,"days"),moment()],ranges[app.vtranslate("JS_NEXT_7_DAYS")]=[moment(),moment().add(6,"days")],ranges[app.vtranslate("JS_CURRENT_MONTH")]=[moment().startOf("month"),moment().endOf("month")],ranges[app.vtranslate("JS_NEXT_MONTH")]=[moment().add(1,"month").startOf("month"),moment().add(1,"month").endOf("month")],ranges[app.vtranslate("JS_LAST_MONTH")]=[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],ranges[app.vtranslate("JS_NEXT_MONTH")]=[moment().add(1,"month").startOf("month"),moment().add(1,"month").endOf("month")],ranges[app.vtranslate("JS_LAST_3_MONTHS")]=[moment().subtract(3,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],ranges[app.vtranslate("JS_NEXT_3_MONTHS")]=[moment().startOf("month"),moment().add(3,"month").endOf("month")],ranges[app.vtranslate("JS_LAST_6_MONTHS")]=[moment().subtract(6,"month").startOf("month"),moment().subtract(1,"month").endOf("month")],ranges[app.vtranslate("JS_NEXT_6_MONTHS")]=[moment().startOf("month"),moment().add(6,"month").endOf("month")];var locale=App.Fields.DateTime.getDefaultLocale();locale.format=format;var params={language:CONFIG.langKey,autoUpdateInput:!1,autoApply:!0,ranges:ranges,locale:locale};"undefined"!=typeof customParams&&(params=$.extend(params,customParams)),parentElement.find(".js-date__btn").off().on("click",function(e){$(e.currentTarget).parent().next(".dateRangeField")[0].focus();}),elements.each(function(_index,element){var el=$(element),currentParams=$.extend(!0,params,el.data("params"));el.daterangepicker(currentParams).on("apply.daterangepicker",function(_ev,picker){$(this).val(picker.startDate.format(currentParams.locale.format)+","+picker.endDate.format(currentParams.locale.format)),$(this).trigger("change");}).on("show.daterangepicker",function(ev,picker){App.Fields.Utils.positionPicker(ev,picker);}).on("showCalendar.daterangepicker",function(ev,picker){App.Fields.Utils.positionPicker(ev,picker),picker.container.addClass("js-visible");}).on("hide.daterangepicker",function(_ev,picker){picker.container.removeClass("js-visible");}),App.Fields.Utils.registerMobileDateRangePicker(el);});}},/**
* Function to get Date Instance
* @param {string} dateTime
* @param {string} dateFormat user date format
* @returns {Date}
*/getDateInstance:function getDateInstance(dateTime){var dateFormat=1<arguments.length&&void 0!==arguments[1]?arguments[1]:CONFIG.dateFormat,dateTimeComponents=dateTime.split(" "),dateComponent=dateTimeComponents[0],timeComponent=dateTimeComponents[1],seconds="00",dotMode="-";-1===dateFormat.indexOf(".")?-1!==dateFormat.indexOf("/")&&(dotMode="/"):dotMode=".";var splittedDate=dateComponent.split(dotMode),splittedDateFormat=dateFormat.split(dotMode),year=splittedDate[splittedDateFormat.indexOf("yyyy")],month=splittedDate[splittedDateFormat.indexOf("mm")],day=splittedDate[splittedDateFormat.indexOf("dd")],dateInstance=Date.parse(year+"/"+month+"/"+day);if(isNaN(dateInstance)||4!==year.length||2<month.length||2<day.length||null==dateInstance)throw app.vtranslate("JS_INVALID_DATE");//Before creating date object time is set to 00
//because as while calculating date object it depends system timezone
"undefined"==typeof timeComponent&&(timeComponent="00:00:00");var timeSections=timeComponent.split(":");return "undefined"!=typeof timeSections[2]&&(seconds=timeSections[2]),"undefined"!=typeof dateTimeComponents[2]&&("pm"===dateTimeComponents[2].toLowerCase()&&"12"!==timeSections[0]&&(timeSections[0]=parseInt(timeSections[0],10)+12),"am"===dateTimeComponents[2].toLowerCase()&&"12"===timeSections[0]&&(timeSections[0]="00")),--month,new Date(year,month,day,timeSections[0],timeSections[1],seconds)},/**
* Format the Date object to a date in the format DB format, example: `2018-07-23`
* @param {Date} date
* @returns {string}
*/dateToDbFormat:function dateToDbFormat(date){var d=date.getDate(),m=date.getMonth()+1,y=date.getFullYear();return d=9>=d?"0"+d:d,m=9>=m?"0"+m:m,y+"-"+m+"-"+d},/**
* Format the Date object to a date in the format user format, example: `2018/07/23`
* @param {Date} date
* @returns {string}
*/dateToUserFormat:function dateToUserFormat(date){var format=1<arguments.length&&void 0!==arguments[1]?arguments[1]:CONFIG.dateFormat;"string"==typeof date&&(date=new Date(date));var m=date.getMonth()+1,d=date.getDate();return d=9>=d?"0"+d:d,m=9>=m?"0"+m:m,format.replace("yyyy",date.getFullYear()).replace("mm",m).replace("dd",d)},/**
* Get last day of month
* @param {integer} year
* @param {integer} month
* @returns {integer}
*/getLastMonthDay:function getLastMonthDay(year,month){var date=new Date(year,month,0);return date.getDate()},/**
* Get number of days from a given date to now
* @param {Date} dateTime
* @returns {integer}
*/howManyDaysFromDate:function howManyDaysFromDate(dateTime){var today=new Date,toTime=new Date(today.getFullYear(),today.getMonth(),today.getDate()).getTime();return Math.floor((toTime-dateTime.getTime())/86400000)+1},/**
* Converting the date format to the format supported in the DatePicker, example: `yyyy-mm-dd` >> `Y-m-d`
* @param {string} dateFormat
* @returns {string}
*/convertToDatePickerFormat:function convertToDatePickerFormat(dateFormat){return "yyyy-mm-dd"===dateFormat?"Y-m-d":"mm-dd-yyyy"===dateFormat?"m-d-Y":"dd-mm-yyyy"===dateFormat?"d-m-Y":"yyyy.mm.dd"===dateFormat?"Y.m.d":"mm.dd.yyyy"===dateFormat?"m.d.Y":"dd.mm.yyyy"===dateFormat?"d.m.Y":"yyyy/mm/dd"===dateFormat?"Y/m/d":"mm/dd/yyyy"===dateFormat?"m/d/Y":"dd/mm/yyyy"===dateFormat?"d/m/Y":void 0}},DateTime:/*#__PURE__*/function(){function DateTime(container,params){_classCallCheck(this,DateTime),this.container=container,this.init(params);}/**
* Register function
* @param {jQuery} container
* @param {Object} params
*/return _createClass(DateTime,[{key:"init",value:/**
* Initialization datetime
*/function init(customParams){$(".input-group-text",this.container.closest(".dateTime")).on("click",function(e){$(e.currentTarget).closest(".dateTime").find("input.dateTimePickerField").get(0).focus();});var dateFormat=CONFIG.dateFormat.toUpperCase(),elementDateFormat=this.container.data("dateFormat");"undefined"!=typeof elementDateFormat&&(dateFormat=elementDateFormat.toUpperCase());var hourFormat=CONFIG.hourFormat,elementHourFormat=this.container.data("hourFormat");"undefined"!=typeof elementHourFormat&&(hourFormat=elementHourFormat);var timePicker24Hour=!0,timeFormat="HH:mm";"24"!=hourFormat&&(timePicker24Hour=!1,timeFormat="hh:mm A");var format=dateFormat+" "+timeFormat,isDateRangePicker="range"!==this.container.data("calendarType"),locale=App.Fields.DateTime.getDefaultLocale();locale.format=format;var params={language:CONFIG.langKey,parentEl:this.container.closest(".dateTime"),singleDatePicker:isDateRangePicker,showDropdowns:!0,timePicker:!0,autoUpdateInput:!1,timePicker24Hour:timePicker24Hour,timePickerIncrement:1,autoApply:!0,opens:"left",locale:locale};"undefined"!=typeof customParams&&(params=$.extend(params,customParams)),this.container.daterangepicker(params).on("apply.daterangepicker",function(_ev,picker){isDateRangePicker?$(this).val(picker.startDate.format(format)):$(this).val(picker.startDate.format(format)+","+picker.endDate.format(format));}).on("showCalendar.daterangepicker",function(ev,picker){App.Fields.Utils.positionPicker(ev,picker),picker.container.addClass("js-visible");}),App.Fields.Utils.registerMobileDateRangePicker(this.container);}}],[{key:"register",value:function register(container,params){if("undefined"==typeof container&&(container=$("body")),container.hasClass("dateTimePickerField")&&!container.prop("disabled"))return new DateTime(container,params);var instances=[];return container.find(".dateTimePickerField:not([disabled])").each(function(_,e){var element=$(e);instances.push(new DateTime(element,params));}),instances}/**
* Format the Date object to a date in the format user format, example: `2018/07/23 03:00`
* @param {Date} dateTime Date object
* @returns {string} `2018/07/23 03:00`
*/},{key:"dateToUserFormat",value:function dateToUserFormat(dateTime){var format=1<arguments.length&&void 0!==arguments[1]?arguments[1]:CONFIG.dateFormat;return format=format.toUpperCase(),format+=24==CONFIG.hourFormat?" HH:mm":" hh:mm A",moment(dateTime).format(format)}/**
* Gets default locale data
* @returns {Object}
*/},{key:"getDefaultLocale",value:function getDefaultLocale(){return this.locale||(this.locale={separator:",",applyLabel:app.vtranslate("JS_APPLY"),cancelLabel:app.vtranslate("JS_CANCEL"),fromLabel:app.vtranslate("JS_FROM"),toLabel:app.vtranslate("JS_TO"),customRangeLabel:app.vtranslate("JS_CUSTOM"),weekLabel:app.vtranslate("JS_WEEK").substr(0,1),firstDay:CONFIG.firstDayOfWeekNo,daysOfWeek:App.Fields.Date.daysTranslated,monthNames:App.Fields.Date.fullMonthsTranslated}),_objectSpread({},this.locale)}}]),DateTime}(),Time:{/**
* Format the Date object to a date in the format user format, example: `2018/07/23`
* @param {Date} date
* @returns {string}
*/dateToUserFormat:function dateToUserFormat(date,timeFormat){return "string"==typeof date&&(date=new Date(date)),timeFormat||(24==CONFIG.hourFormat?timeFormat="HH:mm":timeFormat="hh:mm A"),moment(date).format(timeFormat)}},Colors:{/**
* Function to check whether the color is dark or light
*/getColorContrast:function getColorContrast(hexcolor){var r=parseInt(hexcolor.substr(0,2),16),g=parseInt(hexcolor.substr(2,2),16),b=parseInt(hexcolor.substr(4,2),16);return 128<=(299*r+587*g+114*b)/1e3?"light":"dark"},getRandomColor:function getRandomColor(){for(var letters=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"],color="#",i=0;6>i;i++)color+=letters[Math.floor(16*Math.random())];return color},getRandomColors:function getRandomColors(count){for(var colors=[],i=0;i<count;i++)colors.push(this.getRandomColor());return colors},showPicker:function showPicker(_ref){var color=_ref.color,fieldToUpdate=_ref.fieldToUpdate,bgToUpdate=_ref.bgToUpdate,cb=_ref.cb,url="index.php?module=AppComponents&view=ColorPickerModal".concat(color?"&color="+color:"");app.showModalWindow({url:url,cb:function registerPickerEvents(modalContainer){var picker=window.ColorPicker.mount({el:modalContainer.find(".js-color-picker")[0],currentColor:color});modalContainer.find(".js-modal__save").on("click",function(){var newColor=picker.getColor().hex;cb&&cb(newColor),bgToUpdate&&bgToUpdate.css("background",newColor),fieldToUpdate&&fieldToUpdate.val(newColor),app.hideModalWindow(!1,modalContainer.closest(".js-modal-container")[0].id);});}.bind(this)});}},Text:{/**
* Register clip
* @param {HTMLElement|jQuery} container
* @param {string} key
* @returns {ClipboardJS|undefined}
*/registerCopyClipboard:function registerCopyClipboard(container){var key=1<arguments.length&&void 0!==arguments[1]?arguments[1]:".clipboard";if("object"===_typeof(container)&&0!==$(container).length){container=$(container).get(0);var elements=container.querySelectorAll(key);return 0===elements.length&&(elements=key,container=""),new ClipboardJS(elements,{container:container,text:function text(trigger){app.showNotify({text:app.vtranslate("JS_NOTIFY_COPY_TEXT"),type:"success"}),trigger=$(trigger);var val,element=$(trigger.data("copyTarget"),container);return val="undefined"==typeof trigger.data("copyType")?"undefined"==typeof trigger.data("copy-attribute")?element.val():trigger.data(trigger.data("copy-attribute")):element.is("select")?element.find("option:selected").data(trigger.data("copyType")):element.data(trigger.data("copyType")),val}})}},Editor:(_class=/*#__PURE__*/function(){function Editor(container,params){_classCallCheck(this,Editor),!1===window.App.Fields.Text.Editor.initialization&&(CKEDITOR.disableAutoInline=!0,CKEDITOR.plugins.addExternal("base64image",app.getMainParams("siteUrl")+"layouts/resources/libraries/ckeditor/base64image/"),window.App.Fields.Text.Editor.initialization=!0),this.container=container,this.init(container,params);}/**
* Register function
* @param {jQuery} container
* @param {Object} params
*/return _createClass(Editor,[{key:"init",value:/**
* Initiation
* @param {jQuery} element
* @param {Object} params
*/function init(element,params){var config={};if(element.hasClass("js-editor--basic")&&(config.toolbar="Min"),element.data("height")&&(config.height=element.data("height")),params=$.extend(config,params),this.isModal=element.closest(".js-modal-container").length,this.isModal&&element.is(":visible")){var self=this;this.progressInstance=$.progressIndicator({blockInfo:{enabled:!0,onBlock:function onBlock(){self.loadEditor(element,params);}}});}else App.Fields.Text.destroyEditor(element),this.loadEditor(element,params);}/*
*Function to set the textArea element
*/},{key:"setElement",value:function setElement(element){return this.element=$(element),this}/*
*Function to get the textArea element
*/},{key:"getElement",value:function getElement(){return this.element}/*
* Function to return Element's id atrribute value
*/},{key:"getElementId",value:function getElementId(){return this.getElement().attr("id")}/*
* Function to get the instance of ckeditor
*/},{key:"getEditorInstanceFromName",value:function getEditorInstanceFromName(){return CKEDITOR.instances[this.getElementId()]}/*
* Function to load CkEditor
* @param {HTMLElement|jQuery} element on which CkEditor has to be loaded
* @param {Object} customConfig custom configurations for ckeditor
*/},{key:"loadEditor",value:function loadEditor(element,customConfig){var _this=this;this.setElement(element);var instance=this.getEditorInstanceFromName(),config={language:CONFIG.langKey,allowedContent:!0,disableNativeSpellChecker:!1,extraAllowedContent:"div{page-break-after*}",format_tags:"p;h1;h2;h3;h4;h5;h6;pre;address;div",removeButtons:"",enterMode:CKEDITOR.ENTER_BR,shiftEnterMode:CKEDITOR.ENTER_P,emojiEnabled:!1,mentionsEnabled:!1,clipboard_handleImages:!1,on:{instanceReady:function instanceReady(evt){evt.editor.on("blur",function(){evt.editor.updateElement();}),_this.isModal&&_this.progressInstance&&_this.progressInstance.progressIndicator({mode:"hide"});},beforeCommandExec:function beforeCommandExec(e){if("source"===e.editor.mode)return _this.validate(element,e)}},removePlugins:"scayt",extraPlugins:"colorbutton,pagebreak,colordialog,find,selectall,showblocks,div,print,font,justify,bidi,base64image",toolbar:"Full",toolbar_Full:[{name:"clipboard",items:["Cut","Copy","Paste","PasteText","PasteFromWord","-","Undo","Redo"]},{name:"editing",items:["Find","Replace","-","SelectAll"]},{name:"links",items:["Link","Unlink"]},{name:"insert",items:["base64image","Table","HorizontalRule","SpecialChar","PageBreak"]},{name:"tools",items:["Maximize","ShowBlocks"]},{name:"paragraph",items:["Outdent","Indent","-","Blockquote","CreateDiv"]},{name:"document",items:["Source","Print"]},"/",{name:"styles",items:["Styles","Format","Font","FontSize"]},{name:"basicstyles",items:["Bold","Italic","Underline","Strike","Subscript","Superscript"]},{name:"colors",items:["TextColor","BGColor"]},{name:"paragraph",items:["NumberedList","BulletedList","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl"]},{name:"basicstyles",items:["CopyFormatting","RemoveFormat"]}],toolbar_Min:[{name:"basicstyles",items:["Bold","Italic","Underline","Strike"]},{name:"colors",items:["TextColor","BGColor"]},{name:"tools",items:["Maximize"]},{name:"paragraph",items:["NumberedList","BulletedList","-","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock","-","BidiLtr","BidiRtl"]},{name:"basicstyles",items:["CopyFormatting","RemoveFormat","Source"]}],toolbar_Micro:[{name:"basicstyles",items:["Bold","Italic","Underline","Strike"]},{name:"colors",items:["TextColor","BGColor"]},{name:"paragraph",items:["NumberedList","BulletedList","JustifyLeft","JustifyCenter","JustifyRight","JustifyBlock"]},{name:"basicstyles",items:["CopyFormatting","RemoveFormat"]}],toolbar_Clipboard:[{name:"document",items:["Print"]},{name:"basicstyles",items:["CopyFormatting","RemoveFormat"]},{name:"clipboard",items:["Cut","Copy","Paste","PasteText","PasteFromWord","-","Undo","Redo"]}],toolbar_PDF:[{name:"clipboard",items:["Cut","Copy","Paste","PasteText","PasteFromWord","-","Undo","Redo"]},{name:"editing",items:["Find","Replace","-","SelectAll","-"]},{name:"links",items:["Link","Unlink"]},{name:"insert",items:["base64image","Table","HorizontalRule","PageBreak"]},{name:"tools",items:["Maximize","ShowBlocks"]},{name:"document",items:["Source"]},"/",{name:"styles",items:["Styles","Format","Font","FontSize"]},{name:"basicstyles",items:["Bold","Italic","Underline","Strike"]},{name:"colors",items:["TextColor","BGColor"]},{name:"paragraph",items:["JustifyLeft","JustifyCenter","JustifyRight"]},{name:"basicstyles",items:["CopyFormatting","RemoveFormat"]}]};if("undefined"!=typeof customConfig&&(config=$.extend(config,customConfig)),config=Object.assign(config,element.data()),config.emojiEnabled){var emojiToolbar={name:"links",items:["EmojiPanel"]};"string"==typeof config.toolbar?config["toolbar_".concat(config.toolbar)].push(emojiToolbar):Array.isArray(config.toolbar)&&config.toolbar.push(emojiToolbar),config.extraPlugins+=",emoji",config.outputTemplate="{id}";}config.mentionsEnabled&&(config.extraPlugins+=",mentions",config.mentions=this.registerMentions()),instance&&CKEDITOR.remove(instance),element.ckeditor(config);}/**
* Register mentions
* @returns {Array}
*/},{key:"registerMentions",value:function registerMentions(){var minSerchTextLength=app.getMainParams("gsMinLength");return [{feed:this.getMentionUsersData.bind(this),itemTemplate:"<li data-id=\"{id}\" class=\"row no-gutters\">\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"col-2 c-img__completion__container\">\n\t\t\t\t\t\t\t\t\t\t\t\t<div class=\"{icon} m-auto u-w-fit u-fs-14px\"></div>\n\t\t\t\t\t\t\t\t\t\t\t\t<img src=\"{image}\" class=\"c-img__completion mr-2\" alt=\"{label}\" title=\"{label}\">\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"col row-10 no-gutters u-overflow-x-hidden\">\n\t\t\t\t\t\t\t\t\t\t\t\t<strong class=\"u-text-ellipsis--no-hover col-12\">{label}</strong>\n\t\t\t\t\t\t\t\t\t\t\t\t<div class=\"fullname col-12 u-text-ellipsis--no-hover text-muted small\">{category}</div>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t</li>",outputTemplate:"<a href=\"#\" data-id=\"@{id}\" data-module=\"{module}\">{label}</a>",minChars:minSerchTextLength},{feed:App.Fields.Text.getMentionData,marker:"#",pattern:/#[wа-я]{1,}|#\w{3,}$/,itemTemplate:"<li data-id=\"{id}\" class=\"row no-gutters\">\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"col-2 c-circle-icon\">\n\t\t\t\t\t\t\t\t\t\t\t\t<span class=\"yfm-{module}\"></span>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t\t<div class=\"col-10 row no-gutters pl-1 u-overflow-x-hidden\">\n\t\t\t\t\t\t\t\t\t\t\t\t<strong class=\"u-text-ellipsis--no-hover col-12\">{label}</strong>\n\t\t\t\t\t\t\t\t\t\t\t\t<div class=\"fullname col-12 u-text-ellipsis--no-hover text-muted small\">{category}</div>\n\t\t\t\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t\t\t</li>",outputTemplate:"<a href=\"#\" data-id=\"#{id}\" data-module=\"{module}\">{label}</a>",minChars:minSerchTextLength}]}/**
* Get mention Users data (invoked by ck editor mentions plugin)
* @param {object} opts
* @param {function} callback
*/},{key:"getMentionUsersData",value:function getMentionUsersData(opts,callback){App.Fields.Text.getMentionData(opts,callback,"owners");}/**
* Function to validate the field value
* @param {jQuery} element
* @param {object} e
*/},{key:"validate",value:function validate(element){var params,status=!0,form=element.closest("form");return params=element.data("purifyMode")||!form.find("[name=\"module\"]").length||"Settings"===form.find("[name=\"parent\"]").val()?{module:"Users",action:"Fields",mode:"validateByMode",purifyMode:element.data("purifyMode")||"Html",value:element.val()}:{module:element.closest("form").find("[name=\"module\"]").val(),action:"Fields",mode:"validateForField",fieldName:element.attr("name"),fieldValue:element.val()},AppConnector.request({async:!1,data:params}).done(function(data){element.val(data.result.raw);}).fail(function(){app.showNotify({type:"error",text:app.vtranslate("JS_UNEXPECTED_ERROR")}),status=!1;}),status}}],[{key:"register",value:function register(container,params){if("undefined"==typeof container&&(container=$("body")),container.hasClass("js-editor")&&!container.prop("disabled"))return new App.Fields.Text.Editor(container,$.extend(params,container.data()));var instances=[];return container.find(".js-editor:not([disabled])").each(function(_,e){var element=$(e);instances.push(new App.Fields.Text.Editor(element,$.extend(params,element.data())));}),instances}}]),Editor}(),_defineProperty(_class,"initialization",!1),_class),/**
* Completions class for contenteditable html element for records, users and emojis. Params can be passed in data-completions- of contenteditable element or as argument. Default params:
* {
completionsCollection: {
records: true,
users: true,
emojis: true
}
}
*/Completions:/*#__PURE__*/function(){/**
* Constructor
* @param {jQuery} inputDiv - contenteditable div
* @param params
*/function Completions(){var inputDiv=0<arguments.length&&void 0!==arguments[0]?arguments[0]:$(".js-completions").eq(0),params=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,Completions),"undefined"!=typeof inputDiv&&0!==inputDiv.length){void 0===inputDiv.length&&(inputDiv=$(inputDiv));this.params=Object.assign({completionsCollection:{records:!0,users:!0,emojis:!0},autolink:!0},inputDiv.data(),params),this.inputDiv=inputDiv,this.collection=[],this.params.completionsCollection.records&&this.collection.push(this.registerMentionCollection("#")),this.params.completionsCollection.users&&this.collection.push(this.registerMentionCollection("@","owners")),this.params.completionsCollection.emojis&&this.collection.push(this.registerEmojiCollection()),this.register(inputDiv);}}/**
* Register mention collection for tribute.js
* @param {string} symbol
* @param {string} searchModule
* @returns {{trigger: *, selectTemplate: selectTemplate, values: values, menuItemTemplate: (function(*): string), lookup: string, fillAttr: string}}
*/return _createClass(Completions,[{key:"registerMentionCollection",value:function registerMentionCollection(symbol){var searchModule=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"-",self=this;return {trigger:symbol,selectTemplate:function selectTemplate(item){return this.range.isContentEditable(this.current.element)?"<a href=\"#\" data-id=\"".concat(symbol+item.original.id,"\" data-module=\"").concat(item.original.module,"\">").concat(item.original.label.split("(")[0].trim(),"</a>"):symbol+item.original.label},values:function values(text,cb){text.length>=CONFIG.globalSearchAutocompleteMinLength&&App.Fields.Text.getMentionData(text,function(users){return cb(users)},searchModule);},menuItemTemplate:function menuItemTemplate(item){return self.mentionTemplate({id:item.original.id,module:item.original.module,category:item.original.category,image:item.original.image,label:item.original.label,icon:item.original.icon})},lookup:"label",fillAttr:"label"}}/**
* Register emoji collection for tribute.js
* @returns {{trigger: string, selectTemplate: selectTemplate, menuItemTemplate: (function(*): string), lookup: string, fillAttr: string, values: Array}}
*/},{key:"registerEmojiCollection",value:function registerEmojiCollection(){return {trigger:":",selectTemplate:function selectTemplate(item){return this.range.isContentEditable(this.current.element)?"<span data-id=\"".concat(item.original.id,"\">").concat(item.original.symbol,"</span>"):item.original.symbol},menuItemTemplate:function menuItemTemplate(item){return "<span data-id=\"".concat(item.original.id,"\">").concat(item.original.symbol," ").concat(item.original.id,"</span>")},lookup:"id",fillAttr:"keywords",values:function values(text,cb){2<=text.length&&cb(App.emoji);}}}/*
* Mention template
*/},{key:"mentionTemplate",value:function mentionTemplate(params){var icon="";void 0!==params.module&&(icon="yfm-".concat(params.module)),void 0!==params.icon&&""!==params.icon&&(icon=params.icon);var avatar="<div class=\"col-2 c-circle-icon\">\n\t\t\t\t\t\t\t\t<span class=\"".concat(icon,"\"></span>\n\t\t\t\t\t\t\t</div>");return void 0!==params.image&&""!==params.image&&(avatar="<div class=\"col-2 c-img__completion__container m-0\"><img src=\"".concat(params.image,"\" class=\"c-img__completion\" alt=").concat(params.label,"\" title=\"").concat(params.label,"\"></div>")),"<div data-id=\"".concat(params.id,"\" class=\"row no-gutters\">\n\t\t\t\t\t\t\t").concat(avatar,"\n\t\t\t\t\t\t\t<div class=\"col-10 row no-gutters pl-1 u-overflow-x-hidden\">\n\t\t\t\t\t\t\t\t<strong class=\"u-text-ellipsis--no-hover col-12\">").concat(params.label,"</strong>\n\t\t\t\t\t\t\t\t<div class=\"fullname col-12 u-text-ellipsis--no-hover text-muted small\">").concat(params.category,"</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>")}/**
* Auto link
*/},{key:"autoLink",value:function autoLink(){for(var offset,charCode,fillChar="\u200B",sel=window.getSelection(),range=sel.getRangeAt(0).cloneRange(),getParentByTagName=function(node,tags){if(node&&!isBody(node))for(;node;){if(tags[node.tagName]||isBody(node))return !tags[node.tagName]&&isBody(node)?null:node;node=node.parentNode;}return null},isBody=function(node){return node&&1==node.nodeType&&"body"==node.tagName.toLowerCase()},html=function(str){return str.replace(/&((g|l|quo)t|amp|#39);/g,function(m){return {"<":"<","&":"&",""":"\"",">":">","'":"'"}[m]})},isFillChar=function(node){return 3==node.nodeType&&!node.nodeValue.replace(//,"").length},start=range.startContainer;1==start.nodeType&&0<range.startOffset&&(start=range.startContainer.childNodes[range.startOffset-1],!!start);)range.setStart(start,1==start.nodeType?start.childNodes.length:start.nodeValue.length),range.collapse(!0),start=range.startContainer;do{if(0==range.startOffset){for(start=range.startContainer.previousSibling;start&&1==start.nodeType;)start=start.lastChild;if(!start||isFillChar(start))break;offset=start.nodeValue.length;}else start=range.startContainer,offset=range.startOffset;range.setStart(start,offset-1),charCode=range.toString().charCodeAt(0);}while(160!=charCode&&32!=charCode);if(range.toString().replace(new RegExp(fillChar,"g"),"").match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)){for(;range.toString().length&&!/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString());)try{range.setStart(range.startContainer,range.startOffset+1);}catch(e){for(var startCont=range.startContainer,next=void 0;!(next=startCont.nextSibling);){if(isBody(startCont))return;startCont=startCont.parentNode;}range.setStart(next,0);}if(getParentByTagName(range.startContainer,{a:1,A:1}))return;var href=range.toString().replace(/<[^>]+>/g,"").replace(new RegExp(fillChar,"g"),""),hrefFull=/^(?:https?:\/\/)/gi.test(href)?href:"http://"+href,url=new URL(hrefFull),allowedHosts=CONFIG.purifierAllowedDomains;if(!1!==allowedHosts&&-1===allowedHosts.indexOf(url.host))return;var a=document.createElement("a"),text=document.createTextNode(" ");a.appendChild(range.extractContents()),a.innerHTML=href,a.href=hrefFull?html(hrefFull):"",a.setAttribute("rel","noopener noreferrer"),a.setAttribute("target","_blank"),range.insertNode(a),a.parentNode.insertBefore(text,a.nextSibling),range.setStart(text.nextSibling,0),range.collapse(!0),sel.removeAllRanges(),sel.addRange(range);}}/**
* Register
* @param {jQuery} inputDiv - contenteditable div
*/},{key:"register",value:function register(inputDiv){var self=this;this.completionsCollection=new Tribute({collection:self.collection,allowSpaces:!0}),this.completionsCollection.attach(inputDiv[0]),void 0!==this.params.completionsTextarea&&this.registerCompletionsTextArea(inputDiv),void 0!==this.params.completionsButtons&&this.registerCompletionsButtons(),this.params.autolink&&this.registerAutoLinker(inputDiv),void 0===App.emoji&&fetch("".concat(CONFIG.siteUrl,"/vendor/ckeditor/ckeditor/plugins/emoji/emoji.json")).then(function(response){return response.json()}).then(function(response){App.emoji=response;}).catch(function(error){return console.error("Error:",error)}),this.registerTagClick(inputDiv);}/**
* Register autolink
* @param {jQuery} inputDiv - contenteditable div
*/},{key:"registerAutoLinker",value:function registerAutoLinker(inputDiv){var _this2=this;inputDiv.on("keypress",function(e){(32===e.keyCode||13===e.keyCode)&&_this2.autoLink();});}/**
* Register completons hidden textarea - useful with forms
* @param {jQuery} inputDiv - contenteditable div
*/},{key:"registerCompletionsTextArea",value:function registerCompletionsTextArea(inputDiv){var textarea=inputDiv.siblings("[name=".concat(inputDiv.attr("id"),"]"));inputDiv.on("focus",function(){textarea.val(inputDiv.html());}).on("blur keyup paste input",function(){textarea.val(inputDiv.html());});}/**
* Register tag click
* @param inputDiv
*/},{key:"registerTagClick",value:function registerTagClick(inputDiv){inputDiv.closest(".js-completions__container").find(".js-completions__messages").on("click",".js-completions__tag",function(e){e.preventDefault(),inputDiv.append($(e.target).clone());});}/**
* Register completions buttons
*/},{key:"registerCompletionsButtons",value:function registerCompletionsButtons(){var _this3=this,completionsContainer=this.inputDiv.parents().eq(3);completionsContainer.find(".js-completions__users").on("click",function(){_this3.completionsCollection.showMenuForCollection(_this3.inputDiv[0],1);}),completionsContainer.find(".js-completions__records").on("click",function(){_this3.completionsCollection.showMenuForCollection(_this3.inputDiv[0],0);});}}]),Completions}(),/**
* Get mention data (invoked by ck editor mentions plugin and tribute.js)
* @param {object} opts
* @param {function} callback
* @param {string} searchModule
*/getMentionData:function getMentionData(text,callback){var searchModule=2<arguments.length&&arguments[2]!==void 0?arguments[2]:"-",basicSearch=new Vtiger_BasicSearch_Js;basicSearch.reduceNumberResults=app.getMainParams("gsAmountResponse"),basicSearch.returnHtml=!1,basicSearch.searchModule=searchModule,"object"===_typeof(text)&&(text=text.query.toLowerCase()),"owners"===searchModule?AppConnector.request({action:"Search",mode:"owners",value:text}).done(function(data){callback(data.result);}):basicSearch.search(text).done(function(data){data=JSON.parse(data);var serverDataFormat=data.result,reponseDataList=[];for(var id in serverDataFormat){var responseData=serverDataFormat[id];reponseDataList.push(responseData);}callback(reponseDataList);});},/**
* Destroy ckEditor
* @param {jQuery} element
*/destroyEditor:function destroyEditor(element){"undefined"!=typeof CKEDITOR&&CKEDITOR.instances&&element.attr("id")in CKEDITOR.instances&&CKEDITOR.instances[element.attr("id")].destroy();},/**
* Generate random character
* @returns {string}
*/generateRandomChar:function generateRandomChar(){var rand=Math.floor(Math.random()*"0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ".length);return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ".substring(rand,rand+1)},/**
* generate random hash
* @returns {string}
*/generateRandomHash:function generateRandomHash(){var prefix=0<arguments.length&&arguments[0]!==void 0?arguments[0]:"";prefix=prefix.toString();var hash=Math.random().toString(36).substr(2,10)+Math.random().toString(36).substr(2,10)+new Date().valueOf()+Math.random().toString(36).substr(2,6);return prefix?prefix+hash:hash}},Picklist:{/**
* Function which will convert ui of select boxes.
* @params parent - select element
* @params view - select2
* @params viewParams - select2 params
* @returns jquery object list which represents changed select elements
*/changeSelectElementView:function changeSelectElementView(parent,view,viewParams){var _this4=this;if("undefined"==typeof parent&&(parent=$("body")),"undefined"==typeof view){var select2Elements=$("select.select2",parent).toArray();return void select2Elements.forEach(function(elem){_this4.changeSelectElementView($(elem),"select2",viewParams);})}//If view is select2, This will convert the ui of select boxes to select2 elements.
return "select2"===view?App.Fields.Picklist.showSelect2ElementView(parent,viewParams):void app.errorLog(new Error("Unknown select type [".concat(view,"]")))},/**
* Function which will show the select2 element for select boxes . This will use select2 library
*/showSelect2ElementView:function showSelect2ElementView(selectElement,params){var _this5=this,self=this;if(selectElement=$(selectElement),"undefined"==typeof params&&(params={}),1<$(selectElement).length)return $(selectElement).each(function(_,element){_this5.showSelect2ElementView($(element).eq(0),params);});if(params=this.registerParams(selectElement,params),params.selectLazy&&!selectElement.hasClass("js-lazy-select-active"))return App.Fields.Picklist.showLazySelect(selectElement,{lazyElements:app.getMainParams("picklistLimit"),data:this.registerLazySelectOptions(selectElement),selectParams:params});var computeDropdownHeight=function(e,dropdownContainer){setTimeout(function(){if(!dropdownContainer.find(".select2-dropdown--above").length){var dropdownList=dropdownContainer.find(".select2-results > .select2-results__options"),selectOffsetTop=$(e.currentTarget).offset().top;dropdownList.css({"max-height":$(window).height()-selectOffsetTop-35-(dropdownList.offset().top-selectOffsetTop)});}},100);};return selectElement.each(function(){var select=$(this),htmlBoolParams=select.data("select");"tags"===htmlBoolParams?(params.tags=!0,params.tokenSeparators=[","]):params[htmlBoolParams]=!0,select.select2(params).on("select2:open",function(e){computeDropdownHeight(e,$(".select2-container--open:not(.select2-container--below)")),select.data("unselecting")&&(select.removeData("unselecting"),setTimeout(function(){select.each(function(){$(this).select2("close");});},1));var instance=$(e.currentTarget).data("select2");instance.$dropdown.css("z-index",1000002),instance.dropdown.$search&&instance.dropdown.$search.get(0).focus();}).on("select2:unselect",function(){select.data("unselecting",!0);}),"function"==typeof self[params.selectCb]&&self[params.selectCb](select,params);}),selectElement},/**
* Register params
* @param selectElement
* @param params
* @returns {*}
*/registerParams:function registerParams(selectElement,params){if("undefined"==typeof params.dropdownParent){var modalParent=$(selectElement).closest(".modal-body");modalParent.length&&(params.dropdownParent=modalParent);}var data=selectElement.data();null!=data&&(params=$.extend(data,params)),params.language={},params.theme="bootstrap";var width=$(selectElement).data("width");params.width="undefined"==typeof width?"100%":width,params.containerCssClass="form-control w-100";var containerCssClass=selectElement.data("containerCssClass");return "undefined"!=typeof containerCssClass&&(params.containerCssClass+=" "+containerCssClass),params.language.noResults=function(){return app.vtranslate("JS_NO_RESULTS_FOUND")},params.language.removeAllItems=function(){return app.vtranslate("JS_REMOVE_ALL_ITEMS")},"undefined"!=typeof params.customSortOptGroup&¶ms.customSortOptGroup&&($("optgroup",selectElement).each(function(){var optgroup=$(this),options=optgroup.children().toArray().sort(function(a,b){var aText=$(a).text(),bText=$(b).text();return aText<bText?1:-1});$.each(options,function(i,v){optgroup.prepend(v);});}),delete params.customSortOptGroup),"undefined"!=typeof params.maximumSelectionLength&&"undefined"==typeof params.formatSelectionTooBig&&(params.language.maximumSelected=function(limit){return app.vtranslate("JS_YOU_CAN_SELECT_ONLY")+" "+limit.maximum+" "+app.vtranslate("JS_ITEMS")}),"undefined"==typeof selectElement.attr("multiple")||params.placeholder?!params.placeholder&&(params.placeholder=app.vtranslate("JS_SELECT_AN_OPTION")):params.placeholder=app.vtranslate("JS_SELECT_SOME_OPTIONS"),"undefined"==typeof params.templateResult?params.templateResult=function(data,container){data.element&&data.element.className&&$(container).addClass(data.element.className);var resultContainer=document.createElement("span");if("undefined"==typeof data.name)resultContainer.innerText=data.text;else if("optgroup"==data.type){var strong=document.createElement("strong");strong.innerText=data.name,strong.appendChild(document.createTextNode(file.name)),resultContainer.appendChild(strong);}else resultContainer.innerText=data.name;return resultContainer}:"function"==typeof this[params.templateResult]&&(params.templateResult=this[params.templateResult]),"undefined"==typeof params.templateSelection?params.templateSelection=function(item,container){item.element&&item.element.className&&$(container).addClass(item.element.className);var span=document.createElement("span");return span.innerText=""===item.text?item.name:item.text,span}:"function"==typeof this[params.templateSelection]&&(params.templateSelection=this[params.templateSelection]),1===selectElement.data("ajaxSearch")&&(params=this.registerAjaxParams(selectElement,params)),params},/**
* Register ajax params
* @param {jQuery} selectElement
* @param {Object} params
* @returns {Object}
*/registerAjaxParams:function registerAjaxParams(selectElement,params){return params.tags=!1,params.language.searching=function(){return app.vtranslate("JS_SEARCHING")},params.language.inputTooShort=function(args){var remainingChars=args.minimum-args.input.length;return app.vtranslate("JS_INPUT_TOO_SHORT").replace("_LENGTH_",remainingChars)},params.language.errorLoading=function(){return app.vtranslate("JS_NO_RESULTS_FOUND")},params.placeholder="",params.ajax={url:selectElement.data("ajaxUrl"),dataType:"json",delay:250,method:"POST",data:params.ajax&¶ms.ajax.data?params.ajax.data:function(item){return {value:item.term,// search term
page:item.page}},processResults:params.ajax&¶ms.ajax.processResults?params.ajax.processResults:function(data){var items=new Array;return !0==data.success&&(selectElement.find("option").each(function(){var currentTarget=$(this);items.push({label:currentTarget.html(),value:currentTarget.val()});}),items=items.concat(data.result.items)),{results:items,pagination:{more:!1}}},cache:!1},params.escapeMarkup=function(markup){if("undefined"!==markup)return markup},params.minimumInputLength=3,"undefined"!==selectElement.data("minimumInput")&&(params.minimumInputLength=selectElement.data("minimumInput")),params.templateResult=function(data){return "undefined"==typeof data.name?data.text:"optgroup"==data.type?"<strong>"+data.name+"</strong>":"<span>"+data.name+"</span>"},params.templateSelection=function(data){var span=document.createElement("span");return span.innerText=""===data.text?data.name:data.text,span},params},/**
* Prepend template with a flag, function is called select2
* @param optionData
* @returns {Mixed|jQuery|HTMLElement}
*/prependDataTemplate:function prependDataTemplate(optionData){var span=document.createElement("span");if(void 0===optionData.id||""===optionData.id)span.innerText=optionData.text;else if(span.innerHTML=optionData.element.dataset.template,void 0!==optionData.element.dataset.state){var icon=span.querySelector(".js-select-option-event");//check if element has icons with different states
"active"===optionData.element.dataset.state?icon.classList.replace(optionData.element.dataset.iconInactive,optionData.element.dataset.iconActive):icon.classList.replace(optionData.element.dataset.iconActive,optionData.element.dataset.iconInactive);}return span},/**
* Register select sortable
* @param select
* @param params
*/registerSelectSortable:function registerSelectSortable(select,params){this.sortSelectOptions(select),this.registerSortEvent(select,params.sortableCb);},/**
* Sort elements (options) in select by data-sort-index
* @param {jQuery} select2 element
*/sortSelectOptions:function sortSelectOptions(select){select.find("option[data-sort-index]").sort(function(a,b){return $(b).data("sort-index")<$(a).data("sort-index")?1:-1}).appendTo(select);},/**
* Register select drag and drop sorting
* @param {jQuery} select2 element
* @param {function} callback function
*/registerSortEvent:function registerSortEvent(select){var cb=1<arguments.length&&arguments[1]!==void 0?arguments[1]:function(){},ul=select.next(".select2-container").first("ul.select2-selection__rendered");ul.sortable({items:"li:not(.select2-search__field)",tolerance:"pointer",stop:function stop(){$(ul.find(".select2-selection__choice").get().reverse()).each(function(){var optionTitle=$(this).attr("title");select.find("option").each(function(){$(this).text()===optionTitle&&select.prepend($(this));});}),cb(select),select.trigger("sortable:change");}});},/**
* Register icons events in select2 options
* @param selectElement
*/registerIconsEvents:function registerIconsEvents(selectElement){selectElement.on("select2:selecting",function(event){var currentTarget=$(event.params.args.originalEvent.target);if(currentTarget.hasClass("js-select-option-event")||currentTarget.is("path")){event.preventDefault(),currentTarget.is("path")&&(currentTarget=currentTarget.closest(".js-select-option-event"));var currentElementData=$(event.params.args.data.element).data(),optionElement=$(event.params.args.data.element),progressIndicatorElement=$.progressIndicator({blockInfo:{enabled:!0}});AppConnector.request(currentElementData.url).done(function(data){progressIndicatorElement.progressIndicator({mode:"hide"});var response=data.result,icon=currentTarget.get(0);//check if element has icons with different states
response&&response.result?("active"===optionElement.attr("data-state")?(optionElement.attr("data-state","inactive"),icon.classList.replace(currentElementData.iconActive,currentElementData.iconInactive)):(optionElement.attr("data-state","active"),icon.classList.replace(currentElementData.iconInactive,currentElementData.iconActive)),response.message&&app.showNotify({text:response.message,type:"success"})):response&&response.message&&app.showNotify({text:response.message,type:"error"});}).fail(function(){progressIndicatorElement.progressIndicator({mode:"hide"});});}});},/**
* Show lazy select based on data passed in js.
*
* @param {object} selectElement jQuery
* @param {object} params contains selectParams object, lazyElements number, data array
*/showLazySelect:function showLazySelect(selectElement,params){var _this6=this;$.fn.select2.amd.require(["select2/data/array","select2/utils"],function(ArrayData,Utils){function CustomData($element,params){CustomData.__super__.constructor.call(this,$element,params);}Utils.Extend(CustomData,ArrayData),CustomData.prototype.query=function(options,callback){var results=[];results=options.term&&""!==options.term?params.data.filter(function(e){return 0<=e.text.toUpperCase().indexOf(options.term.toUpperCase())}):params.data,"page"in options||(options.page=1);var data={};data.results=results.slice((options.page-1)*params.lazyElements,options.page*params.lazyElements),data.pagination={},data.pagination.more=options.page*params.lazyElements<results.length,callback(data);},params.selectParams=Object.assign(params.selectParams,{ajax:{},dataAdapter:CustomData}),selectElement.addClass("js-lazy-select-active"),_this6.showSelect2ElementView(selectElement,params.selectParams);var selectedOption=selectElement.data("selected-value");if(selectedOption){var text=selectedOption;selectElement.data("fieldinfo").picklistvalues.hasOwnProperty(selectedOption)&&!selectElement.get(0).dataset.templateResult&&(text=selectElement.data("fieldinfo").picklistvalues[selectedOption]),_this6.createSelectedOption(selectElement,text,selectedOption);}});},/**
* Register lazy select options
*
* @param {object} selectElement [selectElement description]
*
* @return {object} [return description]
*/registerLazySelectOptions:function registerLazySelectOptions(selectElement){var options=[];return options=selectElement.data("fieldinfo")&&selectElement.data("fieldinfo").picklistvalues&&!selectElement.get(0).dataset.templateResult?$.map(selectElement.data("fieldinfo").picklistvalues,function(val,key){return {id:key,text:val}}):$.map(selectElement.find("option"),function(item){return {id:item.value,element:item,text:item.text,selected:item.selected,disabled:item.disabled}}),options},/**
* Set a value for the field
*
* @param {jQuery} field Field element
* @param {mixed} value The value to set
* @param {object} params Additional parameters [optional]
*
* @return {mixed} The value that has been set
*/setValue:function setValue(field,value,params){var type="value";params&¶ms.type&&(type=params.type);var option=this.findOption(field,value,type);return !!option&&(field.hasClass("js-lazy-select-active")?this.createSelectedOption(field,option.text,option.value):field.val(option.value).trigger("change"),option.value)},/**
* Find option.
*
* @param {object} selectElement [selectElement description]
* @param {string} searchValue
* @param {string} type value|text|all
*
* @return {boolean|object} false or option object
*/findOption:function findOption(selectElement,searchValue){var type=2<arguments.length&&void 0!==arguments[2]?arguments[2]:"value",foundOption=!1,selectValues=this.getSelectOptions(selectElement),getFieldValueFromText=function getFieldValueFromText(){return Object.keys(selectValues).find(function(key){return selectValues[key]===searchValue})},valueExists=function valueExists(){return selectValues.hasOwnProperty(searchValue)},createOption=function createOption(){return {text:selectValues[foundOption],value:foundOption}};return "value"===type?valueExists()&&(foundOption=searchValue):"text"===type?foundOption=getFieldValueFromText():"all"===type?foundOption=valueExists()?searchValue:getFieldValueFromText():void 0,!!foundOption&&createOption()},/**
* Get select options
*
* @param {object} selectElement jQuery
*
* @return {object} [return description]
*/getSelectOptions:function getSelectOptions(selectElement){if(selectElement.data("fieldinfo")&&selectElement.data("fieldinfo").picklistvalues)return selectElement.data("fieldinfo").picklistvalues;var optionsObject={};return selectElement.find("option").each(function(_i,element){optionsObject[element.value]=element.text;}),optionsObject},/**
* Create selected option
*
* @param {object} selectElement jQuery
* @param {string} text
* @param {string} value
*/createSelectedOption:function createSelectedOption(selectElement,text,value){var newOption=new Option(text,value,!0,!0);selectElement.append(newOption).trigger("change");}},MultiImage:{currentFileUploads:0,register:function register(container){$(".js-multi-image",container).each(function(){new MultiImage($(this));});}},MultiEmail:{register:function register($container){$(".js-multi-email",$container).each(function(idx,multiEmailField){var $multiEmailField=$(multiEmailField);$multiEmailField.on("change",".js-multi-email",function(e){App.Fields.MultiEmail.parseToJSON($multiEmailField);}),$multiEmailField.on("click",".js-multi-email-consenticon",function(e){App.Fields.MultiEmail.toggleConsent($(e.target)),App.Fields.MultiEmail.parseToJSON($multiEmailField);}),$multiEmailField.on("click",".js-multi-email-add",function(e){App.Fields.MultiEmail.addItem($multiEmailField);}),$multiEmailField.on("click",".js-multi-email-remove",function(e){App.Fields.MultiEmail.removeItem($(e.target)),App.Fields.MultiEmail.parseToJSON($multiEmailField);});});},/**
* Converts data to json and set MultiEmail field value
* @param $multiEmailField
*/parseToJSON:function parseToJSON($multiEmailField){var value=[];$(".js-multi-email-item",$multiEmailField).each(function(idx,item){var $item=$(item),email=$(".js-multi-email",$item).val(),consent=$(".js-multi-email-consent",$item).is(":visible")?1:0;email&&value.push({e:email,o:consent});}),$(".js-multi-email-value",$multiEmailField).val(JSON.stringify(value));},/**
* Adds a new item: email box and consent checkbox
* @param $multiEmailField
*/addItem:function addItem($multiEmailField){var $newItem=$(".js-multi-email-item",$multiEmailField).first().clone(!1,!1);$newItem&&($(".js-multi-email",$newItem).attr("value","").val(""),$(".js-multi-email-consent",$newItem).val(""),$(".js-multi-email-consenticon",$newItem).hide(),$(".js-multi-email-consenticon",$newItem).first().show(),$(".js-multi-email-items",$multiEmailField).append($newItem),$(".js-multi-email-remove",$multiEmailField).show());},/**
* Removes an item: email box and consent checkbox
* @param $deleteBtn
*/removeItem:function removeItem($deleteBtn){var $multiEmailField=$deleteBtn.closest(".js-multi-email");1<$(".js-multi-email-item",$multiEmailField).length&&$deleteBtn.closest(".js-multi-email-item").remove(),1==$(".js-multi-email-item",$multiEmailField).length&&$(".js-multi-email-remove",$multiEmailField).hide();},/**
* Toggle consent boxes
* @param $consentBox
*/toggleConsent:function toggleConsent($consentBox){var $item=$consentBox.closest(".js-multi-email-item");$(".js-multi-email-consenticon",$item).toggle();}},MultiDependField:{/**
* Register function
* @param {jQuery} container
*/register:function register(container){container.find(".js-multi-field").each(function(index,element){var inputElement=$(element),fields=inputElement.find(".js-multi-field-val").data("fields");inputElement.find(".js-multi-field-add-item").on("click",function(e){App.Fields.MultiDependField.addRow(inputElement,fields);}),App.Fields.MultiDependField.registerRow(inputElement,fields);});},/**
* Register row
* @param {jQuery} inputElement
* @param {Object} fields
*/registerRow:function registerRow(inputElement,fields){for(var i in fields)inputElement.find("[name=\""+fields[i]+"\"]").on("change",function(e){App.Fields.MultiDependField.parseToJson(inputElement,fields);});inputElement.find(".js-remove-item").on("click",function(e){App.Fields.MultiDependField.removeRow($(e.target),inputElement),App.Fields.MultiDependField.parseToJson(inputElement.closest(".js-multi-field"),fields);});},/**
* Invoked after clicking the remove button
* @param {jQuery} element
* @param {jQuery} container
*/removeRow:function removeRow(element,container){1<container.find(".js-multi-field-row").length&&element.closest(".js-multi-field-row").remove();},/**
* Convert data to json
* @param {jQuery} element
* @param {Object} fields
*/parseToJson:function parseToJson(element,fields){for(var arr=[],allFields=$(element).find(".js-multi-field-row"),arrayLength=allFields.length,i=0;i<arrayLength;++i){var partData={},skip=!1;for(var k in fields)if(partData[fields[k]]=$(allFields[i]).find("[name=\""+fields[k]+"\"]").val(),0==k&&""===partData[fields[k]]){skip=!0;break}skip||arr.push(partData);}$(element).find("input.js-multi-field-val").val(JSON.stringify(arr));},/**
* Invoked after clicking the add button
* @param {jQuery} container
* @param {Object} fields
*/addRow:function addRow(container,fields){var newField,lastField=container.find(".js-multi-field-row").last(),selectFields=lastField.find("select.select2");for(var i in selectFields.length?(selectFields.select2("destroy").removeAttr("data-select2-id").find("option").removeAttr("data-select2-id"),newField=lastField.clone(!1,!1),App.Fields.Picklist.showSelect2ElementView(lastField.find("select.select2"))):newField=lastField.clone(!1,!1),fields)newField.find("[name=\""+fields[i]+"\"]").val("");newField.insertAfter(container.find(".js-multi-field-row").last()),App.Fields.Picklist.showSelect2ElementView(newField.find("select.select2")),App.Fields.Date.register(newField),App.Fields.MultiDependField.registerRow(container,fields);}},DependentSelect:{/**
* Get options for select from array of items (exclude children)
* @param {Array} data {value,text,selected, children => data[]}
* @returns {string}
*/generateOptionsFromData:function generateOptionsFromData(data){var _step,html="",_iterator=_createForOfIteratorHelper(data);try{for(_iterator.s();!(_step=_iterator.n()).done;){var item=_step.value,selected=!1;"undefined"!=typeof item.selected&&item.selected&&(selected=!0),html+="<option value=".concat(item.value).concat(selected?" selected":"",">").concat(item.text,"</option>");}}catch(err){_iterator.e(err);}finally{_iterator.f();}return html},/**
* Register dependent selects
*
* @param {jQuery} container with data- options:
* data-slave: selector for slave element
* data-data: array of options with children elements for slave select (see getOptions for data format)
* data-sort: do we want to sort slave options by text when master has two items selected? if not - just append options to slave
*/register:function register(container){return "undefined"!=typeof container&&"undefined"!=typeof container.length&&container.length?void container.each(function(){var masterSelect=$(this),slaveSelect=$(masterSelect.data("slave")),data=masterSelect.data("data");return slaveSelect.length?data?void(masterSelect.on("change",function(e){var values=$(e.target).val();Array.isArray(values)||(values=[values]);var _step2,children=[],_iterator2=_createForOfIteratorHelper(values);try{for(_iterator2.s();!(_step2=_iterator2.n()).done;){var _step3,value=_step2.value,_iterator3=_createForOfIteratorHelper(data);try{for(_iterator3.s();!(_step3=_iterator3.n()).done;){var item=_step3.value;item.value===value&&"undefined"!=typeof item.children&&item.children.forEach(function(child){children.push(child);});}}catch(err){_iterator3.e(err);}finally{_iterator3.f();}}}catch(err){_iterator2.e(err);}finally{_iterator2.f();}masterSelect.data("sort")&&children.sort(function(a,b){return a.text.localeCompare(b.text)}),slaveSelect.html(App.Fields.DependentSelect.generateOptionsFromData(children));}),masterSelect.html(App.Fields.DependentSelect.generateOptionsFromData(data))):app.errorLog("Could not load data (data-data attribute)"):app.errorLog("Could not find slave select element (data-slave attribute)")}):app.errorLog("Dependend select field container is missing.")}},Gantt:{register:function register(container,data){return new GanttField(container,data)}},Integer:{/**
* Function returns the integer in user specified format.
* @param {number} value
* @param {int} numberOfDecimal
* @returns {string}
*/formatToDisplay:function formatToDisplay(value){value||(value=0);var groupSeparator=CONFIG.currencyGroupingSeparator,groupingPattern=CONFIG.currencyGroupingPattern;value=parseFloat(value).toFixed(1);var integer=value.toString().split(".")[0];return 3<integer.length&&("123,456,789"===groupingPattern?integer=integer.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+groupSeparator):"123456,789"===groupingPattern?integer=integer.slice(0,-3)+groupSeparator+integer.slice(-3):"12,34,56,789"===groupingPattern&&(integer=integer.slice(0,-3).replace(/(\d)(?=(\d\d)+(?!\d))/g,"$1"+groupSeparator)+groupSeparator+integer.slice(-3))),integer}},Double:{/**
* Function returns the currency in user specified format.
* @param {number} value
* @param {boolean} numberOfDecimal
* @param {int} numberOfDecimal
* @returns {string}
*/formatToDisplay:function formatToDisplay(value){var fixed=!(1<arguments.length&&void 0!==arguments[1])||arguments[1],numberOfDecimal=2<arguments.length&&void 0!==arguments[2]?arguments[2]:CONFIG.noOfCurrencyDecimals;value||(value=0);var strDecimal=value.toString().split(".")[1],numberOfZerosAtTheEnd=0;if("undefined"!=typeof strDecimal)for(var i=strDecimal.length-1;0<i&&"0"==strDecimal[i];--i)numberOfZerosAtTheEnd++;if(value=parseFloat(value),fixed){var base=Math.pow(10,numberOfDecimal);value=Math.round(value*base+Math.sign(value)*Math.pow(.1,15-(Math.round(value*base)/base).toString().length))/base;}var splittedFloat=value.toString().split("."),integer=splittedFloat[0];"-0"!==integer&&"0"!==integer&&(integer=App.Fields.Integer.formatToDisplay(integer));var decimal=splittedFloat[1];if(numberOfDecimal){if(!CONFIG.truncateTrailingZeros&&decimal)for(var _i2=0;_i2<numberOfZerosAtTheEnd&&decimal.length<numberOfDecimal;++_i2)decimal+="0";if(decimal)return integer+CONFIG.currencyDecimalSeparator+decimal}return integer},/**
* Function to get value for db format.
* @param {string} value
* @returns {number}
*/formatToDb:function formatToDb(value){return (null==value||""==value)&&(value=0),value=value.toString(),value=value.split(CONFIG.currencyGroupingSeparator).join(""),value=value.replace(/\s/g,"").replace(CONFIG.currencyDecimalSeparator,"."),parseFloat(value)}},/**
* Tree
*/Tree:/*#__PURE__*/function(){function Tree(container){_classCallCheck(this,Tree),this.container=container,this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(Tree,[{key:"init",value:/**
* Initiation
*/function init(){this.modalEvent(),this.autoCompleteEvent(),this.clearSelectionEvent();}/**
* Function which will handle modal view with tree
*/},{key:"modalEvent",value:function modalEvent(){var _this7=this;$(".js-tree-modal",this.container).off("click").on("click",function(_){var sourceFieldElement=_this7.container.find("input.sourceField"),fieldDisplayElement=_this7.container.find("input[name=\""+sourceFieldElement.attr("name")+"_display\"]");AppConnector.request({module:sourceFieldElement.data("module-name"),view:"TreeModal",template:sourceFieldElement.data("treetemplate"),fieldName:sourceFieldElement.attr("name"),multiple:sourceFieldElement.data("multiple"),value:sourceFieldElement.val()}).done(function(requestData){app.modalEvents.treeModal=function(modal,instance){instance.setSelectEvent(function(responseData){sourceFieldElement.val(responseData.id),fieldDisplayElement.val(responseData.name).attr("readonly",!0),sourceFieldElement.trigger("change");});},app.showModalWindow(requestData,{modalId:"treeModal"});});});}/**
* Function which will handle the reference auto complete event registrations
*/},{key:"autoCompleteEvent",value:function autoCompleteEvent(){var autoCompleteElement=$("input.treeAutoComplete",this.container);autoCompleteElement.hasClass("ui-autocomplete-input")&&autoCompleteElement.autocomplete("destroy"),autoCompleteElement.autocomplete({delay:"600",minLength:"3",source:function source(request,response){var inputElement=$(this.element[0]),searchValue=request.term.toLowerCase(),parentElem=inputElement.closest(".js-tree-container"),sourceFieldElement=$("input.sourceField",parentElem),fieldInfo=sourceFieldElement.data("fieldinfo"),allValues=fieldInfo.picklistvalues,responseDataList=[];for(var id in allValues)0<=allValues[id].toLowerCase().indexOf(searchValue)&&responseDataList.push({label:allValues[id],value:id,id:id});0>=responseDataList.length&&($(inputElement).val(""),responseDataList.push({label:app.vtranslate("JS_NO_RESULTS_FOUND"),type:"no results"})),response(responseDataList);},select:function select(event,ui){var selectedItemData=ui.item;if("undefined"!=typeof selectedItemData.type&&"no results"==selectedItemData.type)return !1;selectedItemData.name=selectedItemData.value,this.value=selectedItemData.label;var element=$(this).attr("readonly",!0);return element.closest(".js-tree-container").find("input.sourceField").val(selectedItemData.id).trigger("change"),!1},change:function change(event,ui){},open:function open(event,ui){$(this).data("ui-autocomplete").menu.element.css("z-index","100001");}});}/**
* Function which will register reference field clear event
*/},{key:"clearSelectionEvent",value:function clearSelectionEvent(){var _this8=this;$(".clearTreeSelection",this.container).off("click").on("click",function(e){var fieldElement=_this8.container.find(".sourceField");$("input[name=\""+fieldElement.attr("name")+"_display\"]",_this8.container).removeAttr("readonly").val(""),fieldElement.val("").trigger("change"),e.preventDefault();});}}],[{key:"register",value:function register(container){if(container.hasClass("js-tree-container"))return new Tree(container);var instances=[];return container.find(".js-tree-container").each(function(n,e){instances.push(new Tree($(e)));}),instances}}]),Tree}(),/**
* TimePeriod class
*
* Save value as time period in 00:m format where '0' is a number of units
* ':' is just separator
* and 'm' is time scale/period in php date format - available formats are [m, d, H, i, s]
* @example 10:i = 10 minutes, 2:m = 2 months, 20:H = 20 hours and so on...
*/TimePeriod:/*#__PURE__*/function(){function TimePeriod(container){if(_classCallCheck(this,TimePeriod),this.container=container,this.value=container.val(),this.value){var split=this.value.split(":");this.time=Number(split[0]),this.period=split[1];}else this.time=0,this.period="H",this.value="0:H",container.val(this.value);this.injectContent();}/**
* Register time period field/s
*
* @param {jQuery} container it could be input type hidden with js-time-period class
* or container that contains multiple js-time-period inputs
*
* @example <input type="hidden" name="field_name" class="js-time-period">
*
* @returns {TimePeriod|TimePeriod[]} instance/s
*/return _createClass(TimePeriod,[{key:"injectContent",value:/**
* Inject content next to container
*
* @returns {jQuery} created element with input and select
*/function injectContent(){var content="<div class=\"input-group c-time-period\" data-js=\"container\">\n\t\t\t\t<div class=\"input-group-prepend\">\n\t\t\t\t\t<a href class=\"btn btn-default c-time-period-input-modifier c-time-period-input-modifier--minus-1\"><span class=\"fas fa-minus\"></span></a>\n\t\t\t\t</div>\n\t\t\t\t<input type=\"number\" class=\"form-control c-time-period-input\" min=\"0\" value=\"".concat(this.time,"\"\n\t\t\t\t\tdata-validation-engine=\"validate[required,funcCall[Vtiger_Integer_Validator_Js.invokeValidation]]\">\n\t\t\t\t<div class=\"input-group-append\">\n\t\t\t\t\t<a href class=\"btn btn-default c-time-period-input-modifier c-time-period-input-modifier--plus-1\"><span class=\"fas fa-plus\"></span></a>\n\t\t\t\t\t<select class=\"select2 js-time-period-select time-period-").concat(this.container.attr("name"),"\">\n\t\t\t\t\t\t<option value=\"d\"").concat("d"===this.period?" selected=\"selected\"":"",">").concat(app.vtranslate("JS_DAYS_FULL"),"</option>\n\t\t\t\t\t\t<option value=\"H\"").concat("H"===this.period?" selected=\"selected\"":"",">").concat(app.vtranslate("JS_HOURS_FULL"),"</option>\n\t\t\t\t\t\t<option value=\"i\"").concat("i"===this.period?" selected=\"selected\"":"",">").concat(app.vtranslate("JS_MINUTES_FULL"),"</option>\n\t\t\t\t\t</select>\n\t\t\t\t</div>\n\t\t\t</div>");return this.element=this.container.parent().append(content),this.input=this.element.find(".c-time-period-input").eq(0),this.select=this.element.find(".select2").eq(0),this.plus1btn=this.element.find(".c-time-period-input-modifier--plus-1").eq(0),this.minus1btn=this.element.find(".c-time-period-input-modifier--minus-1").eq(0),App.Fields.Picklist.showSelect2ElementView(this.select,{width:"100px"}),this.registerEvents(),this.element}/**
* Register events
*/},{key:"registerEvents",value:function registerEvents(){this.input.on("input",this.onChange.bind(this)),this.select.on("change",this.onChange.bind(this)),this.plus1btn.on("click",this.onPlus1Click.bind(this)),this.minus1btn.on("click",this.onMinus1Click.bind(this));}/**
* On change event
*
* @param {Event} event
*/},{key:"onChange",value:function onChange(event){this.time=this.input.val(),this.period=this.select.val(),this.value=this.input.val()+":"+this.select.val(),this.container.val(this.value);}/**
* Plus 1 button click event handler
*
* @param {Event} event
*/},{key:"onPlus1Click",value:function onPlus1Click(event){event.preventDefault(),event.stopPropagation(),this.input.val(Number(this.input.val())+1),this.onChange();}/**
* Minus 1 button click event handler
*
* @param {Event} event
*/},{key:"onMinus1Click",value:function onMinus1Click(event){event.preventDefault(),event.stopPropagation(),0<Number(this.input.val())&&(this.input.val(Number(this.input.val())-1),this.onChange());}}],[{key:"register",value:function register(container){if(container.hasClass("c-time-period"))return new TimePeriod(container);var instances=[];return container.find(".c-time-period").each(function(index,value){instances.push(new TimePeriod($(value)));}),instances}}]),TimePeriod}(),/**
* Multi currency
*/MultiCurrency:/*#__PURE__*/function(){function MultiCurrency(container){_classCallCheck(this,MultiCurrency),this.container=container,this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(MultiCurrency,[{key:"init",value:/**
* Initiation
*/function init(){var _this9=this;$(".js-multicurrency-event",this.container).off("click").on("click",function(){var modal=$("<form>").append(_this9.container.find(".js-currencies-container .js-currencies-modal").clone());_this9.registerEnableCurrencyEvent(modal),_this9.registerResetCurrencyEvent(modal),_this9.loadData(modal),_this9.calculateConversionRate(modal),app.showModalWindow({data:modal,css:{},cb:function cb(data){var form=data.parent();form.validationEngine(app.validationEngineOptionsForRecord),form.on("submit",function(e){if(e.preventDefault(),form.validationEngine("validate")&&_this9.saveCurrencies(form)){var id=form.closest(".js-modal-container").attr("id");app.hideModalWindow(null,id);}});}});}),this.getField().on("focusout",function(e){var element=$(e.currentTarget);element.formatNumber(),_this9.setPrice(element.val());});}/**
* Loading data
* @param {jQuery} modalContainer
*/},{key:"loadData",value:function loadData(modalContainer){var values=JSON.parse(this.getFieldToSave().val()),baseCurrencyId=values.currencyId||CONFIG.currencyId;for(var i in void 0===values.currencies&&(values.currencies=[],values.currencies[baseCurrencyId]={price:0}),values.currencies){var row=modalContainer.find("[data-currency-id=\""+i+"\"]");row.length&&(row.find(".js-enable-currency").prop("checked",!0),row.find(".js-currency-reset,.js-base-currency,[name^=\"currencies[\"]").prop("disabled",!1),row.find(".js-converted-price").val(values.currencies[i].price),i==baseCurrencyId&&row.find(".js-base-currency").prop("checked",!0));}}/**
* Set value
* @param {number} value
*/},{key:"setPrice",value:function setPrice(value){var values=JSON.parse(this.getFieldToSave().val()),baseCurrencyId=values.currencyId||CONFIG.currencyId;values.currencies=values.currencies||{},values.currencies[baseCurrencyId]={price:value},values.currencyId=baseCurrencyId,values=$.extend({},values),this.getFieldToSave().val(JSON.stringify($.extend({},values)));}/**
* Gets field
*/},{key:"getField",value:function getField(){return this.container.find(".js-multicurrency-field")}/**
* Gets field to save
*/},{key:"getFieldToSave",value:function getFieldToSave(){return this.container.find(".js-multicurrency-field-to-save")}/**
* Save
* @param {jQuery} modalContainer
*/},{key:"saveCurrencies",value:function saveCurrencies(modalContainer){var enabledBaseCurrency=modalContainer.find(".js-enable-currency").filter(":checked");if(1>enabledBaseCurrency.length)return Vtiger_Helper_Js.showMessage({text:app.vtranslate("JS_PLEASE_SELECT_BASE_CURRENCY_FOR_PRODUCT"),type:"error"}),!1;var selectedBaseCurrency=modalContainer.find(".js-base-currency").filter(":checked");if(1>selectedBaseCurrency.length)return Vtiger_Helper_Js.showMessage({text:app.vtranslate("JS_PLEASE_ENABLE_BASE_CURRENCY_FOR_PRODUCT"),type:"error"}),!1;var selectedRow=selectedBaseCurrency.closest("tr"),symbol=selectedRow.data("currency-symbol");this.container.find(".js-currency").text(symbol);var data={};return data.currencies={},enabledBaseCurrency.closest("tr").each(function(n,e){var row=$(e),currencyId=row.data("currencyId");data.currencies[currencyId]={},data.currencies[currencyId].price=row.find(".js-converted-price").val(),row.find(".js-base-currency:checked").length&&(data.currencyId=currencyId);}),this.getFieldToSave().val(JSON.stringify(data)),this.getField().val(selectedRow.find(".js-converted-price").val()),selectedBaseCurrency.prop("checked",!1),!0}/**
* Calculate
* @param {jQuery} container
*/},{key:"calculateConversionRate",value:function calculateConversionRate(container){var baseCurrencyConversionRate=container.find(".js-base-currency").filter(":checked").closest("tr").find(".js-conversion-rate");if("1"!=baseCurrencyConversionRate.val()){var baseCurrencyRatePrevValue=baseCurrencyConversionRate.getNumberFromValue();container.find(".js-conversion-rate").each(function(key,domElement){var element=$(domElement);element.is(baseCurrencyConversionRate)||element.val(App.Fields.Double.formatToDisplay(element.getNumberFromValue()/baseCurrencyRatePrevValue,!1));}),baseCurrencyConversionRate.val("1");}}/**
* Function to register event for enabling currency on checkbox checked
* @param {jQuery} container
*/},{key:"registerEnableCurrencyEvent",value:function registerEnableCurrencyEvent(container){var _this10=this;container.on("change",".js-enable-currency",function(e){var element=$(e.currentTarget),parentRow=element.closest("tr");if(element.is(":checked")){element.attr("checked","checked");var price=_this10.getField().getNumberFromValue()*parentRow.find(".js-conversion-rate").getNumberFromValue();$("input",parentRow).removeAttr("disabled"),parentRow.find(".js-currency-reset").removeAttr("disabled"),parentRow.find(".js-converted-price").val(App.Fields.Double.formatToDisplay(price));}else {if(parentRow.find(".js-base-currency").is(":checked"))return app.showNotify({type:"error",title:"\""+parentRow.find(".js-currency-name").text()+"\" "+app.vtranslate("JS_BASE_CURRENCY_CHANGED_TO_DISABLE_CURRENCY")}),void element.prop("checked",!0);parentRow.find("input").attr("disabled","disabled"),parentRow.find(".js-currency-reset").attr("disabled","disabled"),element.removeAttr("disabled checked");}});}/**
* Function to register event for reseting the currencies
* @param {jQuery} container
*/},{key:"registerResetCurrencyEvent",value:function registerResetCurrencyEvent(container){var _this11=this;container.on("click",".js-currency-reset",function(e){var parentElem=$(e.currentTarget).closest("tr"),price=_this11.getField().getNumberFromValue()*parentElem.find(".js-conversion-rate").getNumberFromValue();$(".js-converted-price",parentElem).val(App.Fields.Double.formatToDisplay(price));});}}],[{key:"register",value:function register(container){if(container.hasClass("js-multicurrency-container"))return new MultiCurrency(container);var instances=[];return container.find(".js-multicurrency-container").each(function(n,e){instances.push(new MultiCurrency($(e)));}),instances}}]),MultiCurrency}(),/**
* Meeting URL
*/MeetingUrl:/*#__PURE__*/function(){function MeetingUrl(container){_classCallCheck(this,MeetingUrl),this.container=container,this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(MeetingUrl,[{key:"init",value:/**
* Initiation
*/function init(){var _this12=this,addButton=$(".js-meeting-add",this.container);if(!addButton.length)return !1;var valElement=$(".js-meeting-val",this.container);addButton.off("click").on("click",function(e){var progressIndicatorElement=$.progressIndicator({blockInfo:{enabled:!0}});AppConnector.request(_this12.getUrl(e)).done(function(data){var result=data.result;result&&result.success&&result.url?valElement.attr("readonly",!0).val(result.url):app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}),progressIndicatorElement.progressIndicator({mode:"hide"});}).fail(function(_){app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}),progressIndicatorElement.progressIndicator({mode:"hide"});});}),$(".js-meeting-clear",this.container).off("click").on("click",function(){valElement.attr("readonly",!1).val("");}),this.addEventsForDependentFields();}/**
* Gets URL
*/},{key:"getUrl",value:function getUrl(e){var url=e.currentTarget.dataset.url,formData=$(e.currentTarget).closest("form").serializeFormData(),expField=e.currentTarget.dataset.expField;if(expField&&formData&&formData[expField]){var date=formData[expField].split(" ");url+="&exp="+encodeURIComponent(date[0]);}var roomName=e.currentTarget.dataset.roomName;return roomName&&formData&&formData[roomName]&&(url+="&roomName="+encodeURIComponent(formData[roomName])),url}/**
* Add events for dependent fields
*/},{key:"addEventsForDependentFields",value:function addEventsForDependentFields(){for(var addButton=$(".js-meeting-add",this.container),valElement=$(".js-meeting-val",this.container),data=addButton.data(),formElement=this.container.closest("form"),_i3=0,_arr=["expField","roomName"];_i3<_arr.length;_i3++){var name=_arr[_i3],fieldName=data[name];fieldName&&formElement.on("change","[name=".concat(fieldName,"]"),function(_){data.domain&&0===valElement.val().indexOf(data.domain)&&(addButton.trigger("click"),app.showNotify({type:"info",text:app.vtranslate("JS_MEETING_URL_CHANGED")}));});}}}],[{key:"register",value:function register(container){if(container.hasClass("js-meeting-container"))return new MeetingUrl(container);var instances=[];return container.find(".js-meeting-container").each(function(n,e){instances.push(new MeetingUrl($(e)));}),instances}}]),MeetingUrl}(),/**
* Changes Json
*/ChangesJson:/*#__PURE__*/function(){function ChangesJson(container){_classCallCheck(this,ChangesJson),this.container=container,this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(ChangesJson,[{key:"init",value:/**
* Initiation
*/function init(){var _this13=this;$(".js-changesjson-edit",this.container).off("click").on("click",function(){var field=_this13.getField(),value=field.val()?JSON.parse(field.val()):{record:0,module:"",changes:[]},relatedField=_this13.getRelatedField();if(relatedField.length&&(value.record=relatedField.val(),value.module=$("input[name=\"popupReferenceModule\"]",relatedField.closest(".fieldValue")).val()),!value.record||0==value.record)return app.showNotify({text:app.vtranslate("JS_LACK_INFORMATION_ABOUT_RECORD")}),!1;var progressIndicatorElement=$.progressIndicator({blockInfo:{enabled:!0}});AppConnector.request({module:value.module,record:value.record,changes:value.changes,sourceModule:field.data("module"),sourceField:field.attr("name"),view:"ChangesJsonModal"}).done(function(requestData){progressIndicatorElement.progressIndicator({mode:"hide"}),app.showModalWindow({data:requestData,css:{},cb:function cb(data){_this13.saveData(data,value);}});}).fail(function(_){app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}),progressIndicatorElement.progressIndicator({mode:"hide"});});});}/**
* Save data to field
*/},{key:"saveData",value:function saveData(container,data){var _this14=this,form=container.find("form");container.on("click",".js-modal__save",function(e){if(form.validationEngine("validate")){if(e.preventDefault(),!form.find("input[id^=\"selectRow\"]:checked").length)return void app.showNotify({text:app.vtranslate("JS_NONE_FIELD_MARKED_IN_MASS_EDIT"),type:"error"});var invalidFields=form.data("jqv").InvalidFields;if(0!==invalidFields.length)return;form.find("[id^=\"selectRow\"]").each(function(_,checkbox){checkbox=$(checkbox),checkbox.prop("checked")||checkbox.closest(".js-form-row-container").find(".fieldValue [name]").each(function(_,element){element=$(element),element.attr("data-element-name",element.attr("name")).removeAttr("name");});});var changeData=form.serializeFormData();for(var fieldName in delete changeData._csrf,changeData)if("[]"===fieldName.substr(-2)){var fieldNameShort=fieldName.substr(0,fieldName.length-2);changeData[fieldNameShort]=changeData[fieldName],delete changeData[fieldName];}data.changes=changeData,_this14.getField().val(JSON.stringify(data)),app.hideModalWindow(null,form.closest(".js-modal-container").attr("id"));}});}/**
* Gets field
*/},{key:"getField",value:function getField(){return this.container.find(".js-changesjson-value")}/**
* Gets related field
*/},{key:"getRelatedField",value:function getRelatedField(){var relatedFieldName=this.getField().data("related-field");return this.container.closest("form").find("[name=".concat(relatedFieldName,"]"))}}],[{key:"register",value:function register(container){if(container.hasClass("js-changesjson-container"))return new ChangesJson(container);var instances=[];return container.find(".js-changesjson-container").each(function(_,e){instances.push(new ChangesJson($(e)));}),instances}}]),ChangesJson}(),/**
* MultiReference
*/MultiReference:/*#__PURE__*/function(){function MultiReference(container){_classCallCheck(this,MultiReference),this.container=container,this.select=container.find(".js-multi-reference"),this.form=container.closest("form"),this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(MultiReference,[{key:"init",value:/**
* Initiation
*/function init(){var _this15=this;$(".js-related-popup",this.container).off("click").on("click",function(){app.showRecordsList(_this15.getParams(),function(_modal,instance){instance.setSelectEvent(function(data){_this15.setReferenceFieldValue(data);});});}),$(".js-create-reference-record",this.container).off("click").on("click",function(){_this15.createHandler();}),this.registerAutoComplete();}/**
* Function which will handle the reference auto complete event registrations
*/},{key:"registerAutoComplete",value:function registerAutoComplete(){var _this16=this;App.Fields.Picklist.showSelect2ElementView(this.select,{ajax:{data:function data(item){var _item$term;return {search_value:null!==(_item$term=item.term)&&void 0!==_item$term?_item$term:"",page:item.page}},processResults:function processResults(data,params){var items=new Array;return params.term?data.success&&$.each(data.result,function(_,item){items.push({name:item.label,id:item.id});}):items.push({type:"optgroup",name:_this16.select.attr("placeholder")}),{results:items,pagination:{more:!1}}}}});}/**
* Set reference field value
*/},{key:"createHandler",value:function createHandler(){var _this17=this,formData=this.form.serializeFormData();delete formData.action,App.Components.QuickCreate.createRecord($(".js-popup-reference-module",this.container).val(),{data:{sourceRecordData:formData},callbackFunction:function callbackFunction(data){data.success&&_this17.select.append(new Option(data.result._recordLabel,data.result._recordId,!0,!0));},noCache:!0});}/**
* Set reference field value
* @param {object} data
*/},{key:"setReferenceFieldValue",value:function setReferenceFieldValue(data){var _this18=this,values=this.select.val();$.each(data,function(id,label){values.includes(id)||_this18.select.append(new Option(label,id,!0,!0));});}/**
* Gets params
* @returns {Object}
*/},{key:"getParams",value:function getParams(){var _this19=this,referenceModule=$(".js-popup-reference-module",this.container).val(),sourceFieldName=this.select.attr("name").slice(0,-2),sourceRecordElement=$("input[name=\"record\"]",this.form),listFilterFieldsJson=this.form.find("input[name=\"listFilterFields\"]").val(),listFilterFields=listFilterFieldsJson?JSON.parse(listFilterFieldsJson):[],sourceRecordId="";0<sourceRecordElement.length&&(sourceRecordId=sourceRecordElement.val());var filterFields={};return null!=listFilterFields[sourceFieldName]&&null!=listFilterFields[sourceFieldName][referenceModule]&&$.each(listFilterFields[sourceFieldName][referenceModule],function(index){var mapFieldElement=_this19.form.find("[name=\""+index+"\"]");mapFieldElement.length&&""!=mapFieldElement.val()&&(filterFields[index]=mapFieldElement.val());}),{module:referenceModule,src_module:$("input[name=\"module\"]",this.form).val(),src_field:sourceFieldName,src_record:sourceRecordId,filterFields:filterFields,multi_select:!0}}}],[{key:"register",value:function register(container){if(container.hasClass("js-multiReference-container"))return new MultiReference(container);var instances=[];return container.find(".js-multiReference-container").each(function(_,e){instances.push(new MultiReference($(e)));}),instances}/**
* Set a value for the field
*
* @param {jQuery} field Field element
* @param {mixed} value The value to set
* @param {object} params Additional parameters [optional]
*
* @return {mixed} The value that has been set
*/},{key:"setValue",value:function setValue(field,value,params){params&¶ms.extend||field.val(null);var values=field.val();return $.each(value,function(id,label){values.includes(id)||field.append(new Option(label,id,!0,!0));}),field.trigger("change"),field.val()}}]),MultiReference}(),/**
* Password
*/Password:/*#__PURE__*/function(){function Password(container){_classCallCheck(this,Password),this.container=container,this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(Password,[{key:"init",value:/**
* Initiation
*/function init(){var _this20=this,field=this.getField();$(".js-pwd-auto-generate",this.container).off("click").on("click",function(e){_this20.getResponse($(e.currentTarget).data("url")).then(function(response){response.success&&response.result&&response.result.pwd&&(_this20.clear(),field.val(response.result.pwd).trigger("keyup").focus());});}),$(".js-pwd-validate",this.container).off("click").on("click",function(e){_this20.getResponse($(e.currentTarget).data("url")+"&password="+field.val()).then(function(response){if(response.success&&response.result){var message=response.result.message;Array.isArray(message)&&(message=message.join("<br>")),field.validationEngine("showPrompt",message,response.result.type,"topLeft",!0),field.validationEngine("updatePromptsPosition");}});}),$(".js-pwd-clear",this.container).off("click").on("click",function(){_this20.clear();}),$(".js-pwd-copy",this.container).off("click").on("click",function(){"disabled"===_this20.container.find(".js-pwd-show").attr("disabled")?_this20.getPassword().then(function(response){_this20.clear(),field.val(response.result.text),ClipboardJS.copy(response.result.text),app.showNotify({text:app.vtranslate("JS_NOTIFY_COPY_TEXT"),type:"success"});}):(ClipboardJS.copy(_this20.getField().val()),app.showNotify({text:app.vtranslate("JS_NOTIFY_COPY_TEXT"),type:"success"}));}),$(".js-pwd-get",this.container).off("click").on("click",function(){_this20.getPassword().then(function(response){_this20.clear(),field.val(response.result.text);});}),field.data("strengthMeter")&&field.off("keyup").on("keyup",function(e){var score=_this20.strengthMeter(e.target.value||"");field.attr("data-original-title",App.Fields.Password.getStrengthLevels()[score]).tooltip("show").validationEngine("hide");});}/**
* Get decoded password
* @returns {Promise}
*/},{key:"getPassword",value:function getPassword(){var field=this.getField();return this.getResponse({module:field.data("module"),field:field.attr("name"),record:$("input[name=\"record\"]",this.container.closest("form")).val()||app.getRecordId(),action:"Password",mode:"getPwd"})}/**
* Clear data
*/},{key:"clear",value:function clear(){this.getField().val("").attr("disabled",!1).tooltip("dispose").validationEngine("hide"),this.container.find(".js-pwd-validate, .js-pwd-show").attr("disabled",!1);}/**
* Get response
* @param {Object|string} params
* @returns {Promise}
*/},{key:"getResponse",value:function getResponse(params){var aDeferred=$.Deferred(),progressIndicatorElement=$.progressIndicator({blockInfo:{enabled:!0}});return AppConnector.request(params).done(function(response){progressIndicatorElement.progressIndicator({mode:"hide"}),response.success?aDeferred.resolve(response):aDeferred.reject(response);}).fail(function(_){app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}),progressIndicatorElement.progressIndicator({mode:"hide"}),aDeferred.reject(_);}),aDeferred.promise()}/**
* Get strength meter score
* @param {string} pwd
* @returns {int}
*/},{key:"strengthMeter",value:function strengthMeter(pwd){var score=0;return 6<pwd.length&&score++,pwd.match(/[a-z]/)&&pwd.match(/[A-Z]/)&&score++,pwd.match(/\d+/)&&score++,pwd.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)&&score++,12<pwd.length&&score++,score}/**
* Gets field
*/},{key:"getField",value:function getField(){return this.container.find(".js-pwd-field")}}],[{key:"register",value:function register(container){if(container.hasClass("js-pwd-container"))return new Password(container);var instances=[];return container.find(".js-pwd-container").each(function(_,e){instances.push(new Password($(e)));}),instances}/**
* Get strength meter
* @returns {Object}
*/},{key:"getStrengthLevels",value:function getStrengthLevels(){return this.strengthLevels||(this.strengthLevels={0:app.vtranslate("JS_PWD_RIDICULOUS"),1:app.vtranslate("JS_PWD_VERY_WEAK"),2:app.vtranslate("JS_PWD_WEAK"),3:app.vtranslate("JS_PWD_MEDIUM"),4:app.vtranslate("JS_PWD_STRONG"),5:app.vtranslate("JS_PWD_VERY_STRONG")}),_objectSpread({},this.strengthLevels)}}]),Password}(),/**
* Multi Attachment
*/MultiAttachment:/*#__PURE__*/function(){/**
* Constructor
* @param {jQuery} container
* @param {Object} options
*/function MultiAttachment(container,options){_classCallCheck(this,MultiAttachment),this.container=container,this.fileInput=container.find(".js-multi-attachment__file").eq(0),this.dataInput=container.find(".js-multi-attachment__values"),this.form=container.closest("form"),this.progressBar=container.find(".js-multi-attachment__progress-bar"),this.progress=container.find(".js-multi-attachment__progress"),this.result=container.find(".js-multi-attachment__result"),this.files=this.dataInput.is("input")?JSON.parse(this.dataInput.val()):this.dataInput.data("value");var fieldInfo=this.dataInput.data("fieldinfo")||{};this.options=_objectSpread({formats:fieldInfo.formats||[],limit:fieldInfo.limit||1,maxFileSize:fieldInfo.maxFileSize,maxFileSizeDisplay:fieldInfo.maxFileSizeDisplay||""},options),this.form.length&&this.fileInput.length?this.initEditView():this.initDetailView();}/**
* Register function
* @param {jQuery} container
* @param {Object} options
*/return _createClass(MultiAttachment,[{key:"initDetailView",value:/**
* Initiation for detail view
*/function initDetailView(){var _this21=this;this.files.forEach(function(fileInfo){_this21.createItem(fileInfo);});}/**
* Initiation for edit view
*/},{key:"initEditView",value:function initEditView(){var _this22=this;this.fileInput.detach(),this.container.on("mouseup",this.openBrowser.bind(this)),this.fileInput.fileupload({dataType:"json",replaceFileInput:!1,fileInput:this.fileInput,autoUpload:!1,submit:this.submit.bind(this),add:this.add.bind(this),progressall:this.progressAll.bind(this),change:this.change.bind(this),drop:this.change.bind(this),dragover:this.dragOver.bind(this),fail:this.uploadError.bind(this),done:this.uploadSuccess.bind(this)}),this.container.on("dragleave",this.dragLeave.bind(this)),this.container.on("dragend",this.dragLeave.bind(this)),this.fileInput.fileupload("option","dropZone",this.container),this.enableDragNDrop(),this.form.on("submit",this.onFormSubmit.bind(this)),this.deleteButtonActive=!0,this.container.on("click",".js-multi-attachment__file-buttons-delete",function(e){e.preventDefault(),_this22.deleteFile(e.currentTarget.dataset.key);}),this.files.forEach(function(fileInfo){_this22.createItem(fileInfo);}),this.filesActive=0;}/**
* Add event handler from jQuery-file-upload
*
* @param {Event} e
* @param {Object} data
*/},{key:"add",value:function add(e,data){0<data.files.length&&data.submit();}/**
* Submit event handler from jQuery-file-upload
*
* @param {Event} e
* @param {Object} data
*/},{key:"submit",value:function submit(e,data){this.filesActive++,this.progressInstance=$.progressIndicator({position:"replace",blockInfo:{enabled:!0,elementToBlock:this.container}});}/**
* Prevent form submission before file upload end
* @param e
*/},{key:"onFormSubmit",value:function onFormSubmit(e){return !this.filesActive||(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),app.showAlert(app.vtranslate("JS_WAIT_FOR_FILE_UPLOAD")),!1)}/**
* Progressall event handler from jQuery-file-upload
*
* @param {Event} e
* @param {Object} data
*/},{key:"progressAll",value:function progressAll(e,data){var _this23=this,progress=parseInt(100*(data.loaded/data.total),10);this.progressBar.css({width:progress+"%"}),100===progress?setTimeout(function(){_this23.progress.addClass("d-none"),_this23.progressBar.css({width:"0%"});},1e3):this.progress.removeClass("d-none");}/**
* File change event handler from jQuery-file-upload
*
* @param {Event} e
* @param {object} data
*/},{key:"change",value:function change(e,data){var _this$filterFiles=this.filterFiles(data.files),valid=_this$filterFiles.valid,error=_this$filterFiles.error;data.files=valid,valid.length||this.fileInput.val(""),error.length&&this.showErrors(error),this.dragLeave(e);}/**
* Get only valid files from list
*
* @param {Array} files
* @returns {Object}
*/},{key:"filterFiles",value:function filterFiles(files){var valid=[],error=[];if(files.length+this.files.length>this.options.limit)error.push({error:{text:"".concat(app.vtranslate("JS_FILE_LIMIT")," [").concat(this.options.limit,"]")}});else {var _step4,_iterator4=_createForOfIteratorHelper(files);try{for(_iterator4.s();!(_step4=_iterator4.n()).done;){var _file=_step4.value;this.validateFileType(_file)&&this.validateFileSize(_file)?valid.push(_file):error.push(_file);}}catch(err){_iterator4.e(err);}finally{_iterator4.f();}}return {valid:valid,error:error}}/**
* Validate maximum file size
* @param {Object} file
* @returns {Boolean}
*/},{key:"validateFileSize",value:function validateFileSize(file){var result="number"==typeof file.size&&file.size<this.options.maxFileSize;return result||(file.error={title:"".concat(app.vtranslate("JS_UPLOADED_FILE_SIZE_EXCEEDS")," <br> [").concat(this.options.maxFileSizeDisplay,"]"),text:file.name}),result}/**
* Validate file
*
* @param {Object} file
* @returns {boolean}
*/},{key:"validateFileType",value:function validateFileType(file){var result=!this.options.formats.length||0<this.options.formats.filter(function(format){return file.type===format||"/*"===format.slice(-2)&&0===file.type.indexOf(format.slice(0,-1))}).length;return result||(file.error={title:app.vtranslate("JS_INVALID_FILE_TYPE"),text:file.name}),result}/**
* Show errors
*/},{key:"showErrors",value:function showErrors(){var _step5,errors=0<arguments.length&&void 0!==arguments[0]?arguments[0]:[],_iterator5=_createForOfIteratorHelper(errors);try{for(_iterator5.s();!(_step5=_iterator5.n()).done;){var info=_step5.value;this.showError(info.error);}}catch(err){_iterator5.e(err);}finally{_iterator5.f();}}/**
* Show error
*/},{key:"showError",value:function showError(error){"undefined"==typeof error.type&&(error.type="error"),error.textTrusted=!1,app.showNotify(error);}/**
* Dragover event handler from jQuery-file-upload
*
* @param {Event} e
*/},{key:"dragOver",value:function dragOver(_e){this.container.addClass("c-multi-image__drop-effect");}/**
* Dragleave event handler
* @param {Event} e
*/},{key:"dragLeave",value:function dragLeave(_e){this.container.removeClass("c-multi-image__drop-effect");}/**
* Error event handler from file upload request
*
* @param {Event} e
* @param {Object} data
*/},{key:"uploadError",value:function uploadError(_e,data){var _this24=this;this.progressInstance.progressIndicator({mode:"hide"}),this.filesActive--,app.errorLog("File upload error.");var jqXHR=data.jqXHR,files=data.files;return "undefined"==typeof jqXHR.responseJSON||null===jqXHR.responseJSON?this.showError({title:app.vtranslate("JS_FILE_UPLOAD_ERROR"),type:"error"}):void(files.forEach(function(file){_this24.showError({title:app.vtranslate("JS_FILE_UPLOAD_ERROR"),text:file.name,type:"error"});}),this.updateFormValues())}/**
* Success event handler from file upload request
*
* @param {Event} e
* @param {Object} data
*/},{key:"uploadSuccess",value:function uploadSuccess(e,data){var _this25=this;this.progressInstance.progressIndicator({mode:"hide"});var result=data.result,attach=result.result.attach;attach.forEach(function(fileAttach){if(_this25.filesActive--,"undefined"==typeof fileAttach.key)return _this25.uploadError(e,data);"undefined"!=typeof fileAttach.info&&fileAttach.info&&app.showNotify({type:"notice",text:fileAttach.info}),_this25.files.push(fileAttach);var fileInfo=_this25.getFileInfo(fileAttach.key);_this25.createItem(fileInfo);}),this.updateFormValues();}/**
* Get file information
*
* @param {String} key - file id
* @returns {Object}
*/},{key:"getFileInfo",value:function getFileInfo(key){for(var _file2,i=0,len=this.files.length;i<len;i++)if(_file2=this.files[i],_file2.key===key)return _file2;app.errorLog("File '".concat(key,"' not found.")),app.showNotify({text:app.vtranslate("JS_INVALID_FILE_HASH"),type:"error"});}/**
* Generate preview of image as html string from existing values
* @param {Object} file
*/},{key:"createItem",value:function createItem(file){var item=document.createElement("fieldset");item.setAttribute("class","c-multi-attachment--file bg-light js-handle"),item.setAttribute("data-key",file.key);var legend=document.createElement("legend");legend.appendChild(document.createTextNode(file.name)),item.appendChild(legend);var icon=document.createElement("div");icon.setAttribute("class","c-multi-attachment--file-icon");var span=document.createElement("span");span.setAttribute("class",file.icon),icon.appendChild(span),item.appendChild(icon);var fileInfo=document.createElement("div");fileInfo.setAttribute("class","c-multi-attachment--file-info");var name=document.createElement("span");name.setAttribute("class","c-multi-attachment--file-info-main"),name.setAttribute("aria-hidden",!0),name.appendChild(document.createTextNode(file.name)),fileInfo.appendChild(name);var size=document.createElement("span");size.setAttribute("class","c-multi-attachment--file-info-sub"),size.appendChild(document.createTextNode(file.sizeDisplay)),fileInfo.appendChild(size),item.appendChild(fileInfo);var buttons=document.createElement("div");if(buttons.setAttribute("class","js-multi-attachment__file-buttons"),file.url){var downloadBtn=document.createElement("a");downloadBtn.setAttribute("class","btn btn-sm btn-outline-success js-multi-attachment__file-buttons-download"),downloadBtn.setAttribute("href",file.url),downloadBtn.setAttribute("download",file.name),downloadBtn.setAttribute("title",$("<textarea />").html(app.vtranslate("JS_DOWNLOAD")).text());var downloadBtnIcon=document.createElement("span");downloadBtnIcon.setAttribute("class","fa fa-download"),downloadBtn.appendChild(downloadBtnIcon),buttons.appendChild(downloadBtn);}if(this.deleteButtonActive&&!file.lock){var deleteBtn=document.createElement("button");deleteBtn.setAttribute("class","btn btn-sm btn-outline-danger js-multi-attachment__file-buttons-delete ml-1"),deleteBtn.setAttribute("data-key",file.key),deleteBtn.setAttribute("title",$("<textarea />").html(app.vtranslate("JS_DELETE")).text());var deleteBtnIcon=document.createElement("span");deleteBtnIcon.setAttribute("class","fa fa-trash-alt"),deleteBtn.appendChild(deleteBtnIcon),buttons.appendChild(deleteBtn);}item.appendChild(buttons),this.result.append(item);}/**
* Enable drag and drop files repositioning
*/},{key:"enableDragNDrop",value:function enableDragNDrop(){this.result.sortable({containment:this.container,items:".js-handle",stop:this.sortStop.bind(this)}).disableSelection();}/**
* Prevent form submission
*
* @param {Event} e
*/},{key:"openBrowser",value:function openBrowser(e){e.target.closest("fieldset")||(e.preventDefault(),this.fileInput.trigger("click"));}/**
* Update file position according to elements order
*
* @param {Event} e
* @param {Object} ui
*/},{key:"sortStop",value:function sortStop(e,ui){var _this26=this,actualElements=this.result.find("fieldset").toArray();this.files=actualElements.map(function(element){for(var elementHash,i=0,len=_this26.files.length;i<len;i++)if(elementHash=$(element).data("key"),_this26.files[i].key===elementHash)return _this26.files[i]}),this.updateFormValues();}/**
* Remove file from preview and from file list
*
* @param {String} key
*/},{key:"deleteFile",value:function deleteFile(key){var fileInfo=this.getFileInfo(key);this.result.find("[data-key=\"".concat(fileInfo.key,"\"]")).remove(),this.files=this.files.filter(function(file){return file.key!==fileInfo.key}),this.updateFormValues();}/**
* Update form input values
*/},{key:"updateFormValues",value:function updateFormValues(){this.fileInput.val("");var formValues=this.files.map(function(file){return {key:file.key,name:file.name,size:file.size,type:file.type}});this.dataInput.val(JSON.stringify(formValues));}}],[{key:"register",value:function register(container){var options=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};if(container.hasClass("js-multi-attachment"))return new MultiAttachment(container,options);var instances=[];return container.find(".js-multi-attachment").each(function(_,e){instances.push(new MultiAttachment($(e),options));}),instances}}]),MultiAttachment}(),/**
* Icon
*/Icon:/*#__PURE__*/function(){function Icon(container){_classCallCheck(this,Icon),this.container=container,this.init();}/**
* Register function
* @param {jQuery} container
*/return _createClass(Icon,[{key:"init",value:/**
* Initiation
*/function init(){var _this27=this;this.iconElement=$(".js-icon-show",this.container),$(".js-clear-selection",this.container).off("click").on("click",function(){_this27.clear();}),$(".js-icon-select",this.container).off("click").on("click",function(){App.Components.Icons.modalView().done(function(data){if("icon"===data.type){var span=document.createElement("span");span.setAttribute("class",data.name),_this27.iconElement.html("").append(span);}else if("image"===data.type){var image=document.createElement("img");image.setAttribute("class","icon-img--picklist"),image.setAttribute("src",data.src),_this27.iconElement.html("").append(image);}_this27.setValue(data),_this27.setDisplayValue(data.name);});});}/**
* Clear selection
*/},{key:"clear",value:function clear(){var element=this.getField(),fieldName=element.attr("name");element.val(""),this.container.find("#".concat(fieldName,"_display")).val(""),this.iconElement.html("");}/**
* Set icon name
* @param {string} data
*/},{key:"setDisplayValue",value:function setDisplayValue(name){var fieldName=this.getField().attr("name");this.container.find("#".concat(fieldName,"_display")).val(name).attr("readonly",!0);}/**
* Set value
* @param {Object} data
*/},{key:"setValue",value:function setValue(data){var type=data.type,name=data.name;data.key&&(name=data.key),this.getField().val(JSON.stringify({type:type,name:name}));}/**
* Gets field
*/},{key:"getField",value:function getField(){return this.container.find(".js-source-field")}}],[{key:"register",value:function register(container){if(container.hasClass("js-icon-container"))return new Icon(container);var instances=[];return container.find(".js-icon-container").each(function(_,e){instances.push(new Icon($(e)));}),instances}}]),Icon}(),Utils:{registerMobileDateRangePicker:function registerMobileDateRangePicker(element){this.hideMobileKeyboard(element),Quasar.plugins.Platform.is.desktop||element.on("showCalendar.daterangepicker",function(ev,picker){picker.container.addClass("js-visible");}).on("hide.daterangepicker",function(ev,picker){picker.container.removeClass("js-visible");});},hideMobileKeyboard:function hideMobileKeyboard(element){Quasar.plugins.Platform.is.desktop||element.attr("readonly","true").addClass("bg-white");},positionPicker:function positionPicker(ev,picker){var offset=picker.element.offset(),$window=$(window);picker.opens=offset.left-$window.scrollLeft()+picker.container.outerWidth()>$window.width()?"left":"right",picker.move(),picker.drops=offset.top-$window.scrollTop()+picker.container.outerHeight()>$window.height()?"up":"down",picker.move();},/**
* Set a value for the field
*
* @param {jQuery} field Field element
* @param {mixed} value The value to set
* @param {object} params Additional parameters [optional]
* @param {boolean} animation
*/setValue:function setValue(field,value,params){var animation=!(3<arguments.length&&arguments[3]!==void 0)||arguments[3],fieldInfo=field.data("fieldinfo");switch(fieldInfo.type){case"picklist":case"languages":case"country":case"currencyList":case"modules":App.Fields.Picklist.setValue(field,value,params);break;case"multiReference":App.Fields.MultiReference.setValue(field,value,params);break;default:field.val(value);}if(animation){var fieldValue=field.closest(".fieldValue");fieldValue.addClass("border border-info"),setTimeout(function(){fieldValue.removeClass("border border-info");},5e3);}}}};
//# sourceMappingURL=Fields.min.js.map