YetiForceCompany/YetiForceCRM

View on GitHub
public_html/layouts/basic/modules/Vtiger/resources/Edit.min.js

Summary

Maintainability
A
0 mins
Test Coverage
'use strict';

/*+***********************************************************************************
 * The contents of this file are subject to the vtiger CRM Public License Version 1.0
 * ("License"); You may not use this file except in compliance with the License
 * The Original Code is:  vtiger CRM Open Source
 * The Initial Developer of the Original Code is vtiger.
 * Portions created by vtiger are Copyright (C) vtiger.
 * All Rights Reserved.
 * Contributor(s): YetiForce S.A.
 *************************************************************************************/"use strict";function _toConsumableArray(arr){return _arrayWithoutHoles(arr)||_iterableToArray(arr)||_unsupportedIterableToArray(arr)||_nonIterableSpread()}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}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 _iterableToArray(iter){if("undefined"!=typeof Symbol&&null!=iter[Symbol.iterator]||null!=iter["@@iterator"])return Array.from(iter)}function _arrayWithoutHoles(arr){if(Array.isArray(arr))return _arrayLikeToArray(arr)}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)}$.Class("Vtiger_Edit_Js",{//Event that will triggered when reference field is selected
referenceSelectionEvent:"Vtiger.Reference.Selection",//Event that will triggered when reference field is selected
referenceDeSelectionEvent:"Vtiger.Reference.DeSelection",//Event that will triggered before saving the record
recordPreSave:"Vtiger.Record.PreSave",editInstance:!1,inventoryController:!1,/**
         * Function to get Instance by name
         * @params moduleName:-- Name of the module to create instance
         */getInstanceByModuleName:function getInstanceByModuleName(moduleName){"undefined"==typeof moduleName&&(moduleName=app.getModuleName());var moduleClassName,fallbackClassName,instance,parentModule=app.getParentModuleName();return "Settings"===parentModule?(moduleClassName=parentModule+"_"+moduleName+"_Edit_Js","undefined"==typeof window[moduleClassName]&&(moduleClassName=moduleName+"_Edit_Js"),fallbackClassName=parentModule+"_Vtiger_Edit_Js","undefined"==typeof window[fallbackClassName]&&(fallbackClassName="Vtiger_Edit_Js")):(moduleClassName=moduleName+"_Edit_Js",fallbackClassName="Vtiger_Edit_Js"),instance="undefined"==typeof window[moduleClassName]?new window[fallbackClassName]:new window[moduleClassName],instance.moduleName=moduleName,instance},getInstance:function getInstance(){if(!1==Vtiger_Edit_Js.editInstance){var instance=Vtiger_Edit_Js.getInstanceByModuleName();return Vtiger_Edit_Js.editInstance=instance,instance}return Vtiger_Edit_Js.editInstance},/**
         * Record save ajax
         *
         * `Vtiger_Edit_Js.saveAjax({
         *        value: 'value',
         *        field: 'field'
         *    }).done(() => {})
         *    .fail((error, err) => {});`
         *
         * @param {object} params
         * @returns {Promise}
         */saveAjax:function saveAjax(params){var progressIndicator=!!(1<arguments.length&&void 0!==arguments[1])&&arguments[1],aDeferred=$.Deferred();return "undefined"==typeof params||$.isEmptyObject(params)?(aDeferred.reject(),aDeferred.promise()):(!params.record&&app.getRecordId()&&(params.record=app.getRecordId()),params.module||(params.module=app.getModuleName()),params.action="SaveAjax",params={data:params,async:!1,dataType:"json"},progressIndicator&&(document.progressLoader=$.progressIndicator({message:app.vtranslate("JS_SAVE_LOADER_INFO"),position:"html",blockInfo:{enabled:!0}})),this.saveAjaxValidation(params).then(function(response){!0===response?(delete params.data.mode,AppConnector.request(params).done(function(responseData){aDeferred.resolve(responseData),progressIndicator&&document.progressLoader.progressIndicator({mode:"hide"});}).fail(function(jqXHR,textStatus,errorThrown){aDeferred.reject(jqXHR,textStatus,errorThrown),progressIndicator&&document.progressLoader.progressIndicator({mode:"hide"}),app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"});})):(aDeferred.resolve({success:!1}),progressIndicator&&document.progressLoader.progressIndicator({mode:"hide"}));}),aDeferred.promise())},/**
         * Record pre save validation
         * @param {object} params
         * @returns {Promise}
         */saveAjaxValidation:function saveAjaxValidation(params){var _this=this,aDeferred=$.Deferred();if(this.getInstance().checkPreSaveValidation()){var paramsTemp=JSON.parse(JSON.stringify(params));paramsTemp.data.mode="preSaveValidation",AppConnector.request(paramsTemp).done(function(data){var response=data.result,lock=!1,_loop=function _loop(i){if(!0!==response[i].result){if("confirm"===response[i].type&&"undefined"!=typeof response[i].hash)return app.showConfirmModal({text:response[i].message||"",confirmedCallback:function confirmedCallback(){var handlers={};"undefined"!=typeof params.data.skipHandlers&&(handlers=JSON.parse(params.data.skipHandlers)),handlers[i]=response[i].hash,params.data.skipHandlers=JSON.stringify(handlers),_this.saveAjaxValidation(params,form).then(function(responsePart){aDeferred.resolve(responsePart);});},rejectedCallback:function rejectedCallback(){aDeferred.resolve(!1);}}),lock=!0,1;// break
"undefined"!=typeof response[i].showModal&&"undefined"!=typeof response[i].showModal.url?app.showModalWindow(null,response[i].showModal.url,function(modalContainer){app.registerModalController(void 0,modalContainer,function(_,instance){instance.formContainer=form;});}):app.showNotify({text:response[i].message?response[i].message:app.vtranslate("JS_ERROR"),type:"error"});}};for(var i in response)if(_loop(i))break;0>=data.result.length?aDeferred.resolve(!0):!lock&&aDeferred.resolve(!1);}).fail(function(textStatus,errorThrown){app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}),aDeferred.resolve(!1);});}else aDeferred.resolve(!0);return aDeferred.promise()}},{formElement:!1,relationOperation:"",moduleName:app.getModuleName(),getForm:function getForm(){return !1==this.formElement&&this.setForm($("#EditView")),this.formElement},setForm:function setForm(element){this.formElement=element;var module;return (module=$("input[name=\"module\"]",element))&&(this.moduleName=module.val()),this},getRecordsListParams:function getRecordsListParams(container){var formElement=container.closest("form"),sourceModule=$("input[name=\"module\"]",formElement).val(),popupReferenceModule=$("input[name=\"popupReferenceModule\"]",container).val(),sourceFieldElement=$("input[class=\"sourceField\"]",container),sourceField=sourceFieldElement.attr("name"),sourceRecordElement=$("input[name=\"record\"]",formElement),sourceRecordId="";0<sourceRecordElement.length&&(sourceRecordId=sourceRecordElement.val());var isMultiple=!1;!0==sourceFieldElement.data("multiple")&&(isMultiple=!0);var filterFields={},mappingRelatedField=formElement.find("input[name=\"mappingRelatedField\"]").val(),mappingRelatedModule=mappingRelatedField?JSON.parse(mappingRelatedField):[];null!=mappingRelatedModule[sourceField]&&null!=mappingRelatedModule[sourceField][popupReferenceModule]&&$.each(mappingRelatedModule[sourceField][popupReferenceModule],function(index,value){var mapFieldElement=formElement.find("[name=\""+index+"\"]");mapFieldElement.length&&""!=mapFieldElement.val()&&(filterFields[index]=mapFieldElement.val());});var listFilterFieldsJson=formElement.find("input[name=\"listFilterFields\"]").val(),listFilterFields=listFilterFieldsJson?JSON.parse(listFilterFieldsJson):[];null!=listFilterFields[sourceField]&&null!=listFilterFields[sourceField][popupReferenceModule]&&$.each(listFilterFields[sourceField][popupReferenceModule],function(index,value){var mapFieldElement=formElement.find("[name=\""+index+"\"]");mapFieldElement.length&&""!=mapFieldElement.val()&&(filterFields[index]=mapFieldElement.val());});var params={module:popupReferenceModule,src_module:sourceModule,src_field:sourceField,src_record:sourceRecordId,filterFields:filterFields},searchParamsElement=$("input[name=\"searchParams\"]",container),searchParams=0<searchParamsElement.length?JSON.parse(searchParamsElement.val()):null;searchParams&&searchParams[popupReferenceModule]&&(params.search_params=searchParams[popupReferenceModule]);var modalParamsElement=$("input[name=\"modalParams\"]",container);0<modalParamsElement.length&&(params.modal_params=modalParamsElement.val());var lockedFieldsElement=$("input[name=\"lockedFields\"]",container);return 0<lockedFieldsElement.length&&(params.lockedFields=lockedFieldsElement.val()),$.each(["link","process"],function(index,value){var fieldElement=formElement.find("[name=\""+value+"\"]");fieldElement.length&&""!=fieldElement.val()&&0!=fieldElement.val()&&(params[value]=fieldElement.val());}),isMultiple&&(params.multi_select=!0),params},/**
         * Show records list modal
         * @param {jQuery.Event} e
         */showRecordsList:function showRecordsList(e){var _this2=this,parentElem=$(e.target).closest(".fieldValue");0>=parentElem.length&&(parentElem=$(e.target).closest("td"));var params=this.getRecordsListParams(parentElem);app.showRecordsList(params,function(_modal,instance){instance.setSelectEvent(function(data){_this2.setReferenceFieldValue(parentElem,data);});});},setReferenceFieldValue:function setReferenceFieldValue(container,params){var thisInstance=this,sourceFieldElement=container.find("input.sourceField"),sourceField=sourceFieldElement.attr("name"),fieldElement=container.find("input[name=\""+sourceField+"\"]"),sourceFieldDisplay=sourceField+"_display",fieldDisplayElement=container.find("input[name=\""+sourceFieldDisplay+"\"]"),popupReferenceModule=container.find("input[name=\"popupReferenceModule\"]").val(),selectedName=params.name,id=params.id;if(container.find(".clearReferenceSelection").trigger("click"),fieldElement.val(id),fieldDisplayElement.val(app.decodeHTML(selectedName)).attr("readonly",!0),fieldElement.trigger(Vtiger_Edit_Js.referenceSelectionEvent,{module:popupReferenceModule,record:id,selectedName:selectedName}),fieldDisplayElement.validationEngine("closePrompt",fieldDisplayElement),"inventory"==sourceFieldElement.data("type"))return params;var formElement=container.closest("form"),mappingRelatedField=this.getMappingRelatedField(sourceField,popupReferenceModule,formElement);if("undefined"!=typeof mappingRelatedField){var _params={module:popupReferenceModule,record:id};app.getRecordDetails(_params).done(function(data){var response=_params.data=data.result.data;app.event.trigger("EditView.SelectReference",_params,formElement,data),$.each(mappingRelatedField,function(key,value){if(0!=response[value[0]]){var mapFieldElement=formElement.find("[name=\""+key+"\"]"),fieldinfo=mapFieldElement.data("fieldinfo");if("date"===data.result.type[value[0]]||"datetime"===data.result.type[value[0]])mapFieldElement.val(data.result.displayData[value[0]]);else if("multipicklist"===data.result.type[value[0]]){var mapFieldElementMultiselect=formElement.find("[name=\""+key+"[]\"]");if(0<mapFieldElementMultiselect.length){var multipleAttr=mapFieldElementMultiselect.attr("multiple"),splitValues=response[value[0]].split(" |##| ");"undefined"!=typeof multipleAttr&&!1!==multipleAttr&&0<splitValues.length&&mapFieldElementMultiselect.val(splitValues).trigger("change");}}else if(!mapFieldElement.is("select"))0==mapFieldElement.length?$("<input type='hidden'/>").attr("name",key).attr("value",response[value[0]]).appendTo(formElement):mapFieldElement.val(response[value[0]]);else if(mapFieldElement.find("option[value=\""+response[value[0]]+"\"]").length)mapFieldElement.val(response[value[0]]).trigger("change");else if(mapFieldElement.data("fieldinfo").picklistvalues.hasOwnProperty(response[value[0]])){var newOption=new Option(response[value[0]],response[value[0]],!0,!0);mapFieldElement.append(newOption).trigger("change");}var mapFieldDisplayElement=formElement.find("input[name=\""+key+"_display\"]");if(0<mapFieldDisplayElement.length&&(mapFieldDisplayElement.val(data.result.displayData[value[0]]).attr("readonly",!0),"reference"===fieldinfo.type)){var referenceModulesList=mapFieldElement.closest(".fieldValue").find(".referenceModulesList");0<referenceModulesList.length&&value[1]&&referenceModulesList.val(value[1]).trigger("change"),thisInstance.setReferenceFieldValue(mapFieldDisplayElement.closest(".fieldValue"),{name:data.result.displayData[value[0]],id:response[value[0]]});}}});});}},getRelationOperation:function getRelationOperation(){if(""===this.relationOperation){var relationOperation=$("[name=\"relationOperation\"]");this.relationOperation=!!relationOperation.length&&relationOperation.val();}return this.relationOperation},proceedRegisterEvents:function proceedRegisterEvents(){return 0<$(".recordEditView").length},referenceModulePopupRegisterEvent:function referenceModulePopupRegisterEvent(container){var _this3=this;container.on("click",".relatedPopup",function(e){_this3.showRecordsList(e);});var moduleList=container.find(".referenceModulesList");App.Fields.Picklist.showSelect2ElementView(container.find(".referenceModulesList:visible")),moduleList.on("change",function(e){var element=$(e.currentTarget),parentElem=element.closest(".fieldValue"),popupReferenceModule=element.val(),referenceModuleElement=$("input[name=\"popupReferenceModule\"]",parentElem),prevSelectedReferenceModule=referenceModuleElement.val();referenceModuleElement.val(popupReferenceModule),prevSelectedReferenceModule!=popupReferenceModule&&parentElem.find(".clearReferenceSelection").trigger("click");});},getReferencedModuleName:function getReferencedModuleName(parenElement){return $("input[name=\"popupReferenceModule\"]",parenElement).val()},searchModuleNames:function searchModuleNames(params){var aDeferred=$.Deferred();return "undefined"==typeof params.module&&(params.module=this.moduleName),"undefined"==typeof params.action&&(params.action="BasicAjax"),AppConnector.request(params).done(function(data){aDeferred.resolve(data);}).fail(function(error){aDeferred.reject();}),aDeferred.promise()},/**
         * Function to get reference search params
         */getReferenceSearchParams:function getReferenceSearchParams(element){var tdElement=$(element).closest(".fieldValue"),params={},searchModule=this.getReferencedModuleName(tdElement);return params.search_module=searchModule,params},/**
         * Function which will handle the reference auto complete event registrations
         * @params - container <jQuery> - element in which auto complete fields needs to be searched
         */registerAutoCompleteFields:function registerAutoCompleteFields(container){var thisInstance=this,formElement=container.closest("form");container.find("input.autoComplete").autocomplete({delay:"600",minLength:"3",source:function source(request,response){//element will be array of dom elements
//here this refers to auto complete instance
var inputElement=$(this.element[0]),searchValue=request.term,params=thisInstance.getReferenceSearchParams(inputElement);params.search_value=searchValue;var sourceRecordElement=$("input[name=\"record\"]",formElement);0<sourceRecordElement.length&&sourceRecordElement.val()&&(params.src_record=sourceRecordElement.val()),thisInstance.searchModuleNames(params).done(function(data){var reponseDataList=[],serverDataFormat=data.result;for(var id in 0>=serverDataFormat.length&&($(inputElement).val(""),serverDataFormat=new Array({label:app.vtranslate("JS_NO_RESULTS_FOUND"),type:"no results"})),serverDataFormat){var responseData=serverDataFormat[id];reponseDataList.push(responseData);}response(reponseDataList),app.event.trigger("EditView.AfterSearch",{field:inputElement,params:params});});},select:function select(event,ui){var selectedItemData=ui.item;//To stop selection if no results is selected
if("undefined"!=typeof selectedItemData.type&&"no results"==selectedItemData.type)return !1;selectedItemData.name=selectedItemData.value;var element=$(this),tdElement=element.closest(".fieldValue");thisInstance.setReferenceFieldValue(tdElement,selectedItemData);},change:function change(event,ui){var element=$(this);//if you dont have readonly attribute means the user didnt select the item
element.attr("readonly")==null&&element.closest(".fieldValue").find(".clearReferenceSelection").trigger("click");},open:function open(event,ui){//To Make the menu come up in the case of quick create
$(this).data("ui-autocomplete").menu.element.css("z-index","100001");},position:{collision:"flipfit"}});},/**
         * Function which will register reference field clear event
         * @params - container <jQuery> - element in which auto complete fields needs to be searched
         */registerClearReferenceSelectionEvent:function registerClearReferenceSelectionEvent(container){var thisInstance=this;container.on("click",".clearReferenceSelection",function(e){var element=$(e.currentTarget);thisInstance.clearFieldValue(element),element.closest(".fieldValue").find(".sourceField").trigger(Vtiger_Edit_Js.referenceDeSelectionEvent),e.preventDefault();});},clearFieldValue:function clearFieldValue(element){var self=this,fieldValueContener=element.closest(".fieldValue"),fieldNameElement=fieldValueContener.find(".sourceField"),fieldName=fieldNameElement.attr("name"),referenceModule=fieldValueContener.find("input[name=\"popupReferenceModule\"]").val(),formElement=fieldValueContener.closest("form");"reference"==fieldNameElement.data("fieldtype")?fieldNameElement.val(0):fieldNameElement.val(""),fieldValueContener.find("#"+fieldName+"_display").removeAttr("readonly").val(""),app.event.trigger("EditView.ClearField",{fieldName:fieldName,referenceModule:referenceModule});var mappingRelatedField=this.getMappingRelatedField(fieldName,referenceModule,formElement);$.each(mappingRelatedField,function(key,value){var mapFieldElement=formElement.find("[name=\""+key+"\"]");mapFieldElement.is("select")?mapFieldElement.val(mapFieldElement.find("option:first").val()).trigger("change"):mapFieldElement.val("");var mapFieldDisplayElement=formElement.find("input[name=\""+key+"_display\"]");if(0<mapFieldDisplayElement.length){mapFieldDisplayElement.val("").attr("readonly",!1);var referenceModulesList=formElement.find("#"+self.moduleName+"_editView_fieldName_"+key+"_dropDown");0<referenceModulesList.length&&value[1]&&referenceModulesList.val(referenceModulesList.find("option:first").val()).trigger("change");}});},/**
         * Function which will register event to prevent form submission on pressing on enter
         * @params - container <jQuery> - element in which auto complete fields needs to be searched
         */registerPreventingEnterSubmitEvent:function registerPreventingEnterSubmitEvent(container){container.on("keypress",function(e){//Stop the submit when enter is pressed in the form
var currentElement=$(e.target);13!=e.which||currentElement.is("textarea")||e.preventDefault();});},registerTimeFields:function registerTimeFields(container){app.registerEventForClockPicker(),App.Fields.Date.register(container),App.Fields.DateTime.register(container);},referenceCreateHandler:function referenceCreateHandler(container){var _this4=this,formData=this.getForm().serializeFormData();for(var i in formData)formData[i]&&-1==$.inArray(i,["_csrf","action"])||delete formData[i];App.Components.QuickCreate.createRecord(this.getReferencedModuleName(container),{data:{sourceModule:formData.module,sourceRecordData:formData},callbackFunction:function callbackFunction(data){_this4.setReferenceFieldValue(container,{name:data.result._recordLabel,id:data.result._recordId});},noCache:!0});},/**
         * Function which will register event for create of reference record
         * This will allow users to create reference record from edit view of other record
         */registerReferenceCreate:function registerReferenceCreate(container){var thisInstance=this;container.on("click",".createReferenceRecord",function(e){var element=$(e.currentTarget),controlElementDiv=element.closest(".fieldValue");thisInstance.referenceCreateHandler(controlElementDiv);});},addressFieldsMapping:["buildingnumber","localnumber","addresslevel1","addresslevel2","addresslevel3","addresslevel4","addresslevel5","addresslevel6","addresslevel7","addresslevel8","pobox"],addressFieldsMappingBlockID:{LBL_ADDRESS_INFORMATION:"a",LBL_ADDRESS_BILLING:"a",LBL_ADDRESS_MAILING_INFORMATION:"b",LBL_ADDRESS_SHIPPING:"b",LBL_ADDRESS_DELIVERY_INFORMATION:"c"},addressFieldsData:!1,/**
         * Function to register event for copying addresses
         */registerEventForCopyAddress:function registerEventForCopyAddress(){var thisInstance=this;this.formElement.find(".js-toggle-panel:not(.inventoryHeader):not(.inventoryItems) .fieldValue, .js-toggle-panel:not(.inventoryHeader):not(.inventoryItems) .fieldLabel").each(function(){var block=$(this),referenceModulesList=block.find(".referenceModulesList");if(0<referenceModulesList.length)referenceModulesList.on("change",function(){thisInstance.formElement.find("[class*=\"copyAddressFrom\"]:not(.copyAddressFromMain, .copyAddressFromMailing)").addClass("d-none"),thisInstance.registerEventForCopyBlockAddress($(this).val(),block.find(".sourceField").attr("name"));}),referenceModulesList.trigger("change");else {var referenceFields=block.find("[name=\"popupReferenceModule\"]");0<referenceFields.length&&thisInstance.registerEventForCopyBlockAddress(referenceFields.val(),block.find(".sourceField").attr("name"));}}),this.formElement.find(".js-toggle-panel").each(function(){var hideCopyAddressLabel=!0;$(this).find(".adressAction button").each(function(){!1==$(this).hasClass("d-none")&&(hideCopyAddressLabel=!1);}),hideCopyAddressLabel&&$(this).find(".copyAddressLabel").addClass("d-none");}),this.formElement.find(".copyAddressFromMain").on("click",function(e){var element=$(this),block=element.closest(".js-toggle-panel"),from=element.data("label"),to=block.data("label");thisInstance.copyAddress(from,to,!1,!1);}),this.formElement.find(".copyAddressFromMailing").on("click",function(e){var element=$(this),block=element.closest(".js-toggle-panel"),from=element.data("label"),to=block.data("label");thisInstance.copyAddress(from,to,!1,!1);}),this.formElement.find(".copyAddressFromDelivery").on("click",function(e){var element=$(this),block=element.closest(".js-toggle-panel"),from=element.data("label"),to=block.data("label");thisInstance.copyAddress(from,to,!1,!1);});},registerEventForCopyBlockAddress:function registerEventForCopyBlockAddress(moduleName,fieldName){var self=this;"Accounts"==moduleName?self.enableCopyAddressFromModule(moduleName,self.formElement,"copyAddressFromAccount",fieldName,"JS_PLEASE_SELECT_AN_ACCOUNT_TO_COPY_ADDRESS"):"Contacts"==moduleName?self.enableCopyAddressFromModule(moduleName,self.formElement,"copyAddressFromContact",fieldName,"JS_PLEASE_SELECT_AN_CONTACT_TO_COPY_ADDRESS"):"Leads"==moduleName?self.enableCopyAddressFromModule(moduleName,self.formElement,"copyAddressFromLead",fieldName,"JS_PLEASE_SELECT_AN_LEAD_TO_COPY_ADDRESS"):"Vendors"==moduleName&&self.enableCopyAddressFromModule(moduleName,self.formElement,"copyAddressFromVendor",fieldName,"JS_PLEASE_SELECT_AN_VENDOR_TO_COPY_ADDRESS");},/**
         * Show button to copy the address details from selected module
         */enableCopyAddressFromModule:function enableCopyAddressFromModule(moduleName,formElement,className,fieldName,label){var thisInstance=this;formElement.find("."+className).removeClass("d-none").on("click",function(e){var element=$(this),recordRelativeAccountId=$("[name=\""+fieldName+"\"]").val();if(""==recordRelativeAccountId||"0"==recordRelativeAccountId)app.showNotify({text:app.vtranslate(label),type:"error"});else {var recordRelativeAccountName=$("#"+fieldName+"_display").val(),data={record:recordRelativeAccountId,selectedName:recordRelativeAccountName,module:moduleName};thisInstance.copyAddressDetails(element.data("label"),element.closest(".js-toggle-panel").data("label"),data,element.closest(".js-toggle-panel")),element.attr("checked","checked");}});},/**
         * Function which will copy the address details
         */copyAddressDetails:function copyAddressDetails(from,to,data,container){var _this5=this;app.getRecordDetails(data).done(function(response){_this5.addressFieldsData=response.result,_this5.copyAddress(from,to,!0,data.module),app.event.trigger("Edit.CopyAddress",_this5,from,to,response,data,container);});},/**
         * Function to copy address between fields
         * @param strings which accepts value as either odd or even
         */copyAddress:function copyAddress(fromLabel,toLabel,relatedRecord,sourceModule){var thisInstance=this,formElement=this.getForm(),status=!1,addressMapping=this.addressFieldsMapping,BlockIds=this.addressFieldsMappingBlockID,from=BlockIds[fromLabel];(!1===relatedRecord||!1===sourceModule)&&(from=BlockIds[fromLabel]);var key,fromElement,fromElementLabel,nameElementFrom,nameElementTo,to=BlockIds[toLabel];for(key in addressMapping){nameElementFrom=addressMapping[key]+from,nameElementTo=addressMapping[key]+to,relatedRecord?(fromElement=thisInstance.addressFieldsData.data[nameElementFrom],fromElementLabel=thisInstance.addressFieldsData.displayData[nameElementFrom]):(fromElement=formElement.find("[name=\""+nameElementFrom+"\"]").val(),fromElementLabel=formElement.find("[name=\""+nameElementFrom+"_display\"]").val());var toElement=formElement.find("[name=\""+nameElementTo+"\"]"),toElementLable=formElement.find("[name=\""+nameElementTo+"_display\"]");""!==fromElement&&"0"!==fromElement&&fromElement!==void 0?(0<toElementLable.length&&toElementLable.attr("readonly",!0),status=!0,toElement.val(fromElement),toElementLable.val(fromElementLabel),toElement.is("[data-select2-id]")&&(toElement.val()!==fromElement&&toElement.val(""),toElement.trigger("change"))):(toElement.val(""),toElement.attr("readonly",!1));}if(!1===status){var errorMsg;errorMsg="Accounts"===sourceModule?"JS_SELECTED_ACCOUNT_DOES_NOT_HAVE_AN_ADDRESS":"Contacts"===sourceModule?"JS_SELECTED_CONTACT_DOES_NOT_HAVE_AN_ADDRESS":"JS_DOES_NOT_HAVE_AN_ADDRESS",app.showNotify({text:app.vtranslate(errorMsg),type:"error"});}},registerReferenceSelectionEvent:function registerReferenceSelectionEvent(container){var thisInstance=this,relategField=container.find("input[name*='addresslevel']");relategField.on(Vtiger_Edit_Js.referenceSelectionEvent,function(e,data){var blockContainer=$(e.currentTarget).closest(".js-toggle-panel");thisInstance.copyAddressDetailsRef(data,blockContainer);});},copyAddressDetailsRef:function copyAddressDetailsRef(data,container){var thisInstance=this;app.getRecordDetails(data).done(function(data){var response=data.result;thisInstance.mapAddressDetails(response,container);}).fail(function(error,err){});},mapAddressDetails:function mapAddressDetails(result,container){for(var key in result)-1!=key.indexOf("addresslevel")&&(0!=container.find("[name=\""+key+"\"]").length&&(container.find("[name=\""+key+"\"]").val(result.data[key]),container.find("[name=\""+key+"\"]").attr("readonly",!0),container.find("[name=\""+key+"_display\"]").val(result.displayData[key]),container.find("[name=\""+key+"_display\"]").attr("readonly",!0)),0!=container.find("[name=\""+key+"a\"]").length&&0==container.find("[name=\""+key+"a\"]").val()&&0!=result.data[key]&&(container.find("[name=\""+key+"a\"]").val(result.data[key]),container.find("[name=\""+key+"a\"]").attr("readonly",!0),container.find("[name=\""+key+"a_display\"]").val(result.displayData[key]),container.find("[name=\""+key+"a_display\"]").attr("readonly",!0)),0!=container.find("[name=\""+key+"b\"]").length&&0==container.find("[name=\""+key+"b\"]").val()&&0!=result.data[key]&&(container.find("[name=\""+key+"b\"]").val(result.data[key]),container.find("[name=\""+key+"b\"]").attr("readonly",!0),container.find("[name=\""+key+"b_display\"]").val(result.displayData[key]),container.find("[name=\""+key+"b_display\"]").attr("readonly",!0)),0!=container.find("[name=\""+key+"c\"]").length&&0==container.find("[name=\""+key+"c\"]").val()&&0!=result.data[key]&&(container.find("[name=\""+key+"c\"]").val(result.data[key]),container.find("[name=\""+key+"c\"]").attr("readonly",!0),container.find("[name=\""+key+"c_display\"]").val(result.displayData[key]),container.find("[name=\""+key+"c_display\"]").attr("readonly",!0)));},registerMaskFields:function registerMaskFields(container){container.find("[data-inputmask]").inputmask();},registerSubmitEvent:function registerSubmitEvent(){var editViewForm=this.getForm();editViewForm.on("submit",function(e){//Form should submit only once for multiple clicks also
if("undefined"!=typeof editViewForm.data("submit"))return !1;if(document.progressLoader=$.progressIndicator({message:app.vtranslate("JS_SAVE_LOADER_INFO"),position:"html",blockInfo:{enabled:!0}}),editViewForm.find(".js-toggle-panel").find(".js-block-content").removeClass("d-none"),editViewForm.validationEngine("validate")){editViewForm.data("submit","true");//on submit form trigger the recordPreSave event
var recordPreSaveEvent=$.Event(Vtiger_Edit_Js.recordPreSave);editViewForm.trigger(recordPreSaveEvent,{value:"edit"}),recordPreSaveEvent.isDefaultPrevented()&&(document.progressLoader.progressIndicator({mode:"hide"}),editViewForm.removeData("submit"),e.preventDefault());}else//If validation fails, form should submit again
document.progressLoader.progressIndicator({mode:"hide"}),editViewForm.removeData("submit"),app.formAlignmentAfterValidation(editViewForm);});},/*
         * Function to check the view permission of a record after save
         */registerRecordPreSaveEventEvent:function registerRecordPreSaveEventEvent(form){var _this6=this;form.on(Vtiger_Edit_Js.recordPreSave,function(e,data){_this6.preSaveValidation(form).done(function(response){!0!==response&&e.preventDefault();});});},preSaveValidation:function preSaveValidation(form){var aDeferred=$.Deferred();if(form.find("#preSaveValidation").val()){document.progressLoader=$.progressIndicator({message:app.vtranslate("JS_SAVE_LOADER_INFO"),position:"html",blockInfo:{enabled:!0}});var formData=new FormData(form[0]);formData.append("mode","preSaveValidation"),AppConnector.request({async:!1,url:"index.php",type:"POST",data:formData,processData:!1,contentType:!1}).done(function(data){document.progressLoader.progressIndicator({mode:"hide"});var response=data.result,_loop2=function _loop2(i){if(!0!==response[i].result){if("confirm"===response[i].type&&"undefined"!=typeof response[i].hash)return app.showConfirmModal({text:response[i].message||"",confirmedCallback:function confirmedCallback(){var handlers={},handlerElement=form.find("input[name=\"skipHandlers\"]");handlerElement.length&&(handlers=JSON.parse(handlerElement.val()),handlerElement.remove()),handlers[i]=response[i].hash,form.append($("<input>",{name:"skipHandlers",value:JSON.stringify(handlers),type:"hidden"})),form.submit();}}),aDeferred.resolve(!1),1;// break
"undefined"!=typeof response[i].showModal&&"undefined"!=typeof response[i].showModal.url?app.showModalWindow(null,response[i].showModal.url,function(modalContainer){app.registerModalController(void 0,modalContainer,function(_,instance){instance.formContainer=form;});}):app.showNotify({text:response[i].message?response[i].message:app.vtranslate("JS_ERROR"),type:"error"});response[i].hoverField!=null&&form.find("[name=\""+response[i].hoverField+"\"]").focus();}};for(var i in response)if(_loop2(i))break;aDeferred.resolve(0>=data.result.length);}).fail(function(textStatus,errorThrown){document.progressLoader.progressIndicator({mode:"hide"}),app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}),app.errorLog(textStatus,errorThrown),aDeferred.resolve(!1);});}else aDeferred.resolve(!0);return aDeferred.promise()},registerLeavePageWithoutSubmit:function registerLeavePageWithoutSubmit(form){if("undefined"!=typeof CKEDITOR&&"undefined"!=typeof CKEDITOR.instances&&Object.keys(CKEDITOR.instances).length)CKEDITOR.on("instanceReady",function(e){var initialFormData=form.serialize();window.onbeforeunload=function(e){if(initialFormData!=form.serialize()&&"true"!=form.data("submit"))return app.vtranslate("JS_CHANGES_WILL_BE_LOST")};});else {var initialFormData=form.serialize();window.onbeforeunload=function(e){if(initialFormData!=form.serialize()&&"true"!=form.data("submit"))return app.vtranslate("JS_CHANGES_WILL_BE_LOST")};}},stretchCKEditor:function stretchCKEditor(){var row=$(".js-editor").parents(".fieldRow"),td=$(".js-editor").parent();$(row).find(".fieldLabel").remove(),$(td).removeClass("col-md-10"),$(td).addClass("col-md-12");},/**
         * Function to register event for ckeditor for description field
         */registerEventForEditor:function registerEventForEditor(){var _this7=this,form=this.getForm();$.each(form.find(".js-editor:not(.js-inventory-item-comment)"),function(key,data){_this7.loadEditorElement($(data));});},loadEditorElement:function loadEditorElement(noteContentElement){App.Fields.Text.Editor.register(noteContentElement);},registerHelpInfo:function registerHelpInfo(form){form||(form=this.getForm()),app.showPopoverElementView(form.find(".js-help-info"));},registerBlockStatusCheckOnLoad:function registerBlockStatusCheckOnLoad(){var blocks=this.getForm().find(".js-toggle-panel"),module=this.moduleName;blocks.each(function(index,block){var currentBlock=$(block);0!==currentBlock.find(".js-field-block-column").length&&0===currentBlock.find(".js-field-block-column:not(.d-none)").length&&currentBlock.addClass("d-none");var dynamicAttr=currentBlock.attr("data-dynamic");if(_typeof(dynamicAttr)!==("undefined"==typeof void 0?"undefined":_typeof(void 0))&&!1!==dynamicAttr){var headerAnimationElement=currentBlock.find(".js-block-toggle").not(".d-none"),bodyContents=currentBlock.find(".blockContent"),blockId=headerAnimationElement.data("id"),cacheKey=module+"."+blockId,value=app.cacheGet(cacheKey,null);null!=value&&(1==value?(headerAnimationElement.addClass("d-none"),currentBlock.find("[data-mode='show']").removeClass("d-none"),bodyContents.removeClass("d-none")):(headerAnimationElement.addClass("d-none"),currentBlock.find("[data-mode='hide']").removeClass("d-none"),bodyContents.addClass("d-none")));}});},/**
         * Visibility check block
         */checkVisibilityBlocks:function checkVisibilityBlocks(){this.getForm().find(".js-toggle-panel").each(function(index,block){var currentBlock=$(block);0!==currentBlock.find(".js-field-block-column").length&&(0===currentBlock.find(".js-field-block-column:not(.d-none)").length?currentBlock.addClass("d-none"):currentBlock.removeClass("d-none"));});},registerAutoloadAddress:function registerAutoloadAddress(){var self=this;this.getForm().find(".js-search-address").each(function(_index,e){var search=$(e),container=search.closest(".js-block-content"),input=search.find(".js-autoload-address");input.autocomplete({source:function source(request,response){AppConnector.request({module:self.moduleName,action:"Fields",mode:"findAddress",type:search.find(".js-select-operator").val(),value:request.term}).done(function(requestData){!1===requestData.result?app.showNotify({text:app.vtranslate("JS_ERROR"),type:"error"}):requestData.result.length?response(requestData.result):response([{label:app.vtranslate("JS_NO_RESULTS_FOUND"),value:""}]);}).fail(function(_textStatus,_errorThrown,jqXHR){app.showNotify({text:jqXHR.responseJSON.error.message,type:"error",animation:"show"}),response([{label:app.vtranslate("JS_NO_RESULTS_FOUND"),value:""}]);});},minLength:input.data("min"),select:function select(_event,ui){$.each(ui.item.address,function(index,value){var field=container.find(".fieldValue [name^="+index+"]");field.length&&value?("object"!==_typeof(value)&&(value=[value]),$.each(value,function(_idx,v){var select=!1,element=!1;"SELECT"===field.prop("tagName")?"object"===_typeof(v)?$.each(v,function(idx,x){element=field.find("option[data-"+idx+"='"+x+"']"),x&&element.length&&(select=element.val());}):(element=field.find("option:contains("+v+")"),v&&element.length&&(select=element.val()),element=field.find("option[value=\""+v+"\"]"),v&&element.length&&(select=element.val())):select=v,select&&field.val(select).change();})):field.val("").change();}),ui.item.value=input.val();}}).autocomplete("instance")._renderItem=function(ul,item){return $("<li>").append("<div><span class=\"fi fi-".concat(item.countryCode," mr-2\"></span>").concat(item.label,"</div>")).appendTo(ul)};});},setEnabledFields:function setEnabledFields(element){var fieldValue=element.closest(".fieldValue"),fieldName=fieldValue.find("input.sourceField").attr("name"),fieldDisplay=fieldValue.find("#"+fieldName+"_display");fieldValue.find("button").removeAttr("disabled"),""==fieldDisplay.val()&&fieldValue.find("input").removeAttr("readonly"),fieldValue.find(".referenceModulesListGroup").removeClass("d-none");var placeholder=fieldDisplay.attr("placeholderDisabled");fieldDisplay.removeAttr("placeholderDisabled"),fieldDisplay.attr("placeholder",placeholder),fieldValue.find(".referenceModulesList").attr("required","required");},setDisabledFields:function setDisabledFields(element){var fieldValue=element.closest(".fieldValue"),fieldName=fieldValue.find("input.sourceField").attr("name"),fieldDisplay=fieldValue.find("#"+fieldName+"_display");fieldValue.find("input").attr("readonly","readonly"),fieldValue.find("button").attr("disabled","disabled"),fieldValue.find(".referenceModulesListGroup").addClass("d-none");var placeholder=fieldDisplay.attr("placeholder");fieldDisplay.removeAttr("placeholder"),fieldDisplay.attr("placeholderDisabled",placeholder),fieldValue.find(".referenceModulesList").removeAttr("required");},getMappingRelatedField:function getMappingRelatedField(sourceField,sourceFieldModule,container){var mappingRelatedField=container.find("input[name=\"mappingRelatedField\"]").val(),mappingRelatedModule=mappingRelatedField?JSON.parse(mappingRelatedField):[];return "undefined"!=typeof mappingRelatedModule[sourceField]&&"undefined"!=typeof mappingRelatedModule[sourceField][sourceFieldModule]?mappingRelatedModule[sourceField][sourceFieldModule]:[]},registerValidationsFields:function registerValidationsFields(container){var params=app.validationEngineOptionsForRecord;container.validationEngine(params);},checkReferencesField:function checkReferencesField(container,clear){var thisInstance=this,activeProcess=!1,activeSubProcess=!1;return !!CONFIG.fieldsReferencesDependent&&void(container.find("input[data-fieldtype=\"referenceLink\"]").each(function(index,element){element=$(element);var t=!0;0<element.closest(".tab-pane").length&&(t=!1,0<element.closest(".tab-pane.active").length&&(t=!0));var referenceLink=element.val();t&&""!=referenceLink&&"0"!=referenceLink&&(activeProcess=!0);}),container.find("input[data-fieldtype=\"referenceProcess\"]").each(function(index,element){element=$(element),activeProcess?thisInstance.setEnabledFields(element):(clear&&thisInstance.clearFieldValue(element),thisInstance.setDisabledFields(element));var t=!0;0<element.closest(".tab-pane").length&&(t=!1,0<element.closest(".tab-pane.active").length&&(t=!0));var referenceLink=element.val();t&&""!=referenceLink&&"0"!=referenceLink&&(activeSubProcess=!0);}),container.find("input[data-fieldtype=\"referenceSubProcess\"]").each(function(index,element){element=$(element);var processfieldElement=element.closest(".fieldValue"),length=processfieldElement.find(".referenceModulesList option[disabled!=\"disabled\"]").length;activeSubProcess&&0<length?thisInstance.setEnabledFields(element):(clear&&thisInstance.clearFieldValue(element),thisInstance.setDisabledFields(element));}))},checkSubProcessModulesList:function checkSubProcessModulesList(element){var option=element.find("option:selected");1==option.data("is-quickcreate")?element.closest(".fieldValue").find(".createReferenceRecord").removeClass("d-none"):element.closest(".fieldValue").find(".createReferenceRecord").addClass("d-none");},checkReferenceModulesList:function checkReferenceModulesList(container){var thisInstance=this,processfieldElement=container.find("input[data-fieldtype=\"referenceProcess\"]").closest(".fieldValue"),referenceProcess=processfieldElement.find("input[name=\"popupReferenceModule\"]").val(),subProcessfieldElement=container.find("input[data-fieldtype=\"referenceSubProcess\"]").closest(".fieldValue");Vtiger_Helper_Js.hideOptions(subProcessfieldElement.find(".referenceModulesList"),"parent",referenceProcess);var subProcessValue=subProcessfieldElement.find(".referenceModulesList").val();subProcessfieldElement.find("[name=\"popupReferenceModule\"]").val(subProcessValue),thisInstance.checkSubProcessModulesList(subProcessfieldElement.find(".referenceModulesList"));},registerReferenceFields:function registerReferenceFields(container){var thisInstance=this;return !!CONFIG.fieldsReferencesDependent&&void(thisInstance.checkReferenceModulesList(container),thisInstance.checkReferencesField(container,!1),container.find(".sourceField").on(Vtiger_Edit_Js.referenceSelectionEvent,function(e,data){thisInstance.checkReferencesField(container,!0);}),container.find(".sourceField").on(Vtiger_Edit_Js.referenceDeSelectionEvent,function(e){thisInstance.checkReferencesField(container,!0);}),container.find("input[data-fieldtype=\"referenceProcess\"]").closest(".fieldValue").find(".referenceModulesList").on("change",function(){thisInstance.checkReferenceModulesList(container);}),container.find("input[data-fieldtype=\"referenceSubProcess\"]").closest(".fieldValue").find(".referenceModulesList").on("change",function(e){thisInstance.checkSubProcessModulesList($(e.currentTarget));}))},registerFocusFirstField:function registerFocusFirstField(container,afterTimeout){var elementToFocus,elementToFocusTabindex,_this8=this;return void 0===afterTimeout&&container.closest(".js-modal-container").length?void setTimeout(function(_){_this8.registerFocusFirstField(container,!0);},500):void(container.find(".fieldValue input.form-control:not([type=hidden],.dateField,.clockPicker), .fieldValue input[type=checkbox], .select2-selection.form-control").each(function(i,e){var element=$(e);if(!element.prop("readonly")&&!element.prop("disabled")){if(element=element.get(0),"number"!==element.type&&"checkbox"!==element.type&&void 0!==element.value){var elemLen=element.value.length;element.selectionStart=elemLen,element.selectionEnd=elemLen;}0!==i&&elementToFocus||(elementToFocus=element);var tabindex=$(element).attr("tabindex");if(0<tabindex&&void 0===elementToFocusTabindex)return void(elementToFocusTabindex=tabindex);0<tabindex&&tabindex<elementToFocusTabindex&&(elementToFocusTabindex=tabindex,elementToFocus=element);}}),elementToFocus&&elementToFocus.focus())},registerCopyValue:function registerCopyValue(container){container.find(".fieldValue [data-copy-to-field]").on("change",function(e){var element=$(e.currentTarget);container.find("[name=\""+element.data("copyToField")+"\"]").val(element.val());});},/**
         * Register multi image upload fields
         * @param {HTMLElement|jQuery} container
         */registerMultiImageFields:function registerMultiImageFields(container){return App.Fields.MultiImage.register(container)},/**
         * Register inventory controller
         * @param {jQuery} container
         */registerInventoryController:function registerInventoryController(container){"undefined"!=typeof Vtiger_Inventory_Js&&(this.inventoryController=Vtiger_Inventory_Js.getInventoryInstance(container));},/**
         * Register record collector modal
         * @param {jQuery} container
         */registerRecordCollectorModal:function registerRecordCollectorModal(container){var self=this;container.on("click",".js-record-collector-modal",function(e){e.preventDefault();var element=$(this),formData=container.serializeFormData();formData.view="RecordCollector",formData.collectorType=element.data("type"),delete formData.action,AppConnector.request(formData).done(function(html){app.showModalWindow(html,function(container){var modalForm=container.find("form.js-record-collector__form"),summary=container.find(".js-record-collector__summary");modalForm.validationEngine(app.validationEngineOptions),modalForm.on("submit",function(e){modalForm.validationEngine("validate")&&(summary.html(""),summary.progressIndicator({}),e.preventDefault(),AppConnector.request(modalForm.serializeFormData()).done(function(data){summary.progressIndicator({mode:"hide"}),summary.html(data);}));});var recordForm=self.getForm();container.on("click",".js-record-collector__select",function(){container.find(".js-record-collector__column[data-column=\"".concat(this.dataset.column,"\"] input")).prop("checked",!0);}),container.on("click",".js-record-collector__fill_fields",function(){var formData=container.find(".js-record-collector__fill_form").serializeFormData();$.each(formData,function(key,value){if(""!==value){var fieldElement=recordForm.find("[name=\"".concat(key,"\"]"));fieldElement.length?fieldElement.setValue(value):recordForm.append("<input type=\"hidden\" name=\"".concat(key,"\" value=\"").concat(value,"\" />"));}}),app.hideModalWindow(null,"collectorModal");});},{modalId:"collectorModal"});});});},/**
         * Register account name function
         * @param {jQuery} container
         */registerAccountName:function registerAccountName(container){var first=container.find(".js-first-name"),firstInput=first.find("input"),last=container.find(".js-last-name"),lastInput=last.find("input"),full=container.find(".js-account-name"),fullInput=full.find("input"),legalForm=container.find("select[name=\"legal_form\"]"),legalFormVal=legalForm.val();firstInput.keyup(function(){fullInput.val(this.value+"|##|"+lastInput.val());}),lastInput.keyup(function(){fullInput.val(firstInput.val()+"|##|"+this.value);}),legalForm.change(function(){"PLL_NATURAL_PERSON"==this.value?(full.addClass("d-none"),fullInput.val(firstInput.val()+"|##|"+lastInput.val()),first.removeClass("d-none"),last.removeClass("d-none")):"PLL_NATURAL_PERSON"==legalFormVal&&(full.removeClass("d-none"),first.addClass("d-none"),last.addClass("d-none"),fullInput.val("")),legalFormVal=this.value;});},/**
         * Trigger record edit view events
         * @param {object} data
         */triggerRecordEditEvents:function triggerRecordEditEvents(data){var self=this,form=this.getForm();"object"==_typeof(data.changeValues)&&$.each(data.changeValues,function(_,field){self.setFieldValue(field);}),"undefined"!=typeof data.changeOptions&&$.each(data.changeOptions,function(fieldName,options){self.setFieldOptions(fieldName,options);}),"undefined"!=typeof data.hoverField&&form.find("[name=\"".concat(data.hoverField,"\"]")).focus(),"undefined"!=typeof data.showNotify&&app.showNotify(data.showNotify),"undefined"!=typeof data.showModal&&app.showModalWindow(null,data.showModal.url),"undefined"!=typeof data.showFields&&$.each(data.showFields,function(_,fieldName){form.find(".js-field-block-column[data-field=\"".concat(fieldName,"\"]")).removeClass("d-none"),self.checkVisibilityBlocks();}),"undefined"!=typeof data.hideFields&&$.each(data.hideFields,function(_,fieldName){form.find(".js-field-block-column[data-field=\"".concat(fieldName,"\"]")).addClass("d-none"),self.checkVisibilityBlocks();});},/**
         * Set field value
         * @param {object} params
         */setFieldValue:function setFieldValue(params){var fieldElement=this.getForm().find("[name=\"".concat(params.fieldName,"\"]")),fieldInfo=fieldElement.data("fieldinfo");fieldElement.is("select")?fieldElement.find("option[value=\"".concat(params.value,"\"]")).length?fieldElement.val(params.value).trigger("change"):fieldInfo.picklistvalues.hasOwnProperty(params.value)&&fieldElement.append(new Option(params.value,params.value,!0,!0)).trigger("change"):"checkbox"==fieldElement.attr("type")?fieldElement.prop("checked","1"==params.value).trigger("change"):"reference"===fieldElement.data("fieldtype")?this.setReferenceFieldValue(fieldElement.closest(".js-field-block-column"),{id:params.value,name:params.display}):fieldElement.val(params.value);},/**
         * Set field options
         * @param {string} fieldName
         * @param {object} options
         */setFieldOptions:function setFieldOptions(fieldName,options){var fieldElement=this.getForm().find("[name=\"".concat(fieldName,"\"]")),fieldInfo=fieldElement.data("fieldinfo");if(fieldElement.is("select")&&fieldInfo){var _fieldElement$val,val=null!==(_fieldElement$val=fieldElement.val())&&void 0!==_fieldElement$val?_fieldElement$val:"",fieldValue=fieldElement.closest(".fieldValue"),currentValues=_toConsumableArray(fieldElement.get(0).options).map(function(o){return o.value}).filter(function(e){return ""!==e}).sort(),newOptions=new $;fieldInfo.mandatory||(newOptions=newOptions.add(new Option(app.vtranslate("JS_SELECT_AN_OPTION"),"",!1,!val||!options.includes(val)))),$.each(options,function(_,e){newOptions=newOptions.add(new Option(fieldInfo.picklistvalues[e],e,!1,val==e));});var newValues=_toConsumableArray(newOptions.map(function(_,e){return e.value})).filter(function(e){return ""!==e}).sort();if(currentValues.length===newValues.length&&currentValues.every(function(e,i){return e===newValues[i]}))return;var selected=0<newOptions.filter(":selected").length;fieldElement.html(newOptions);var change=val&&val!==fieldElement.val();(""===val&&!selected||change)&&fieldElement.val(null),change&&(fieldValue.addClass("border border-info"),fieldElement.trigger("change"),setTimeout(function(){fieldValue.removeClass("border border-info");},5e3));}},/**
         * Check if pre save validation is active
         * @returns {bool}
         */checkPreSaveValidation:function checkPreSaveValidation(){var validation=!0;return "undefined"!=typeof app.pageController.getForm&&0!==app.pageController.getForm().find("#preSaveValidation").length&&(validation=1==app.pageController.getForm().find("#preSaveValidation").val()),validation},/**
         * Register change value handler events
         * @param {jQuery} container
         */registerChangeValueHandlerEvent:function registerChangeValueHandlerEvent(container){var _this9=this,event=container.find(".js-change-value-event");if(!(0>=event.length||"[]"===event.val())){var fields=JSON.parse(event.val());$.each(fields,function(_,fieldName){container.find("[name=\"".concat(fieldName,"\"],[name=\"").concat(fieldName,"[]\"]")).on("change ".concat(Vtiger_Edit_Js.referenceSelectionEvent," ").concat(Vtiger_Edit_Js.referenceDeSelectionEvent),function(){_this9.sendChangeValueHandlerEvent(container.serializeFormData());});}),this.sendChangeValueHandlerEvent(container.serializeFormData());}},/**
         * Send change value handler events
         * @param {object} formData
         */sendChangeValueHandlerEvent:function sendChangeValueHandlerEvent(formData){var _this10=this;formData.action="ChangeValueHandler",delete formData.view;var progress=$.progressIndicator({position:"html",blockInfo:{enabled:!0}});AppConnector.request(formData).done(function(response){$.each(response.result,function(_,data){_this10.triggerRecordEditEvents(data);}),progress.progressIndicator({mode:"hide"});});},/**
         * Register keyboard shortcuts events
         */registerKeyboardShortcutsEvent:function registerKeyboardShortcutsEvent(){document.addEventListener("keydown",function(event){if(event.shiftKey&&event.ctrlKey&&"KeyS"===event.code){var _form=event.target.closest("form");_form?$(_form).trigger("submit"):(_form=$(event.target).find("form"),_form.length&&_form.hasClass("recordEditView")&&_form.last().trigger("submit"));}});},/**
         * Function which will register basic events which will be used in quick create as well
         *
         */registerBasicEvents:function registerBasicEvents(container){this.registerEventForEditor(),this.stretchCKEditor(),this.referenceModulePopupRegisterEvent(container),this.registerAutoCompleteFields(container),this.registerClearReferenceSelectionEvent(container),this.registerPreventingEnterSubmitEvent(container),this.registerTimeFields(container),this.registerRecordPreSaveEventEvent(container),this.registerReferenceSelectionEvent(container),this.registerChangeValueHandlerEvent(container),this.registerMaskFields(container),this.registerHelpInfo(container),this.registerReferenceFields(container),this.registerFocusFirstField(container),this.registerCopyValue(container),this.registerMultiImageFields(container),this.registerReferenceCreate(container),this.registerRecordCollectorModal(container),this.registerAccountName(container),this.registerKeyboardShortcutsEvent(),App.Fields.MultiEmail.register(container),App.Fields.MultiDependField.register(container),App.Fields.Tree.register(container),App.Fields.MultiCurrency.register(container),App.Fields.MeetingUrl.register(container),App.Fields.ChangesJson.register(container),App.Fields.MultiReference.register(container),App.Fields.Password.register(container),App.Components.ActivityNotifier.register(container),App.Fields.MultiAttachment.register(container);},registerEvents:function registerEvents(){var editViewForm=this.getForm();this.proceedRegisterEvents()&&(this.registerInventoryController(editViewForm),app.registerBlockAnimationEvent(editViewForm),this.registerBlockStatusCheckOnLoad(),this.registerBasicEvents(editViewForm),this.registerEventForCopyAddress(),this.registerSubmitEvent(),this.registerLeavePageWithoutSubmit(editViewForm),this.registerValidationsFields(editViewForm),this.registerAutoloadAddress(),editViewForm.find(".js-form-submit-btn").prop("disabled",!1));}});
//# sourceMappingURL=Edit.min.js.map