let CommunityManagement = {
	config: {},
	jsonUser: [],
	userrole: [],
	usernotif: [],
	onlyAppZone: '1',
	printedDatesInchat: [],
	messageToResend: [],
	usersToResend: [],
	usersToBroadcast: [],
	chatsEmailArray: [],
	chatFile: null,
	currentChat: '',
	isVoiceAssistant: false,
	isBotEnabled: false,
	isChatEmpty: false,
	isNewBotChat: false,
	isChatbot: false,
	isAdmin: false,
	userEmail: null,
	isChatbotManager: false,
	isNewChat: false,
	textNoMatch: '',
	noMatchNotificationText: '',
	notifyUserNoMatch: '',
	notifyMsgNoMatch: '',
	acceptedNoMatches: 0,
	noMatchNow:0,
	needRefresh:false,
	messageNoMatch: false,
	firstStampServer: '',
	lastStampServer: '',
	activeScroll: false,
	firebaseToken: null,
	auxlist: [],
	newGroup: {
		name: '',
		img: '',
		selectedGroupUsers: []
	},
	newDistributionList: {
		name: '',
		selectedUsers: []
	},
	editDistributionList: {
		name: '',
		selectedUsers: []
	},
	loaders: {
		initializeDictionary: false,
		getChatList_SaaS: false,
		getUsers_SaaS: true,
		getPlatformConfig_SaaS: false
	},
	contactLimit: 50,
	contactPage: 0,
	usersGroup: [],
	activeService: '',
	inGroup: false,
	directChatDir: '',
	directChatDirWithContacts: false,
	usersLimit: 20,
	userspage: 0,
	activeUsersScroll: false,
	newGroupMembers: [],
	newListMembers: [],
	editListMembers: [],
	editBroadcastMembers: [],
	chatMode: null,

	resetData() {
		let self = this;
		const USER_DETAILS = JSON.parse(sessionStorage['STCMBackEnd:appUserDetails']);
		const USER = JSON.parse(sessionStorage.getItem('STCMBackEnd:user'));

		self.config = {};
		self.jsonUser = USER_DETAILS;
		self.userrole = self.jsonUser.role[0];
		self.usernotif = self.jsonUser.notif;
		self.onlyAppZone = sessionStorage['STCMBackEnd:onlyAppZone'];
		self.messageToResend = [];
		self.usersToResend = [];
		self.usersToBroadcast = [];
		// Añadir al array al usuario para no mostrarlo en la lista de contactos
		self.chatsEmailArray = [self.jsonUser.token];
		self.chatFile = null;
		self.currentChat = '';
		self.isVoiceAssistant = false;
		self.isBotEnabled = false;
		self.isChatEmpty = false;
		self.isNewBotChat = false;
		self.isChatbot= Boolean(Number(USER_DETAILS.isChatbot));
		self.isAdmin= sessionStorage.getItem('STCMBackEnd:administrator_permission') !== null;
		self.userEmail = USER ? USER.email : null;
		self.isChatbotManager= false;
		self.isChatActive = false;
		self.textNoMatch = '',
		self.noMatchNotificationText = '',
		self.notifyUserNoMatch = '',
		self.notifyMsgNoMatch = '',
		self.acceptedNoMatches = 0,
		self.noMatchNow = 0,
		self.needRefresh = false,
		self.messageNoMatch = false,
		self.isNewChat = false,
		self.firstStampServer = '';
		self.lastStampServer = '';
		self.activeScroll = false;
		document.body.style.setProperty('--maincoloropacity03', getComputedStyle(document.body).getPropertyValue('--maincolor') + '4c');
		self.contactLimit = 50;
		self.contactPage = 0;
		self.usersGroup = [];
		self.activeService = '';
		self.inGroup = false;
		self.directChatDir = '';
		self.directChatDirWithContacts = false;
		self.usersLimit = 20;
		self.userspage = 0;
		self.activeUsersScroll = false;
		self.newGroupMembers = [];
		self.newListMembers = [];
		self.editListMembers = [];
		self.editBroadcastMembers = [];
	},

	resetDataNewGroup() {
		let self = this;

		self.newGroup = {
			name: '',
			img: '',
			selectedGroupUsers: []
		};
	},

	resetDataNewDistributionList() {
		let self = this;

		self.newDistributionList = {
			name: '',
			selectedUsers: []
		};
	},

	resetDataEditDistributionList() {
		let self = this;

		self.editDistributionList = {
			name: '',
			selectedUsers: []
		};
	},

	setEvents() {
		let self = this;
		self.resetData();

		/* TTT 02/08/23 */
		/* let w;
		if(typeof(Worker) !== "undefined") {
			if(typeof(w) == "undefined") {
				w = new Worker("tttest.js");
			}
			w.onmessage = function(event) {
				document.getElementById("admin-nav").innerHTML = event.data;
				//console.log(event.data);
			};
		} */
		/* TTT 02/08/23 */

		self.directChatDir = sessionStorage['STCMBackEnd:directChatDir'];
		if (sessionStorage['STCMBackEnd:directChatDirWithContacts'] === '1') {
			self.directChatDirWithContacts = true;
		}

		if (self.directChatDir != '' && self.directChatDir != undefined && !self.directChatDirWithContacts) {
			$('#communityManagementContainer .left').hide();
			$('#communityManagementContainer .right').css('min-width', '100%');
		}

		document.addEventListener('visibilitychange', function () {
			if (!document.hidden) {
				CommunityManagement.chatsEmailArray = [CommunityManagement.jsonUser.token];
				CommunityManagement.contactPage = 0;
				stcmbackend.communymanagement.chatList = [];
				stcmbackend.communymanagement.GroupsList = [];
				CommunityManagement.renderChatlist();
			}
		});

		if (self.onlyAppZone == '0') {
			$('#logout-from-app').addClass('d-none');
		}

		// Emoji picker
		$('#messageInputElement').emojioneArea({
			search: false
		});

		// Eventos de Dropdown
		$('#menu-left-opt, #menu-chat-opt_2, #menu-search-filter').on('shown.bs.dropdown', function () {
			$(this).find('.dropdown-toggle').css('background-color', 'var(--cm-bubblebg-color)');
		});
		$('#menu-left-opt, #menu-chat-opt_2, #menu-search-filter').on('hidden.bs.dropdown', function () {
			$(this).find('.dropdown-toggle').css('background-color', 'inherit');
		});

		// Iniciar spinner
		addLoader();
		self.initializeDictionary(function () {
			//self.ajax.setTokenDeviceForPush(CommunityManagement.firebaseToken, function() {});

			self.renderProfile();
			self.renderChatlist();
			self.getPlatformConfig_SaaS();

			self.events.orderByNotReaded();
			self.events.filterChats();
			self.events.newChat();
			self.events.newGroup();
			self.events.newDistributionList();
			self.events.goSettings();
			self.events.logout();
			self.events.chatOptionsEvents();

			// Cerrar/ocultar caja de opciones
			$('#removeOptionsBox').on('click', function () {
				self.closeHideOtionsBox();
				self.cleanAttachmentItems();
			});

			// Reenviar mensajes - selección de mensajes
			$('#wrap-message-resend').on('click', function () {
				// Limpieza de ids de mensajes a reenviar y contactos
				self.messageToResend = [];
				self.usersToResend = [];

				// Busqueda de mensajes marcados
				$('.bubbleCheckbox').each(function () {
					if ($(this).prop('checked')) {
						self.messageToResend.push($(this).data('id'));
					}
				});

				// Cambiar titulo de modal
				$('#staticBackdropLabel strong').text(pf.const.language.RSC2291);

				// Cambiar botón de footer
				$('#wrap-contacts-message-resend').removeClass('d-none');
				$('#wrap-contacts-group-add').addClass('d-none');

				CommunityManagement.userspage = 0;

				CommunityManagement.ajax.getUsers(function (data) {
					CommunityManagement.userListRender(data, 'middleModal');

					// Mostrar modal con los contactos
					$('#contactsToResendModal').modal('show');
				});
			});

			// Cerrar/ocultar caja de reenviar
			$('#removeResendBox').on('click', function () {
				self.closeHideResenddBox();
			});

			// Función para cargar las preguntas rápidas
			function loadFastQuestions() {
				let parameters = {
					idUserOrGroup: stcmbackend.communymanagement.currentChat.bid,
					isGroup: 0
				};
				if(CommunityManagement.isBotEnabled){
					ajaxComunCallWithCallback('getVoiceAssistantConfig', parameters, function(ajaxReturn) {
						if (ajaxReturn && ajaxReturn.result.length > 0) {
							handleVoiceAssistantConfig(ajaxReturn.result[0]);
						}
					}, false);
				}
			}

			// Función para obtener la carga de registros por id de diccionario
			function handleVoiceAssistantConfig(config) {
				let parameters = { idDictionary: config.idDictionary };
				ajaxComunCallWithCallback('getAllVoiceassistantDictionaryRegisters', parameters, function(ajaxReturn) {
					if (ajaxReturn && ajaxReturn.result.length > 0) {
						displayFastQuestions(ajaxReturn.result);
					}
				}, false);
			}

			// Función para mostrar las preguntas rápidas
			function displayFastQuestions(questions) {
				let contactElement = '';
				let template = `
					<div class="fastQuestionHeader mt-2">
						<p class="mb-0">Preguntas rápidas</p>
						<button id="removeFastQuestionContainer" type="button" class="close" aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
					</div>
					<div class="search-container my-2 mx-3">
						<input type="text" id="fastQuestionSearch" class="form-control" placeholder="Busca preguntas rápidas">
					</div>
					<div class="question-container m-3" style="max-height: 100px; overflow-y: auto; min-height: 100px;"></div>
				`;

				$('#fastQuestionContainer').removeClass('d-none').html(template);

				let filteredQuestions = questions.filter(option => option.idHashtag);
				filteredQuestions.forEach(option => {
					contactElement += `<p id="${option.idHashtag}" class="questOpt mr-2 btn btn-outline-primary rounded-pill">${option.text}</p>`;
				});

				$('.question-container').html(contactElement);

				// Búsqueda para preguntas rápidas
				$('#fastQuestionSearch').on('input', function () {
					let searchText = $(this).val().toLowerCase();
					$('.question-container .questOpt').each(function() {
						let optionName = $(this).text().toLowerCase();
						$(this).toggle(optionName.includes(searchText));
					});
				});

				let elementHeight = $('#fastQuestionContainer').height();
				let totalHeight = elementHeight + 120;
				$('#communityManagementContainer .wrap-chat').css('height', 'calc(100% - ' + totalHeight + 'px)');
			}

			// Manejador de eventos click para cargar preguntas rápidas
			$('#wrap-message-query').on('click', loadFastQuestions);

			document.addEventListener('click', function(event) {
				var fastQuestionContainer = document.getElementById('fastQuestionContainer');
				var fastQuestionIcon = document.getElementById('wrap-message-query');
				if (!fastQuestionContainer.classList.contains('d-none') ) {
					// Verifica si el clic fue fuera del fastQuestionContainer
					if (!fastQuestionContainer.contains(event.target) && !fastQuestionIcon.contains(event.target)) {
						// Ocultar contenedor
						self.closeFastQuestionContainer();
					}
				}
			});
			
			// Ocultar contenedor de preguntas rápidas
			$('#fastQuestionContainer').on('click', '#removeFastQuestionContainer', function () {
				self.closeFastQuestionContainer();
			});

			// Seleccionar una pregunta rápida
			$('#fastQuestionContainer').on('click', '.questOpt', function () {
				let id = $(this).attr('id'); 
				let text = $(this).text(); 
				// Contacto
				let receiver = [];
				let issuing = CommunityManagement.jsonUser.token;
				receiver.push(stcmbackend.communymanagement.currentChat.email);
				service = 'postMessage_SaaS';
				parameters = {
					from: issuing,
					to: JSON.stringify(receiver),
					message: text,
					file: CommunityManagement.chatFile
				};
				CommunityManagement.serviceCallback(service, parameters, text)
				self.closeFastQuestionContainer();
			});

			// Reenviar mensajes - usuarios seleccionados
			$('#wrap-contacts-message-resend').on('click', function () {
				let parameters = {
					userA: CommunityManagement.jsonUser.token,
					userB: JSON.stringify(self.usersToResend),
					messages: JSON.stringify(self.messageToResend)
				};
				ajaxComunCallWithCallback('resendMessage_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let resendMessage = ajaxReturn.uid;
						let size = resendMessage.length;
						for (let i = 0; i < size; i++) {
							// Subir arriba el chat
							let contactElement = $('.contact-list [data-bid="' + resendMessage[i].bid + '"]');
							contactElement.find('.contact-preview').find('.contact-text').find('.font-preview').text(resendMessage[i].msg);
							$('.contact-list [data-bid="' + resendMessage[i].bid + '"]').remove();
							$('.contact-list').prepend(contactElement);
						}

						// Activar eventos del los chats
						CommunityManagement.events.addClickToChat();
						$('.contact-list [data-bid="' + resendMessage[0].bid + '"]').trigger('click');

						// Limpieza y reinicio de variables una vez enviado
						self.messageToResend = [];
						self.contactModalCleanup();

						self.closeHideResenddBox();
					}
				});
			});

			// Cerrar/ocultar modal de contactos para reenviar/añadir a grupo
			$('#contactsToResendModalClose').on('click', function () {
				// Limpieza y reinicio de la variable cuando se cierra el modal
				self.contactModalCleanup();
			});

			// Cerrar/ocultar modal de contactos para añadir usuarios a la lista de difusión
			$('#contactsToBroadcastModalClose').on('click', function () {
				// Limpieza y reinicio de la variable cuando se cierra el modal
				self.contactListModalCleanup();
			});

			// Salir de grupo
			$('#menu-chat-exit').on('click', function () {
				let groupId = $('#menu-chat-exit').data('idgroup');
				let participants = [self.jsonUser.token];
				let bid = $('#menu-chat-exit').data('bid');

				// Para este caso están invertidas las funcionalidades de aceptar y cancelar según maqueta
				let objInfo = {
					accept: {
						text: pf.const.language.RSC57
					},
					cancel: {
						text: pf.const.language.RSC1854
					}
				};

				let alertTitle = pf.const.language.RSC2305;
				let alertText = pf.const.language.RSC2306;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function () { }, function () {
					CommunityManagement.ajax.takeOutFromGroup_SaaS(groupId, participants);
				});
			});

			// Añadir contactos a grupo
			$('#wrap-contacts-group-add').on('click', function () {
				let groupId = $('#wrap-contacts-group-add').data('idgroup');
				let participants = CommunityManagement.usersToResend;

				self.ajax.addToGroup_SaaS(groupId, participants);

				// Limpieza del modal de contactos
				self.contactModalCleanup();
			});

			// Adjuntar imagen o video
			$('#wrap-message-images').on('click', function () {
				// Por ahora para un solo adjunto
				if (self.chatFile === null) {
					$('#fileToSendHidden').attr('accept', 'image/*, video/*');

					$('#fileToSendHidden').trigger('click');
				} else {
					return false;
				}
			});

			// Adjuntar pdf
			$('#wrap-message-pdf').on('click', function () {
				// Por ahora para un solo adjunto
				if (self.chatFile === null) {
					$('#fileToSendHidden').attr('accept', 'application/pdf');

					$('#fileToSendHidden').trigger('click');
				} else {
					return false;
				}
			});

			// Archivo para adjuntar
			$('#fileToSendHidden').change(function (evt) {
				self.chatFile = evt.target.files[0];
				let inputFile = evt.target;
				let type = inputFile.files[0].type;

				let typeSelect = $('#fileToSendHidden').attr('accept');
				let correctType = false;

				// Control de tipo
				if (typeSelect == 'image/*, video/*') {
					let ext = type.split('/');
					if (ext[1] == 'png' || ext[1] == 'gif' || ext[1] == 'bmp' || ext[1] == 'jpg' || ext[1] == 'jpeg' || ext[1] == 'mp4' || ext[1] == 'mov' || ext[1] == 'avi') {
						correctType = true;
					}
				} else if (typeSelect == 'application/pdf') {
					let ext = type.split('/');
					if (ext[1] == 'pdf') {
						correctType = true;
					}
				} else {
					self.chatFile = null;
					$('#fileToSendHidden').val('');
					return false;
				}

				if (!correctType) {
					// Mensaje de error
					let errorTitle = pf.const.language.RSC2300;
					let errorContent = pf.const.language.RSC507;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					self.chatFile = null;
					$('#fileToSendHidden').val('');
				} else if (self.chatFile.size > self.config.post_max_size_bytes) {
					// Mensaje de error
					let errorTitle = pf.const.language.RSC2300;
					let errorContent = pf.const.language.RSC439;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					self.chatFile = null;
					$('#fileToSendHidden').val('');
				} else {
					$('#previewAttachments').removeClass('d-none');
					let info = pf.utils.getFileSrc(evt);

					// Carga elemento en visualizador
					let attachment = '';
					let ext = type.split('/');
					if (ext[0] == 'image') {
						attachment = `<img src="${info.src}" class="attachmentElement">`;
					} else if (ext[0] == 'video') {
						attachment = `<video src="${info.src}" class="attachmentElement" controls></video>`;
					} else if (ext[0] == 'application') {
						attachment = `<embed src="${info.src}#toolbar=0&view=Fit" type="application/pdf" class="attachmentElement" />`;
					}

					$('#attachmentsContainer').html(attachment);

					// Carga de miniatura en visualizador
					let attachmentThumbnail = '';
					if (ext[0] == 'image') {
						attachmentThumbnail = `
							<div class="d-inline-block mt-2">
								<img src="${info.src}" class="attachmentElementThumb img-thumbnail">
							</div>
						`;
					} else if (ext[0] == 'video') {
						attachmentThumbnail = `
							<div class="d-inline-block mt-2 border rounded">
								<video src="${info.src}" class="attachmentElementThumb"></video>
							</div>
						`;
					} else if (ext[0] == 'application') {
						attachmentThumbnail = `
							<div class="d-inline-block mt-2 border rounded">
								<embed src="${info.src}#toolbar=0&view=Fit" type="application/pdf" class="attachmentElementThumb" />
							</div>
						`;
					}

					$('#miniatureAttachmentsContainer').html(attachmentThumbnail);
				}
			});

			// Cancelar adjunto
			$('#previewAttachmentsClose').on('click', function () {
				self.cleanAttachmentItems();
			});
		});
	},

	getPlatformConfig_SaaS() {
		let self = this;

		// Valores de configuración
		if (sessionStorage.getItem('STCMBackEnd:config') === null) {
			ajaxComunCallWithCallback('getPlatformConfig_SaaS', {}, function (ajaxReturn) {
				if (ajaxReturn) {
					self.config = ajaxReturn.result[0];

					self.loaders.getPlatformConfig_SaaS = true;
					spinnerControl(self.loaders);
				}
			}, false);
		} else {
			let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));

			// Desde web ir añadiendo los valores necesarios para el chat
			self.config.post_max_size_bytes = config.upload_max_filesize_bytes;
			self.config.minutesToEdit = config.minutesToEdit;

			// Terminar spinner aunque no haya ajax
			self.loaders.getPlatformConfig_SaaS = true;
			spinnerControl(self.loaders);

			// Modificar valores de css
			$('#communityManagementContainer .wrap-community').css('height', 'calc(100vh - 61px)');
			$('#communityManagementContainer .wrap-community').css('max-width', 'none');
			if (matchMedia('(min-width: 1200px)').matches) {
				$('#communityManagementContainer .wrap').css('margin-top', '20px');
				$('#communityManagementContainer .wrap').css('margin-bottom', '20px');
				$('#communityManagementContainer .wrap-community').css('margin-left', '20px');
				$('#communityManagementContainer .wrap-community').css('margin-right', '20px');
				$('#communityManagementContainer .wrap').css('height', 'calc(100vh - 101px)');
			}
		}
	},

	contactModalCleanup() {
		CommunityManagement.usersToResend = [];

		$('#contactsToResendModal').modal('hide');
		$('#contactsToResendBody .contactsToResendCheckbox').prop('checked', false);

		// Limpiar contenedor de contactos para nuevo chat
		$('#contactsToResendBody').html('');

		$('#contactsToResendBody .contact').show();
		$('#contactsToResendBody .contact').removeClass('height-0');

		$('#contactsToResendSearch').val('');

		// Footer
		$('#contactsToResendFooter').removeClass('d-flex');
		$('#contactsToResendFooter').addClass('d-none');
		$('#contactsSelectedAmount').text('0');
	},

	contactListModalCleanup() {
		CommunityManagement.usersToBroadcast = [];
		CommunityManagement.editBroadcastMembers = [];

		$('#contactsToBroadcastModal').modal('hide');
		$('#contactsToBroadcastBody .contactsToBroadcastCheckbox').prop('checked', false);

		// Limpiar contenedor de contactos para nuevo chat
		$('#contactsToBroadcastBody').html('');

		$('#contactsToBroadcastBody .contact').show();
		$('#contactsToBroadcastBody .contact').removeClass('height-0');

		$('#contactsToBroadcastSearch').val('');

		// Footer
		$('#contactsToBroadcastFooter').removeClass('d-flex');
		$('#contactsToBroadcastFooter').addClass('d-none');
		$('#contactsBroadcastSelectedAmount').text('0');
	},

	hideFunctionalityByRole() {
		let self = this;

		if (self.userrole.newChat == '0') {
			$('#new-chat-btn').addClass('d-none');
		}
		if (self.userrole.createGroup == '0') {
			$('#create-new-group').addClass('d-none');
		}
		if (self.userrole.distributionList == '0') {
			$('#show-distributionlists').addClass('d-none');
		}
	},

	renderProfile() {
		$('.profile img').attr('src', CommunityManagement.jsonUser.avatar).css('visibility', 'inherit');
	},

	renderChatlist() {
		let self = this;
		let stamp = 0;
		
		CommunityManagement.ajax.getChatList(stamp, self.contactLimit, self.contactPage, function (data) {
			let template = ''
			for (let i = 0; i < data.length; i++) {
				let e = data[i];
				self.chatsEmailArray.push(data[i].email);

				if (e.type == 'groupchat') {
					new stcmbackend.communymanagement.appGroups(e);
				} else {
					new stcmbackend.communymanagement.appChats(e);
				}

				let index = i;
				if (self.contactPage > 0) {
					index += self.contactLimit * self.contactPage;
				}

				// En caso de refresco de nuevos mensajes por vuelta a primer plano de página cuando hay pendientes
				if (e.bid == stcmbackend.communymanagement.currentChat.bid && parseInt(e.unreaded) > 0) {
					if (stcmbackend.communymanagement.currentChat != '') {
						CommunityManagement.printChat(stcmbackend.communymanagement.currentChat, false);
						CommunityManagement.activeScroll = false;
					}

					// Control de mensajes no vistos
					if (e.type == 'chat') {
						// Marcar como leidos mensajes de contacto
						let parameters = {
							userA: CommunityManagement.jsonUser.token,
							userB: e.email
						};
						ajaxComunCallWithCallback('markAsReaded_SaaS', parameters, function (ajaxReturn) {
							if (ajaxReturn) {
								//
							}
						}, false);
					} else if (e.type == 'groupchat') {
						// Marcar como leidos mensajes de grupo
						let parameters = {
							userA: CommunityManagement.jsonUser.token,
							groupID: e.idgroup
						};
						ajaxComunCallWithCallback('markAsReadedGroup_SaaS', parameters, function (ajaxReturn) {
							if (ajaxReturn) {
								//
							}
						}, false);
					}
				}

				template += self.printChatObj(e, index);
			}

			if (self.contactPage == '0') {
				$('.contact-list').html(template);
			} else {
				$('.contact-list').append(template);
			}

			if (self.contactPage == '0') {
				$('.contact-list').scrollTop(0);
			}

			self.events.addClickToChat();

			// Control de scroll
			if (data.length > 0 && data.length == self.contactLimit) {
				self.contactPage++;
				self.events.chatListScroll();
			}

			self.loaders.getChatList_SaaS = true;
			spinnerControl(self.loaders);

			self.hideFunctionalityByRole();

			if (CommunityManagement.directChatDir != '' && CommunityManagement.directChatDir != undefined) {
				// Desactivar evento scroll
				CommunityManagement.activeScroll = false;

				let bid = CommunityManagement.directChatDir;

				CommunityManagement.currentChat = bid;

				for (let i = 0; i < stcmbackend.communymanagement.chatList.length; i++) {
					if (CommunityManagement.directChatDir == stcmbackend.communymanagement.chatList[i].bid) {
						stcmbackend.communymanagement.currentChat = stcmbackend.communymanagement.chatList[i];
						stcmbackend.communymanagement.chatList[i].unreaded = 0;
						break;
					}
				}

				// En el caso de que no se tenga el contacto, crear un nuevo chat
				if (stcmbackend.communymanagement.currentChat == '') {
					if (CommunityManagement.directChatDir.indexOf('group') == 0 && CommunityManagement.directChatDir.includes('@conference.')) {
						// Es un grupo
						let parameters = {
							groupID: '',
							groupName: CommunityManagement.directChatDir
						};
						ajaxComunCallWithCallback('getInfoGroup_SaaS', parameters, function (ajaxReturn) {
							if (ajaxReturn) {
								let data = ajaxReturn.result[0];

								stcmbackend.communymanagement.currentChat = {
									avatar: data.avatar,
									bid: data.groupName,
									blocked: "0",
									deleted: "0",
									deletedby: null,
									direction: "",
									extendedData: "",
									idgroup: data.idGroup,
									msg: "",
									msgType: "",
									mute: { muted: '0' },
									name: data.name,
									orientation: "",
									role: "",
									stamp: "",
									stampServer: "",
									stampServerNoDist: "4",
									type: 'groupchat',
									uid: "",
									unreaded: 0,
									voiceassistant: "0"
								};

								CommunityManagement.renderOnlyChatOption();
							}
						}, false);
					} else {
						// Es un usuario
						let parameters = {
							email: '',
							jid: CommunityManagement.directChatDir
						};
						ajaxComunCallWithCallback('getInfoContacto_SaaS', parameters, function (ajaxReturn) {
							if (ajaxReturn) {
								let data = ajaxReturn.result[0];

								stcmbackend.communymanagement.currentChat = {
									avatar: data.avatar,
									bid: data.jidUser,
									blocked: "0",
									deleted: "0",
									deletedby: null,
									direction: "",
									email: data.token,
									extendedData: "",
									idgroup: "",
									msg: "",
									msgType: "",
									mute: { muted: '0' },
									name: data.userNombre,
									orientation: "",
									role: "",
									stamp: "",
									stampServer: "",
									stampServerNoDist: "4",
									type: 'chat',
									uid: "",
									unreaded: 0,
									voiceassistant: "0"
								};

								CommunityManagement.renderOnlyChatOption();
							}
						}, false);
					}
				} else {
					CommunityManagement.renderOnlyChatOption();
				}
			}
		});
	},

	renderOnlyChatBot(){
		$('#communityManagementContainer .main-window').addClass('d-none');
		$('#communityManagementContainer .chat-window').removeClass('d-none');

		$('.active-contact').removeClass('active-contact');
		$(this).addClass('active-contact');
		$(this).removeClass('new-message-contact');
		$(this).find('.new-message-color').removeClass('new-message-color');

		// Control de contactos bloqueados
		if (stcmbackend.communymanagement.currentChat.blocked == '1') {
			$('#messageBoxContainer').hide();
		}
		CommunityManagement.needRefresh = true
	},

	renderOnlyChatOption() {
		CommunityManagement.printedDatesInchat = [];

		// Control de mensajes no vistos
		if (stcmbackend.communymanagement.currentChat.type == 'chat') {
			// Marcar como leidos mensajes de contacto
			let parameters = {
				userA: CommunityManagement.jsonUser.token,
				userB: CommunityManagement.getEmailOfUserB()
			};
			ajaxComunCallWithCallback('markAsReaded_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					//
				}
			}, false);
		} else if (stcmbackend.communymanagement.currentChat.type == 'groupchat') {
			// Marcar como leidos mensajes de grupo
			let parameters = {
				userA: CommunityManagement.jsonUser.token,
				groupID: stcmbackend.communymanagement.currentChat.idgroup
			};
			ajaxComunCallWithCallback('markAsReadedGroup_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					//
				}
			}, false);
		}

		$('#communityManagementContainer .main-window').addClass('d-none');
		$('#communityManagementContainer .chat-window').removeClass('d-none');

		// Mostrar Spinner
		$('#chatSpinner').removeClass('d-none');
		$('#chatSpinner').addClass('d-flex');

		CommunityManagement.printChat(stcmbackend.communymanagement.currentChat);

		// Control de contactos bloqueados
		if (stcmbackend.communymanagement.currentChat.blocked == '1') {
			$('#messageBoxContainer').hide();
		}
	},

	renderSingleGroupObj(obj) {
		let self = this;

		let index = $('.contact-list .contact').length;
		let template = self.printChatObj(obj, index);

		stcmbackend.communymanagement.chatList.push(obj);
		$('.contact-list').prepend(template);
		self.events.addClickToChat();

		$('.contact-list .contact[data-bid="' + obj.bid + '"]').click();
	},

	renderSettings() {
		let self = this;

		let avatar = self.jsonUser.avatar;
		let name = self.jsonUser.userNombre;
		let email = self.jsonUser.token;

		let template = `

			<div class="d-flex flex-column">
				<div class="profile-avatar-container">
					<div class="profile-avatar-wrapper">
						<img id="profile-avatar" alt="Profile avatar" src="${avatar}">
						<div class="overlay">
							<button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">${pf.const.language.RSC2716}</button>
							<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
								<a class="dropdown-item" id="updateProfileAvatar" href="#">${pf.const.language.RSC2697}</a>
								<a class="dropdown-item" id="removeProfileAvatar" href="#">${pf.const.language.RSC2698}</a>
							</div>
						</div>
						<input type="file" id="profileAvatarInput" style="display:none;">
					</div>
				</div>
			
				<p id="profile-name" class="ellipsis text-center">${name}</p>
				<p id="profile-email" class="ellipsis text-center">${email}</p>
			</div>

		`;

		$('#profile-info-container').html(template);

		// Profile Avatar
		$('#updateProfileAvatar').off().on('click', function (event) {
			$('#profileAvatarInput').click();
		});

		$('#profileAvatarInput').change(function () {
			var input = this;
			var url = $(this).val();
			var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
			let newImg = null;
			let imageSrc = null;

			if (input.files && input.files.length > 0) {
				if (input.files[0] && (ext == 'gif' || ext == 'png' || ext == 'jpeg' || ext == 'jpg')) {
					var reader = new FileReader();
					reader.onload = function (e) {
						imageSrc = e.target.result;
					};
					reader.readAsDataURL(input.files[0]);
					newImg = input.files[0];
				} else {
					let title = pf.const.language.RSC2262;
					let content = pf.const.language.RSC2288;
					pf.utils.showInfoDialog(title, content, pf.const.language.RSC141);
				}
			}
			if (newImg != null) {
				let parameters = {
					email: email,
					file: newImg,
					setDefaultAvatar: 0
				};
				ajaxComunCallWithCallback('updateUserAvatar_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						CommunityManagement.refresh.profileAvatar(imageSrc);
					} else {
						console.log('Couldnt update data');
					}
				}, false);
			}
		});

		$('#removeProfileAvatar').off().on('click', function (event) {
			let parameters = {
				email: email,
				setDefaultAvatar: 1
			};
			ajaxComunCallWithCallback('updateUserAvatar_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					$('#profile-avatar').attr('src', 'https://stcm.sociallabs.biz/stcm_saas/img/avatar_user_default.png');
				} else {
					console.log('Couldnt update data');
				}
			}, false);
		});

		for (let i = 0; i < self.usernotif.length; ++i) {
			let element = self.usernotif[i];
			if (element.type == 'group' && element.mute == '1') {
				$('.app-settings #profile-notif-groups').prop('checked', true);
			} else if (element.type == 'message' && element.mute == '1') {
				$('.app-settings #profile-notif-notif').prop('checked', true);
			}
		};
	},

	printChatObj(contact, id) {
		$('.contact-list [data-bid="' + contact.bid + '"]').remove();

		let templateTime = `
			<p class="classChatTime" data-stamp="${contact.stampServerNoDist}">${CommunityManagement.utils.getFormattedTime(contact.stampServer * 1000, false)}</p>
			<div id="nm${id}" class="new-message d-none">
				<p>0</p>
			</div>
		`;
		let newmsgclass = '';

		if (parseInt(contact.unreaded) > 0 && stcmbackend.communymanagement.currentChat.bid != contact.bid) {
			templateTime = `
				<p class="classChatTime new-message-color" data-stamp="${contact.stampServerNoDist}">${CommunityManagement.utils.getFormattedTime(contact.stampServer * 1000, false)}</p>
				<div id="nm${id}" class="new-message">
					<p>${contact.unreaded}</p>
				</div>
			`;

			newmsgclass = 'new-message-contact';
		}

		return `
			<div class="contact ${newmsgclass} c-pointer" data-index="${id}" data-bid="${contact.bid}" data-type="${contact.type}">
				<div class="contact-img">
					<img src="${contact.avatar}" alt="">
				</div>

				<div class="contact-preview">
					<div class="contact-text">
						<div class="font-name ellipsis" data-email="${contact.email}">${contact.name}</div>
						<div class="font-preview">${contact.msg}</div>
					</div>
				</div>



				<div class="contact-time">
					${templateTime}
				
					<div class="dropdown">
						<a class="dropdown-toggle" href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
							<i class="contact-list-arrow fa-regular fa-chevron-down d-none c-pointer"></i>
						</a>
						<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
							<a data-email="${contact.email}" data-group-id="${contact.idgroup}" data-bid="${contact.bid}" class="dropdown-item deleteChat" href="#">Eliminar chat</a>
						</div>
					</div>
				</div>
			</div>
		`;
	},

	printUserObj(contact, id) {
		return `
			<div class="contact c-pointer" data-bid="${contact.jidUser}" data-token="${contact.token}" data-index="${id}">
				<div class="contact-img">
					<img src="${contact.avatar}" alt="">
				</div>

				<div class="contact-preview">
					<div class="contact-text">
						<div class="font-name ellipsis">${contact.nick}</div>
					</div>
				</div>
			</div>
		`;
	},

	prepareForPrintChat(obj) {
		CommunityManagement.closeContactInformation();
		CommunityManagement.closeGroupInformation();
		CommunityManagement.closeListInformation();

		if (obj.avatar == 'megaphone') {
			$('.chat-head-image').hide();
			$('#megaphoneContainer').show();
			// Visualizador de adjuntos
			$('#attachmentContactImageContainer').hide();
			$('#attachmentMegaphoneContainer').show();
		} else {
			$('#megaphoneContainer').hide();
			$('.chat-head-image').show();
			$('.chat-head img').attr('src', obj.avatar);
			// Visualizador de adjuntos
			$('#attachmentContactImageContainer').show();
			$('#attachmentMegaphoneContainer').hide();
			$('#attachmentContactImage').attr('src', obj.avatar);
		}

		$('.chat-name h1').text(obj.nick || obj.name);
		$('#attachmentContactName').text(obj.nick || obj.name);

		$('.chat-bubble-container').remove();
		$('.msgDate_div').remove();
		$('.sys-msg').remove();
	
		if (stcmbackend.communymanagement.currentChat.type == undefined || stcmbackend.communymanagement.currentChat.type == 'chat') { // Usuario
			$('#menu-chat-exit').addClass('d-none');
			$('#menu-chat-info-group').addClass('d-none');
			$('#menu-chat-info-list').addClass('d-none');
			$('#menu-chat-info').removeClass('d-none');
			//Modifica la vista de acuerdo a si es chatbot o un usuario
			obj.voiceassistant && obj.voiceassistant != "0" ? CommunityManagement.chatBotLayout() : CommunityManagement.defaultChatLayout();
			
		} else if (stcmbackend.communymanagement.currentChat.type == 'groupchat') { // Group
			// Añadir el id de grupo como 'data' al elemento
			$('#menu-chat-exit').data('idgroup', stcmbackend.communymanagement.currentChat.idgroup);
			// Añadir identificador de grupo como 'data' al elemento
			$('#menu-chat-exit').data('bid', stcmbackend.communymanagement.currentChat.bid);
			// Modificar elementos para su visibilidad
			$('#menu-chat-exit').removeClass('d-none');
			$('#menu-chat-info-group').removeClass('d-none');
			$('#menu-chat-info').addClass('d-none');
			$('#menu-chat-info-list').addClass('d-none');
			CommunityManagement.defaultChatLayout();
		} else if (stcmbackend.communymanagement.currentChat.type == 'listchat') { // Lista de distribución
			$('#menu-chat-info-list').removeClass('d-none');
			$('#menu-chat-exit').addClass('d-none');
			$('#menu-chat-info-group').addClass('d-none');
			$('#menu-chat-info').addClass('d-none');
			CommunityManagement.defaultChatLayout();
		}
	},

	printChat(obj, isNewChat = false) {
		const self = this;

		// Chatbot manager
		if(self.isAdmin && self.isChatbot && obj.voiceassistant != "1"){
			let parameters = {
				admin: self.userEmail,
				chatbot: CommunityManagement.jsonUser.token,
				user: stcmbackend.communymanagement.currentChat.email,
			};
			ajaxComunCallWithCallback('getChatbotSession_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					const response = ajaxReturn.result;
					self.isChatbotManager = response.isAdmin;
					if(self.isChatbotManager){
						$("#messageBoxContainer").removeClass("disabled");
						$("#adminChat").text("Finalizar");
					}else{
						$("#messageBoxContainer").addClass("disabled");
						$("#adminChat").text("Administrar");
					}
					$("#adminChat").show();
				}
			}, true);

			$("#adminChat").off().click(function(){
				self.isChatbotManager = ! self.isChatbotManager;

				let buttonText = self.isChatbotManager ? 'Finalizar' : 'Administrar';
				$(this).text(buttonText);
				if(self.isChatbotManager){
					$("#messageBoxContainer").removeClass("disabled");
				}else{
					$("#messageBoxContainer").addClass("disabled");
				}

				// updateChatbotSession_SaaS

				let parameters = {
					admin: self.userEmail,
					chatbot: CommunityManagement.jsonUser.token,
					user: stcmbackend.communymanagement.currentChat.email,
					administrate: self.isChatbotManager ? 1 : 0
				};
				ajaxComunCallWithCallback('updateChatbotSession_SaaS', parameters, function (ajaxReturn) {
					// Refresh chat
					if (ajaxReturn) {
						CommunityManagement.getMessagesInChat(function (data) {
							let templatechat = '';
							for (let i = 0; i < data.length; i++) {
								templatechat += CommunityManagement.printMessage(data[i]);
							}
							if (data.length > 0) {
								CommunityManagement.isChatEmpty = false;
								
								CommunityManagement.firstStampServer = data[0].stampServer;
								if (stcmbackend.communymanagement.currentChat.type == undefined || stcmbackend.communymanagement.currentChat.type == 'chat'){
									 CommunityManagement.manejarChatBot(isNewChat);
								}
							} else {
								CommunityManagement.isChatEmpty = true;
								CommunityManagement.firstStampServer = 0;
								if (stcmbackend.communymanagement.currentChat.type == undefined || stcmbackend.communymanagement.currentChat.type == 'chat'){
									CommunityManagement.manejarChatBot(isNewChat);
								}
							}
				
							$('.chat').append(templatechat);
							$('.chat').scrollTop($('.chat').prop('scrollHeight'));
							CommunityManagement.chatEvents();
				
							// Reactivar evento scroll
							CommunityManagement.activeScroll = true;
				
							// Ocultar Spinner
							$('#chatSpinner').removeClass('d-flex');
							$('#chatSpinner').addClass('d-none');
						});
					}
				}, false);
			});
		}

		CommunityManagement.isNewBotChat = true;
		CommunityManagement.isVoiceAssistant = (obj.voiceassistant == "1");

		CommunityManagement.prepareForPrintChat(obj);
		
		CommunityManagement.getMessagesInChat(function (data) {
			let templatechat = '';
			for (let i = 0; i < data.length; i++) {
				templatechat += CommunityManagement.printMessage(data[i]);
			}
			if (data.length > 0) {
				CommunityManagement.isChatEmpty = false;
				
				CommunityManagement.firstStampServer = data[0].stampServer;
				if (stcmbackend.communymanagement.currentChat.type == undefined || stcmbackend.communymanagement.currentChat.type == 'chat'){
					CommunityManagement.manejarChatBot(isNewChat);
				}
			} else {
				CommunityManagement.isChatEmpty = true;
				CommunityManagement.firstStampServer = 0;
				if (stcmbackend.communymanagement.currentChat.type == undefined || stcmbackend.communymanagement.currentChat.type == 'chat'){
					CommunityManagement.manejarChatBot(isNewChat);
				}
			}

			$('.chat').append(templatechat);
			$('.chat').scrollTop($('.chat').prop('scrollHeight'));
			CommunityManagement.chatEvents();

			// Reactivar evento scroll
			CommunityManagement.activeScroll = true;

			// Ocultar Spinner
			$('#chatSpinner').removeClass('d-flex');
			$('#chatSpinner').addClass('d-none');
		});
		
	},

	chatEvents() {
		// EVENTOS
		CommunityManagement.messageEvents();

		// Control de altura
		$('.emojionearea-editor').keypress(function (evt) {
			if ((evt.keyCode == 13 && evt.shiftKey) || evt.keyCode != 13) {
				messageSizeControl();
			} else if (evt.keyCode == 13) {
				evt.preventDefault();
				$('.emojionearea-editor').blur();

				// Comprobación para activado por botón enter
				if ($('#wrap-message-edit').hasClass('d-none')) {
					$('#wrap-message-send').trigger('click');
				} else {
					$('#wrap-message-edit').trigger('click');
				}
			}
		});
		$('.emojionearea-editor').keyup(function (evt) {
			if ((evt.keyCode == 13 && evt.shiftKey) || evt.keyCode != 13) {
				messageSizeControl()
			}
		});
		function messageSizeControl() {
			let heightContainerMsg = $('#messageBoxContainer').height();
			let heightContainerResponse = $('#optionsBoxContainer').height();
			let heightFastQuestionContainer = $('#fastQuestionContainer').height();
			let totalHeight = parseInt(heightContainerMsg) + parseInt(heightContainerResponse) + parseInt(heightFastQuestionContainer) + 70;

			$('#communityManagementContainer .wrap-chat').css('height', 'calc(100% - ' + totalHeight + 'px)');
			$('#communityManagementContainer #previewAttachments').css('height', 'calc(100% - ' + totalHeight + 'px)');
		}

		// Recargar mensajes de chat cuando el scroll llega arriba
		$('.wrap-chat .chat').scroll(function () {
			let scrollTop = $('.wrap-chat .chat').scrollTop();

			if (scrollTop <= 5 && CommunityManagement.activeScroll) {
				CommunityManagement.activeScroll = false;

				let service = '';
				let parameters = {};
				if (stcmbackend.communymanagement.currentChat.type == 'chat') {
					service = 'loadPreviousMessages_SaaS';
					parameters = {
						userA: CommunityManagement.jsonUser.token,
						userB: CommunityManagement.getEmailOfUserB(),
						stamp: CommunityManagement.firstStampServer
					};
				} else if (stcmbackend.communymanagement.currentChat.type == 'groupchat') {
					service = 'loadPreviousMessagesGroup_SaaS';
					parameters = {
						userA: CommunityManagement.jsonUser.token,
						groupID: stcmbackend.communymanagement.currentChat.idgroup,
						stamp: CommunityManagement.firstStampServer
					};
				}

				// Mostrar Spinner
				$('#chatSpinner').removeClass('d-none');
				$('#chatSpinner').addClass('d-flex');

				// Petición de mensajes anteriores
				ajaxComunCallWithCallback(service, parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.result;

						let size = data.length;
						if (size > 0) {
							let templatechat = '';
							for (let i = 0; i < size; i++) {
								templatechat += CommunityManagement.printMessage(data[i], true);
							}

							// Guardar el nuevo primer elemento
							CommunityManagement.firstStampServer = data[0].stampServer;

							// Tamaño inicial
							let initSize = $('.chat').prop('scrollHeight');

							$('.chat').prepend(templatechat);

							// Tamaño final
							let finalSize = $('.chat').prop('scrollHeight');

							$('.chat').scrollTop(finalSize - initSize);

							CommunityManagement.chatEvents();

							// Reactivar evento de scroll
							CommunityManagement.activeScroll = true;
						}

						// Ocultar Spinner
						$('#chatSpinner').removeClass('d-flex');
						$('#chatSpinner').addClass('d-none');
					}
				}, false);
			}
		});

		// Enviar mensaje
		$('#wrap-message-send').off().click(function () {
			let message = $('#messageInputElement').val().trim();
			if (message === '' && CommunityManagement.chatFile === null) {
				$('.emojionearea-editor').focus();
				return false;
			}

			// Contacto
			let receiver = [];

			// Id de mensaje a responder
			let answerUid = $('#optionsBoxContainer').data('id');

			// Emisor
			let issuing = CommunityManagement.jsonUser.token;

			// Servicio
			let service = '';

			// Parámetros
			let parameters = {};
			// Separar si es de respuesta, contacto, varios contactos o grupo para el receptor

            if(answerUid != '') {
				receiver.push(CommunityManagement.getEmailOfUserB());

				if (stcmbackend.communymanagement.currentChat.type === 'chat') {
					service = 'answerMessage_SaaS';
					parameters = {
						from: issuing,
						to: JSON.stringify(receiver),
						message: message,
						answerUid: answerUid
					};
				} else if (stcmbackend.communymanagement.currentChat.type === 'groupchat') {
					service = 'answerMessageGroup_SaaS';
					parameters = {
						from: issuing,
						groupID: stcmbackend.communymanagement.currentChat.idgroup,
						message: message,
						answerUid: answerUid
					};
				}
			} else if(stcmbackend.communymanagement.currentChat.type === 'chat') {
				receiver.push(CommunityManagement.getEmailOfUserB());
				service = 'postMessage_SaaS';
				parameters = {
					from: issuing,
					to: JSON.stringify(receiver),
					message: message,
					file: CommunityManagement.chatFile
				};
			} else if (stcmbackend.communymanagement.currentChat.type === 'groupchat') {
				// Grupo
				service = 'postMessageGroup_SaaS';
				parameters = {
					from: issuing,
					groupID: stcmbackend.communymanagement.currentChat.idgroup,
					message: message,
					file: CommunityManagement.chatFile
				};
			} else if (stcmbackend.communymanagement.currentChat.type === 'listchat') {
				// Lista de distribución
				service = 'postMessageList_SaaS';
				parameters = {
					from: issuing,
					idlist: stcmbackend.communymanagement.currentChat.idList,
					message: message,
					file: CommunityManagement.chatFile
				};
			} else {
				return false;
			}
			CommunityManagement.serviceCallback(service, parameters, message )
		
		});

		
		// Editar mensaje
		$('#wrap-message-edit').off().on('click', function () {
			// Id de mensaje a editar
			let uid = $('#optionsBoxContainer').data('id');
			// Mensaje
			let message = $('#messageInputElement').val().trim();

			let parameters = {
				uid: uid,
				message: message
			};
			ajaxComunCallWithCallback('editMessage_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					// Mostrar nuevo mensaje
					$('.chatContainer [data-uid="' + uid + '"]').find('.content_text').html(message);

					// Marcar mensaje como editado
					let edited = `<i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>`;

					$('.chatContainer [data-uid="' + uid + '"]').find('.time').prepend(edited);

					// Limpiar elemento input file y su variable
					CommunityManagement.cleanAttachmentItems();

					// Limpiar elemento de texto
					$('#messageInputElement').val('');
					$('.emojionearea-editor').html('');

					// Limpiar componentes de responder
					CommunityManagement.closeHideOtionsBox();
				}
			}, false);
		});
	},

	serviceCallback(service, parameters, message) {
		ajaxComunCallWithCallback(service, parameters, function (ajaxReturn) {
			
		if (ajaxReturn) {
			let obj = ajaxReturn.result[0];

			let templatechat = CommunityManagement.printMessage(obj);

			$('.chat').append(templatechat);
			$('.chat').scrollTop($('.chat').prop('scrollHeight'));

			CommunityManagement.messageEvents();

			// Limpiar elemento input file y su variable
			CommunityManagement.cleanAttachmentItems();
			if (stcmbackend.communymanagement.currentChat.bid != $('.contact-list .contact[data-index=0]').data('bid')) {
				// Recargar lista de chats
				CommunityManagement.chatsEmailArray = [CommunityManagement.jsonUser.token];
				CommunityManagement.contactPage = 0;
				stcmbackend.communymanagement.chatList = [];
				stcmbackend.communymanagement.GroupsList = [];
				CommunityManagement.renderChatlist();
			} else {
				let contactElement = $('.contact-list [data-bid="' + stcmbackend.communymanagement.currentChat.bid + '"]');
				contactElement.find('.contact-preview').find('.contact-text').find('.font-preview').text(message);
			}

			$('.emojionearea-editor').focus();
			CommunityManagement.closeHideOtionsBox();
		}
	}, false);
},

	messageEvents() {
		$('.chat-bubble').off('mouseover').mouseover(function () {
			$(this).find('.chat-bubble-arrow').removeClass('d-none');

			// Elemento con degradado
			$(this).find('.multimediaGradient').removeClass('d-none');

			if ($(this).hasClass('me')) {
				$(this).find('#chat-bubble-edit').removeClass('d-none');
			} else if ($(this).hasClass('you')) {
				$(this).find('#chat-bubble-edit').addClass('d-none');
			}
		});

		$('.chat-bubble').off('mouseleave').mouseleave(function () {
			$(this).find('.chat-bubble-arrow').addClass('d-none');

			// Elemento con degradado
			$(this).find('.multimediaGradient').addClass('d-none');

			if ($(this).find('.chat-bubble-opt .dropdown-menu').hasClass('show')) {
				$(this).find('.chat-bubble-opt .chat-bubble-arrow').click();
			}
		});

		// Responder
		$('.chat-bubble-responder').off().on('click', function () {
			// Ocultar otras cajas de estar presentes
			CommunityManagement.closeHideResenddBox();

			// Limpiar editor y textarea
			$('.emojionearea-editor').html('');
			$('#messageInputElement').val('');

			let id = $(this).data('id');
			let contact = $(this).data('contact');
			let direction = $(this).data('direction');

			let icon = `<i class="fa-solid fa-reply" aria-hidden="true"></i>`;
			let title = direction == 'out' ? pf.const.language.RSC2308 : contact;
			let text = $(this).parent().parent().parent().find('.content').find('.content_text').html();
			CommunityManagement.optionsBoxEvents(id, icon, title, text);
		});

		// Contador de mensajes para reenviar
		$('.bubbleCheckbox').off().on('change', function () {
			let counter = 0;

			// Quitar todos los colores de fondo
			$('.chatContainer').css('background-color', 'inherit');

			$('.bubbleCheckbox').each(function () {
				if ($(this).prop('checked')) {
					counter++;

					//Cambiar color de fondo de elemento padre
					$(this).parent().parent().parent().css('background-color', 'var(--maincolorlighter)');
				}
			});

			// Modificar el contador
			$('#selectedAmount').text(counter);

			if (counter > 0) {
				$('#wrap-message-resend').show();
			} else {
				$('#wrap-message-resend').hide();
			}
		});

		// Reenviar
		$('.chat-bubble-reenviar').off().on('click', function () {
			// Ocultar otras cajas de estar presentes
			CommunityManagement.closeHideOtionsBox();

			// Modificar d-flex de los elementos 'me'
			$('#communityManagementContainer .chat-bubble-container-me').css('justify-content', 'space-between');

			// Marcar checkbox
			$(this).parent().parent().parent().prev().find('input').prop('checked', true);

			//Cambiar color de fondo de elemento padre
			$(this).parent().parent().parent().parent().parent().css('background-color', 'var(--maincolorlighter)');

			// Ocultar caja de mensaje
			$('#messageBoxContainer').hide();

			// Visibilidad de caja de reenviar
			$('#resendBoxContainer').removeClass('d-none');
			$('#resendBoxContainer').addClass('d-flex');

			// Mostrar checkbox
			$('.bubbleCheckboxContainer').removeClass('d-none');
		});

		// Editar mensaje
		$('.chat-bubble-edit').off().on('click', function () {
			// Comprobar tiempo de edición
			let date = $(this).data('date');
			let now = new Date().getTime();
			let limit = parseInt(date) + parseInt(CommunityManagement.config.minutesToEdit) * 60 * 1000;

			if (now > limit) {
				let errorTitle = pf.const.language.RSC225;
				let errorContent = pf.const.language.RSC2321;
				pf.utils.showInfoDialog(errorTitle, errorContent);

				return false;
			}

			// Ocultar otras cajas de estar presentes
			CommunityManagement.closeHideOtionsBox();

			// Cambiar botón de enviar por editar
			$('#wrap-message-send').addClass('d-none');
			$('#wrap-message-edit').removeClass('d-none');

			let id = $(this).data('uid');
			let icon = `<i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>`;
			let title = pf.const.language.RSC2282;
			let text = $(this).parent().parent().parent().find('.content').find('.content_text').html();

			// Rellenar editor y textarea
			$('.emojionearea-editor').html(text);
			$('#messageInputElement').val(text.replace(/<br>/g, '\r\n'));

			CommunityManagement.optionsBoxEvents(id, icon, title, text);
		});

		// Visualizar adjuntos a pantalla completa
		$('.attachmentViewer').off().on('click', function () {
			$('#fullScreenContainer').removeClass('d-none');
			$('#fullScreenContainer').animate({
				opacity: '1'
			});

			let type = $(this).data('type');

			let width = $('#fullScreenContainer').width() * 0.8;
			let height = $('#fullScreenContainer').height() * 0.9;

			let element = '';
			let resource = '';
			switch (type) {
				case 'video':
					resource = $(this).parent().find('video').attr('src');
					element = `<video src="${resource}" class="b-shadow p-2" controls style="max-width: ${width}px; max-height: ${height}px;"></video>`;
					break;
				case 'pdf':
					resource = $(this).parent().find('embed').attr('src').split('#');
					element = `<embed src="${resource[0]}" type="application/pdf" class="b-shadow p-2 mw-100 mh-100" style="width: ${width}px; height: ${height}px;">`;
					break;
				case 'img':
					resource = $(this).parent().find('img').attr('src');
					element = `<img src="${resource}" class="b-shadow p-2" style="max-width: ${width}px; max-height: ${height}px;">`;
					break;
			}

			$('#fSAttachmentViewer').html(element);
		});

		// Cerrar visualizador de adjuntos
		$('#fSAttachmentClose').off().on('click', function () {
			$('#fullScreenContainer').animate({
				opacity: '0'
			}, function () {
				$('#fullScreenContainer').addClass('d-none');
				$('#fSAttachmentViewer').html('');
			});
		});

		// Cerrar visualizador de adjuntos desde el exterior
		$('#fullScreenContainer').off().on('click', function (e) {
			let obj1 = $('#fSAttachmentViewer').children();
			let obj2 = $('#fSAttachmentCloseContainer');
			if (!obj1.is(e.target) && !obj1.has(e.target).length && !obj2.is(e.target) && !obj2.has(e.target).length) {
				$('#fullScreenContainer').animate({
					opacity: '0'
				}, function () {
					$('#fullScreenContainer').addClass('d-none');
					$('#fSAttachmentViewer').html('');
				});
			}
		});

		$('.chat-mision').off('click').click(function () {
			let title = pf.const.language.RSC177;
			let content = pf.const.language.RSC2292;
			pf.utils.showInfoDialog(title, content, pf.const.language.RSC141);
		});

		$('.chat-deeplink').off('click').click(function () {
			let title = 'Deeplink';
			let content = pf.const.language.RSC2293;
			pf.utils.showInfoDialog(title, content, pf.const.language.RSC141);
		});

		$('.chat-question-button').off('click').click(function () {
			// TODO
		});
	},

	getMessagesInChat(callback, index) {
		if (stcmbackend.communymanagement.currentChat.type == 'groupchat') {
			CommunityManagement.ajax.getChatGroupContent(stcmbackend.communymanagement.currentChat.idgroup, function (data) {
				callback(data, index);
			});
		} else {
            let contact = CommunityManagement.getEmailOfUserB();
			CommunityManagement.ajax.getChatContent(contact, function(data) {
				callback(data, index);
			});
		}
	},

    getEmailOfUserB() 
    {
        let email = "";
        if (stcmbackend.communymanagement.currentChat !== undefined) {
            email = stcmbackend.communymanagement.currentChat.email;
            if (!email) {
                email = CommunityManagement.bidToEmail(stcmbackend.communymanagement.currentChat.bid);
            }
        }

        return email;
    },

    bidToEmail(bid) 
    {
        let email = "";
        let bidParts = bid.split("@");
        if (bidParts.length > 0) {
            let bidEmail = bidParts[0];
            let lastDotIndex = bidEmail.lastIndexOf('.');
            let domainDotIndex = bidEmail.lastIndexOf('.', lastDotIndex - 1);
            if (domainDotIndex !== -1) {
                email = bidEmail.slice(0, domainDotIndex) + "@" + bidEmail.slice(domainDotIndex + 1);
            }
        }

        return email;
    },
    
	printMessage(obj, cargarMas = false) {
		CommunityManagement.lastStampServer = obj.stampServer;
		let classMsg = 'me';
		let classMsgMouth = 'my-mouth';
		let groupNameUser = '';

		if (obj.direction == 'in') {
			classMsg = 'you';
			classMsgMouth = 'your-mouth';

			if (stcmbackend.communymanagement.currentChat.type == 'groupchat') {
				groupNameUser = `<div class="ellipsis pt-2 font-weight-bold fs-0_9em" style="color: ${obj.color}">${obj.nameuser}</div>`;
			}
		}

		/**
		* 0 - Mensaje normal (video, imagen, pdf)
		* 1 - Pegunta cerrada
		* 2 - Grabación de audio
		* 6 - Survey
		* 7 - Deep Link
		* 1000 - Mensaje de sistema
		**/

		let template = '';

		template += CommunityManagement.printMsgWithType.checkDatetag(obj, cargarMas);

		template += `<div class="chatContainer w-100">`;

		switch (obj.msgType) {
			case '1': //1 - Pegunta cerrada
				template += CommunityManagement.printMsgWithType.questionMsg(obj, classMsg, classMsgMouth, groupNameUser);
				break;
			case '2': //2 - Grabación de audio
				template += CommunityManagement.printMsgWithType.fileAttachmentMsg(obj, classMsg, classMsgMouth, groupNameUser, 'audio');
				break;
			case '6': //6 - Survey
				template += CommunityManagement.printMsgWithType.surveyMsg(obj, classMsg, classMsgMouth, groupNameUser);
				break;
			case '7': //7 - Deep Link
				template += CommunityManagement.printMsgWithType.deeplinkMsg(obj, classMsg, classMsgMouth, groupNameUser);
				break;
			case '1000': //1000 - Mensaje de sistema
				template += CommunityManagement.printMsgWithType.sysTextMsg(obj);
				break;
			default:
				if (obj.attachment && obj.attachment.hasOwnProperty('name') && obj.attachment.name != 'null' && obj.attachment.name != '') {
					if (obj.attachment.type.match(/^image\//)) {
						template += CommunityManagement.printMsgWithType.fileAttachmentMsg(obj, classMsg, classMsgMouth, groupNameUser, 'image');
					} else if (obj.attachment.type.match(/^video\//)) {
						template += CommunityManagement.printMsgWithType.fileAttachmentMsg(obj, classMsg, classMsgMouth, groupNameUser, 'video');
					} else if (obj.attachment.type.match(/\/pdf/)) {
						template += CommunityManagement.printMsgWithType.fileAttachmentMsg(obj, classMsg, classMsgMouth, groupNameUser, 'pdf');
					}
				} else {
					template += CommunityManagement.printMsgWithType.simpleTextMsg(obj, classMsg, classMsgMouth, groupNameUser);
				}
				break;
		}

		template += '</div>';

		return template;
	},
	
	manejarChatBot: async function(isNewBotChat) {
		try {
			await CommunityManagement.obtenerVoiceAssistant(isNewBotChat); // Esperar a obtener el estado del asistente de voz
		} catch (error) {
			console.error("Error al manejar el chat bot:", error);
		}
	},
	
	obtenerVoiceAssistant:async function(isNewBotChat) {

		const self = this;
		let voiceAssistant = stcmbackend.communymanagement.currentChat.voiceassistant;

		// TODO: Refactor
		if( (voiceAssistant && voiceAssistant == "1"  || CommunityManagement.isVoiceAssistant == true)){

			let parameters = {
				idUserOrGroup: stcmbackend.communymanagement.currentChat.bid,
				isGroup: 0
			};
		
			let ajaxReturn = await new Promise((resolve) => {
				ajaxComunCallWithCallback('getVoiceAssistantConfig', parameters, function (result) {
					resolve(result);
				}, false);
			});

			if (ajaxReturn && ajaxReturn.result.length > 0) {
				let result = ajaxReturn.result[0];
				CommunityManagement.isBotEnabled = result.enabled == "1";
				let messageNoMatch = result.messageNoMatch == "1";
				let saludoInicial = result.saludoInicial == "1";
				if(CommunityManagement.isBotEnabled){
					$('#wrap-message-query').removeClass('disabled');
				}else{
					$('#wrap-message-query').addClass('disabled');
				}
				if(messageNoMatch && CommunityManagement.isBotEnabled){
					CommunityManagement.acceptedNoMatches = result.numVecesNoMatch;
					CommunityManagement.textNoMatch = result.textoNoMatch;
					CommunityManagement.noMatchNotificationText = result.textoNotificarNoMatch;
					CommunityManagement.notifyUserNoMatch = result.notifyUserNoMatch;
					CommunityManagement.notifyMsgNoMatch = result.texttouser;
				}
				
				if(saludoInicial && CommunityManagement.isBotEnabled){
					if(isNewBotChat){	
						//Si es chatBot es nuevo y tiene un saludo inicial se pone como currentChat 
						CommunityManagement.renderOnlyChatBot();
						CommunityManagement.currentChat = stcmbackend.communymanagement.currentChat.bid;
						CommunityManagement.initializeChatbot();
					}else{
						CommunityManagement.isNewBotChat = false;
						if(CommunityManagement.needRefresh){
							CommunityManagement.needRefresh = false
						}else{
							// CommunityManagement.sendBotMessage('SLinicializaBot');
						}
					}
			
				}else{
					CommunityManagement.renderOnlyChatBot()
					CommunityManagement.currentChat = stcmbackend.communymanagement.currentChat.bid;
				}
			
			}
		}
		return CommunityManagement.isVoiceAssistant;
	},

	resetChatVoiceAssistantValues(){
		CommunityManagement.textNoMatch = '',
		CommunityManagement.noMatchNotificationText = '',
		CommunityManagement.notifyUserNoMatch = '',
		CommunityManagement.acceptedNoMatches = 0,
		CommunityManagement.noMatchNow = 0,
		CommunityManagement.messageNoMatch = false

		$("#messageBoxContainer").removeClass("disabled");
		$("#adminChat").hide();
	},

	//Vista para Chat de usuario normal
	defaultChatLayout(){
		var inputMessage = document.querySelector('.wrap-message-content');
		$('#menu-chat-opt').removeClass("d-none")
		$('#wrap-message-query').addClass("d-none")
		inputMessage.classList.add('my-25');
		$('#communityManagementContainer .emojionearea-button').removeClass("d-none")
		$('#communityManagementContainer .emojionearea .emojionearea-editor').removeClass('pl-2')
		$('#communityManagementContainer .wrap-message-content .message').removeClass('w-100')
	},
	//Vista para Chat de Bot
	chatBotLayout(){
		var inputMessage = document.querySelector('.wrap-message-content');

			$('#menu-chat-opt').addClass("d-none")
			$('#wrap-message-query').removeClass("d-none")
			$(this).find('.wrap-message-content').removeClass('my-25');
			inputMessage.classList.remove('my-25');
			$('#communityManagementContainer .emojionearea-button').addClass("d-none")
			$('#communityManagementContainer .emojionearea .emojionearea-editor').addClass('pl-2')
			$('#communityManagementContainer .wrap-message-content .message').addClass('w-100')
	},

	//Enviar mensaje al Bot
	sendBotMessage(message){
		let parameters = {
			to: CommunityManagement.jsonUser.token,
			from: stcmbackend.communymanagement.currentChat.email,
			message: message
		};
		
		ajaxComunCallWithCallback('sendBotMessage', parameters, function(ajaxReturn) {
			if (ajaxReturn && ajaxReturn.result.length > 0) {
				let obj = ajaxReturn.result;
			}
		}, false);
	},

	SendMessageAdminBot: async function(to, from, message){
		let parameters = {
			to: to,
			from: from,
			message: message
		};
		
		let ajaxReturn = await new Promise((resolve) => {
			ajaxComunCallWithCallback('SendMessageAdminBot', parameters, function (result) {
				resolve(result);
			}, false);
		});
			if (ajaxReturn && ajaxReturn.result.length > 0) {
				//
			}
	},

	 sendMessage: async function(to, from, message) {
		let receiver = [];
		receiver.push(to);
		let parameters = {
			to: JSON.stringify(receiver),
			from: from,
			message: message
		};
		let ajaxReturn = await new Promise((resolve, reject) => {
			ajaxComunCallWithCallback('postMessage_SaaS', parameters, function (result) {
				resolve(result);
			}, false);
		});
			if (ajaxReturn && ajaxReturn.result.length > 0) {
				//
			}
	},

	notifyNoMatch:async function () {
		await CommunityManagement.SendMessageAdminBot(
			CommunityManagement.notifyUserNoMatch,
			stcmbackend.communymanagement.currentChat.email,
			CommunityManagement.noMatchNotificationText
		);


		// await CommunityManagement.sendMessage(
		// 	CommunityManagement.jsonUser.token,
		// 	stcmbackend.communymanagement.currentChat.email,
		// 	CommunityManagement.notifyMsgNoMatch
		// );
	},

	printReplyMessage(obj) {
		/**
		* 0 - Mensaje normal (video, imagen, pdf)
		* 1 - Pegunta cerrada
		* 2 - Grabación de audio
		* 6 - Survey
		* 7 - Deep Link
		* 1000 - Mensaje de sistema
		**/

		let template = `
			<div class="replyMessageBox rounded pl-2 pr-1">
				<span style="color: var(--maincolor);"><strong>${obj.user || obj.nameuser}</strong></span>
		`;
		switch (obj.msgType) {
			case '1': //1 - Pegunta cerrada
				template += `
					<div class="content pb-1 ${pt}">
						<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
					</div>
				`;
				break;
			case '2': //2 - Grabación de audio
				template += `
					<div class="content-file-audio">
						<audio controls>
							<source src="${obj.attachment.url}" type="${obj.attachment.type}">
						</audio>
					</div>

					<div class="content pb-1">
						<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
					</div>
				`;
				break;
			case '6': //6 - Survey
				template += `
					<div class="content pb-1">
						<div class="d-flex chat-mision c-pointer">
							<i class="fa-duotone fa-list-check"></i>
							<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
						</div>
					</div>
				`;
				break;
			case '7': //7 - Deep Link
				template += `
					<div class="content pb-1 ${pt}">
						<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
					</div>

					<div class="d-flex chat-deeplink pt-2 c-pointer">
						<div class="deeplinkIcon">
							<img src="${obj.deeplink.icon}">
						</div>
						<div class="jsxc_deeplinkText">${obj.deeplink.text}</div>
					</div>
				`;
				break;
			case '1000': //1000 - Mensaje de sistema
				template += `
					<div class="content pb-1">
						<span>${obj.msg}</span>
					</div>
				`;
				break;
			default:
				if (obj.attachment && obj.attachment.hasOwnProperty('name') && obj.attachment.length > 0 && obj.attachment.name != 'null' && obj.attachment.name != '') {
					if (obj.attachment.type.match(/^image\//)) {
						template += `
							<div class="content-file">
								<img src="${obj.attachment.url}"/>
							</div>

							<div class="content pb-1">
								<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
							</div>
						`;
					} else if (obj.attachment.type.match(/^video\//)) {
						template += `
							<div class="content-file">
								<video src="${obj.attachment.url}" controls></video>
							</div>

							<div class="content pb-1">
								<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
							</div>
						`;
					} else if (obj.attachment.type.match(/\/pdf/)) {
						template += `
							<div class="content-file">
								<embed src="${obj.attachment.url}#toolbar=0&view=Fit" type="application/pdf" />
							</div>

							<div class="content pb-1">
								<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
							</div>
						`;
					}
				} else {
					template += `
						<div class="content pb-1">
							<span>${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
						</div>
					`;
				}
				break;
		}

		template += `
			</div>
		`;

		return template;
	},

	renderDetallePagosByUserWithPoints(data) {
		let table = `
			<table id="contactRemunerationTable" class="table table-hover tRegs tv-80">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC348}">${pf.const.language.RSC348}</th>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
						<th scope="col" title="${pf.const.language.RSC2297}">${pf.const.language.RSC2297}</th>
						<th scope="col" title="${pf.const.language.RSC1334}">${pf.const.language.RSC1334}</th>
						<th scope="col" title="${pf.const.language.RSC1335}">${pf.const.language.RSC1335}</th>
						<th scope="col" title="${pf.const.language.RSC506}">${pf.const.language.RSC506}</th>
						<th scope="col" title="${pf.const.language.RSC1633}">${pf.const.language.RSC1633}</th>
						<th scope="col" title="${pf.const.language.RSC1336}">${pf.const.language.RSC1336}</th>
					</tr>
				</thead>

				<thead class="filtersRemuneration">
					<tr>
						<td>concepto</td>
						<td>fecha</td>
						<td>valor</td>
						<td>exportado</td>
						<td>fecha_exportacion</td>
						<td>cobrado</td>
						<td>no_cobrable</td>
						<td>fecha_cobro</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = data.length;
		for (let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${data[i].concepto}">${data[i].concepto}</td>
					<td class="text-truncate" title="${data[i].fecha}">${data[i].fecha}</td>
					<td class="text-truncate" title="${data[i].valor}">${data[i].valor}</td>
					<td class="text-center">
						<span class="d-none">${(data[i].exported == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(data[i].exported == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${data[i].fechaExported}">${data[i].fechaExported}</td>
					<td class="text-center">
						<span class="d-none">${(data[i].cobrado == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(data[i].cobrado == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						<span class="d-none">${(data[i].noCobrable == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(data[i].noCobrable == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${data[i].fechaCobro}">${data[i].fechaCobro}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

		$('#ContactRemunerationTableContainer').html(table);

		// Setup - add a text input to each footer cell
		$('#contactRemunerationTable .filtersRemuneration td').each(function () {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

			if (title == 'exportado' || title == 'cobrado' || title == 'no_cobrable') {
				value = optionsSelectAllYesNo();
			}

			$(this).html(value);
		});

		let tableRemuneration = $('#contactRemunerationTable').DataTable({
			language: pf.const.language_table,
			autoWidth: false,
			aaSorting: [],
			columnDefs: [
				{ width: '40px', targets: 2 },
				{ width: '80px', targets: 3 },
				{ width: '70px', targets: 5 },
				{ width: '95px', targets: 6 }
			],
			retrieve: true,
			scrollY: 300,
			scrollCollapse: true,
			scroller: false,
			pageLength: 25,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC118,
				className: 'd-none',
				title: pf.const.language.RSC118,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		// Ocultar botones de tabla
		hideTableButtons('contactRemunerationTable');

		// Apply the search
		applyTheSearch(tableRemuneration, 'filtersRemuneration');

		// Exportar tabla
		$('#exportContactRemuneration').off().on('click', function () {
			$('#ContactRemunerationTableContainer .buttons-excel').trigger('click');
		});
	},

	printMsgWithType: {
		normalizeMsg(message) {
			if (message == 'null' || message == null) {
				return '';
			}
			message = message.replace(/\\n/g, '\n');
			message = message.replace(/(\r\n|\n|\r)/g, '<br>');
			return message;
		},

		getIconsMsg(type) {
			if (type == 'double') {
				return `
					<svg class="bi bi-check2-all" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
						<path d="M12.354 4.354a.5.5 0 0 0-.708-.708L5 10.293 1.854 7.146a.5.5 0 1 0-.708.708l3.5 3.5a.5.5 0 0 0 .708 0l7-7zm-4.208 7-.896-.897.707-.707.543.543 6.646-6.647a.5.5 0 0 1 .708.708l-7 7a.5.5 0 0 1-.708 0z"/>
						<path d="m5.354 7.146.896.897-.707.707-.897-.896a.5.5 0 1 1 .708-.708z"/>
					</svg>
				`;
			} else {
				return `
					<svg class="bi bi-check2" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
						<path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/>
					</svg>
				`;
			}
		},

		getReadedStatus(message) {
			if (message.direction == 'in') {
				return { 'icon': '', 'class': '' };
			}

			//si de WS me indica que no es un mensaje enviado cuando el bidme tenia bloqueado
			//si no se me indica nada pero el usuario bid me tiene bloqueado (mensaje enviado desde IM)
			if (message.blocked == '1') {
				return { 'icon': CommunityManagement.printMsgWithType.getIconsMsg('single'), 'class': 'chat-message-sendCheck' };
			}

			if (message.readed) {
				return { 'icon': CommunityManagement.printMsgWithType.getIconsMsg('double'), 'class': 'chat-message-readedCheck' };
			}

			return { 'icon': CommunityManagement.printMsgWithType.getIconsMsg('double'), 'class': 'chat-message-received' };
		},

		chekIfDistributionListMsg(obj) {
			if (obj.idlist != null && obj.idlist != 'null' && obj.idlist != '') {
				return '<i class="fa-light fa-bullhorn"></i>';
			}

			return '';
		},

		fileAttachmentMsg(obj, classMsg, classMsgMouth, groupNameUser, filetype) {
			var checkstatus = CommunityManagement.printMsgWithType.getReadedStatus(obj);
			var classaudio = '';
			var templateFile = '';
			var pt = '';
			let forwardMessage = `
				<div class="custom-control custom-checkbox bubbleCheckboxContainer d-none">
					<input id="customCheck_0_${obj._uid}" type="checkbox" class="custom-control-input bubbleCheckbox" data-id="${obj._uid}">
					<label for="customCheck_0_${obj._uid}" class="custom-control-label"></label>
				</div>
			`;
			let visibility = '';
			let groupOptions = '';

			if (groupNameUser != '') {
				pt = 'pt-2';
				groupOptions = ' groupOptions';
			}

			let styleGradient = 'background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0));';
			if (classMsg == 'me') {
				styleGradient = 'background-image: linear-gradient(to bottom, var(--maincoloropacity03), rgba(0, 0, 0, 0));';
			}

			switch (filetype) {
				case 'video':
					templateFile += `
						<div class="attContainer attachmentViewer c-pointer" data-type="video">
							<video src="${obj.attachment.url}" controls></video>
							<div class="attScreen"></div>
							<div class="multimediaGradient rounded d-none" style="${styleGradient}"></div>
						</div>
					`;
					break;
				case 'pdf':
					templateFile += `
						<div class="attContainer attachmentViewer c-pointer" data-type="pdf">
							<embed src="${obj.attachment.url}#toolbar=0&view=Fit" type="application/pdf" />
							<div class="attScreen"></div>
							<div class="multimediaGradient rounded d-none" style="${styleGradient}"></div>
						</div>
					`;
					break;
				case 'audio':
					templateFile += `
						<audio controls>
							<source src="${obj.attachment.url}" type="${obj.attachment.type}">
						</audio>
					`;
					classaudio = '-audio';
					forwardMessage = `<div class="custom-control custom-checkbox bubbleCheckboxContainer d-none"></div>`;
					visibility = 'd-none';
					break;
				default:
					templateFile += `
						<div class="attContainer attachmentViewer c-pointer" data-type="img">
							<img src="${obj.attachment.url}">
							<div class="attScreen"></div>
							<div class="multimediaGradient rounded d-none" style="${styleGradient}"></div>
						</div>
					`;
					break;
			}

			// Mensaje de respuesta
			let replyMessage = '';
			if (obj.msgOld != undefined) {
				replyMessage = CommunityManagement.printReplyMessage(obj.msgOld);
			}

			// Mensaje reenviado
			let forwarded = '';
			if (obj.reenviado == '1') {
				forwarded = `
					<span class="text-muted">
						<i class="fa-solid fa-share" aria-hidden="true"></i>
						<em>${pf.const.language.RSC2314}</em>
					</span><br>
				`;
			}

			// Mensaje editado
			let editedMessage = '';
			if (obj.editado == '1') {
				editedMessage = `<i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>`;
			}

			// Opción de editar mensaje
			let editMessage = '';
			if (classMsg == 'me') {
				editMessage = `<a href="#" class="dropdown-item chat-bubble-edit py-2" data-uid="${obj._uid}" data-date="${obj.stampServer * 1000}">${pf.const.language.RSC2282}</a>`;
			}

			// Opción de responder mensaje
			let replyMessageOption = `<a href="#" class="dropdown-item chat-bubble-responder py-2" data-id="${obj._uid}" data-contact="${obj.user || obj.nameuser}" data-direction="${obj.direction}">${pf.const.language.RSC2280}</a>`;
			if (stcmbackend.communymanagement.currentChat.idList != '' && stcmbackend.communymanagement.currentChat.idList != undefined) {
				replyMessageOption = '';
			}

			return `
				<div class="d-flex py-1 chat-bubble-container chat-bubble-container-${classMsg}">
					${forwardMessage}

					<div class="chat-bubble ${classMsg}" data-uid="${obj._uid}">
						${replyMessage}

						<div class="${classMsgMouth}"></div>
						${groupNameUser}
						<div class="chat-bubble-opt nav-item dropdown ml-auto${groupOptions}">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
								<i class="fa-regular fa-chevron-down c-pointer chat-bubble-arrow d-none p-1 mt-2 text-white"></i>
							</a>
							<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
								${replyMessageOption}
								<a href="#" class="dropdown-item chat-bubble-reenviar ${visibility} py-2">${pf.const.language.RSC2281}</a>
								${editMessage}
							</div>
						</div>

						<div class="content-file${classaudio} ${pt}">${templateFile}</div>

						<div class="d-flex justify-content-between align-items-end">
							<div class="content">
								${forwarded}
								<span class="content_text">${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
							</div>

							<div class="d-flex chat-info-msg">
								${CommunityManagement.printMsgWithType.chekIfDistributionListMsg(obj)}
								<div class="time">
									${editedMessage}
									${CommunityManagement.utils.getFormattedTime(obj.stampServer * 1000, true)}
								</div>
								<div class="${checkstatus.class}">${checkstatus.icon}</div>
							</div>
						</div>
					</div>
				</div>
			`;
		},

		simpleTextMsg(obj, classMsg, classMsgMouth, groupNameUser) {
			var checkstatus = CommunityManagement.printMsgWithType.getReadedStatus(obj);
			var pt = '';

			if (groupNameUser != '') {
				pt = 'pt-2';
			}

			// Mensaje de respuesta
			let replyMessage = '';
			if (obj.msgOld != undefined) {
				replyMessage = CommunityManagement.printReplyMessage(obj.msgOld);
			}

			// Mensaje reenviado
			let forwarded = '';
			if (obj.reenviado == '1') {
				forwarded = `
					<span class="text-muted">
						<i class="fa-solid fa-share" aria-hidden="true"></i>
						<em>${pf.const.language.RSC2314}</em>
					</span><br>
				`;
			}

			// Mensaje editado
			let editedMessage = '';
			if (obj.editado == '1') {
				editedMessage = `<i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>`;
			}

			// Opción de editar mensaje
			let editMessage = '';
			if (classMsg == 'me') {
				editMessage = `<a href="#" class="dropdown-item chat-bubble-edit py-2" data-uid="${obj._uid}" data-date="${obj.stampServer * 1000}">${pf.const.language.RSC2282}</a>`;
			}

			// Opción de responder mensaje
			let replyMessageOption = `<a href="#" class="dropdown-item chat-bubble-responder py-2" data-id="${obj._uid}" data-contact="${obj.user || obj.nameuser}" data-direction="${obj.direction}">${pf.const.language.RSC2280}</a>`;
			if (stcmbackend.communymanagement.currentChat.idList != '' && stcmbackend.communymanagement.currentChat.idList != undefined) {
				replyMessageOption = '';
			}

			return `
				<div class="d-flex py-1 chat-bubble-container chat-bubble-container-${classMsg}">
					<div class="custom-control custom-checkbox bubbleCheckboxContainer d-none">
						<input id="customCheck_0_${obj._uid}" type="checkbox" class="custom-control-input bubbleCheckbox" data-id="${obj._uid}">
						<label for="customCheck_0_${obj._uid}" class="custom-control-label"></label>
					</div>

					<div class="chat-bubble ${classMsg}" data-uid="${obj._uid}">
						${replyMessage}

						<div class="${classMsgMouth}"></div>
						${groupNameUser}
						<div class="chat-bubble-opt nav-item dropdown ml-auto">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
								<i class="fa-regular fa-chevron-down c-pointer chat-bubble-arrow d-none p-1 mt-1"></i>
							</a>
							<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
								${replyMessageOption}
								<a href="#" class="dropdown-item chat-bubble-reenviar py-2">${pf.const.language.RSC2281}</a>
								${editMessage}
							</div>
						</div>

						<div class="d-flex justify-content-between align-items-end pt-1">
							<div class="content ${pt}">
								${forwarded}
								<span class="content_text">${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
							</div>

							<div class="d-flex chat-info-msg">
								${CommunityManagement.printMsgWithType.chekIfDistributionListMsg(obj)}
								<div class="time">
									${editedMessage}
									${CommunityManagement.utils.getFormattedTime(obj.stampServer * 1000, true)}
								</div>
								<div class="${checkstatus.class}">${checkstatus.icon}</div>
							</div>
						</div>
					</div>
				</div>
			`;
		},

		questionMsg(obj, classMsg, classMsgMouth, groupNameUser) {
			var checkstatus = CommunityManagement.printMsgWithType.getReadedStatus(obj);
			var botonesDisabled = '';
			var classEvents = '';
			var botonClass = 'btn-default';
			var templateBtn = '';
			var pt = '';

			if (groupNameUser != '') {
				pt = 'pt-2';
			}

			//si no es del user que lo envia, lo desabilita
			if (obj.direction == 'out' || obj.answered != '0') {
				botonesDisabled = 'disabled';
				classEvents = 'noEventsAllowed';
			}

			//prepara los botones
			for (var i = 0; i < obj.params.length; i++) {
				//filtros class de boton
				if (obj.answered != '0') {
					if (obj.params[i].id == obj.selectedAnswer) {
						botonClass = 'mainbgClassWhiteColor';
					} else {
						botonClass = 'btn-default';
					}
				}

				templateBtn += `<button class="chat-question-button btn btn-sm ${botonClass} ${classEvents}" ${botonesDisabled} data-id="${obj.params[i].id}"> ${obj.params[i].value} </button>`;
			}

			var templateAnswer = '';
			if (obj.answered == '1') {
				templateAnswer = `<div class="time">${CommunityManagement.utils.getFormattedTime(obj.stampAnswer * 1000, true)}</div>`;
			}

			// Mensaje de respuesta
			let replyMessage = '';
			if (obj.msgOld != undefined) {
				replyMessage = CommunityManagement.printReplyMessage(obj.msgOld);
			}

			// Mensaje reenviado
			let forwarded = '';
			if (obj.reenviado == '1') {
				forwarded = `
					<span class="text-muted">
						<i class="fa-solid fa-share" aria-hidden="true"></i>
						<em>${pf.const.language.RSC2314}</em>
					</span><br>
				`;
			}

			// Mensaje editado
			let editedMessage = '';
			if (obj.editado == '1') {
				editedMessage = `<i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>`;
			}

			// Opción de editar mensaje
			let editMessage = '';
			if (classMsg == 'me') {
				editMessage = `<a href="#" class="dropdown-item chat-bubble-edit py-2" data-uid="${obj._uid}" data-date="${obj.stampServer * 1000}">${pf.const.language.RSC2282}</a>`;
			}

			// Opción de responder mensaje
			let replyMessageOption = `<a href="#" class="dropdown-item chat-bubble-responder py-2" data-id="${obj._uid}" data-contact="${obj.user || obj.nameuser}" data-direction="${obj.direction}">${pf.const.language.RSC2280}</a>`;
			if (stcmbackend.communymanagement.currentChat.idList != '' && stcmbackend.communymanagement.currentChat.idList != undefined) {
				replyMessageOption = '';
			}

			return `
				<div class="d-flex py-1 chat-bubble-container chat-bubble-container-${classMsg}">
					<div class="custom-control custom-checkbox bubbleCheckboxContainer d-none">
						<input id="customCheck_0_${obj._uid}" type="checkbox" class="custom-control-input bubbleCheckbox" data-id="${obj._uid}">
						<label for="customCheck_0_${obj._uid}" class="custom-control-label"></label>
					</div>

					<div class="chat-bubble ${classMsg}" data-uid="${obj._uid}">
						${replyMessage}

						<div class="${classMsgMouth}"></div>
						${groupNameUser}
						<div class="chat-bubble-opt nav-item dropdown ml-auto">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
								<i class="fa-regular fa-chevron-down c-pointer chat-bubble-arrow d-none p-1 mt-1"></i>
							</a>
							<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
								${replyMessageOption}
								<a href="#" class="dropdown-item chat-bubble-reenviar py-2">${pf.const.language.RSC2281}</a>
								${editMessage}
							</div>
						</div>

						<div class="content ${pt}">
							${forwarded}
							<span class="content_text">${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
						</div>

						<div class="time questionStamp">
							${editedMessage}
							${CommunityManagement.utils.getFormattedTime(obj.stampServer * 1000, true)}
						</div>

						<div class="questionButton d-flex pb-2">${templateBtn}</div>

						<div class="d-flex chat-info-msg">
							${CommunityManagement.printMsgWithType.chekIfDistributionListMsg(obj)}
							${templateAnswer}
							<div class="${checkstatus.class}">${checkstatus.icon}</div>
						</div>
					</div>
				</div>
			`;
		},

		surveyMsg(obj, classMsg, classMsgMouth, groupNameUser) {
			var checkstatus = CommunityManagement.printMsgWithType.getReadedStatus(obj);
			var pt = '';

			if (groupNameUser != '') {
				pt = 'pt-2';
			}

			// Mensaje de respuesta
			let replyMessage = '';
			if (obj.msgOld != undefined) {
				replyMessage = CommunityManagement.printReplyMessage(obj.msgOld);
			}

			// Mensaje reenviado
			let forwarded = '';
			if (obj.reenviado == '1') {
				forwarded = `
					<span class="text-muted">
						<i class="fa-solid fa-share" aria-hidden="true"></i>
						<em>${pf.const.language.RSC2314}</em>
					</span><br>
				`;
			}

			return `
				<div class="d-flex py-1 chat-bubble-container chat-bubble-container-${classMsg}">
					<div class="chat-bubble ${classMsg}" data-uid="${obj._uid}">
						${replyMessage}

						<div class="${classMsgMouth}"></div>
						${groupNameUser}
						<div class="chat-bubble-opt nav-item dropdown ml-auto">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
								<i class="fa-regular fa-chevron-down c-pointer chat-bubble-arrow d-none p-1 mt-1"></i>
							</a>
							<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
								<a href="#" class="dropdown-item chat-bubble-responder py-2" data-id="${obj._uid}" data-contact="${obj.user || obj.nameuser}" data-direction="${obj.direction}">${pf.const.language.RSC2280}</a>
							</div>
						</div>

						<div class="d-flex justify-content-between align-items-end">
							<div class="content ${pt}">
								<div class="d-flex chat-mision c-pointer">
									${forwarded}
									<i class="fa-duotone fa-list-check"></i>
									<span class="content_text">${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
								</div>
							</div>

							<div class="d-flex chat-info-msg">
								${CommunityManagement.printMsgWithType.chekIfDistributionListMsg(obj)}
								<div class="time">${CommunityManagement.utils.getFormattedTime(obj.stampServer * 1000, true)}</div>
								<div class="${checkstatus.class}">${checkstatus.icon}</div>
							</div>
						</div>
					</div>
				</div>
			`;
		},

		deeplinkMsg(obj, classMsg, classMsgMouth, groupNameUser) {
			var checkstatus = CommunityManagement.printMsgWithType.getReadedStatus(obj);
			var pt = '';

			if (groupNameUser != '') {
				pt = 'pt-2';
			}

			// Mensaje de respuesta
			let replyMessage = '';
			if (obj.msgOld != undefined) {
				replyMessage = CommunityManagement.printReplyMessage(obj.msgOld);
			}

			// Mensaje reenviado
			let forwarded = '';
			if (obj.reenviado == '1') {
				forwarded = `
					<span class="text-muted">
						<i class="fa-solid fa-share" aria-hidden="true"></i>
						<em>${pf.const.language.RSC2314}</em>
					</span><br>
				`;
			}

			return `
				<div class="d-flex py-1 chat-bubble-container chat-bubble-container-${classMsg}">
					<div class="chat-bubble ${classMsg}" data-uid="${obj._uid}">
						${replyMessage}

						<div class="${classMsgMouth}"></div>
						${groupNameUser}
						<div class="chat-bubble-opt nav-item dropdown ml-auto">
							<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
								<i class="fa-regular fa-chevron-down c-pointer chat-bubble-arrow d-none p-1 mt-1"></i>
							</a>
							<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
								<a href="#" class="dropdown-item chat-bubble-responder py-2" data-id="${obj._uid}" data-contact="${obj.user || obj.nameuser}" data-direction="${obj.direction}">${pf.const.language.RSC2280}</a>
							</div>
						</div>

						<div class="content ${pt}">
							${forwarded}
							<span class="content_text">${CommunityManagement.printMsgWithType.normalizeMsg(obj.msg)}</span>
						</div>

						<div class="d-flex chat-deeplink pt-2 c-pointer">
							<div class="deeplinkIcon">
								<img src="${obj.deeplink.icon}"/>
							</div>
							<div class="jsxc_deeplinkText">${obj.deeplink.text}</div>
						</div>

						<div class="d-flex chat-info-msg">
							${CommunityManagement.printMsgWithType.chekIfDistributionListMsg(obj)}
							<div class="time">${CommunityManagement.utils.getFormattedTime(obj.stampServer * 1000, true)}</div>
							<div class="${checkstatus.class}">${checkstatus.icon}</div>
						</div>
					</div>
				</div>
			`;
		},

		sysTextMsg(obj) {
			// Mensaje de respuesta
			let replyMessage = '';
			if (obj.msgOld != undefined) {
				replyMessage = CommunityManagement.printReplyMessage(obj.msgOld);
			}

			// Mensaje reenviado
			let forwarded = '';
			if (obj.reenviado == '1') {
				forwarded = `
					<span class="text-muted">
						<i class="fa-solid fa-share" aria-hidden="true"></i>
						<em>${pf.const.language.RSC2314}</em>
					</span><br>
				`;
			}

			return `
				<div class="sys-msg d-flex pb-2">
					<div class="chat-bubble" data-uid="${obj._uid}">
						${replyMessage}

						<div class="content">
							${forwarded}
							<span class="content_text">${obj.msg}</span>
						</div>
					</div>
				</div>
			`;
		},

		checkDatetag(message, cargarMas) {
			//Creamos un Date(unixtime) con la fecha del mensaje
			var msgDate = new Date(parseInt(message.stamp));
			if (message.msgType == '1' && message.answered == '1') {
				msgDate = new Date(parseInt(message.stampAnswer));
			}
			msgDate.setHours(0, 0, 0, 0); //Reseteamos las hh:mm:ss:ms - msgDate = dd/MM/yyyy

			if (!CommunityManagement.printedDatesInchat.includes(msgDate.toLocaleDateString())) {
				CommunityManagement.printedDatesInchat.push(msgDate.toLocaleDateString());
				return CommunityManagement.printMsgWithType.createDateTag(msgDate, cargarMas);
			}

			return '';
		},

		createDateTag(msgDate, cargarMas) {
			var dateNow = new Date();
			var msgDateYest = new Date();
			msgDateYest.setDate(msgDateYest.getDate() - 1);

			var msgDayTagClass = 'msgDate_tag';
			if (!cargarMas) {
				msgDayTagClass = 'msgDate_tag lastmsgDateTag';
			}

			var dateString = msgDate.toLocaleDateString();
			if (msgDate.toLocaleDateString() == dateNow.toLocaleDateString()) {
				dateString = pf.const.language.RSC2311;
			} else if (msgDate.toLocaleDateString() == msgDateYest.toLocaleDateString()) {
				dateString = pf.const.language.RSC2312;
			}

			return `
				<div class="msgDate_div pt-2 pb-3">
					<span class="${msgDayTagClass}" datetagstamp="${msgDate.toLocaleDateString()}">${dateString}</span>
				</div>
			`;
		}
	},

	showContactInformation(chat, data) {
		const self = this;
		$('.chat-window-container .chat-head i').hide();
		$('.chat-window-container').css('width', 'calc(100% - 350px)');

		if (chat.type == undefined || chat.type == 'chat') {
			$('.information-chat').css('display', 'flex');

			var template = `
				<div class="d-flex flex-column">
					<img src="${chat.avatar}">
					<p class="ellipsis text-center font-weight-bold m-1 pl-4 pr-4">${chat.name}</p>
					<p class="ellipsis text-center chat-window-info-email pl-4 pr-4">${chat.bid}</p>
				</div>
				<div class="d-flex chatwindows-media pl-4 pr-4 c-pointer">
					<i class="">${stcmbackend.svg.image}</i>
					<span class="w100 pl-3">Archivos del chat</span>
					<i class="fa-light fa-chevron-right"></i>
				</div>
				<div>
					<span class="chat-window-info-title">${pf.const.language.RSC2283}</span>
					<p></p>
				</div>
				<div>
					<span class="chat-window-info-title">${pf.const.language.RSC305}</span>
					<div class="d-flex pl-3 pt-1 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC303}:</p>
						<p class="ellipsis w50 m-0">${data.username || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC123}:</p>
						<p class="ellipsis w50 m-0">${data.userNombre || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC1626}:</p>
						<p class="ellipsis w50 m-0">${data.userApellidos || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC1627}:</p>
						<p class="ellipsis w50 m-0">${data.userApellidos2 || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC550}:</p>
						<p class="ellipsis w50 m-0">${data.countrydesc || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC308}:</p>
						<p class="ellipsis w50 m-0">${chat.name || ''}</p>
					</div>
				</div>
				<div>
					<span class="chat-window-info-title">${pf.const.language.RSC115}</span>
					<div class="d-flex pl-3 pt-1 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC564}:</p>
						<p class="ellipsis w50 m-0">${data.questionEstado || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC151}:</p>
						<p class="ellipsis w50 m-0">${data.questionGenero || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC2284}:</p>
						<p class="ellipsis w50 m-0">${data.questionEdadFecha || ''}</p>
					</div>
					<div class="d-flex pl-3 pb-1">
						<p class="chat-window-info-data">${pf.const.language.RSC598}:</p>
						<p class="ellipsis w50 m-0">${data.questionABI || ''}</p>
					</div>
				</div>
				<div class="d-flex chat-window-info-remuneration pl-4 pr-4 c-pointer">
					<i class="fa-light fa-money-check-dollar"></i>
					<span class="w100 pl-3">${pf.const.language.RSC2285}</span>
					<i class="fa-light fa-chevron-right"></i>
				</div>
				<div class="pl-4 pr-4 d-flex flex-column">
					<div class="d-flex chat-window-info-mute">
						<i class="fa-light fa-bell"></i>
						<label for="chatwindows-notif" class="mr-1 pl-4 mb-0 w80">${pf.const.language.RSC2272}</label>
						<div class="custom-control custom-switch d-inline-block pt-4">
							<input id="chatwindows-notif" type="checkbox" class="custom-control-input profile-notif-config" data-type="message" ${data.mute == '0' ? '' : 'checked'}>
							<label for="chatwindows-notif" class="custom-control-label c-pointer"></label>
						</div>
					</div>
					<div class="c-pointer d-flex chat-window-info-block red-app" data-blocked="${data.blocked}">
						<i class="fa-light fa-ban"></i>
						<span class="w100 pl-3">${data.blocked == '0' ? pf.const.language.RSC2286 : pf.const.language.RSC2294}</span>
					</div>
				</div>
			`;

			$('.information-container').html(template);

			// Ver remuneraciones
			$('.chat-window-info-remuneration').off().on('click', function () {
				$('#modalContactRemuneration').modal('show');

				let parameters = {
					user: data.token,
					idTenantApp: data.idTenant,
					idCPGApp: data.idCPG
				};
				ajaxComunCallWithCallback('getDetallePagosByUserWithPoints_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.result_currency_detail;

						CommunityManagement.renderDetallePagosByUserWithPoints(data);
					}
				}, false);
			});

			// Mostrar multimedia
			$('.chatwindows-media').off().on('click', function () {
				// Mostrar Spinner
				$('#MediaSpinner').removeClass('d-none');
				$('#MediaSpinner').addClass('d-flex');

				$('.chat-media').removeClass('d-none');
				CommunityManagement.transitions.hideSlide($('.information-chat'), 'right');
				CommunityManagement.transitions.showSlide($('.chat-media'), 'left');

				let parameters = {
					userA: CommunityManagement.jsonUser.token,
					userB: data.token
				};
				ajaxComunCallWithCallback('getChatMedia_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.media;
						CommunityManagement.chatMedia(data);
						// Ocultar Spinner
						$('#MediaSpinner').removeClass('d-flex');
						$('#MediaSpinner').addClass('d-none');
					}
				}, false);


			});


			$('#close-media-chat').off().click(function () {
				CommunityManagement.transitions.showSlide($('.information-chat'), 'left');
				CommunityManagement.transitions.hideSlide($('.chat-media'), 'right');
				$('.chat-media').addClass('d-none');
				// $('.information-chat').removeClass('d-none');
			});

			// Silenciar contacto
			$('#chatwindows-notif').off().on('change', function () {
				let mute = $('#chatwindows-notif').prop('checked') ? '1' : '0';

				let parameters = {
					userA: CommunityManagement.jsonUser.token,
					userB: data.token,
					mute: mute
				};
				ajaxComunCallWithCallback('muteChat_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						stcmbackend.communymanagement.currentChat.mute.muted = mute;
					}
				}, false);
			});

			// Bloquear contacto
			$('.chat-window-info-block').off().on('click', function () {
				let value = $('.chat-window-info-block').data('blocked') == '0' ? '1' : '0';

				let parameters = {
					email: CommunityManagement.jsonUser.token,
					userBloqueado: data.token,
					value: value
				};
				ajaxComunCallWithCallback('bloquearContacto_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						// Actualización de elemento
						$('.chat-window-info-block').data('blocked', value);
						let text = value == '0' ? pf.const.language.RSC2286 : pf.const.language.RSC2294;
						$('.chat-window-info-block span').text(text);
						stcmbackend.communymanagement.currentChat.blocked = value;

						if (value == '1') {
							$('#messageBoxContainer').hide();

							// Aviso de usuario bloqueado
							let warningTitle = stcmbackend.communymanagement.currentChat.name;
							let warningContent = pf.const.language.RSC2626;
							pf.utils.showInfoDialog(warningTitle, warningContent);
						} else {
							$('#messageBoxContainer').show();
						}
					}
				}, false);
			});
		} else if (chat.type == 'groupchat') {
			$('.information-group').css('display', 'flex');

			let users = '';
			let emails = [];
			let jidAdmin = data.jidUser;

			let isAdmin = jidAdmin == CommunityManagement.jsonUser.jidUser;
			let isMuted = chat.mute.muted !== '0';


			const hasDescription = data.description !== null && data.description !== '' && data.description !== '\"\"';
			const isGroupMember = data.members.some(user => user.email === CommunityManagement.jsonUser.token && user.jidUser === CommunityManagement.jsonUser.jidUser);

			let description = '';

			if (hasDescription || isGroupMember) {
				description = `
					<div id="editGroupDescription" class="d-flex flex-column pl-4 pr-4 ${isGroupMember ? 'c-pointer' : ''}">
						<span class="chat-window-info-title mb-2">${pf.const.language.RSC2699}</span>
						<div class="d-flex align-items-center">
							<span id="groupDescriptionText" class="flex-grow-1">${hasDescription ? data.description.replace(/^"(.*)"$/, '$1') : pf.const.language.RSC2693}</span>
							${isGroupMember ? '<i class="fa-light fa-chevron-right"></i>' : ''}
						</div>
					</div>
				`;
			}

			let userOptions = isAdmin ? `
				<div class="group-user-opt dropdown ml-auto">
					<a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color:unset">
						<i class="fa-light fa-chevron-down c-pointer p-1 mt-2"></i>
					</a>
					<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
						<a class="dropdown-item changeGroupAdmin" href="#" data-email="\${userId}">${pf.const.language.RSC2694}</a>
						<a class="dropdown-item removeFromGroup" href="#" data-email="\${userId}">${pf.const.language.RSC2695}</a>
					</div>
				</div>` : '';

			// Lista de miembros del grupo
			for (let i = 0; i < data.numMembers; i++) {
				let admin = '';
				if (jidAdmin == data.members[i].jidUser) {
					admin = ' - ' + pf.const.language.RSC163;
				}

				let user = `
					<div class="chat-window-info-user">
						<img src="${data.members[i].avatar}">
						<p class="ellipsis text-center font-weight-bold m-0 pl-2">${data.members[i].name + admin}</p>
						${userOptions.replace(/\${userId}/g, data.members[i].email)}
					</div>
				`;

				users += user;

				// Control de emails de miembros del grupo
				emails.push(data.members[i].email);
			}

			// Add participants
			var addParticipants = isAdmin ? `
			<div id="addContactsToGroup" class="c-pointer" title="${pf.const.language.RSC987}">
				<i class="fa-light fa-circle-plus maincolorClass"></i>
				<span class="maincolorClass">${pf.const.language.RSC987}</span>
			</div>
			` : '';

			// Mute
			var muteChat = isMuted ? `
				<i id="groupChatMuteToggle" class="fas fa-toggle-on fa-lg"></i>
			` : `
				<i id="groupChatMuteToggle" class="fas fa-toggle-off fa-lg"></i>
			`;

			var actions = isGroupMember ? `
				<!-- Mute chat -->
				<div id="muteGroupChat" class="d-flex align-items-center mb-4 c-pointer">
					<i class="fas fa-volume-mute text-primary"></i>
					<span class="flex-grow-1 pl-3">${pf.const.language.RSC2701}</span>
					${muteChat}
				</div>

				<!-- Clean conversation -->
				<div id="cleanChatGroup" class="mb-4 c-pointer">
					<span class="w100 text-danger">${pf.const.language.RSC2703}</span>
				</div>

				<!-- Leave group -->
				<div id="leaveGroup" class="mb-2 c-pointer">
					<span class="w100 text-danger">${pf.const.language.RSC2704}</span>
				</div>
			` : `
				<div class="d-flex">
					<span class="flex-grow-1">${pf.const.language.RSC2735}</span>
				</div>
			`;

			var template = `
				<!-- Information -->
				<div class="d-flex flex-column">
					<div class="group-avatar-container">
						<div class="avatar-wrapper">
							<img id="group-avatar" alt="Group avatar" src="${chat.avatar}">
							<div class="overlay">
								<button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">${pf.const.language.RSC2696}</button>
								<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
									<a class="dropdown-item" id="updateGroupAvatar" href="#">${pf.const.language.RSC2697}</a>
									<a class="dropdown-item" id="removeGroupAvatar" href="#">${pf.const.language.RSC2698}</a>
								</div>
							</div>
							<input type="file" id="groupAvatarInput" style="display:none;">
						</div>
					</div>
				
					<p class="ellipsis text-center font-weight-bold m-1 pl-4 pr-4">${chat.name}</p>
					<p class="ellipsis text-center chat-window-info-email pl-4 pr-4">${data.numMembers} ${pf.const.language.RSC443}</p>
				</div>


				<!-- Description -->
				${description}


				<!-- Media -->
				<div class="d-flex align-items-center chatwindows-media pl-4 pr-4 c-pointer">
					<i class="">${stcmbackend.svg.image}</i>
					<span class="flex-grow-1 pl-3">${pf.const.language.RSC2700}</span>
					<i class="fa-light fa-chevron-right"></i>
				</div>

				
				<!-- Actions -->
				<div class="d-flex flex-column pl-4 pr-4">
					<span class="chat-window-info-title mb-2">${pf.const.language.RSC2701}</span>
					${actions}
				</div>


				<!-- Participants -->
				<div>
					<span class="chat-window-info-title mb-2">${pf.const.language.RSC443}</span>
					<div class="pl-2 pt-2 pb-2">
						${addParticipants}
						<div class="pt-2 groupParticipants">${users}</div>
					</div>
				</div>

				<!-- Update group description modal -->
				<div class="modal fade" id="updateGroupDescriptionModal" tabindex="-1" role="dialog" aria-labelledby="Modal advertencia" aria-hidden="true" style="background: unset">
					<div class="modal-dialog modal-dialog-centered" role="document">
						<div class="modal-content">
							<div class="modal-header">
								<h5 class="modal-title">${pf.const.language.RSC2705}</h5>
								<button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
							</div>
							<div class="modal-body">
								<div class="form-group">
								<label for="groupDescription">${pf.const.language.RSC2706}</label>
								<textarea class="form-control" id="groupDescription" rows="3"></textarea>
							</div>
								
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">${pf.const.language.RSC2707}</button>
								<button type="button" class="btn btn-danger" id="updateGroupDescription">${pf.const.language.RSC2708}</button>
							</div>
						</div>
					</div>
				</div>
				`;

			$('.information-container-group').html(template);

			// Group Avatar
			$('#updateGroupAvatar').off().on('click', function () {
				$('#groupAvatarInput').click();
			});

			$('#groupAvatarInput').change(function () {
				var input = this;
				var url = $(this).val();
				var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
				let newImg = null;
				let imageSrc = null;

				if (input.files && input.files.length > 0) {
					if (input.files[0] && (ext == 'gif' || ext == 'png' || ext == 'jpeg' || ext == 'jpg')) {
						var reader = new FileReader();
						reader.onload = function (e) {
							imageSrc = e.target.result;
						};
						reader.readAsDataURL(input.files[0]);
						newImg = input.files[0];
					} else {
						pf.utils.showInfoDialog(pf.const.language.RSC2262, pf.const.language.RSC2288, pf.const.language.RSC141);
					}
				}
				if (newImg != null) {
					let parameters = {
						file: newImg,
						groupID: stcmbackend.communymanagement.currentChat.idgroup,
						groupName: stcmbackend.communymanagement.currentChat.name,
						description: '',
						removeAvatar: 0
					};
					ajaxComunCallWithCallback('updateInfoGroup_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							CommunityManagement.refresh.groupAvatar(imageSrc);

						} else {
							pf.utils.showInfoDialog(pf.const.language.RSC2739, pf.const.language.RSC2741);
						}
					}, false);
				}
			});

			$('#removeGroupAvatar').off().on('click', function () {
				let parameters = {
					groupID: stcmbackend.communymanagement.currentChat.idgroup,
					groupName: stcmbackend.communymanagement.currentChat.name,
					description: '',
					removeAvatar: 1
				};
				ajaxComunCallWithCallback('updateInfoGroup_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						CommunityManagement.refresh.groupAvatar('https://stcm.sociallabs.biz/stcm_saas/img/avatar_group_default.png');
					} else {
						pf.utils.showInfoDialog(pf.const.language.RSC2739, pf.const.language.RSC2741);
					}
				}, false);
			});

			// Description
			$('#editGroupDescription').off().on('click', function () {
				$('#updateGroupDescriptionModal').modal('show');
			});

			$('#updateGroupDescription').off().on('click', function () {
				let description = $('#groupDescription').val();

				if (description !== '') {
					let groupDescription = description.charAt(0).toUpperCase() + description.slice(1);

					let parameters = {
						groupID: stcmbackend.communymanagement.currentChat.idgroup,
						groupName: stcmbackend.communymanagement.currentChat.name,
						description: groupDescription,
						removeAvatar: 0
					};
					ajaxComunCallWithCallback('updateInfoGroup_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							CommunityManagement.refresh.groupDescription(description);
						} else {
							pf.utils.showInfoDialog(pf.const.language.RSC2743, pf.const.language.RSC2745);
						}
					}, false);
				}
				$('#updateGroupDescriptionModal').modal('hide');
			});

			// ACTIONS
			$('#muteGroupChat').off().on('click', function () {
				let parameters = {
					groupID: stcmbackend.communymanagement.currentChat.idgroup,
					email: CommunityManagement.jsonUser.token,
					mute: isMuted ? '0' : '1'
				};
				ajaxComunCallWithCallback('muteChatGroup_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						CommunityManagement.refresh.groupVolume(isMuted);
						isMuted = !isMuted;
						chat.mute.muted = isMuted ? '1' : '0';
					} else {
						pf.utils.showInfoDialog('Error al silenciar el chat', 'No se ha podido silenciar el chat. Por favor itentelo mas tarde.');
					}
				}, false);
			});


			$('#cleanChatGroup').off().on('click', function () {
				alertTitle = pf.const.language.RSC2711;
				alertText = pf.const.language.RSC2712;
				objInfo = {
					accept: {
						text: pf.const.language.RSC57
					},
					cancel: {
						text: pf.const.language.RSC2708
					}
				};
				success = function () {
					let parameters = {
						groupID: stcmbackend.communymanagement.currentChat.idgroup,
						email: CommunityManagement.jsonUser.token,
					};
					ajaxComunCallWithCallback('cleanChatGroupContent_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							// TODO: Implement proper
							CommunityManagement.refresh.completeContactList();
							CommunityManagement.refresh.completeGroupInfo();
						} else {
							pf.utils.showInfoDialog('Error al vaciar el chat', 'No se ha podido vaciar el chat. Por favor itentelo mas tarde.');
						}
					}, false);
				}
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function () { }, success);
			});


			$('#leaveGroup').off().on('click', function () {
				if (isAdmin) {
					pf.utils.showInfoDialog(
						pf.const.language.RSC2709,
						pf.const.language.RSC2713,
						pf.const.language.RSC2708,
						function () { }
					);
					return;
				}

				const leaveGroup = () => {
					const parameters = {
						groupId: stcmbackend.communymanagement.currentChat.idgroup,
						participants: JSON.stringify([CommunityManagement.jsonUser.token])
					};
					ajaxComunCallWithCallback('takeOutFromGroup_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							CommunityManagement.refresh.leaveGroup();
						} else {
							pf.utils.showInfoDialog(pf.const.language.RSC2726, pf.const.language.RSC2728);
						}
					}, false);
				};

				pf.utils.showInfoDialogAcceptCancel(
					pf.const.language.RSC2305,
					pf.const.language.RSC2306,
					{
						accept: { text: pf.const.language.RSC57 },
						cancel: { text: pf.const.language.RSC2708 }
					},
					function () { },
					leaveGroup
				);
			});

			// Multimedia
			$('.chatwindows-media').off().on('click', function () {
				$('.chat-media').removeClass('d-none');
				CommunityManagement.transitions.hideSlide($('.information-group'), 'left');
				CommunityManagement.transitions.showSlide($('.chat-media'), 'right');

				let parameters = {
					email: CommunityManagement.jsonUser.token,
					groupID: stcmbackend.communymanagement.currentChat.idgroup
				};
				ajaxComunCallWithCallback('getChatGroupMedia_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.media;
						CommunityManagement.chatMedia(data);
					}
				}, false);
			});
			$('#close-media-chat').off().click(function () {
				CommunityManagement.transitions.showSlide($('.information-group'), 'left');
				CommunityManagement.transitions.hideSlide($('.chat-media'), 'right');
				$('.information-group').removeClass('d-none');
			});

			// Ocultar "Añadir participantes" cuando el usuario ya no está en el grupo
			if (!CommunityManagement.inGroup) {
				$('#addContactsToGroup').addClass('d-none');
			}

			// Add contacts to group
			$('#addContactsToGroup').on('click', function () {
				let idGroup = data.idGroup;
				CommunityManagement.ajax.getUsers(function (data) {
					// Filter data
					data = data.filter(item => {
						return !emails.includes(item.token) && item.token !== CommunityManagement.jsonUser.token;
					});
					// Create modal
					let userSelector = new CommunityManagement.ui.UserSelector(data);
					let modal = new CommunityManagement.ui.Modal(
						pf.const.language.RSC2302,
						userSelector.getHtml(),
						{
							text: "Confirmar",
							callback: () => {
								if (userSelector.getSelectedUsers().length === 0) {
									return;
								} else {
									let participants = userSelector.getSelectedUsers();
									self.ajax.addToGroup_SaaS(idGroup, participants);
									modal.hide();
								}
							}
						}
					);
					modal.show();
					userSelector.bindEvents();
				});
			});

			// User options
			$('.changeGroupAdmin').off().on('click', function () {
				const email = $(this).data('email');

				const changeGroupAdmin = () => {
					const parameters = {
						groupID: stcmbackend.communymanagement.currentChat.idgroup,
						email: email
					};

					ajaxComunCallWithCallback('changeAdminGroup_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							CommunityManagement.refresh.completeGroupInfo();
						} else {
							pf.utils.showInfoDialog(pf.const.language.RSC2732, pf.const.language.RSC2734);
						}
					}, false);
				};

				pf.utils.showInfoDialogAcceptCancel(
					pf.const.language.RSC2729,
					pf.const.language.RSC2730,
					{
						accept: { text: pf.const.language.RSC57 },
						cancel: { text: pf.const.language.RSC2708 }
					},
					function () { },
					changeGroupAdmin
				);
			});

			$('.removeFromGroup').off().on('click', function () {
				const email = $(this).data('email');

				const removeFromGroup = () => {
					let parameters = {
						groupId: stcmbackend.communymanagement.currentChat.idgroup,
						participants: `["${email}"]`
					};
					ajaxComunCallWithCallback('takeOutFromGroup_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							CommunityManagement.refresh.groupInfo();
						} else {
							pf.utils.showInfoDialog(pf.const.language.RSC2718, pf.const.language.RSC2720);
						}
					}, false);
				};

				pf.utils.showInfoDialogAcceptCancel(
					pf.const.language.RSC2736,
					pf.const.language.RSC2737,
					{
						accept: { text: pf.const.language.RSC57 },
						cancel: { text: pf.const.language.RSC2708 }
					},
					function () { },
					removeFromGroup
				);
			});

		} else if (chat.type == 'listchat') {
			$('.information-list').removeClass('d-none');
			$('.information-list').addClass('d-flex');
			let users = '';
			let emails = [];
			// Lista de miembros de la lista
			for (let i = 0; i < data.length; i++) {
				let user = `
					<div class="chat-window-info-user">
						<img src="${data[i].avatar}">
						<p class="ellipsis text-center font-weight-bold m-0 pl-2">${data[i].idUser}</p>
						<div class="group-user-opt dropdown ml-auto">
						<a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="color:unset">
							<i class="fa-light fa-chevron-down c-pointer p-1 mt-2"></i>
						</a>
						<div class="dropdown-menu dropdown-menu-right pr-3 mt-1 mr-2 community-dropdown-style" x-placement="bottom-end">
							<a class="dropdown-item removeFromBroadcast" href="#" data-email="${data[i].jidUser}">Eliminar de la lista</a>
						</div>
					</div>
					</div>
				`;
				users += user;
				emails.push(data[i].emailUser);
			}
			var template = `

			<!-- Title -->
			<div id="editChatListTitle" class="d-flex chatwindows-media pl-4 pr-4 c-pointer">
				<i class="">${stcmbackend.svg.bellWithoutColor}</i>
				<span id="listName" class="w100 pl-3">${chat.listName}</span>
				<i class="fa-light fa-chevron-right"></i>
			</div>

			<div>
				<div class="row justify-content-between">
					<div class="col">
						<p class="ellipsis text-center chat-window-info-email pl-4 pr-4">${data.length} ${pf.const.language.RSC443}</p>
					</div>
					<div class="col c-pointer">
						<i class="fa-light fa-circle-plus maincolorClass"></i>
						<span id="addContactsToBroadcast" type="button" class="maincolorClass">Añadir</span>
					</div>
				</div>

				<div class="pl-2 pt-2 pb-2">
						<div class="list-window-info-user pt-2">${users}
						</div>
				</div>
			</div>

			
			<!-- Update ChatList title modal -->
				<div class="modal fade" id="updateChatListModal" tabindex="-1" role="dialog" aria-labelledby="Modal advertencia" aria-hidden="true" style="background: unset">
					<div class="modal-dialog modal-dialog-centered" role="document">
						<div class="modal-content">
							<div class="modal-header">
								<h5 class="modal-title">Cambiar título de la Lista de difusión</h5>
								<button type="button" class="close" data-dismiss="modal" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
							</div>
							<div class="modal-body">
								<div class="form-group">
								<label for="chatListTitle">Título de la lista:</label>
								<textarea class="form-control" id="chatListTitle" rows="3"></textarea>
							</div>
								
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">${pf.const.language.RSC2707}</button>
								<button type="button" class="btn btn-danger" id="updateChatList">${pf.const.language.RSC2708}</button>
							</div>
						</div>
					</div>
				</div>
				
			`;

			$('.information-container-list').html(template);
			// Title
			$('#editChatListTitle').off().on('click', function () {
				$('#updateChatListModal').modal('show');
			});

			$('.removeFromBroadcast').off().on('click', function () {
				const email = $(this).data('email');
				let updateList = CommunityManagement.usersGroup.filter(user => user !== email);
				const removeFromList = () => {
					let parameters = {
						admin: CommunityManagement.jsonUser.token,
						idlist: stcmbackend.communymanagement.currentChat.idList,
						activa: stcmbackend.communymanagement.currentChat.Activa,
						description: stcmbackend.communymanagement.currentChat.listName,
						destinatarios: JSON.stringify(updateList),
						country: stcmbackend.communymanagement.currentChat.country
					};
					ajaxComunCallWithCallback('updateDistributionList', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							CommunityManagement.refresh.broadcastList();
							CommunityManagement.usersGroup = updateList
						} else {
							console.log('Couldnt update data');
						}
					}, false);
				};


				pf.utils.showInfoDialogAcceptCancel(
					pf.const.language.RSC2736,
					"El usuario será eliminado de la lista, perdiendo acceso a nuevas conversaciones y archivos compartidos.",
					{
						accept: { text: pf.const.language.RSC57 },
						cancel: { text: pf.const.language.RSC2708 }
					},
					function () { },
					removeFromList
				);
			});

			// Add contacts to distribution list
			$('#addContactsToBroadcast').on('click', function () {
				let membersJid = stcmbackend.communymanagement.currentChat.members.map(member => member.jidUser);
				CommunityManagement.ajax.getUsers(function (data) {
					// Filter data
					data = data.filter(item => {
						return !emails.includes(item.token) && item.token !== CommunityManagement.jsonUser.token;
					});
					// Create modal
					let userSelector = new CommunityManagement.ui.UserSelector(data);
					let modal = new CommunityManagement.ui.Modal(
						pf.const.language.RSC2302,
						userSelector.getHtml(),
						{
							text: "Confirmar",
							callback: () => {
								if (userSelector.getSelectedUsers().length === 0) {
									return;
								} else {
									let participants = userSelector.getSelectedUsers();
									let participantsJid = data
										.filter(user => participants.includes(user.token))
										.map(user => user.jidUser);
									let parameters = {
										admin: CommunityManagement.jsonUser.token,
										idlist: stcmbackend.communymanagement.currentChat.idList,
										activa: stcmbackend.communymanagement.currentChat.Activa,
										description: stcmbackend.communymanagement.currentChat.listName,
										destinatarios: JSON.stringify(membersJid.concat(participantsJid)),
										country: stcmbackend.communymanagement.currentChat.country
									};
									ajaxComunCallWithCallback('updateDistributionList', parameters, function (ajaxReturn) {
										if (ajaxReturn) {
											CommunityManagement.refresh.broadcastList();
										} else {
											console.log('Couldnt update data');
										}
									}, false);
									modal.hide();
								}
							}
						}
					);
					modal.show();
					userSelector.bindEvents();
				});
			});


			$('#updateChatList').off().on('click', function () {
				let description = $('#chatListTitle').val();

				if (description.trim() !== '') {
					let listDescription = description.charAt(0).toUpperCase() + description.slice(1);
					var itemId = 'listName-' + stcmbackend.communymanagement.currentChat.idList;
					let parameters = {
						admin: CommunityManagement.jsonUser.token,
						idlist: stcmbackend.communymanagement.currentChat.idList,
						activa: stcmbackend.communymanagement.currentChat.Activa,
						description: listDescription,
						destinatarios: JSON.stringify(CommunityManagement.usersGroup),
						country: stcmbackend.communymanagement.currentChat.country
					};
					ajaxComunCallWithCallback('updateDistributionList', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							$('#updateChatListModal').modal('hide');
							$('#listName').text(listDescription);
							$('#' + itemId).text(listDescription);
						} else {
							console.log('Couldnt update data');
						}
					}, false);
				} else {
					$('#updateChatListModal').modal('hide');
				}
			});
		}
	},

	chatMedia(data) {
		var totalImages = 0;
		var totalVideos = 0;
		var template = '';

		template += `
			<div class="tab-content" id="pills-tabContent">
			<!--FOTOS-->
				<div class="tab-pane fade show active" id="pills-home" role="tabpanel" aria-labelledby="pills-home-tab">`
		if (Object.keys(data.image).length > 0) {
			for (let group in data.image) {
				template += `
							<div class="font-weight-bold container">${group}</div>
		  					<div class="row no-gutters fixed-height-row text-center">
						`;

				data.image[group].forEach(image => {
					template += `
								<div class="col-md-4 c-pointer">
			  						<img src="${image.url}" alt="${image.attachmentName}" class="img-thumbnail" data-type="img">
								</div>`;
					totalImages++; // Increment the count for each image
				});

				template += `
		  					</div>
							 `;
			}
			template += `
						<div class="col-md-12 text-center pt-3">
						${totalImages} Fotos
						</div>`
		} else {
			template += `
						<div class="col-md-12 text-center pt-5">
						No hay fotos
						</div>`;
		}

		template += `
					</div>
				<!--VIDEOS-->
				<div class="tab-pane fade" id="pills-profile" role="tabpanel" aria-labelledby="pills-profile-tab">`
		if (Object.keys(data.video).length > 0) {
			for (let group in data.video) {
				template += `
							<div class="font-weight-bold container">${group}</div>
							<div class="row no-gutters fixed-height-row">
								`;
				data.video[group].forEach(video => {
					template += `
										<div class="col-md-4 c-pointer">
											<img src="${video.urlThumbnail}" alt="${video.attachmentName}" class="img-thumbnail" data-type="video" data-video-url="${video.url}">
										</div>`;
					totalVideos++; // Increment the count for each image
				});
				template += `
							</div>`;
			}
			template += `
					<div class="col-md-12 text-center pt-3">
					${totalVideos} Videos
					</div>`
		} else {
			template += `
						<div class="col-md-12 text-center pt-5">
						No hay videos
						</div>`;
		}
		template += `
					</div>
				<!--DOCS-->
				<div class="tab-pane fade" id="pills-contact" role="tabpanel" aria-labelledby="pills-contact-tab">`
		if (data.docs && Object.keys(data.docs).length > 0) {
			for (let group in data.docs) {
				template += `
						<div class="font-weight-bold container">${group}</div>
					`;
				data.docs[group].forEach(docs => {
					template += `
						<div class="list-group list-group-flush">
 
						<a href="#" class="list-group-item list-group-item-action docs-link" data-type="pdf" data-url="${docs.url}">
						<div class="row justify-content-between">
							<div class="col-9">
						  		<p class="mb-1" style="word-wrap: break-word;">${docs.attachmentName} <br> <small class="text-muted">${group}</small></p>
						  	</div>
							<div class="col-3">
						  		<img src="${docs.urlThumbnail}" alt="${docs.attachmentName}" class="doc-img" style="width: 50px; height: 50px;" data-type="pdf">
						  	</div>
						</div>
						 
						</a>
					  </div>`;
				});

			}
		} else {
			template += `
					<div class="col-md-12 text-center pt-5">
					No hay documentos
					</div>`;
		}
		template += `
				</div>
				</div>
			<div>`;


		$('.media-container').html(template);

		$('.media-container .docs-link').click(function (e) {
			e.preventDefault();

			$('#fullScreenContainer').removeClass('d-none');
			$('#fullScreenContainer').animate({
				opacity: '1'
			});

			let type = $(this).data('type');
			let width = $('#fullScreenContainer').width() * 0.8;
			let height = $('#fullScreenContainer').height() * 0.9;
			let resource = $(this).data('url');
			let element = '';

			switch (type) {
				case 'pdf':
					element = `<embed src="${resource}" type="application/pdf" class="b-shadow p-2 mw-100 mh-100" style="width: ${width}px; height: ${height}px;">`;
					break;
			}

			$('#fSAttachmentViewer').html(element);
		});

		$('.media-container img').click(function () {
			$('#fullScreenContainer').removeClass('d-none');
			$('#fullScreenContainer').animate({
				opacity: '1'
			});

			let type = $(this).data('type');

			let width = $('#fullScreenContainer').width() * 0.8;
			let height = $('#fullScreenContainer').height() * 0.9;
			let videoUrl = $(this).data('video-url');

			let element = '';
			let resource = '';
			switch (type) {
				case 'video':
					resource = $(this).parent().find('video').attr('src');
					element = `<video src="${videoUrl}" class="b-shadow p-2" controls autoplay style="max-width: ${width}px; max-height: ${height}px;"></video>`;
					break;
				// case 'pdf':
				// 	// resource = $(this).parent().find('embed').attr('src').split('#');
				// 	resource = $(this).parent().find('img').attr('src');
				// 	element = `<embed src="${resource}" type="application/pdf" class="b-shadow p-2 mw-100 mh-100" style="width: ${width}px; height: ${height}px;">`;
				// 	break;
				case 'img':
					resource = $(this).parent().find('img').attr('src');
					element = `<img src="${resource}" class="b-shadow p-2" style="max-width: ${width}px; max-height: ${height}px;">`;
					break;
			}

			$('#fSAttachmentViewer').html(element);
		});
	},

	closeContactInformation() {
		$('.chat-window-container .chat-head i').show();
		$('.information-container >').remove();
		$('.information-chat').hide();
		$('.chat-media').hide();
		$('.chat-window-container').css('width', '100%');
	},

	closeGroupInformation() {
		CommunityManagement.usersGroup = [];
		$('.chat-window-container .chat-head i').show();
		$('.information-container-group >').remove();
		$('.information-group').hide();
		$('.chat-window-container').css('width', '100%');
	},

	closeListInformation() {
		CommunityManagement.usersGroup = [];
		$('.chat-window-container .chat-head i').show();
		$('.information-container-list >').remove();
		$('.information-list').removeClass('d-flex');
		$('.information-list').addClass('d-none');
		$('.chat-window-container').css('width', '100%');
	},

	optionsBoxEvents(id, icon, title, text) {
		// Gestión de elemento (tamaño y visibilidad)
		$('#optionsBoxContainer').removeClass('d-none');
		$('#optionsBoxContainer').addClass('d-flex');

		// id
		$('#optionsBoxContainer').data('id', id);

		// Icono
		$('#actionOptionsBox').html(icon);

		// Textos
		$('#optionsBoxTitle').html(title);
		$('#optionsBoxText').html(text);

		let elementHeight = $('#optionsBoxContainer').height();
		let totalHeight = elementHeight + 120;

		$('#communityManagementContainer .wrap-chat').css('height', 'calc(100% - ' + totalHeight + 'px)');

		$('.chat').scrollTop($('.chat').prop('scrollHeight'));
	},

	closeHideOtionsBox() {
		// Gestión de elemento (tamaño y visibilidad)
		$('#optionsBoxContainer').removeClass('d-flex');
		$('#optionsBoxContainer').addClass('d-none');

		// id
		$('#optionsBoxContainer').data('id', '');

		// Icono
		$('#actionOptionsBox').html('');

		// Textos
		$('#optionsBoxTitle').html('');
		$('#optionsBoxText').html('');

		$('#communityManagementContainer .wrap-chat').css('height', 'calc(100% - 120px)');

		// Limpiar editor y textarea
		$('.emojionearea-editor').html('');
		//$('#messageInputElement').val('');
		// Cambiar botón de editar por enviar
		$('#wrap-message-send').removeClass('d-none');
		$('#wrap-message-edit').addClass('d-none');
	},

	closeFastQuestionContainer() {
		$('#fastQuestionContainer').removeClass('d-flex');
		$('#fastQuestionContainer').addClass('d-none');

		$('#communityManagementContainer .wrap-chat').css('height', 'calc(100% - 120px)');
	},

	closeHideResenddBox() {
		// Gestión de elemento
		$('#resendBoxContainer').removeClass('d-flex');
		$('#resendBoxContainer').addClass('d-none');

		// Mostrar caja de mensaje
		$('#messageBoxContainer').show();

		// Pasar el contador a 1
		$('#selectedAmount').text('1');

		// Quitar todos los colores de fondo
		$('.chatContainer').css('background-color', 'inherit');

		// Desmarcar y ocultar todos los checkbox
		$('.bubbleCheckbox').prop('checked', false);
		$('.bubbleCheckboxContainer').addClass('d-none');

		// Restaurar d-flex de los elementos 'me'
		$('#communityManagementContainer .chat-bubble-container-me').css('justify-content', 'end');
	},

	events: {
		addClickToChat() {
			$('.contact-list .contact').off().click(function (e) {
				if (sessionStorage['STCMBackEnd:notifications_activated'] === '0') {
					notifNotActi();
				} else {
					// Desactivar evento scroll
					CommunityManagement.activeScroll = false;

					let bid = $(this).data('bid');
					let count = $(this).find('.contact-time').find('.new-message').find('p').text();

					CommunityManagement.currentChat = bid;
				
					if (bid != stcmbackend.communymanagement.currentChat.bid) {
						CommunityManagement.resetChatVoiceAssistantValues();
						// Limpieza de elemento a adjuntar
						CommunityManagement.cleanAttachmentItems();

						// Limpieza de cajas
						CommunityManagement.closeHideOtionsBox();
						CommunityManagement.closeHideResenddBox();

						$('.active-contact').removeClass('active-contact');
						$(this).addClass('active-contact');
						$(this).removeClass('new-message-contact');
						$(this).find('.new-message-color').removeClass('new-message-color');

						let index = $(this).data('index');
						$('#nm' + index).addClass('d-none');
						$('#nm' + index + ' p').text('0');
						stcmbackend.communymanagement.currentChat = stcmbackend.communymanagement.chatList[index];
						stcmbackend.communymanagement.chatList[index].unreaded = 0;
						CommunityManagement.printedDatesInchat = [];

						// Control de mensajes no vistos
						if (stcmbackend.communymanagement.currentChat.type == 'chat' && count > 0) {
							// Marcar como leidos mensajes de contacto
							let parameters = {
								userA: CommunityManagement.jsonUser.token,
								userB: CommunityManagement.getEmailOfUserB()
							};
							ajaxComunCallWithCallback('markAsReaded_SaaS', parameters, function (ajaxReturn) {
								if (ajaxReturn) {
									//
								}
							}, false);
						} else if (stcmbackend.communymanagement.currentChat.type == 'groupchat' && count > 0) {
							// Marcar como leidos mensajes de grupo
							let parameters = {
								userA: CommunityManagement.jsonUser.token,
								groupID: stcmbackend.communymanagement.currentChat.idgroup
							};
							ajaxComunCallWithCallback('markAsReadedGroup_SaaS', parameters, function (ajaxReturn) {
								if (ajaxReturn) {
									//
								}
							}, false);
						}

						if(stcmbackend.communymanagement.currentChat.voiceassistant === '1'){
							CommunityManagement.initializeChatbot();
						}

						$('#communityManagementContainer .main-window').addClass('d-none');
						$('#communityManagementContainer .chat-window').removeClass('d-none');

						// Mostrar Spinner
						$('#chatSpinner').removeClass('d-none');
						$('#chatSpinner').addClass('d-flex');
						CommunityManagement.printChat(stcmbackend.communymanagement.currentChat);

						// Control de contactos bloqueados
						if (stcmbackend.communymanagement.currentChat.blocked == '1') {
							$('#messageBoxContainer').hide();
						}
					}
				}
			});

			// Chat dropdown
			$('.contact').off('mouseover').mouseover(function () {
				$(this).find('.contact-list-arrow').removeClass('d-none');
			});

			$('.contact').off('mouseleave').mouseleave(function () {
				$(this).find('.contact-list-arrow').addClass('d-none');
			});

			$('.dropdown-item.deleteChat').off().on('click', function () {
				const email = $(this).data('email');
				const groupId = $(this).data('group-id');

				// Determine API endpoint and request data based on email and groupId
				let apiEndpoint = (email !== null && email !== '') ? 'deleteChatFromList_SaaS' : 'deleteChatGroupFromList_SaaS';
				let requestData = (email !== null && email !== '') ? { userA: CommunityManagement.jsonUser.token, userB: email } : { email: CommunityManagement.jsonUser.token, groupID: groupId };

				// Callback function to handle API call result
				let handleApiResponse = function (ajaxReturn) {
					let title = ajaxReturn ? pf.const.language.RSC2721 : pf.const.language.RSC2722;
					let content = ajaxReturn ? pf.const.language.RSC2723 : pf.const.language.RSC2724;
					if (ajaxReturn) {
						CommunityManagement.refresh.completeContactList();
						$('#communityManagementContainer .chat-window').addClass('d-none');
					}
					pf.utils.showInfoDialog(title, content);
				};

				// Show confirmation dialog before making the API call
				pf.utils.showInfoDialogAcceptCancel(pf.const.language.RSC2714, pf.const.language.RSC2715, {
					accept: {
						text: pf.const.language.RSC57
					},
					cancel: {
						text: pf.const.language.RSC2708
					}
				}, function () { }, function () {
					ajaxComunCallWithCallback(apiEndpoint, requestData, handleApiResponse, false);
				});
			});
		},


		addClickToNewChat() {
			$('.new-chat .new-chat-contact-list .contact').off().click(function (e) {
				// Limpieza de elemento a adjuntar
				CommunityManagement.cleanAttachmentItems();

				// Limpieza de cajas
				CommunityManagement.closeHideOtionsBox();
				CommunityManagement.closeHideResenddBox();

				let token = $(this).data('token');

				let size = stcmbackend.communymanagement.usersList.length;
				for (let i = 0; i < size; i++) {
					if (token == stcmbackend.communymanagement.usersList[i].token) {
						stcmbackend.communymanagement.currentChat = stcmbackend.communymanagement.usersList[i];
						break;
					}
				}

				stcmbackend.communymanagement.currentChat.type = 'chat';
				CommunityManagement.printedDatesInchat = [];

				$('#close-new-chat').click();
				$('#communityManagementContainer .main-window').addClass('d-none');
				$('#communityManagementContainer .chat-window').removeClass('d-none');
				CommunityManagement.printChat(stcmbackend.communymanagement.currentChat, true);
			});
		},

		addClickToNewGroup() {
			$('.new-group-contact-list .contact').off().click(function (e) {
				var elembid = $(this).data('bid');
				var elemtoken = $(this).data('token');
				var srcimg = $(this).find('.contact-img img').attr('src');
				var elemname = $(this).find('.font-name').text();
				$(this).hide();

				$('.new-group-selected-users').removeClass('d-none');
				$('.new-group-users-next').removeClass('d-none');

				// Control de elementos seleccionados
				CommunityManagement.newGroupMembers.push(elembid);

				var template = `
					<div class="bubble-selector" data-bid="${elembid}" data-token="${elemtoken}">
						<div class="bubble-bg-container">
							<img src="${srcimg}" />
							<div class="ellipsis user-name-bubble">${elemname}</div>
							<i class="fa-light fa-xmark c-pointer close-bubble"></i>
						</div>
					</div>
				`;

				$('.new-group-selected-users').append(template);
				CommunityManagement.utils.setHeightToListUsersToAddGroup();

				$('.bubble-selector .close-bubble').off().click(function () {
					var bid = $(this).closest('.bubble-selector').data('bid');
					$(this).closest('.bubble-selector').remove();
					$('.new-group-contact-list .contact[data-bid="' + bid + '"').show();

					// Control de elementos seleccionados
					let index = CommunityManagement.newGroupMembers.indexOf(bid);
					CommunityManagement.newGroupMembers.splice(index, 1);

					if ($('.new-group-selected-users .bubble-selector').length == 0) {
						$('.new-group-selected-users').addClass('d-none');
						$('.new-group-users-next').addClass('d-none');
					}
					CommunityManagement.utils.setHeightToListUsersToAddGroup();
				});
			});
		},

		addClickToNewDistributionList() {
			$('.new-distributionlist-contact-list .contact').off().click(function (e) {
				var elembid = $(this).data('bid');
				var elemtoken = $(this).data('token');
				var srcimg = $(this).find('.contact-img img').attr('src');
				var elemname = $(this).find('.font-name').text();
				$(this).hide();

				$('.new-distributionlist-selected-users').removeClass('d-none');

				// Control de elementos seleccionados
				CommunityManagement.newListMembers.push(elembid);

				var template = `
					<div class="bubble-selector" data-bid="${elembid}" data-token="${elemtoken}">
						<div class="bubble-bg-container">
							<img src="${srcimg}" />
							<div class="ellipsis user-name-bubble">${elemname}</div>
							<i class="fa-light fa-xmark c-pointer close-bubble"></i>
						</div>
					</div>
				`;

				$('.new-distributionlist-selected-users').append(template);
				CommunityManagement.utils.setHeightToListUsersToAddList();

				if ($('.new-distributionlist-selected-users .bubble-selector').length > 1) {
					$('.new-distributionlist-users-next').removeClass('d-none');
				}

				$('.bubble-selector .close-bubble').off().click(function () {
					var bid = $(this).closest('.bubble-selector').data('bid');
					$(this).closest('.bubble-selector').remove();
					$('.new-distributionlist-contact-list .contact[data-bid="' + bid + '"').show();

					// Control de elementos seleccionados
					let index = CommunityManagement.newListMembers.indexOf(bid);
					CommunityManagement.newListMembers.splice(index, 1);

					if ($('.new-distributionlist-selected-users .bubble-selector').length == 0) {
						$('.new-distributionlist-selected-users').addClass('d-none');
					}

					if ($('.new-distributionlist-selected-users .bubble-selector').length < 2) {
						$('.new-distributionlist-users-next').addClass('d-none');
					}

					CommunityManagement.utils.setHeightToListUsersToAddList();
				});
			});
		},

		contactsToResendEvents() {
			// Limpieza de checkbox
			$('#contactsToResendBody .contact .contactsToResend').remove();

			// Mostrar checkbox
			$('#contactsToResendBody .contact').each(function (i) {
				let token = $(this).data('token');
				let bid = $(this).data('bid');

				if (!CommunityManagement.usersGroup.includes(bid)) {
					// Comprobación de si ya ha sido seleccionado
					let checked = '';
					if (CommunityManagement.usersToResend.includes(token)) {
						checked = ' checked';
					}

					let checkbox = `
						<div class="custom-control custom-checkbox contactsToResend">
							<input id="customCheck_1_${i}" type="checkbox" class="custom-control-input contactsToResendCheckbox"${checked}>
							<label for="customCheck_1_${i}" class="custom-control-label contactsToResendLabel"></label>
						</div>
					`;
					$(this).prepend(checkbox);
				} else {
					$(this).hide();
				}
			});

			// Cambiar la forma del cursor
			$('#contactsToResendBody .contact').removeClass('c-pointer');

			$('#contactsToResendBody .contactsToResendCheckbox').off().on('change', function () {
				let uid = $(this).parent().parent().data('bid');
				let token = $(this).parent().parent().data('token');

				if ($(this).prop('checked')) {
					CommunityManagement.usersToResend.push(token);
				} else {
					for (let i = 0; i < CommunityManagement.usersToResend.length; i++) {
						if (CommunityManagement.usersToResend[i] == token) {
							CommunityManagement.usersToResend.splice(i, 1);
							break;
						}
					}
				}

				let amount = CommunityManagement.usersToResend.length;
				$('#contactsSelectedAmount').text(amount);

				if (amount > 0) {
					$('#contactsToResendFooter').removeClass('d-none');
					$('#contactsToResendFooter').addClass('d-flex');
				} else {
					$('#contactsToResendFooter').removeClass('d-flex');
					$('#contactsToResendFooter').addClass('d-none');
				}
			});
		},

		contactsToBroadcastEvents() {
			// Limpieza de checkbox
			$(`#${id} .contact .contactsToBroadcast`).remove();
			// Mostrar checkbox
			$(`#${id} .contact`).each(function (i) {
				let token = $(this).data('token');
				let bid = $(this).data('bid');
				if (!CommunityManagement.usersGroup.includes(bid)) {
					// Comprobación de si ya ha sido seleccionado
					let checked = '';
					if (CommunityManagement.usersToBroadcast.includes(token)) {
						checked = ' checked';
					}

					let checkbox = `
						<div class="custom-control custom-checkbox contactsToBroadcast">
							<input id="customCheck_1_${i}" type="checkbox" class="custom-control-input contactsToBroadcastCheckbox"${checked}>
							<label for="customCheck_1_${i}" class="custom-control-label contactsToBroadcastLabel"></label>
						</div>
					`;
					$(this).prepend(checkbox);
				} else {
					$(this).hide();
				}
			});

			// Cambiar la forma del cursor
			$(`#${id} .contact`).removeClass('c-pointer');

			$(`#${id} .contactsToBroadcastCheckbox`).off().on('change', function () {
				let uid = $(this).parent().parent().data('bid');
				let token = $(this).parent().parent().data('token');

				if ($(this).prop('checked')) {
					CommunityManagement.usersToBroadcast.push(token);
					CommunityManagement.editListMembers.push(uid);
					CommunityManagement.editBroadcastMembers.push(uid);
				} else {
					for (let i = 0; i < CommunityManagement.usersToBroadcast.length; i++) {
						if (CommunityManagement.usersToBroadcast[i] == token) {
							CommunityManagement.usersToBroadcast.splice(i, 1);
							CommunityManagement.editListMembers.splice(i, 1);
							CommunityManagement.editBroadcastMembers.splice(i, 1);
							break;
						}
					}
				}

				let amount = CommunityManagement.usersToBroadcast.length;
				$('#contactsBroadcastSelectedAmount').text(amount);

				if (amount > 0) {
					$('#contactsToBroadcastFooter').removeClass('d-none');
					$('#contactsToBroadcastFooter').addClass('d-flex');
				} else {
					$('#contactsToBroadcastFooter').removeClass('d-flex');
					$('#contactsToBroadcastFooter').addClass('d-none');
				}
			});
		},

		orderByNotReaded() {
			$('#order-chats-notreaded').off('click').click(function () {
				$('.new-message-contact').prependTo('.contact-list');
			});

			$('#order-chats').off('click').click(function () {
				$('.contact-list .contact').sort((a, b) => String.prototype.localeCompare.call($(b).find('.contact-time .classChatTime').data('stamp'), $(a).find('.contact-time .classChatTime').data('stamp'))).appendTo('.contact-list');
			});
		},

		filterChats() {
			// Búsqueda por teclado
			$('#chats-search').keyup(function () {
				let text = $(this).val().trim().toLowerCase();

				if (text === '') {
					$('.contact-list .contact').show();
				} else {
					setTimeout(function () {
						if ($('#chats-search').val().trim().toLowerCase() === text) {
							$('.contact-list .contact').show();
							$('.contact-list .contact').each(function () {
								if (!$(this).find('.font-name').text().trim().toLowerCase().includes(text) && !$(this).find('.font-name').data('email').toLowerCase().includes(text)) {
									$(this).hide();
								}
							});
						}
					}, 500);
				}
			});

			// Buscar por pegado
			$('#chats-search').on('paste', function () {
				setTimeout(function () {
					$('.contact-list .contact').show();

					let text = $('#chats-search').val().trim().toLowerCase();

					$('.contact-list .contact').each(function () {
						if (!$(this).find('.font-name').text().trim().toLowerCase().includes(text) && !$(this).find('.font-name').data('email').toLowerCase().includes(text)) {
							$(this).hide();
						}
					});
				}, 200);
			});

			// Busqueda para nuevo chat activación por tecla enter
			$('#contacts-search').keyup(function (evt) {
				if (evt.keyCode == 13) {
					$('#contacts-search-button').trigger('click');
				}
			});

			// Busqueda para nuevo chat activación por botón
			$('#contacts-search-button').off().on('click', function () {
				let text = $('#contacts-search').val().trim().toLowerCase();
				stcmbackend.communymanagement.usersList = [];

				if (text != '') {
					// Desactivar el evento scroll de nuevo chat
					$('.new-chat-contact-list').off();

					let parameters = {
						onlyEnabled: 1,
						fullMode: 0,
						searchWord: text
					};
					ajaxComunCallWithCallback('getUsersSearch_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							let data = ajaxReturn.result;
							let templateNewChat = '';

							if (data.length == 0) {
								// Aviso para cuando no hay resultados
								let warningTitle = pf.const.language.RSC2267;
								let warningContent = pf.const.language.RSC2343;
								pf.utils.showInfoDialog(warningTitle, warningContent);

								$('.new-chat-contact-list').html('');
							} else {
								for (let i = 0; i < data.length; i++) {
									let e = data[i];
									new stcmbackend.communymanagement.appUsers(e);

									if (!CommunityManagement.chatsEmailArray.includes(data[i].token)) {
										templateNewChat += CommunityManagement.printUserObj(e, i);
									}
								}

								$('.new-chat-contact-list').html(templateNewChat);

								CommunityManagement.events.addClickToNewChat();
							}
						}
					}, false);
				} else {
					CommunityManagement.userspage = 0;

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'newChat');
					});
				}

				// Subir hasta arriba en la lista de usuarios
				$('.new-chat-contact-list').scrollTop(0);
			});

			// Busqueda para grupo activación por tecla enter
			$('#contacts-group-search').keyup(function (evt) {
				if (evt.keyCode == 13) {
					$('#contacts-group-search-button').trigger('click');
				}
			});

			// Busqueda para grupo activación por botón
			$('#contacts-group-search-button').off().on('click', function () {
				let text = $('#contacts-group-search').val().trim().toLowerCase();
				stcmbackend.communymanagement.usersList = [];

				if (text != '') {
					// Desactivar el evento scroll de nuevo grupo
					$('.new-group-contact-list').off();

					let parameters = {
						onlyEnabled: 1,
						fullMode: 0,
						searchWord: text
					};
					ajaxComunCallWithCallback('getUsersSearch_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							let data = ajaxReturn.result;
							let template = '';

							if (data.length == 0) {
								// Aviso para cuando no hay resultados
								let warningTitle = pf.const.language.RSC2262;
								let warningContent = pf.const.language.RSC2343;
								pf.utils.showInfoDialog(warningTitle, warningContent);

								$('.new-group-contact-list').html('');
							} else {
								for (let i = 0; i < data.length; i++) {
									let e = data[i];

									// Control para que no salga el usuario
									if (CommunityManagement.jsonUser.token == e.token) {
										continue;
									}

									new stcmbackend.communymanagement.appUsers(e);

									template += CommunityManagement.printUserObj(e, i);
								}

								$('.new-group-contact-list').html(template);

								// Array de usuarios que ya están añadidos al grupo
								let usersInGroup = [];
								$('.new-group-selected-users .bubble-selector').each(function () {
									usersInGroup.push($(this).data('token'));
								});

								// Control para ocultar los contactos ya añadidos
								$('.new-group-contact-list .contact').each(function () {
									let token = $(this).data('token');

									if (usersInGroup.includes(token)) {
										$(this).css('display', 'none');
									}
								});

								CommunityManagement.events.addClickToNewGroup();
							}
						}
					}, false);
				} else {
					CommunityManagement.userspage = 0;

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'newGroup');
					});
				}

				// Subir hasta arriba en la lista de usuarios
				$('.new-group-contact-list').scrollTop(0);
			});

			// Busqueda para lista de distribución activación por tecla enter
			$('#contacts-distributionlist-search').keyup(function (evt) {
				if (evt.keyCode == 13) {
					$('#contacts-distributionlist-search-button').trigger('click');
				}
			});

			// Busqueda para lista de distribución activación por botón
			$('#contacts-distributionlist-search-button').off().on('click', function () {
				let text = $('#contacts-distributionlist-search').val().trim().toLowerCase();

				if (text != '') {
					// Desactivar el evento scroll de nueva lista de distribución
					$('.new-distributionlist-contact-list').off();

					let parameters = {
						onlyEnabled: 1,
						fullMode: 0,
						searchWord: text
					};
					ajaxComunCallWithCallback('getUsersSearch_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							let data = ajaxReturn.result;
							let template = '';

							if (data.length == 0) {
								// Aviso para cuando no hay resultados
								let warningTitle = pf.const.language.RSC2270;
								let warningContent = pf.const.language.RSC2343;
								pf.utils.showInfoDialog(warningTitle, warningContent);

								$('.new-distributionlist-contact-list').html('');
							} else {
								for (let i = 0; i < data.length; i++) {
									let e = data[i];

									// Control para que no salga el usuario
									if (CommunityManagement.jsonUser.token == e.token) {
										continue;
									}

									new stcmbackend.communymanagement.appUsers(e);

									template += CommunityManagement.printUserObj(e, i);
								}

								$('.new-distributionlist-contact-list').html(template);

								CommunityManagement.events.addClickToNewDistributionList();
							}
						}
					}, false);
				} else {
					CommunityManagement.userspage = 0;

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'newList');
					});
				}

				// Subir hasta arriba en la lista de usuarios
				$('.new-group-contact-list').scrollTop(0);
			});

			// Busqueda para reenvio y añadir asesor a grupo activación por tecla enter
			$('#contactsToResendSearch').keyup(function (evt) {
				if (evt.keyCode == 13) {
					$('#contactsToResendSearch-button').trigger('click');
				}
			});

			$('#contactsToBroadcastSearch').keyup(function (evt) {
				if (evt.keyCode == 13) {
					$('#contactsToBroadcastSearch-button').trigger('click');
				}
			});

			// Busqueda para reenvio y añadir asesor a grupo por botón
			$('#contactsToResendSearch-button').off().on('click', function () {
				let text = $('#contactsToResendSearch').val().trim().toLowerCase();

				if (text != '') {
					// Desactivar el evento scroll de añadir usuarios
					$('#contactsToResendBody').off();

					let parameters = {
						onlyEnabled: 1,
						fullMode: 0,
						searchWord: text
					};
					ajaxComunCallWithCallback('getUsersSearch_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							let data = ajaxReturn.result;
							let template = '';

							if (data.length == 0) {
								// Aviso para cuando no hay resultados
								let warningTitle = pf.const.language.RSC2303;
								let warningContent = pf.const.language.RSC2343;
								pf.utils.showInfoDialog(warningTitle, warningContent);

								$('#contactsToResendBody').html('');
							} else {
								for (let i = 0; i < data.length; i++) {
									let e = data[i];
									new stcmbackend.communymanagement.appUsers(e);

									template += CommunityManagement.printUserObj(e, i);
								}

								$('#contactsToResendBody').html(template);

								CommunityManagement.events.contactsToResendEvents();
							}
						}
					}, false);
				} else {
					CommunityManagement.userspage = 0;

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'middleModal');
					});
				}

				// Subir hasta arriba en la lista de usuarios
				$('#contactsToResendBody').scrollTop(0);
			});

			// Busqueda para reenvio y añadir usuario a lista por botón
			$('#contactsToBroadcastSearch-button').off().on('click', function () {
				let text = $('#contactsToBroadcastSearch').val().trim().toLowerCase();

				if (text != '') {
					// Desactivar el evento scroll de añadir usuarios
					$('#contactsToBroadcastBody').off();

					let parameters = {
						onlyEnabled: 1,
						fullMode: 0,
						searchWord: text
					};
					ajaxComunCallWithCallback('getUsersSearch_SaaS', parameters, function (ajaxReturn) {
						if (ajaxReturn) {
							let data = ajaxReturn.result;
							let template = '';

							if (data.length == 0) {
								// Aviso para cuando no hay resultados
								let warningTitle = pf.const.language.RSC2303;
								let warningContent = pf.const.language.RSC2343;
								pf.utils.showInfoDialog(warningTitle, warningContent);

								$('#contactsToBroadcastBody').html('');
							} else {
								for (let i = 0; i < data.length; i++) {
									let e = data[i];
									new stcmbackend.communymanagement.appUsers(e);

									template += CommunityManagement.printUserObj(e, i);
								}

								$('#contactsToBroadcastBody').html(template);

								CommunityManagement.events.contactsToBroadcastEvents();
							}
						}
					}, false);
				} else {
					CommunityManagement.userspage = 0;

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'broadcastList');
					});
				}

				// Subir hasta arriba en la lista de usuarios
				$('#contactsToBroadcastBody').scrollTop(0);
			});
		},

		newChat() {
			// Nuevo chat
			$('#new-chat-btn').off().click(function () {
				if (sessionStorage['STCMBackEnd:notifications_activated'] === '0') {
					notifNotActi();
				} else {
					CommunityManagement.userspage = 0;

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'newChat');

						$('.new-chat').removeClass('d-none');
						CommunityManagement.transitions.showSlide($('.new-chat'), 'left');
					});
				}
			});

			$('#close-new-chat').off().click(function () {
				// Limpiar input de búsqueda
				$('#contacts-search').val('');

				// Limpiar contenedor de contactos para nuevo chat
				$('.new-chat-contact-list').html('');

				CommunityManagement.transitions.hideSlide($('.new-chat'), 'left');
			});
		},

		newGroup() {
			$('#create-new-group').off().click(function () {
				if (sessionStorage['STCMBackEnd:notifications_activated'] === '0') {
					notifNotActi();
				} else {
					CommunityManagement.userspage = 0;
					CommunityManagement.newGroupMembers = [];

					CommunityManagement.ajax.getUsers(function (data) {
						CommunityManagement.userListRender(data, 'newGroup');

						$('.new-group').removeClass('d-none');
						CommunityManagement.transitions.showSlide($('.new-group'), 'left');
					});
				}
			});

			$('#close-new-group').off().click(function () {
				if ($('#new-group-second-step').is(':visible')) {
					$('#new-group-first-step').removeClass('d-none');
					$('#new-group-second-step').addClass('d-none');
				} else {
					CommunityManagement.resetScreenData.resetNewGroup();
					CommunityManagement.transitions.hideSlide($('.new-group'), 'left');
				}
			});

			$('.new-group-users-next-btnbg').off('click').click(function () {
				$('#new-group-first-step').addClass('d-none');
				$('#new-group-second-step').removeClass('d-none');

				$('.new-group-selected-users .bubble-selector').each(function () {
					CommunityManagement.newGroup.selectedGroupUsers.push($(this).data('token'));
				});
			});

			$('.new-group-imagebg, .new-group-imageicon, .new-group-imagetext').off('click').click(function () {
				$('#new-group-image-upload').click();
			});

			$('#new-group-image-upload').change(function () {
				var input = this;
				var url = $(this).val();
				var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
				if (input.files && input.files.length > 0) {
					if (input.files[0] && (ext == 'gif' || ext == 'png' || ext == 'jpeg' || ext == 'jpg')) {
						var reader = new FileReader();
						reader.onload = function (e) {
							$('.new-group-file-container img').attr('src', e.target.result);
						}
						reader.readAsDataURL(input.files[0]);
						$('.new-group-file-container').removeClass('d-none');
						CommunityManagement.newGroup.img = input.files[0];
					} else {
						let title = pf.const.language.RSC2262;
						let content = pf.const.language.RSC2288;
						pf.utils.showInfoDialog(title, content, pf.const.language.RSC141);
					}
				}
			});

			$('.new-group-create-btnbg').off('click').click(function () {
				var groupname = $('#new-group-name-text').val().trim();
				if (groupname != '') {
					CommunityManagement.newGroup.name = groupname;
					//callto ws new group
					CommunityManagement.ajax.createGroup(CommunityManagement.newGroup.name, CommunityManagement.newGroup.selectedGroupUsers, CommunityManagement.newGroup.img, function (data) {
						CommunityManagement.resetScreenData.resetNewGroup();
						CommunityManagement.renderSingleGroupObj(data);
						CommunityManagement.transitions.hideSlide($('.new-group'), 'left');
					});
				} else {
					let title = pf.const.language.RSC2262;
					let content = pf.const.language.RSC2289;
					pf.utils.showInfoDialog(title, content, pf.const.language.RSC141);
				}
			});
		},

		newDistributionList() {
			// Ver listas de distribución de las que se es administrador
			$('#show-distributionlists').off().click(function () {
				if (sessionStorage['STCMBackEnd:notifications_activated'] === '0') {
					notifNotActi();
				} else {
					$('.show-distributionlists').removeClass('d-none');
					CommunityManagement.transitions.showSlide($('.show-distributionlists'), 'left');

					CommunityManagement.events.getAllDistributionListByAdmin_SaaS();
				}
			});

			// Cerrar listas de distribución
			$('#close-show-distributionlist').off().click(function () {
				CommunityManagement.transitions.hideSlide($('.show-distributionlists'), 'left');
			});

			$('#create-new-distributionlist').off().click(function () {
				CommunityManagement.userspage = 0;
				CommunityManagement.newListMembers = [];

				CommunityManagement.ajax.getUsers(function (data) {
					CommunityManagement.userListRender(data, 'newList');

					$('.new-distributionlist').removeClass('d-none');
					CommunityManagement.transitions.showSlide($('.new-distributionlist'), 'left');
				});
			});

			$('#close-new-distributionlist').off().click(function () {
				if ($('#new-distributionlist-second-step').is(':visible')) {
					$('#new-distributionlist-first-step').removeClass('d-none');
					$('#new-distributionlist-second-step').addClass('d-none');
				} else {
					CommunityManagement.resetScreenData.resetNewDistributionList();
					CommunityManagement.transitions.hideSlide($('.new-distributionlist'), 'left');
				}
			});

			$('.new-distributionlist-users-next-btnbg').off('click').click(function () {
				$('#new-distributionlist-first-step').addClass('d-none');
				$('#new-distributionlist-second-step').removeClass('d-none');

				CommunityManagement.newDistributionList.selectedUsers = [];
				$('.new-distributionlist-selected-users .bubble-selector').each(function () {
					CommunityManagement.newDistributionList.selectedUsers.push($(this).data('token'));
				});
			});

			$('.new-distributionlist-create-btnbg').off('click').click(function () {
				var listname = $('#new-distributionlist-name-text').val().trim();
				if (listname != '') {
					CommunityManagement.newDistributionList.name = listname;

					//callto ws new distribution list
					CommunityManagement.ajax.createDistributionList(CommunityManagement.newDistributionList.name, CommunityManagement.newDistributionList.selectedUsers, function (data) {
						CommunityManagement.resetScreenData.resetNewDistributionList();
						CommunityManagement.transitions.hideSlide($('.new-distributionlist'), 'left');

						// Cargar de nuevo las listas de distribución y seleccionar la recién creada
						CommunityManagement.events.getAllDistributionListByAdmin_SaaS(true);
					});
				} else {
					let title = pf.const.language.RSC2270;
					let content = pf.const.language.RSC2290;
					pf.utils.showInfoDialog(title, content, pf.const.language.RSC141);
				}
			});
		},

		getAllDistributionListByAdmin_SaaS(newList = false) {
			let parameters = {
				email: CommunityManagement.jsonUser.token
			};
			ajaxComunCallWithCallback('getAllDistributionListByAdmin_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					let data = ajaxReturn.result;

					let distributionList = '';

					let size = data.length;
					for (let i = 0; i < size; i++) {
						distributionList += `
							<div class="contact c-pointer pl-2" data-id="${data[i].id}" data-name="${data[i].Descripcion}">
								<div class="list-svg d-flex align-items-center justify-content-center">
									<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-megaphone" viewBox="0 0 16 16">
										<path d="M13 2.5a1.5 1.5 0 0 1 3 0v11a1.5 1.5 0 0 1-3 0v-.214c-2.162-1.241-4.49-1.843-6.912-2.083l.405 2.712A1 1 0 0 1 5.51 15.1h-.548a1 1 0 0 1-.916-.599l-1.85-3.49a68.14 68.14 0 0 0-.202-.003A2.014 2.014 0 0 1 0 9V7a2.02 2.02 0 0 1 1.992-2.013 74.663 74.663 0 0 0 2.483-.075c3.043-.154 6.148-.849 8.525-2.199V2.5zm1 0v11a.5.5 0 0 0 1 0v-11a.5.5 0 0 0-1 0zm-1 1.35c-2.344 1.205-5.209 1.842-8 2.033v4.233c.18.01.359.022.537.036 2.568.189 5.093.744 7.463 1.993V3.85zm-9 6.215v-4.13a95.09 95.09 0 0 1-1.992.052A1.02 1.02 0 0 0 1 7v2c0 .55.448 1.002 1.006 1.009A60.49 60.49 0 0 1 4 10.065zm-.657.975 1.609 3.037.01.024h.548l-.002-.014-.443-2.966a68.019 68.019 0 0 0-1.722-.082z"/>
									</svg>
								</div>
								<div class="contact-preview">
									<div class="contact-text">
										<div id="listName-${data[i].id}" class="font-name ellipsis">${data[i].Descripcion}</div>
									</div>
								</div>
								<div class="dropdown">
										<a class="dropdown-toggle" href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
											<i class="contact-list-arrow fa-regular fa-chevron-down  c-pointer"></i>
										</a>
										<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
											<a data-email="uno" data-broadcast-id="${data[i].id}" data-bid="ID" class="dropdown-item deleteBroadcast" href="#">Eliminar
												lista</a>
										</div>
								</div>
							</div>
						`;
					}

					// Chat dropdown
					$('.contact').off('mouseover').mouseover(function () {
						$(this).find('.contact-list-arrow').removeClass('d-none');
					});

					$('.contact').off('mouseleave').mouseleave(function () {
						$(this).find('.contact-list-arrow').addClass('d-none');
					});

					$('#distributionlistAdmin .show-distributionlist-contact-list').off().on('click', '.dropdown-item.deleteBroadcast', function () {
						let lists = [];
						var broadcastId = $(this).data('broadcast-id');
						let obj = {
							idlist: broadcastId
						}
						lists.push(obj);
						let parameters = {
							lists: JSON.stringify(lists)
						};
						ajaxComunCallWithCallback('deleteDistributionList', parameters, function (ajaxReturn) {
							let title = "Lista eliminada";
							let content = "La lista se eliminó correctamente";
							if (ajaxReturn) {
								CommunityManagement.events.getAllDistributionListByAdmin_SaaS(true);

								pf.utils.showInfoDialog(title, content);
							} else {
								console.log('Couldnt update data');
							}
						}, false);
					});

					$('#distributionlistAdmin .show-distributionlist-contact-list').html(distributionList);

					$('#distributionlistAdmin .show-distributionlist-contact-list .contact').off().on('click', function () {
						let id = $(this).data('id');
						let name = $(this).data('name');

						// Mostrar Spinner
						$('#chatSpinner').removeClass('d-none');
						$('#chatSpinner').addClass('d-flex');

						let parameters = {
							email: CommunityManagement.jsonUser.token,
							idList: id
						};
						ajaxComunCallWithCallback('getChatDistibutionListContent_SaaS', parameters, function (ajaxReturn) {
							if (ajaxReturn) {
								let data = ajaxReturn.result;

								// Limpieza de elemento a adjuntar
								CommunityManagement.cleanAttachmentItems();

								// Limpieza de cajas
								CommunityManagement.closeHideOtionsBox();
								CommunityManagement.closeHideResenddBox();

								// Desactivar evento scroll
								CommunityManagement.activeScroll = false;

								stcmbackend.communymanagement.currentChat = {
									type: 'listchat',
									idList: id
								};

								let obj = {
									avatar: 'megaphone',
									name: name
								};

								CommunityManagement.prepareForPrintChat(obj);

								let templatechat = '';
								for (let i = 0; i < data.length; i++) {
									data[i]._uid = data[i].uid,
										templatechat += CommunityManagement.printMessage(data[i]);
								}

								$('.chat').append(templatechat);
								$('.chat').scrollTop($('.chat').prop('scrollHeight'));
								CommunityManagement.chatEvents();

								// Ocultar Spinner
								$('#chatSpinner').removeClass('d-flex');
								$('#chatSpinner').addClass('d-none');

								$('#communityManagementContainer .main-window').addClass('d-none');
								$('#communityManagementContainer .chat-window').removeClass('d-none');
							}
						}, false);
					});

					if (newList) {
						$('#distributionlistAdmin .show-distributionlist-contact-list .contact:first').trigger('click');
					}
				}
			}, false);
		},

		goSettings() {
			$('#go-app-settings').off().click(function () {
				if (sessionStorage['STCMBackEnd:notifications_activated'] === '0') {
					notifNotActi();
				} else {
					CommunityManagement.renderSettings();
					$('.app-settings').removeClass('d-none');
					CommunityManagement.transitions.showSlide($('.app-settings'), 'left');
				}
			});

			$('#close-app-settings').off().click(function () {
				CommunityManagement.transitions.hideSlide($('.app-settings'), 'left');
			});

			$('.profile-notif-config').off().click(function () {
				var notifType = $(this).data('type');
				var mute = $(this).prop('checked');
				CommunityManagement.ajax.setUserConfigNotif(notifType, mute, function (data) {
					if (notifType == 'message') {
						if (mute) {
							CommunityManagement.jsonUser.notif[1].mute = '1';
						} else {
							CommunityManagement.jsonUser.notif[1].mute = '0';
						}
					} else if (notifType == 'group') {
						if (mute) {
							CommunityManagement.jsonUser.notif[0].mute = '1';
						} else {
							CommunityManagement.jsonUser.notif[0].mute = '0';
						}
					}

					sessionStorage['STCMBackEnd:appUserDetails'] = JSON.stringify(CommunityManagement.jsonUser);
				});
			});
		},

		logout() {
			$('#logout-from-app').off().click(function () {
				// Borrar sessionStorage
				sessionStorage.clear();

				pf.ajax.setWindowLocationIndex();
			});
		},

		chatOptionsEvents() {
			// Forma ampliada de ver la información del chat
			$('.chatElementInfo').off().on('click', function () {
				if (stcmbackend.communymanagement.currentChat.type == 'chat') {
					$('#menu-chat-info').trigger('click');
				} else if (stcmbackend.communymanagement.currentChat.type == 'listchat') {
					$('#menu-chat-info-list').trigger('click');
				} else if (stcmbackend.communymanagement.currentChat.type == 'groupchat') {
					$('#menu-chat-info-group').trigger('click');
				}
			});

			// Información de contacto
			$('#menu-chat-info').off('click').click(function () {
				$('.information-chat').removeClass('d-none');
				$('.information-group').addClass('d-none');

				let email = CommunityManagement.getEmailOfUserB();
				let parameters = {
					email: email,
					jid: ''
				};
				ajaxComunCallWithCallback('getInfoContacto_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.result[0];
						data.blocked = stcmbackend.communymanagement.currentChat.blocked;
						data.mute = stcmbackend.communymanagement.currentChat.mute.muted;

						CommunityManagement.showContactInformation(stcmbackend.communymanagement.currentChat, data);
					}
				}, false);
			});

			// Información de grupo
			$('#menu-chat-info-group').off('click').click(function () {
				$('.information-group').removeClass('d-none');
				$('.information-chat').addClass('d-none');

				let groupID = stcmbackend.communymanagement.currentChat.idgroup;

				let parameters = {
					groupID: groupID,
					groupName: ''
				};
				ajaxComunCallWithCallback('getInfoGroup_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.result[0];

						CommunityManagement.usersGroup.push(data.jidUser);
						for (let members in data.members) {
							CommunityManagement.usersGroup.push(data.members[members].jidUser);
						}

						CommunityManagement.showContactInformation(stcmbackend.communymanagement.currentChat, data);
					}
				}, false);
			});

			// Información de lista
			$('#menu-chat-info-list').off('click').click(function () {
				$('.information-group').removeClass('d-none');
				$('.information-chat').addClass('d-none');

				let idList = stcmbackend.communymanagement.currentChat.idList;

				let parameters = {
					idList: idList
				};
				ajaxComunCallWithCallback('getDistibutionListInfo_SaaS', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						let data = ajaxReturn.result[0].Members;
						let listName = ajaxReturn.result[0].Descripcion;
						let members = ajaxReturn.result[0].Members;
						let country = ajaxReturn.result[0].country;
						let Activa = ajaxReturn.result[0].Activa;

						for (let members in data) {
							CommunityManagement.usersGroup.push(data[members].jidUser);
						}
						stcmbackend.communymanagement.currentChat.listName = listName;
						stcmbackend.communymanagement.currentChat.members = members;
						stcmbackend.communymanagement.currentChat.country = country;
						stcmbackend.communymanagement.currentChat.Activa = Activa;
						CommunityManagement.showContactInformation(stcmbackend.communymanagement.currentChat, data);
					}
				}, false);
			});

			$('.dropdown').on('shown.bs.dropdown', function () {
				if ($(this).attr('id') == 'menu-chat-opt') {
					$(this).find('#wrap-message-clipboard').addClass('main-color-text');
				}
			}).on('hidden.bs.dropdown', function () {
				if ($(this).attr('id') == 'menu-chat-opt') {
					$(this).find('#wrap-message-clipboard').removeClass('main-color-text');
				}
			});

			$('#close-contact-information').off('click').click(function () {
				CommunityManagement.closeContactInformation();
			});

			$('#close-group-information').off('click').click(function () {
				CommunityManagement.closeGroupInformation();
			});

			$('#close-list-information').off('click').click(function () {
				CommunityManagement.closeListInformation();
			});
		},

		chatListScroll() {
			// Tamaño de caja de contacto
			let contactBoxSize = $('div.contact').height() * 0.75;

			// Tamaño en página de contenedor de contactos
			let contactListHeight = Math.ceil($('.contact-list').height());

			// Tamaño de evento de recarga de contactos
			let eventSize = Math.floor(contactBoxSize * CommunityManagement.contactLimit * CommunityManagement.contactPage - contactListHeight);

			$('.contact-list').off().on('scroll', function () {
				let scrollPosition = Math.ceil($('.contact-list').scrollTop());
				if (scrollPosition >= eventSize) {
					$('.contact-list').off();
					CommunityManagement.renderChatlist();
				}
			});
		}
	},

	resetScreenData: {
		resetNewGroup() {
			$('.new-group-selected-users .bubble-selector').remove();
			$('.new-group-selected-users, .new-group-users-next').addClass('d-none');

			// Limpiar input de búsqueda
			$('#contacts-group-search').val('');

			// Limpiar nombre de grupo
			$('#new-group-name-text').val('');

			// Ocultar último paso y mostrar el primero
			$('#new-group-first-step').removeClass('d-none');
			$('#new-group-second-step').addClass('d-none');

			// Quitar imagen
			$('.new-group-file-container').addClass('d-none');
			$('.new-group-file-container img').attr('src', '');
			CommunityManagement.newGroup.img = '';
			$('#new-group-image-upload').val('');

			// Limpiar contenedor de contactos para lista de difusión
			$('.new-group-contact-list').html('');

			CommunityManagement.utils.setHeightToListUsersToAddGroup();
			CommunityManagement.resetDataNewGroup();
		},

		resetNewDistributionList() {
			$('.new-distributionlist-selected-users .bubble-selector').remove();

			// Ocultar segunda parte de creación y mostrar la primera
			$('#new-distributionlist-second-step').addClass('d-none');
			$('#new-distributionlist-first-step').removeClass('d-none');

			// Limpiar input de búsqueda
			$('#contacts-distributionlist-search').val('');

			// Limpiar contenedor de contactos para lista de difusión
			$('.new-distributionlist-contact-list').html('');

			// Limpiar nombre de la lista
			$('#new-distributionlist-name-text').val('');

			// Ocultar botón de siguiente
			$('.new-distributionlist-users-next').addClass('d-none');

			CommunityManagement.utils.setHeightToListUsersToAddList();
			CommunityManagement.resetDataNewDistributionList();
		},

		resetEditDistributionList() {
			$('.edit-distributionlist-selected-users .bubble-selector').remove();

			// Ocultar segunda parte de creación y mostrar la primera
			$('#edit-distributionlist-second-step').addClass('d-none');
			$('#edit-distributionlist-first-step').removeClass('d-none');

			// Limpiar input de búsqueda
			$('#contacts-distributionlist-search').val('');

			// Limpiar contenedor de contactos para lista de difusión
			$('.edit-distributionlist-contact-list').html('');

			// Limpiar nombre de la lista
			$('#edit-distributionlist-name-text').val('');

			// Ocultar botón de siguiente
			$('.edit-distributionlist-users-next').addClass('d-none');

			CommunityManagement.utils.setHeightToListUsersToAddList();
			CommunityManagement.resetDataEditDistributionList();
		}
	},

	// Register functions to execute UI and Data refresh after API action
	refresh: {
		completeContactList() {
			CommunityManagement.chatsEmailArray = [CommunityManagement.jsonUser.token];
			CommunityManagement.contactPage = 0;
			stcmbackend.communymanagement.chatList = [];
			stcmbackend.communymanagement.GroupsList = [];
			CommunityManagement.renderChatlist();
		},
		completeGroupInfo() {
			let parameters = {
				groupID: stcmbackend.communymanagement.currentChat.idgroup,
				groupName: ''
			};
			ajaxComunCallWithCallback('getInfoGroup_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					let data = ajaxReturn.result[0];
					CommunityManagement.usersGroup = [];
					CommunityManagement.usersGroup.push(data.jidUser);
					for (let members in data.members) {
						CommunityManagement.usersGroup.push(data.members[members].jidUser);
					}
					stcmbackend.communymanagement.currentChat = {
						avatar: data.avatar,
						bid: data.groupName,
						blocked: "0",
						deleted: "0",
						deletedby: null,
						direction: "",
						extendedData: "",
						idgroup: data.idGroup,
						msg: "",
						msgType: "",
						mute: { muted: '0' },
						name: data.name,
						orientation: "",
						role: "",
						stamp: "",
						stampServer: "",
						stampServerNoDist: "4",
						type: 'groupchat',
						uid: "",
						unreaded: 0,
						voiceassistant: "0"
					};
					data.blocked = stcmbackend.communymanagement.currentChat.blocked;
					data.mute = stcmbackend.communymanagement.currentChat.mute.muted;
					CommunityManagement.showContactInformation(stcmbackend.communymanagement.currentChat, data);
				}
			}, false);
		},
		profileAvatar(source) {
			$('#profile-avatar').attr('src', source);
			$('.profile img').attr('src', source);
		},
		groupAvatar(source) {
			$('#group-avatar').attr('src', source);
			$('.chat-head img').attr('src', source);
			$(`.contact.active-contact[data-bid="${stcmbackend.communymanagement.currentChat.bid}"] .contact-img img`).attr('src', source);
		},
		groupDescription(description) {
			$('#groupDescriptionText').text(description);
		},
		groupVolume(isMuted) {
			if (isMuted) {
				$('#groupChatMuteToggle').removeClass('fa-toggle-on').addClass('fa-toggle-off');
			} else {
				$('#groupChatMuteToggle').removeClass('fa-toggle-off').addClass('fa-toggle-on');
			}
		},
		leaveGroup() {
			CommunityManagement.refresh.completeGroupInfo();
			$('#messageBoxContainer').hide();
		},
		broadcastList() {
			let idList = stcmbackend.communymanagement.currentChat.idList;

			let parameters = {
				idList: idList
			};
			ajaxComunCallWithCallback('getDistibutionListInfo_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					let data = ajaxReturn.result[0].Members;
					CommunityManagement.showContactInformation(stcmbackend.communymanagement.currentChat, data);
				}
			}, false);
		}
	},

	utils: {
		getFormattedTime(unixtime, isChatMsg) {
			var msgDate = new Date(parseInt(unixtime));
			var day = ('0' + msgDate.getDate()).slice(-2);
			var month = ('0' + (msgDate.getMonth() + 1)).slice(-2);
			var year = msgDate.getFullYear();
			var hours = ('0' + msgDate.getHours()).slice(-2);
			var minutes = ('0' + msgDate.getMinutes()).slice(-2);
			var dateNow = new Date();

			// compare dates only
			dateNow.setHours(0, 0, 0, 0);
			msgDate.setHours(0, 0, 0, 0);

			if (dateNow.getTime() !== msgDate.getTime() && !isChatMsg) {
				if (day.toLowerCase().indexOf('an') !== -1) {
					return '';
				}

				return day + '/' + month + '/' + year;
			}

			return hours + ':' + minutes;
		},

		setHeightToListUsersToAddGroup() {
			var heightToRest = 60 + parseInt($('.new-group-selected-users').css('height').replace('px', ''));
			if ($('.new-group-users-next').is(':visible')) {
				heightToRest += 80;
			}
			$('.new-group-contact-list').css('height', 'calc(100% - ' + heightToRest + 'px)');
		},

		setHeightToListUsersToAddList() {
			var heightToRest = 60 + parseInt($('.new-distributionlist-selected-users').css('height').replace('px', ''));
			if ($('.new-distributionlist-users-next').is(':visible')) {
				heightToRest += 80;
			}
			$('.new-distributionlist-contact-list').css('height', 'calc(100% - ' + heightToRest + 'px)');
		},
	},

	ui: {
		Modal: class {
			id = '';
			_html = '';
			title = '';
			template = '';
			primaryTxt = '';
			primaryCallback = null;
			primaryColor = '';
			secondaryTxt = '';
			secondaryCallback = null;
			secondaryColor = '';

			constructor(title, template, { text: primaryText = 'Ok', callback: primaryCallback = () => this.hide(), color: primaryColor = 'primary' } = {}, { text: secondaryText = '', callback: secondaryCallback = null, color: secondaryColor = 'secondary' } = {}) {
				this.id = this._generateId();
				this.title = title;
				this.template = template;
				this.primaryTxt = primaryText;
				this.primaryCallback = primaryCallback;
				this.primaryColor = primaryColor;
				this.secondaryTxt = secondaryText;
				this.secondaryCallback = secondaryCallback;
				this.secondaryColor = secondaryColor;

				this._html = `
				<div class="modal fade" id="${this.id}" tabindex="-1" role="dialog" aria-labelledby="Modal ${title}" aria-hidden="true" style="background: unset">
				  <div class="modal-dialog modal-dialog-centered" role="document" style="max-height: 80vh; position:relative;">
					<div class="modal-content" style="height: 100%;">
					  <div class="modal-header chat-bar-color">
						<h5 class="modal-title">${title}</h5>
						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						  <span aria-hidden="true">&times;</span>
						</button>
					  </div>
					  <div class="modal-body" style="max-height: calc(80vh - 120px); overflow-y: auto;">
						${template}
					  </div>
					  <div class="modal-footer">
						<button type="button" class="btn primary-btn btn-${this.primaryColor}">${this.primaryTxt}</button>
						${this.secondaryTxt && this.secondaryCallback ? `<button type="button" class="btn secondary-btn btn-${this.secondaryColor}">${this.secondaryTxt}</button>` : ''}
					  </div>
					</div>
				  </div>
				</div>
			  `;
			}

			show() {
				const container = document.getElementById('communityManagementContainer');
				if (container) {
					container.insertAdjacentHTML('beforeend', this._html);
					this._setButtonEventListeners();
					$(`#${this.id}`).modal('show');
				}
			}

			hide() {
				$(`#${this.id}`).modal('hide');
				const modalElement = document.getElementById(this.id);
				if (modalElement) {
					modalElement.parentNode.removeChild(modalElement);
				}
			}

			getId() {
				return this.id;
			}

			_generateId() {
				return `modal-${Math.floor(Math.random() * 1e10)}`;
			}

			_setButtonEventListeners() {
				if (this.primaryCallback && this.primaryTxt) {
					$(`#${this.id} .modal-footer .btn-${this.primaryColor}`).off().on('click', this.primaryCallback.bind(this));
				}
				if (this.secondaryCallback && this.secondaryTxt) {
					$(`#${this.id} .modal-footer .btn-${this.secondaryColor}`).off().on('click', this.secondaryCallback.bind(this));
				}
			}
		},

		UserSelector: class {

			html = '';
			users = null;
			selectedUsers = [];

			constructor(users) {
				this.users = users;
			}

			getHtml() {
				let template = '';
				this.users.forEach((user, i) => {
					new stcmbackend.communymanagement.appUsers(user);
					template += `
						<div class="form-check c-pointer d-flex align-items-center">
							<input id="check_${user.jidUser}" class="form-check-input" type="checkbox" value="">
							<label for="check_${user.jidUser}" class="form-check-label flex-grow-1">
								<div class="contact" data-bid="${user.jidUser}" data-token="${user.token}" data-index="${i}">
									<div class="contact-img">
										<img src="${user.avatar}" alt="">
									</div>
									<div class="contact-preview">
										<div class="contact-text">
											<div class="font-name user-nick ellipsis">${user.nick}</div>
										</div>
									</div>
								</div>
							</label>
						</div>
						`;
				});

				template = `
					<div class="search-container mb-3">
						<input type="text" id="userSearch" class="form-control" placeholder="Search by name">
					</div>
					<div class="contacts-container">
						${template}
					</div>
					<div class="my-0" style="position: sticky; bottom: calc(-1rem - 1px); background: white; padding: 1rem; z-index=999">
						<span id="totalSelected">0</span> <span idRSC="RSC406">${pf.const.language.RSC406}</span>
					</div>
				`;

				return template;
			}

			bindEvents() {
				const _this = this;

				$('#userSearch').on('input', function () {
					const searchText = $(this).val().toLowerCase();
					$('.contact').each(function () {
						const userName = $(this).find('.font-name.user-nick').text().toLowerCase();
						if (userName.includes(searchText)) {
							$(this).closest('.form-check').removeClass('hidden');
						} else {
							$(this).closest('.form-check').addClass('hidden');
						}
					});
				});

				$('.form-check-input').on('click', function () {
					const email = $(this).closest('.form-check').find('.contact').data('token');
					if ($(this).prop('checked')) {
						_this.selectedUsers.push(email);
					} else {
						const index = _this.selectedUsers.indexOf(email);
						if (index !== -1) {
							_this.selectedUsers.splice(index, 1);
						}
					}
					_this._updateSelectedCount();
				});
			}

			getSelectedUsers() {
				return this.selectedUsers;
			}

			_updateSelectedCount() {
				$('#totalSelected').text(this.selectedUsers.length);
			}
		}
	},

	transitions: {
		showSlide(elem, direction) { //left or right
			elem.hide();
			elem.show('slide', { direction: direction }, 500);
		},

		hideSlide(elem, direction) { //left or right
			elem.show();
			elem.hide('slide', { direction: direction }, 500);
		}
	},

	ajax: {
		doAjax(ws, parameters, spinner, callback) {
			CommunityManagement.activeService = ws;
			ajaxComunCallWithCallback(ws, parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					var data = ajaxReturn.result;
					$('#messageBoxContainer').show();

					if (ws == 'getChatContent_SaaS') {
						if (data.length > 0 && data[0].bid != stcmbackend.communymanagement.currentChat.bid) {
							if (CommunityManagement.activeService == 'getChatContent_SaaS') {
								CommunityManagement.ajax.doAjax(ws, parameters, spinner, callback)
							}
						} else {
							// Control de contactos bloqueados
							if (stcmbackend.communymanagement.currentChat.blocked == '1') {
								$('#messageBoxContainer').hide();
							}

							callback(data);
						}
					} else if (ws == 'getChatGroupContent_SaaS') {
						CommunityManagement.inGroup = ajaxReturn.inGroup;
						if (!CommunityManagement.inGroup) {
							// Modificar elementos para su visibilidad
							$('#menu-chat-exit').addClass('d-none');
							$('#messageBoxContainer').hide();
						}
						if (Array.isArray(data.length) && data.length > 0 && data[0].bid != stcmbackend.communymanagement.currentChat.bid) {
							if (CommunityManagement.activeService == 'getChatGroupContent_SaaS') {
								CommunityManagement.ajax.doAjax(ws, parameters, spinner, callback)
							}
						} else {
							if (data == 'Group ID especificated not exists.') {
								// Este grupo ya no existe en la plataforma
								let warningTitle = pf.const.language.RSC6;
								let warningContent = pf.const.language.RSC2627;
								pf.utils.showInfoDialog(warningTitle, warningContent);

								// Refrescar secciones de página
								CommunityManagement.chatsEmailArray = [CommunityManagement.jsonUser.token];
								CommunityManagement.contactPage = 0;
								stcmbackend.communymanagement.chatList = [];
								stcmbackend.communymanagement.GroupsList = [];
								CommunityManagement.renderChatlist();
								$('#communityManagement .main-window').removeClass('d-none');
								$('#communityManagement .chat-window').addClass('d-none');
							} else {
								callback(data);
							}
						}
					} else {
						callback(data);
					}
				}
			}, spinner);
		},

		createDistributionList(name, users, callback) {
			let parameters = {
				admin: CommunityManagement.jsonUser.token,
				activa: 1,
				description: name,
				destinatarios: JSON.stringify(users)
			};

			CommunityManagement.ajax.doAjax('createDistributionList_SaaS', parameters, false, callback);
		},
		createGroup(name, participants, file, callback) {
			let parameters = {
				groupAdmin: CommunityManagement.jsonUser.token,
				groupName: name,
				participants: JSON.stringify(participants),
				file: file
			};

			CommunityManagement.ajax.doAjax('createGroup_SaaS', parameters, false, callback);
		},

		getChatList: function (stamp, limit, page, callback) {
			let parameters = {
				email: CommunityManagement.jsonUser.token,
				stamp: stamp,
				onlyEnabled: 1,
				limit: limit,
				page: page
			};

			CommunityManagement.ajax.doAjax('getChatList_SaaS', parameters, false, callback);
		},

		getChatContent(contact, callback) {
			let parameters = {
				userA: CommunityManagement.jsonUser.token,
				userB: contact
			};
			// Cambiado a false por el nuevo Spinner
			CommunityManagement.ajax.doAjax('getChatContent_SaaS', parameters, false, callback);
		},

		getChatGroupContent(group, callback) {
			let parameters = {
				email: CommunityManagement.jsonUser.token,
				groupID: group
			};
			// Cambiado a false por el nuevo Spinner
			CommunityManagement.ajax.doAjax('getChatGroupContent_SaaS', parameters, false, callback);
		},

		getUsers(callback) {
			let parameters = {
				onlyEnabled: 1,
				fullMode: 0,
				limit: CommunityManagement.usersLimit,
				page: CommunityManagement.userspage
			};

			CommunityManagement.ajax.doAjax('getUsers_SaaS', parameters, false, callback);
		},

		setTokenDeviceForPush(token, callback) {
			let parameters = {
				email: CommunityManagement.jsonUser.token,
				platform: 'Web',
				deviceId: token
			};

			CommunityManagement.ajax.doAjax('setTokenDeviceForPush_SaaS', parameters, false, callback);
		},

		setUserConfigNotif(notifType, mute, callback) {
			let parameters = {
				email: CommunityManagement.jsonUser.token,
				type: notifType,
				mute: mute
			};

			CommunityManagement.ajax.doAjax('setUserConfigNotif_SaaS', parameters, false, callback);
		},

		// Salir de grupo
		takeOutFromGroup_SaaS(groupId, participants) {
			let parameters = {
				groupId: groupId,
				participants: JSON.stringify(participants)
			};
			ajaxComunCallWithCallback('takeOutFromGroup_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					// Modificar elementos para su visibilidad
					$('#menu-chat-exit').addClass('d-none');
					$('#messageBoxContainer').hide();
					CommunityManagement.inGroup = false;
				}
			}, false);
		},

		// Añadir contactos a grupo
		addToGroup_SaaS(groupId, participants) {
			let parameters = {
				groupId: groupId,
				participants: JSON.stringify(participants)
			};
			ajaxComunCallWithCallback('addToGroup_SaaS', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					CommunityManagement.refresh.completeGroupInfo();
				}
			}, false);
		}
	},

	// Limpiar elementos de adjuntos y ocultar visualizador
	cleanAttachmentItems() {
		$('#previewAttachments').addClass('d-none');
		$('#attachmentsContainer').html('');
		$('#miniatureAttachmentsContainer').html('');
		CommunityManagement.chatFile = null;
		$('#fileToSendHidden').val('');
	},

	initializeDictionary(callback) {
		let self = this;
		let lenguage = sessionStorage['STCMBackEnd:lenguage'];

		if (sessionStorage.getItem('STCMBackEnd:config') === null) {
			let parameters = {
				lenguage: lenguage,
				system: '1'
			};
			ajaxComunCallWithCallbackOne('getAllRSCByLenguage', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					let resp = ajaxReturn.resData.response;
					response = JSON.parse(resp);
					if (response.status == 'OK') {
						let resp = response.result;
						if (!Array.isArray(resp)) {
							resp = [];
						}

						self.diccionario = '{';
						$.each(resp, function (ind, elem,) {
							self.diccionario += '"RSC' + elem.idRSC + '":"' + elem[lenguage] + '"';
							if (ind != (resp.length - 1)) {
								self.diccionario += ', ';
							}
						});

						self.diccionario += '}';
						pf.const.language = JSON.parse(self.diccionario);

						self.loaders.initializeDictionary = true;
						spinnerControl(self.loaders);
						callback();

						pf.rsc.translateByTag('text');
						pf.rsc.translateByTag('placeholder');
						pf.rsc.translateByTag('title');

						// Caso especial de RSC
						$('.emojionearea-editor').attr('placeholder', pf.const.language.RSC2277);

						if (sessionStorage['STCMBackEnd:lenguage'] == 'ENG') {
							pf.const.language_table = '';
						} else {
							pf.const.language_table = {
								sProcessing: pf.const.language.RSC1050,
								sLengthMenu: pf.const.language.RSC1051,
								sZeroRecords: pf.const.language.RSC1052,
								sEmptyTable: pf.const.language.RSC1053,
								sInfo: pf.const.language.RSC1054,
								sInfoEmpty: pf.const.language.RSC1055,
								sInfoFiltered: pf.const.language.RSC1056,
								sInfoPostFix: '',
								sSearch: pf.const.language.RSC1057,
								sUrl: '',
								sInfoThousands: ',',
								sLoadingRecords: pf.const.language.RSC1058,
								oPaginate: {
									sFirst: pf.const.language.RSC1059,
									sLast: pf.const.language.RSC1060,
									sNext: pf.const.language.RSC663,
									sPrevious: pf.const.language.RSC1061
								},
								oAria: {
									sSortAscending: pf.const.language.RSC1062,
									sSortDescending: pf.const.language.RSC1063
								},
								buttons: {
									copy: pf.const.language.RSC445,
									colvis: pf.const.language.RSC1064
								}
							}
						}

						// Atributo 'title' para botones de busqueda
						$('.search_button_title').attr('title', pf.const.language.RSC2264);
					} else {
						if (response.result == 'Not authorized') {
							pf.ajax.setWindowLocationIndex();
						}
						pf.const.language = {};
					}
				}
			}, false);
		} else {
			// Terminar spinner aunque no haya ajax
			self.loaders.initializeDictionary = true;
			spinnerControl(self.loaders);
			callback();

			// Carga de idioma para los elementos
			pf.rsc.translateByTag('text');
			pf.rsc.translateByTag('placeholder');
			pf.rsc.translateByTag('title');

			// Caso especial de RSC
			$('.emojionearea-editor').attr('placeholder', pf.const.language.RSC2277);
		}
	},

	userListRender(data, call) {
		// Lista de usuarios
		let template = '';
		// Lista de usuarios sin chat creado
		let templateNewChat = '';

		if (CommunityManagement.userspage == 0) {
			stcmbackend.communymanagement.usersList = [];
		}

		for (let i = 0; i < data.length; i++) {
			let e = data[i];
			// Control para que no salga el usuario
			if (CommunityManagement.jsonUser.token == e.token) {
				continue;
			}

			new stcmbackend.communymanagement.appUsers(e);
			template += CommunityManagement.printUserObj(e, i);

			if (!CommunityManagement.chatsEmailArray.includes(data[i].token)) {
				templateNewChat += CommunityManagement.printUserObj(e, i);
			}
		}

		if (call == 'newChat') {
			if (CommunityManagement.userspage == 0) {
				$('.new-chat-contact-list').html(templateNewChat);
			} else {
				$('.new-chat-contact-list').append(templateNewChat);
			}

			// Control de scroll
			if (data.length > 0 && data.length == CommunityManagement.usersLimit) {
				CommunityManagement.userspage++;
				CommunityManagement.usersListScroll('.new-chat-contact-list', 'newChat');
			} else {
				$('.new-chat-contact-list').off();
			}

			CommunityManagement.events.addClickToNewChat();
		} else if (call == 'newGroup') {
			if (CommunityManagement.userspage == 0) {
				$('.new-group-contact-list').html(template);
			} else {
				$('.new-group-contact-list').append(template);
			}

			// Ocultar los usuarios ya añadidos al grupo
			let size = CommunityManagement.newGroupMembers.length;
			for (let i = 0; i < size; i++) {
				$('.new-group-contact-list .contact[data-bid="' + CommunityManagement.newGroupMembers[i] + '"').hide();
			}

			// Control de scroll
			if (data.length > 0 && data.length == CommunityManagement.usersLimit) {
				CommunityManagement.userspage++;
				CommunityManagement.usersListScroll('.new-group-contact-list', 'newGroup');
			} else {
				$('.new-group-contact-list').off();
			}

			CommunityManagement.events.addClickToNewGroup();
		} else if (call == 'newList') {
			if (CommunityManagement.userspage == 0) {
				$('.new-distributionlist-contact-list').html(template);
			} else {
				$('.new-distributionlist-contact-list').append(template);
			}

			// Ocultar los usuarios ya añadidos a la lista
			let size = CommunityManagement.newListMembers.length;
			for (let i = 0; i < size; i++) {
				$('.new-distributionlist-contact-list .contact[data-bid="' + CommunityManagement.newListMembers[i] + '"').hide();
			}

			// Control de scroll
			if (data.length > 0 && data.length == CommunityManagement.usersLimit) {
				CommunityManagement.userspage++;
				CommunityManagement.usersListScroll('.new-distributionlist-contact-list', 'newList');
			} else {
				$('.new-distributionlist-contact-list').off();
			}

			CommunityManagement.events.addClickToNewDistributionList();
		} else {
			// Creación de modal con contactos para reenviar
			if (CommunityManagement.userspage == 0) {
				$('#contactsToResendBody').html(template);
			} else {
				$('#contactsToResendBody').append(template);
			}

			// Control de scroll
			if (data.length > 0 && data.length == CommunityManagement.usersLimit) {
				CommunityManagement.userspage++;
				CommunityManagement.usersListScroll('#contactsToResendBody', 'addToGroup');
			} else {
				$('#contactsToResendBody').off();
			}

			// Añadir eventos para reenviar
			CommunityManagement.events.contactsToResendEvents();
		}
	},

	usersListScroll(element, call) {
		// Tamaño de caja de contacto
		let contactBoxSize = $(element + ' .contact').height();

		// Tamaño en página de contenedor de contactos
		let contactListHeight = contactBoxSize * CommunityManagement.usersLimit;

		// Tamaño de evento de recarga de contactos
		let eventSize = Math.floor(contactBoxSize * CommunityManagement.usersLimit * CommunityManagement.userspage - (CommunityManagement.userspage == 1 ? Math.floor(contactListHeight / 2) : contactListHeight));

		$(element).off().on('scroll', function () {
			let scrollPosition = Math.ceil($(element).scrollTop());

			if (scrollPosition >= eventSize) {
				// Desactivar el evento scroll de nuevo chat
				$(element).off();

				CommunityManagement.ajax.getUsers(function (data) {
					CommunityManagement.userListRender(data, call);
				});
			}
		});
	},
	initializeChatbot(){
		let params = {
			email: CommunityManagement.jsonUser.token,
			chatbotEmail: stcmbackend.communymanagement.currentChat.email
		};
		ajaxComunCallWithCallback('initChatbotSession_SaaS', params, () => {}, false);
	}
};