let ProyectosEditController = {
	user: null,
	language: '',
	idProject: '',
	project: '',
	leader: '',
	requestType: '',
	surveysProfiling: '',
	profilingName: [],
	targetsSurvey: [],
	targetsSurveySID: [],
	columnName: '',
	columnNameK: '',
	surveyValues: '',
	renderSurveyValuesFlag: false,
	valueCode: [],
	projectMissions: [],
	allMissions: '',
	participants: '',
	participantsFiltered: '',
	country: '',
	participantsIDExp: '',
	motivosExpulsion: '',
	filesRecorded: '',
	leaderModal: null,
	countryFilter: '',
	updateRotations: false,
	loaded: false,
	selectedSurveys: [],
	maxSurveysProfiling: 5,
	sidRelations: [],
	surveysProfilingFlag: false,
	segmentations: '',
	selectedSegmentations: [],
	selectedIDSegmentations: [],
	segmentationName: '',
	segmentationsData: {},
	maxSize: 0,
	videoFile: null,
	userName: '',
	loaders: {},
	color1RGB: '',
	viewTranscription: {},
	missionRemoved: [],
	wordCloudURL: '',
	numberWordsWordcloud: 0,
	primaryColor: '',
	secundaryColor: '',
	wordCloudImg: null,
	transcriptionText: '',
	fileToUpload: null,
	fileToUploadDesc: '',
	filesToUploadInfo: [],
	userMail: '',
	useCPG: '',
	cpgList: '0',
	cpgActive: null,
	profilingSections: null,
	previousQuotaAllocation: null,
	quotaElementsArray: [],
	modifiedQuota: false,
	quotaElementsArrayMissions: [],
	deliveryMissions: [],
	idCliente: '',
	dateFormat: '',
	missionsWhitVideocall: [],
	audit: [],
	stores: [],

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.idProject = sessionStorage.getItem('idProject');
		self.project = '';
		self.leader = '';
		self.requestType = '';
		self.surveysProfiling = '';
		self.profilingName = [];
		self.targetsSurvey = [];
		self.targetsSurveySID = [];
		self.columnName = '';
		self.columnNameK = '';
		self.surveyValues = '';
		self.renderSurveyValuesFlag = false;
		self.valueCode = [];
		self.projectMissions = [];
		self.allMissions = '';
		self.participants = '';
		self.participantsFiltered = '';
		self.country = '';
		self.participantsIDExp = '';
		self.motivosExpulsion = '';
		self.filesRecorded = '';
		self.leaderModal = null;
		self.countryFilter = '';
		self.updateRotations = false;
		self.loaded = false;
		self.selectedSurveys = [];
		self.maxSurveysProfiling = 5;
		self.sidRelations = [];
		self.surveysProfilingFlag = false;
		self.segmentations = '';
		self.selectedSegmentations = [];
		self.selectedIDSegmentations = [];
		self.segmentationName = '';
		self.segmentationsData = {};
		self.maxSize = 0;
		self.videoFile = null;
		self.userName = '';
		self.loaders = {
			getCMBPProjects: false,
			getAllRotacionesProject: false,
			getFilesRecordedByProject: false
		};
		self.color1RGB = '';
		self.viewTranscription = {
			idCall: '',
			path: '',
			fileName: ''
		};
		self.missionRemoved = [];
		self.wordCloudURL = '';
		self.numberWordsWordcloud = 0;
		self.primaryColor = '';
		self.secundaryColor = '';
		self.wordCloudImg = null;
		self.transcriptionText = '';
		self.fileToUpload = null;
		self.fileToUploadDesc = '';
		self.filesToUploadInfo = [];
		self.userMail = '';
		self.useCPG = sessionStorage['STCMBackEnd:multicpg'];
		self.cpgList = '0';
		self.cpgActive = null;
		self.profilingSections = null;
		self.quotaElementsArray = [];
		self.modifiedQuota = false;
		self.previousQuotaAllocation = false;
		self.quotaElementsArrayMissions = [];
		self.deliveryMissions = [];
		self.idCliente = '';
		self.dateFormat = '';
		self.missionsWhitVideocall = [];
		self.audit = [];
		self.stores = [];
	},

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

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.maxSize = config.upload_max_filesize_bytes;
		self.color1RGB = config.RGBInicio;
		self.wordCloudURL = config.URLWordCloud;
		self.numberWordsWordcloud = config.numWordSentenceWordCloud;
		self.primaryColor = config.tenant[0].colorPrimario.replace('#', '');
		self.secundaryColor = config.tenant[0].colorSecundario.replace('#', '');

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.userMail = user.email;
		let user_split = self.userMail.split('@');
		self.user = user_split[0].replace('.', '_');
		self.userName = user.name.trim() + '_' + user.apellido1.trim();
		self.idCliente = user.idCliente;
		self.dateFormat = user.formatoFecha;

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC10 + ' - ' + pf.const.language.RSC225);

		// Opciones de header
		let jsonsubopt = {
			back: 'back',
			save: 'save',
			results: 'getResults'
		};

		let nav = `
			<div class="row mx-0">
				${createSubOptionSave(jsonsubopt.save)}
				${createSubOptionGetResults(jsonsubopt.results)}
			</div>

			${createSubOptionBack(jsonsubopt.back)}
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		$('#getResults svg').css('width', '16px');
		$('#getResults svg').css('height', '16px');

		// Botón principal
		$('#getResults').addClass('main-button');

		// Botones secundarios
		$('#back').addClass('secondary-button');
		$('#save').addClass('secondary-button');

		// Tamaño especial por ser botón secundario
		$('#save svg').css('width', '16px');
		$('#save svg').css('height', '16px');

		// Control de uso de CPG
		if(self.useCPG == '0' || sessionStorage['STCMBackEnd:idCPG'] != '0') {
			self.cpgList = sessionStorage['STCMBackEnd:idCPG'];
			$('#searchCPG').prop('disabled', true);
		}
		$('#cpgList').val(self.cpgList);
		$('#cpgList').attr('title', self.cpgList);

		// Añadir textos
		$('#greetingTooltip').attr('title', pf.const.language.RSC1258);
		$('#inclusiveContainer').hide();

		// Encuestas Vs Segmentacione
		$('#algorithmSurvey').hide();
		$('#algorithmSegmentation').hide();

		// Ocultar botón de repartición
		$('#distributionAdvisers').hide();

		// Ocultar el botón de videollamada
		$('#videocall').hide();

		self.loadLang();

		addLoader();
		self.requestProject();
		self.getFilesRecordedByProject();
		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();

		// Collapse encuestas
		$('.arrowSurvey').on('click', function() {
			let arrow = $(this).attr('data-arrow');
			let direction = '';
			if(arrow == 'left') {
				direction = stcmbackend.svg.chevronDown;
				$(this).attr('data-arrow', 'down');
			} else {
				direction = stcmbackend.svg.chevronRight;
				$(this).attr('data-arrow', 'left');
			}
			$(this).html(direction);
			$(this).parent().parent().parent().parent().find('.collapse').collapse('toggle');
		});

		// Pintar texto de label
		changeLabelsColor();
	},

	loadLang() {
		pf.rsc.translateByTag('text');
		pf.rsc.translateByTag('placeholder');

		let arrObj = ['RSC393'];
		pf.rsc.translateByTagHTMLFormat(':', arrObj);

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
		$('#videocall').attr('title', pf.const.language.RSC2499);
		$('#videocallNoParticipants').attr('title', pf.const.language.RSC1949);
		$('#externalVideocall').attr('title', pf.const.language.RSC1952);
		$('#importVideoLlamadas').attr('title', pf.const.language.RSC1957);
		$('#importAdditionalDocuments').attr('title', pf.const.language.RSC2063);
	},

	// Petición del proyecto por ID
	requestProject() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.project = ajaxReturn.result[0];

				self.requestProjectMissions();

				// Select inclusivo
				$('#inclusive').val(self.project.resultadoInclusivo);

				self.country = {
					isocode: self.project.country,
				}

				// Encuestas o Segmentaciones
				if(self.project.useSegmentation == '1' && self.project.targetTotalPanel == '0') {
					// Segmentación
					$('#searchAlgorithmSegmentation').prop('checked', true);
					$('#searchAlgorithmSegmentation').parent().addClass('option-box-check-selected');
					$('#algorithmSegmentation').show();
				} else if(self.project.useSegmentation == '0' && self.project.targetTotalPanel == '0') {
					// Encuesta
					$('#searchAlgorithmSurvey').prop('checked', true);
					$('#searchAlgorithmSurvey').parent().addClass('option-box-check-selected');
					$('#algorithmSurvey').show();
				} else if(self.project.targetTotalPanel == '1') {
					// Todos los usuarios
					$('#searchAlgorithmTotal').prop('checked', true);
					$('#searchAlgorithmTotal').parent().addClass('option-box-check-selected');
					$('#algorithmSurvey').show();
					$('#algorithmSurvey').css('visibility', 'hidden');
					$('#algorithmSegmentation').css('visibility', 'hidden');
				}

				// Búsqueda de líder de proyecto
				if(self.leader.LeaderExists == '0') {
					let errorTitle = pf.const.language.RSC1616;
					let errorContent = pf.const.language.RSC1728;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				} else {
					self.leader = {
						id: self.project.LiderProyectoJID,
						nameUser: self.project.userNombre,
						userApellidos: self.project.userApellidos,
						userApellidos2: self.project.userApellidos2,
						email: self.project.LiderProyectoEmail
					};
				}

				// Control de spinner
				self.loaders.getCMBPProjects = true;
				spinnerControl(self.loaders);

				// Formulario a editar
				self.renderForm();
			}
		}, false);
	},

	renderForm() {
		let self = this;

		let relations = self.project.sidRelations.split(',');
		for(let i = 0; i < relations.length; i++) {
			let rel = relations[i].split('#');
			if(rel[1] === undefined) {
				self.sidRelations.push('&');
			} else {
				self.sidRelations.push(rel[1].replace('amp;', ''));
			}
		}

		$('#projectName').val(self.project.NombreProyecto);

		self.cpgList = self.project.cpgList;
		$('#cpgList').val(self.cpgList);
		$('#cpgList').attr('title', self.cpgList);

		$('#proyectoReparticion').prop('checked', (self.project.proyectoReparticion == 1 ? true : false));
		self.countryFilter = self.project.country;
		$('#projectCountry').val(self.project.country);
		$('#projectLeader').val(self.project.LiderProyecto);

		// BRIEFING
		if(self.project.briefing.length > 0) {
			$('#ApplicantName').val(self.project.briefing[0].applicantName);
			$('#brandsInvolved').val(self.project.briefing[0].brandsInvolved);
			$('#projectDescription').val(self.project.briefing[0].projectDescription);
			$('#background').val(self.project.briefing[0].background);
			$('#businessObjective').val(self.project.briefing[0].businessObjective);
			$('#investigationObjective').val(self.project.briefing[0].investigationObjective);
			$('#actionStandard').val(self.project.briefing[0].actionStandard);
			$('#resultsFavorable').val(self.project.briefing[0].favorableResults);
			$('#resultsNotFavorable').val(self.project.briefing[0].notFavorableResults);
		}

		// Documentos adicionales
		let sizeDocs = self.project.files.length;
		for(let n = 0; n < sizeDocs; n++) {
			let obj = {
				id: self.project.files[n].id,
				fecha: self.project.files[n].stampServer,
				admin: self.project.files[n].admin,
				documento: self.project.files[n].fileName,
				descripcion: self.project.files[n].descripcion,
				tamano: self.project.files[n].fileSize
			};
			self.filesToUploadInfo.push(obj);
		}

		self.additionalDocumentsTable();

		// Encuestas o Segmentaciones
		if(self.project.useSegmentation == '1') {
			if(self.project.IdSegmentacion != '') {
				// Nombres de Segmentaciones
				self.segmentationName = self.project.IdSegmentacion.split(',');

				// Conversión a array de IDs de Segmentaciones
				self.selectedIDSegmentations = self.project.sidRelationsSegmentation.split(',');
				if(self.selectedIDSegmentations.length > 1) {
					$('#inclusiveContainer').show();
				} else {
					$('#inclusiveContainer').hide();
				}

				self.getCMBPProjectsTargetsSegmentation(0);
			}
		} else {
			if(self.project.IdPerfilacion != '') {
				// Nombres de encuestas de perfilación
				self.profilingName = self.project.IdPerfilacion.split(',');

				// Conversión a array de sid de perfilación
				self.targetsSurveySID = self.project.sidPerfilacion.split(',');
				if(self.targetsSurveySID.length > 1) {
					$('#inclusiveContainer').show();
				} else {
					$('#inclusiveContainer').hide();
				}

				self.selectedSurveys = [];
				for(let i = 0; i < self.targetsSurveySID.length; i++) {
					let obj = {
						sid: self.targetsSurveySID[i],
						surveyls_title: self.profilingName[i]
					};
					self.selectedSurveys.push(obj);
				}

				// Petición inicial
				self.requestTargetsSurvey(0, true);
			}
		}

		let numberRecords = sessionStorage.getItem('numberRecords');
		if(numberRecords === null) {
			numberRecords = 0;
		}
		$('#numberRecords').val(numberRecords);

		$('#individualChat').prop('checked', (self.project.ChatIndividual == 1 ? true : false));
		$('#groupChat').prop('checked', (self.project.ChatGrupal == 1 ? true : false));
		$('#diffusionList').prop('checked', (self.project.ListaDistribucion == 1 ? true : false));
		$('#greeting').prop('checked', (self.project.notificarInclusion == 1 ? true : false));

		// Líder de proyecto
		self.leaderModal = new TableUsers(0, 'editProjectLeader', '', '', '', 1);
		self.leaderModal.surname = false;
		$('#searchLeader').on('click', function() {
			self.requestType = 'leader';
			self.leaderModal.setEvents();
		});
	},

	getCMBPProjectsTargetsSegmentation(index) {
		let self = this;

		let parameters = {
			id: self.project.id,
			sidRelationsSegmentation: self.selectedIDSegmentations[index]
		};
		ajaxComunCallWithCallback('getCMBPProjectsTargetsSegmentation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Preparación de json con las diferentes segmentaciones
				self.segmentationsData[self.selectedIDSegmentations[index]] = ajaxReturn.result;

				index++;
				if(index < self.selectedIDSegmentations.length) {
					self.getCMBPProjectsTargetsSegmentation(index);
				} else {
					self.getAllSegmentaciones(true);
				}
			}
		}, false);
	},

	// Petición de misiones de proyecto
	requestProjectMissions() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjectsMisiones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.projectMissions = ajaxReturn.result || [];

				let size = self.projectMissions.length;
				for(let i = 0; i < size; i++) {
					if(self.projectMissions[i].objetivo == 'VideoCallGrupal' || self.projectMissions[i].objetivo == 'VideoCallUnitaria') {
						self.missionsWhitVideocall.push(self.projectMissions[i]);
					}

					// Control de auditorías
					if(self.projectMissions[i].isAuditoria == '1') {
						auditObj = {
							idmision: self.projectMissions[i].idmision,
							stampMision: self.projectMissions[i].stampMision
						};

						self.audit.push(auditObj);
					}
				}

				//participantes 
				self.requestProjectParticipants();
			}
		}, false);
	},

	renderProjectsMissions: async function() {
		let self = this;

		let rotation_distribution_head = `
			<th scope="col" title="${pf.const.language.RSC1404}">${pf.const.language.RSC1404}</th>
		`;

		// En el caso de que sea un proyecto de repartición
		if(self.project.proyectoReparticion == '1') {
			rotation_distribution_head = `
				<th scope="col" title="${pf.const.language.RSC2229}">${pf.const.language.RSC2229}</th>
			`;
		}

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC177}">${pf.const.language.RSC177}</th>
					<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
					<th scope="col" title="${pf.const.language.RSC133}">${pf.const.language.RSC133}</th>
					<th scope="col" title="${pf.const.language.RSC1968}">${pf.const.language.RSC1968}</th>
					<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
					<th scope="col" title="${pf.const.language.RSC118}">${pf.const.language.RSC118}</th>
					<th scope="col" title="${pf.const.language.RSC1969}">${pf.const.language.RSC1969}</th>
					<th scope="col" title="${pf.const.language.RSC1970}">${pf.const.language.RSC1970}</th>
					${rotation_distribution_head}
					<th scope="col" title="${pf.const.language.RSC572}">${pf.const.language.RSC572}</th>
					<th scope="col" title="${pf.const.language.RSC2125}">${pf.const.language.RSC2125}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersResultM">
				<tr>
					<td>mission</td>
					<td>description</td>
					<td>start</td>
					<td>end</td>
					<td>estado</td>
					<td>remuneration</td>
					<td>numberNotifications</td>
					<td>Notified</td>
					<td>rotations</td>
					<td>validate</td>
					<td>quota</td>
					<td>delete</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.projectMissions.length;
		for(let i = 0; i < size; i++) {
			let startDateTime = self.projectMissions[i].fechahorainicio.split(' ');
			let startDateArray = startDateTime[0].split('/');
			let startDate = startDateArray[2] + '-' + startDateArray[1] + '-' + startDateArray[0];
			let startTimeArray = startDateTime[1].split(':');
			let startTime = startTimeArray[0] + ':' + startTimeArray[1];

			let endDateTime = self.projectMissions[i].fechahorafin.split(' ');
			let endDateArray = endDateTime[0].split('/');
			let endDate = endDateArray[2] + '-' + endDateArray[1] + '-' + endDateArray[0];
			let endTimeArray = endDateTime[1].split(':');
			let endTime = endTimeArray[0] + ':' + endTimeArray[1];

			let validate = '';
			if(self.projectMissions[i].needValidation === '1') {
				validate += `
					<button type="button" class="btn table-button main-color-text btn-validate" data-id="${i}">
						${stcmbackend.svg.bigEyeWithoutColor}
					</button>
				`;
			}

			let rotation = '';
			if(self.projectMissions[i].isSurvey == '1') {
				let disabled = '';
				let title = pf.const.language.RSC1404;

				if(self.participants.length === 0) {
					disabled = 'disabled';
					title = pf.const.language.RSC2139;
				}

				rotation += `
					<button type="button" class="btn table-button main-color-text btn-rotation" data-id="${i}" data-surveyid="${self.projectMissions[i].sid}" title="${title}" ${disabled}>
						${stcmbackend.svg.bigArrowRepeatWithoutColor}
					</button>
				`;
			}

			// En el caso de que sea un proyecto de repartición
			if(self.project.proyectoReparticion == '1') {
				rotation = `
					<div class="row ml-2 mt-1">
						<input type="number" class="col form-control percentageDelivery" value="${self.projectMissions[i].cuotaReparto}" data-stampmision="${self.projectMissions[i].stampMision}">
						<div class="col px-0 pt-1">
							<button type="button" class="btn table-button main-color-text btn-reparticion" data-stamp="${self.projectMissions[i].stampMision}">
								${stcmbackend.svg.bigEyeWithoutColor}
							</button>
						</div>
					</div>
				`;
			}

			// Control de finalización de misión
			let missionClosed = false;

			// Reloj - Zona horaria
			let timeZone = sessionStorage['STCMBackEnd:timeZone'];
			let date = new Date();
			let renderTimeNow = moment.tz(date, timeZone).format('YYYY-MM-DD HH:mm:ss');

			let nowDate = new Date(renderTimeNow);
			let dateEnd = new Date(endDate + ' ' + endTime);
			let dateStart = new Date(startDate + ' ' + startTime);

			if(nowDate >= dateEnd) {
				missionClosed = true;
			}

			// Control de estado
			// Estado en curso
			let estado = pf.const.language.RSC977;
			let estateVal = 1;
			let estadoClass = 'text-warning';
			if(nowDate < dateStart) {
				// Estado no empezada
				estado = pf.const.language.RSC976;
				estateVal = 0;
				estadoClass = 'text-secondary';
			}

			if(nowDate > dateEnd) {
				// Estado finalizada
				estado = pf.const.language.RSC978;
				estateVal = 2;
				estadoClass = 'text-success';
			}

			// Botón de reparto de cupo
			let quota = '';
			if(self.projectMissions[i].finmisioncupo != '0' && !missionClosed) {
				quota += `
					<button type="button" class="btn table-button main-color-text btn-quota" data-id="${i}" data-surveyid="${self.projectMissions[i].sid}" data-quota="${self.projectMissions[i].finmisioncupo}" data-stamp="${self.projectMissions[i].stampMision}">
						${stcmbackend.svg.bigEyeWithoutColor}
					</button>
				`;
			}

			table += `
				<tr id="${self.projectMissions[i].idmision}">
					<td class="text-truncate" title="${self.projectMissions[i].idmision}">${self.projectMissions[i].idmision}</td>
					<td class="text-truncate" title="${self.projectMissions[i].descripcion}">${self.projectMissions[i].descripcion}</td>
					<td class="text-truncate" title="${startDate} ${startTime}">${startDate} ${startTime}</td>
					<td class="text-truncate" title="${endDate} ${endTime}">${endDate} ${endTime}</td>
					<td class="text-truncate font-weight-bold ${estadoClass}" title="${estado}"> ${estado} </td>
					<td class="text-truncate" title="${self.projectMissions[i].importe}">${self.projectMissions[i].importe}</td>
					<td class="text-truncate" title="${(self.projectMissions[i].usuariosNotificados || '')}">${(self.projectMissions[i].usuariosNotificados || '')}</td>
					<td class="text-center">
						<span class="d-none">-</span>
						<button type="button" class="btn table-button main-color-text btn-notified" data-id="${i}" data-stamp="${self.projectMissions[i].stampMision}">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
					<td class="text-center">
						<span class="d-none">-</span>
						${rotation}
					</td>
					<td class="text-center">
						<span class="d-none">-</span>
						${validate}
					</td>
					<td class="text-center">
						<span class="d-none">-</span>
						${quota}
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer circle-container deleteMission">
							${stcmbackend.svg.trash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title === 'delete' || title === 'Notified' || title === 'rotations' || title === 'validate' || title === 'quota') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#tableMissions').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{'max-width': '100px', targets: 2},
				{'max-width': '100px', targets: 3},
				{'max-width': '115px', targets: 4},
				{width: '90px', orderable: false, targets: 7},
				{width: '90px', orderable: false, targets: 8},
				{width: '80px', orderable: false, targets: 9},
				{width: '65px', orderable: false, targets: 10},
				{width: '30px', orderable: false, targets: 11}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC14,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResultM');

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

		self.tableMissionsEvents();

		$('#tableMissions').on('draw.dt', function() {
			self.tableMissionsEvents();
		});
	},

	tableMissionsEvents() {
		let self = this;

		// Borrar misión
		$('.deleteMission').off().on('click', function() {
			let id = $(this).parent().parent().attr('id');

			let size = self.projectMissions.length;
			for(let i = 0; i < size; i++) {
				if(id == self.projectMissions[i].idmision) {
					self.projectMissions.splice(i, 1);
					break;
				}
			}

			// Recargar tabla de misiones
			$('#tableMissions').dataTable().fnDestroy();
			self.renderProjectsMissions();
		});

		// Usuarios notificados
		$('.btn-notified').off().on('click', function() {
			let stamp = $(this).data('stamp');

			let parameters = {
				id: self.idProject,
				missionStamp: stamp
			};
			ajaxComunCallWithCallback('getCMBPProjectsMisionesUsersNotif', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let usersNotified = ajaxReturn.result;

					self.participantesNotificadosTable(usersNotified);
					$('#notifiedUsers').modal('toggle');
				}
			});
		});

		// Validar participante
		$('.btn-validate').off().on('click', function() {
			let id = $(this).data('id');
			let vMision = self.projectMissions[id];
			let vProject = self.project;
			let params = {
				mision: vMision,
				project: vProject
			};

			sessionStorage.setItem('STCMBackEnd:validate', btoa(JSON.stringify(params)));
			sessionStorage.setItem('validationSource', 'projects');
			window.location.href = '#!proyectos_validar';
		});

		// Rotación
		$('.btn-rotation').off().on('click', function() {
			let id = $(this).data('id');
			let rMision = self.projectMissions[id].stampMision;
			let rSurvey =$(this).data('surveyid');
			let rProject = self.project.id;
			let params = {
				survey: rSurvey,
				project: rProject,
				mision: rMision,
			};
			$('#modalContainer').modal();
			let tr = new TableRotation('editProject', params);
			tr.setEvents();
		});

		// Repartición de cupo
		$('.btn-quota').off().on('click', function() {
			let quota = $(this).data('quota');
			let stampMision = $(this).data('stamp');
			let algorithm = '';
			let identifier = '';
			let segmentations = [];

			// Limpieza de modal
			$('#tableQuotaContainer').html('');

			// Comprobación de que haya una encuesta o segmentación seleccionada y guardado de tipo
			if($('#searchAlgorithmSurvey').prop('checked')) {
				identifier = $('#surveyProfiling').val();
				if(identifier === '') {
					return false;
				}

				algorithm = 'survey';
			} else if($('#searchAlgorithmSegmentation').prop('checked')) {
				identifier = $('#segmentation').val();
				if(identifier === '') {
					return false;
				}

				algorithm = 'segmentation';
			} else {
				algorithm = 'survey';
			}

			// Secciones de perfilación
			addLoader();
			let parameters = {
				project: self.idProject,
				stampMision: stampMision,
				country: self.country.isocode
			};

			ajaxComunCallWithCallback('getMissionQuotaBreakdown', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					self.previousQuotaAllocation = ajaxReturn.result;
					self.quota_details = ajaxReturn.result;
		
					// Apertura de modal y asignación de cupo de misión
					$('#modalQuota').modal();
					$('#assignedQuota').text(quota);

					if (algorithm === 'survey') {
						// Si el algoritmo es de encuesta se muestra una única sección
						self.renderQuotaTablesSurvey(quota, stampMision);
						removeLoader();
					} 
					//TODO: refactor segmentation quota
					// else if (algorithm === 'segmentation') { 
					// 	// Si el algoritmo es de segmentación se muestra una sección por cada uno de los segmentos
					// 	let segmentationsArray = identifier.split(',');

					// 	self.getSegmentacionQuota(0, segmentationsArray, segmentations, quota, algorithm, stampMision);
					// }
				}
			}, false);
		});

		// Control de inputs de porcentaje
		$('#tableMissions .percentageDelivery').off().on('blur', function() {
			let inputValue = $(this).val();

			// Control para input vacío
			if(inputValue === '') {
				inputValue = 0;
			}
			let value = parseInt(inputValue);

			// Control para números no enteros
			if(value < 0 || value === NaN) {
				value = 0;
			}

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

		// Asesores asignados a mision de proyecto con repartición
		$('.btn-reparticion').off().on('click', function() {
			let missionStamp = $(this).data('stamp');

			let parameters = {
				idProject: self.idProject,
				missionStamp: missionStamp
			};
			ajaxComunCallWithCallback('getRepartoPartProjByMissions', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					self.deliveryMissionsModal(ajaxReturn.result);
				}
			});
		});
	},

	//TODO: refactor segmentation quota
	// getSegmentacionQuota(index, segmentationsArray, segmentations, quota, algorithm, stampMision) {
	// 	let self = this;

	// 	let parameters = {
	// 		idSegmentacion: segmentationsArray[index]
	// 	};
	// 	ajaxComunCallWithCallback('getSegmentacion', parameters, function(ajaxReturn) {
	// 		if(ajaxReturn) {
	// 			// Se añaden los segmentos de la segmentación
	// 			segmentations.push(ajaxReturn.result[0].segmentos);
	// 			index++;

	// 			// Se repite tantas veces como segmentaciones haya seleccionadas
	// 			if(index < segmentationsArray.length) {
	// 				self.getSegmentacionQuota(index, segmentationsArray, segmentations, quota, algorithm, stampMision);
	// 			} else {
	// 				self.renderQuotaTables(quota, segmentations, stampMision);
	// 				removeLoader();
	// 			}
	// 		}
	// 	}, false);
	// },

	participantesNotificadosTable(participants) {
		let self = this;

		let excelTitle = pf.const.language.RSC1962;

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
			<th scope="col" title="${pf.const.language.RSC1626}">${pf.const.language.RSC1626}</th>
			<th scope="col" title="${pf.const.language.RSC1627}">${pf.const.language.RSC1627}</th>
		`;
		let nameSurnameFilter = `
			<td>name</td>
			<td>surname1</td>
			<td>surname2</td>
		`;

		// Control GDPR
		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<table id="tableNotifiedUsers" class="table table-hover tRegs">
				<thead>
					<tr>
						${nameSurnameHead}
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
						<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
						<th scope="col" title="${pf.const.language.RSC601}">${pf.const.language.RSC601}</th>
						<th scope="col" title="${pf.const.language.RSC164}">${pf.const.language.RSC164}</th>
						<th scope="col" title="${pf.const.language.RSC1964}">${pf.const.language.RSC1964}</th>
					</tr>
				</thead>

				<thead class="filtersNotifiedUsers">
					<tr>
						${nameSurnameFilter}
						<td>mail</td>
						<td>questionGenero</td>
						<td>questionEdad</td>
						<td>questionPais</td>
						<td>questionEstado</td>
						<td>questionABI</td>
						<td>msg</td>
						<td>fechaNotificacion</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = participants.length;
		for(let i = 0; i < size; i++) {
			let nameSurnameBody = `
				<td class="text-truncate" title="${participants[i].userNombre}">${participants[i].userNombre}</td>
				<td class="text-truncate" title="${participants[i].userApellidos}">${participants[i].userApellidos}</td>
				<td class="text-truncate" title="${participants[i].userApellidos2}">${participants[i].userApellidos2}</td>
			`;

			// Control GDPR
			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${participants[i].email}">${participants[i].email}</td>
					<td class="text-truncate" title="${participants[i].questionGenero}">${participants[i].questionGenero}</td>
					<td class="text-truncate" title="${participants[i].questionEdad}">${participants[i].questionEdad}</td>
					<td class="text-truncate" title="${participants[i].questionPais}">${participants[i].questionPais}</td>
					<td class="text-truncate" title="${participants[i].questionEstado}">${participants[i].questionEstado}</td>
					<td class="text-truncate" title="${participants[i].questionABI}">${participants[i].questionABI}</td>
					<td class="text-truncate" title="${participants[i].msg}">${participants[i].msg}</td>
					<td class="text-truncate" title="${participants[i].fechaNotificacion}">${participants[i].fechaNotificacion}</td>
				</tr>
			`;
		}

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

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

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

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

		let columnDefs = [
			{width: '65px', targets: 4},
			{width: '45px', targets: 5},
			{width: '45px', targets: 6},
			{width: '90px', targets: 8},
			{width: '165px', targets: 10}
		];

		// Control GDPR
		if(gdpr == '1') {
			columnDefs = [
				{width: '65px', targets: 1},
				{width: '45px', targets: 2},
				{width: '45px', targets: 3},
				{width: '90px', targets: 5},
				{width: '165px', targets: 6}
			];
		}

		let tableNotifiedUsers = $('#tableNotifiedUsers').DataTable({
			retrieve: true,
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1067 + '_' + pf.const.language.RSC965,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

		setTimeout(function() {
			tableNotifiedUsers.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableNotifiedUsers, 'filtersNotifiedUsers');

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

	getAllTipoMision() {
		return new Promise((resolve, reject) => {
			let token = sessionStorage['STCMBackEnd:token'];
			let reqName = 'getAllTipoMision';

			let form = new FormData();
			form.append('action', reqName);
			form.append('token', token);

			let reqData = {
				url: stcm.const.serverAPI,
				method: 'POST',
				timeout: stcm.const.AJAX_TIMEOUT,
				processData: false,
				mimeType: 'application/x-www-form-urlencoded',
				contentType: false,
				data: form
			};

			pf.ajax.request(reqName, reqData);
			$(document).off(reqName);
			$(document).on(reqName, function(event, response) {
				let resp = JSON.parse(response.resData.response);
				resolve(resp.result);
			});
		});
	},

	// Petición de participantes del proyecto
	requestProjectParticipants() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjectsParticipantes', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.participants = ajaxReturn.result;

				// Control para reparticion de usuarios
				// Control de que haya participantes en el proyecto
				if(self.participants.length > 0) {
					self.deliveryMissions = [];

					let missionsSize = self.projectMissions.length;

					for(let i = 0; i < missionsSize; i++) {
						// Controlar que la misión no esté empezada para incluirla en las misiones de repartición
						let startDateTime = self.projectMissions[i].fechahorainicio.split(' ');
						let startDateArray = startDateTime[0].split('/');
						let startDate = startDateArray[2] + '-' + startDateArray[1] + '-' + startDateArray[0];
						let startTimeArray = startDateTime[1].split(':');
						let startTime = startDateTime[1] + ':' + startTimeArray[0];

						// Reloj - Zona horaria
						let timeZone = sessionStorage['STCMBackEnd:timeZone'];
						let date = new Date();
						let renderTimeNow = moment.tz(date, timeZone).format('YYYY-MM-DD HH:mm:ss');

						let nowDate = new Date(renderTimeNow);
						let dateStart = new Date(startDate + ' ' + startTime);

						if(nowDate >= dateStart) {
							continue;
						}

						self.deliveryMissions.push(self.projectMissions[i]);
					}

					if(self.deliveryMissions.length > 1 && self.project.proyectoReparticion == '1') {
						// Mostrar botón de repartición
						$('#distributionAdvisers').show();

						$('#distributionAdvisers').off().on('click', function() {
							// Reparto de misiones de proyecto
							let parameters = {
								idProject: self.idProject
							};
							ajaxComunCallWithCallback('setRepartoPartProjByMissions', parameters, function(ajaxReturn) {
								if(ajaxReturn) {
									// Distribución realizada con éxito
									let successTitle = pf.const.language.RSC10;
									let successContent = pf.const.language.RSC2238;
									pf.utils.showInfoDialog(successTitle, successContent);
								}
							});
						});
					}
				}

				if(stcm.const.AllowVideoCalls) {
					let size = self.projectMissions.length;
					for(let i = 0; i < size; i++) {
						if(self.projectMissions[i].objetivo == 'VideoCallGrupal' || self.projectMissions[i].objetivo == 'VideoCallUnitaria') {
							// Mostrar el botón de videollamada
							$('#videocall').show();
							$('#videocall').attr('disabled', false);
						}
					}

					$('#externalVideocall').show();
					if(self.participants.length > 0) {
						$('#externalVideocall').attr('disabled', false);
					} else {
						$('#externalVideocall').attr('disabled', true);
					}
				} else {
					$('#externalVideocall').hide();
				}

				// Tabla de participantes
				self.getSelectedUsersRotacionesProject();
			}
		}, false);
	},

	renderProjectParticipants() {
		let self = this;

		self.assignRotationsToUsers();

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
		`;
		let nameSurnameFilter = `
			<td>name</td>
		`;

		// Control GDPR
		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let rotation_distribution_head = `<th scope="col" title="${pf.const.language.RSC1404}">${pf.const.language.RSC1404}</th>`;
		let rotation_distribution_filter = `<td>rotations</td>`;

		// En el caso de que sea un proyecto de repartición
		if(self.project.proyectoReparticion == '1') {
			rotation_distribution_head = '';
			rotation_distribution_filter = '';
		}

		// En caso de que haya una misión de auditoría
		let audit_head = ``;
		let audit_filter = ``;
		if(self.audit.length > 0) {
			audit_head = `<th scope="col" title="${pf.const.language.RSC2636}">${pf.const.language.RSC2636}</th>`;
			audit_filter = `<td>auditoria</td>`;
		}

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC134}">${pf.const.language.RSC134}</th>
					<th scope="col" title="${pf.const.language.RSC456}">${pf.const.language.RSC456}</th>
					${rotation_distribution_head}
					${audit_head}
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersResultP">
				<tr>
					${nameSurnameFilter}
					<td>mail</td>
					<td>id</td>
					<td>profile</td>
					<td>since</td>
					${rotation_distribution_filter}
					${audit_filter}
					<td>delete</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.participants.length;
		for(let i = 0; i < size; i++) {
			let rotaciones = '';
			if(self.participants[i].rotations) {
				self.participants[i].rotations.forEach(rotation => {
					rotaciones += rotation.description + ', ';
				});
				rotaciones = rotaciones.substring(0, rotaciones.length - 2);
			}

			let nameSurnameBody = `'<td class="text-truncate" title="${self.participants[i].user}">${self.participants[i].user}</td>`;

			// Control GDPR
			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			let rotation_distribution_body = `<td class="text-truncate" title="${rotaciones}">${rotaciones}</td>`;

			// En el caso de que sea un proyecto de repartición
			if(self.project.proyectoReparticion == '1') {
				rotation_distribution_body = '';
			}

			// En caso de que haya una misión de auditoría
			let audit_body = ``;
			if(self.audit.length > 0) {
				audit_body = `
					<td class="text-center">
						<span class="d-none">-</span>
						<button type="button" class="btn table-button main-color-text btn-audit" data-email="${self.participants[i].email}">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
				`;
			}

			table += `
				<tr id="${self.participants[i].idUser}">
					${nameSurnameBody}
					<td class="text-truncate" title="${self.participants[i].email}">${self.participants[i].email}</td>
					<td class="text-truncate" title="${self.participants[i].idUser}">${self.participants[i].idUser}</td>
					<td class="text-truncate" title="${self.participants[i].profile}">${self.participants[i].profile}</td>
					<td class="text-truncate" title="${self.participants[i].miembrodesde}">${self.participants[i].miembrodesde}</td>
					${rotation_distribution_body}
					${audit_body}
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer circle-container deleteParticipant">
							${stcmbackend.svg.trash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title === 'delete') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let columnDefs = [
			{width: '100px', targets: 3},
			{width: '75px', orderable: false, targets: 5},
			{width: '30px', orderable: false, targets: 6}
		];

		// En el caso de que sea un proyecto de repartición y/o misión de auditoría
		if(self.project.proyectoReparticion == '1' && self.audit.length > 0) {
			columnDefs = [
				{width: '100px', targets: 3},
				{width: '60px', orderable: false, targets: 5},
				{width: '30px', orderable: false, targets: 6}
			];
		} else if(self.project.proyectoReparticion == '1' && self.audit.length == 0) {
			columnDefs = [
				{width: '100px', targets: 3},
				{width: '30px', orderable: false, targets: 5}
			];
		} else if(self.project.proyectoReparticion != '1' && self.audit.length > 0) {
			columnDefs = [
				{width: '100px', targets: 3},
				{width: '75px', orderable: false, targets: 5},
				{width: '60px', orderable: false, targets: 6},
				{width: '30px', orderable: false, targets: 7}
			];
		}

		// Control GDPR
		if(gdpr == '1') {
			columnDefs = [
				{width: '100px', targets: 2},
				{width: '75px', orderable: false, targets: 4},
				{width: '30px', orderable: false, targets: 5}
			];

			// En el caso de que sea un proyecto de repartición
			if(self.project.proyectoReparticion == '1' && self.audit.length > 0) {
				columnDefs = [
					{width: '100px', targets: 2},
					{width: '60px', orderable: false, targets: 4},
					{width: '30px', orderable: false, targets: 5}
				];
			} else if(self.project.proyectoReparticion == '1' && self.audit.length == 0) {
				columnDefs = [
					{width: '100px', targets: 2},
					{width: '30px', orderable: false, targets: 4}
				];
			} else if(self.project.proyectoReparticion != '1' && self.audit.length > 0) {
				columnDefs = [
					{width: '100px', targets: 2},
					{width: '75px', orderable: false, targets: 4},
					{width: '60px', orderable: false, targets: 5},
					{width: '30px', orderable: false, targets: 6}
				];
			}
		}

		let dataTable = $('#tableParticipants').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC443,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResultP');

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

		self.tableParticipantsEvents();

		$('#tableParticipants').on('draw.dt', function() {
			self.tableParticipantsEvents();
		});
	},

	tableParticipantsEvents() {
		let self = this;

		// Borrar participante
		$('.deleteParticipant').off().on('click', function() {
			self.participantsIDExp = $(this).parent().parent().attr('id');

			// Modal de motivo de expulsión
			if(self.motivosExpulsion == '') {
				self.getAllMotivosExpulsionProject();
			} else {
				$('#motivosExpProjectTable').modal('toggle');
			}
		});

		// Gestionar tiendas y artículos para auditorías
		$('.btn-audit').off().on('click', function() {
			let email = $(this).data('email');

			addLoader();
			if(self.stores.length == 0) {
				self.getListStoresItems(email);
			} else {
				self.getUserComerciosItems(email);
			}

			// UserStoresItemsModal
			$('#UserStoresItemsModal').modal('toggle');
		});
	},

	getListStoresItems(email) {
		let self = this;

		ajaxComunCallWithCallback('getAllComercios', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(ajaxReturn.result[i].items.length > 0) {
						self.stores.push(ajaxReturn.result[i]);
					}
				}

				self.getUserComerciosItems(email);
			}
		}, false);
	},

	getUserComerciosItems(email) {
		let self = this;

		let parameters = {
			email: email,
			idProject: self.idProject,
			stampMision: self.audit[0].stampMision
		};
		ajaxComunCallWithCallback('getUserComerciosItems', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let userComerciosItems = {};

				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(userComerciosItems[ajaxReturn.result[i].id] == undefined) {
						userComerciosItems[ajaxReturn.result[i].id] = [ajaxReturn.result[i].idItem];
					} else {
						userComerciosItems[ajaxReturn.result[i].id].push(ajaxReturn.result[i].idItem);
					}
				}

				self.renderComerciosItems(userComerciosItems, email);

				removeLoader();
			}
		}, false);
	},

	renderComerciosItems(userComerciosItems, email) {
		let self = this;

		$('#UserStoresItemsBody').html('');

		//let secctionsContent = '';
		let size = self.stores.length;
		for(let i = 0; i < size; i++) {
			// Tiendas
			let checked = '';
			if(userComerciosItems[self.stores[i].id] !== undefined) {
				checked = 'checked'
			}

			let secctionsContent = `
				<div class="m-0 p-0">
					<div class="card border-bottom-0">
						<div class="card-header d-flex align-items-center">
							<strong>${self.stores[i].nombre}</strong>

							<button id="button_${self.stores[i].id}" type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#store_${self.stores[i].id}_collapse" data-arrow="left" data-sub="1">
								${stcmbackend.svg.chevronRight}
							</button>

							<div class="custom-control custom-switch ml-auto">
								<input id="switch_${self.stores[i].id}_store" type="checkbox" class="custom-control-input pSwitch" data-idstore="${self.stores[i].id}" ${checked}>
								<label for="switch_${self.stores[i].id}_store" class="custom-control-label c-pointer"></label>
							</div>
						</div>

						<div id="store_${self.stores[i].id}_collapse" class="card-body m-0 p0 collapse basicTable">
							<table id="items_${self.stores[i].id}" class="table table-hover tRegs"></table>
						</div>
					</div>
				</div>
			`;

			$('#UserStoresItemsBody').append(secctionsContent);

			// Artículos
			let table = `
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1674}">${pf.const.language.RSC1674}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC1822}">${pf.const.language.RSC1822}</th>
						<th scope="col" title="${pf.const.language.RSC2515}">${pf.const.language.RSC2515}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>barcode</td>
						<td>nombre</td>
						<td>descripcion</td>
						<td>categoria</td>
						<td>select</td>
					</tr>
				</thead>

				<tbody>
			`;

			let sizeA = self.stores[i].items.length;
			for(let j = 0; j < sizeA; j++) {
				let checked = '';
				if(userComerciosItems[self.stores[i].id] !== undefined && userComerciosItems[self.stores[i].id].includes(self.stores[i].items[j].idItem)) {
					checked = 'checked'
				}

				table += `
					<tr>
						<td class="text-truncate c-pointer editRow" title="${self.stores[i].items[j].barcode}">${'\0' + self.stores[i].items[j].barcode}</td>
						<td class="text-truncate c-pointer editRow" title="${self.stores[i].items[j].nombre}">${self.stores[i].items[j].nombre}</td>
						<td class="text-truncate c-pointer editRow" title="${self.stores[i].items[j].descripcion}">${self.stores[i].items[j].descripcion}</td>
						<td class="text-truncate c-pointer editRow" title="${self.stores[i].items[j].categoria}">${self.stores[i].items[j].categoria}</td>
						<td>
							<div class="custom-control custom-switch">
								<input id="switch_${self.stores[i].items[j].idItem}_item_${self.stores[i].id}_store" type="checkbox" class="custom-control-input uSwitch item${self.stores[i].id}" data-id="${self.stores[i].id}" data-iditem="${self.stores[i].items[j].idItem}" ${checked}>
								<label for="switch_${self.stores[i].items[j].idItem}_item_${self.stores[i].id}_store" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					</tr>
				`;
			}

			$('#items_' + self.stores[i].id).html(table);
			
			// Setup - add a text input to each footer cell
			$('#items_' + self.stores[i].id + ' .filtersResult td').each(function() {
				let title = $(this).text();
				let value = `<input type="text" class="form-control form-control-sm">`;

				if(title === 'select') {
					value = `<input type="text" class="form-control form-control-sm" disabled>`;
				}

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

			let dataTable = $('#items_' + self.stores[i].id).DataTable({
				retrieve: true,
				language: pf.const.language_table,
				paging: false,
				autoWidth: false,
				columnDefs: [
					{width: '50px', orderable: false, targets: 4}
				],
				aaSorting: []
			});

			// Apply the search
			applyTheSearch(dataTable, 'filtersResult');

			// Ocultar botones de tabla
			hideTableButtons('items_' + self.stores[i].id);
		}

		self.eventsComerciosItems(email);
	},

	eventsComerciosItems(email) {
		let self = this;

		// Collapse
		addEventArrowTableHeader();

		// Si se marca un checkbox general, se marcan todos los checkbox de artículos
		$('.pSwitch').off().on('click', function() {
			let id = $(this).data('idstore');
			let checked = $(this).prop('checked');

			$('.item' + id).prop('checked', checked);

			// En caso de estar colapsado se abre
			let elementClass = $('#store_' + id + '_collapse').attr('class');
			if(checked && !elementClass.includes("show")) {
				$('#button_' + id).trigger('click');
			}
		});

		// Si se marca un check de artículo se marca el check general, si todos están desmarcado, se desmarca el general
		$('.uSwitch').off().on('click', function() {
			let id = $(this).data('id');
			let checked = $(this).prop('checked');

			if(checked) {
				$('#switch_' + id + '_store').prop('checked', true);
			} else {
				if($('.item' + id + ':checked').length == 0) {
					$('#switch_' + id + '_store').prop('checked', false);
				}
			}
		});

		// Aceptar relación de tiendas y artículos
		$('#acceptStoresItems').off().on('click', function() {
			let values = [];

			$('.pSwitch').each(function() {
				if($(this).prop('checked')) {
					let idStore = $(this).data('idstore');

					$('#items_' + idStore + ' tr .uSwitch').each(function() {
						if($(this).prop('checked')) {
							let idItem = $(this).data('iditem');
							values.push(idStore + '#' + idItem);
						}
					});
				}
			});

			let parameters = {
				email: email,
				idProject: self.idProject,
				stampMision: self.audit[0].stampMision,
				values: JSON.stringify(values)
			};
			ajaxComunCallWithCallback('setUserComerciosItems', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let successTitle = pf.const.language.RSC2636;
					let successContent = pf.const.language.RSC2637;
					pf.utils.showInfoDialog(successTitle, successContent);

					$('#UserStoresItemsClose').trigger('click');
				}
			});
		});
	},

	requestPrevTargetsSurvey(index, idProject, sidPerfilacion) {
		let self = this;

		let parameters = {
			id: idProject,
			sidPerfilacion: sidPerfilacion
		};
		ajaxComunCallWithCallback('getCMBPProjectsTargets', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.valueCode.push(ajaxReturn.result);

				self.renderTargetsSurvey(index);

				index++;
				if(index < self.selectedSurveys.length) {
					self.requestTargetsSurvey(index, true);
				} else {
					$('#surveyProfiling').val(self.targetsSurveySID.toString());
				}
			}
		}, false);
	},

	applyEvents() {
		let self = this;

		stcmbackend.proyectos.sharedEvents(self);

		// Editar proyecto
		$('#save').on('click', function() {
			self.editProject('edit');
		});

		// Obtener resultados
		$('#getResults').on('click', function() {
			setTimeout(function() {
				self.editProject('getResults');
			}, 500);
		});

		//ejecutar procedure
		$('#executeSP').on('click', function() {
			self.spAddFieldsPerf();
		})

		// País
		let countryModal = new TableCountries(0, 'editProjectCountry');
		$('#searchCountry').on('click', function() {
			self.requestType = 'country';

			countryModal.setEvents();
		});

		// Input radio encuesta
		$('#searchAlgorithmSurvey').on('click', function() {
			// LImpieza de repartición de cupos
			self.quotaElementsArray = [];
			self.quotaElementsArrayMissions = [];
			$('#algorithmSurvey').css('visibility', 'visible');
			$('#algorithmSurvey').show();
			$('#algorithmSegmentation').hide();
			$('#selectSurveys').click();

			$('.option-box-check').removeClass('option-box-check-selected');
			$(this).parent().addClass('option-box-check-selected');
		});

		// Input radio segmentación
		$('#searchAlgorithmSegmentation').on('click', function() {
			// LImpieza de repartición de cupos
			self.quotaElementsArray = [];
			self.quotaElementsArrayMissions = [];
			$('#algorithmSurvey').hide();
			$('#algorithmSegmentation').css('visibility', 'visible');
			$('#algorithmSegmentation').show();
			$('#selectSegmentations').click();

			$('.option-box-check').removeClass('option-box-check-selected');
			$(this).parent().addClass('option-box-check-selected');
		});

		// Input radio toda la comunidad
		$('#searchAlgorithmTotal').on('click', function() {
			// LImpieza de repartición de cupos
			self.quotaElementsArray = [];
			self.quotaElementsArrayMissions = [];
			$('#algorithmSurvey').css('visibility', 'hidden');
			$('#algorithmSegmentation').css('visibility', 'hidden');

			$('.option-box-check').removeClass('option-box-check-selected');
			$(this).parent().addClass('option-box-check-selected');
		});

		// Encuesta de perfilación
		$('#searchSurvey').on('click', function() {
			if(self.surveysProfiling === '') {
				self.requestSurveysProfiling();
			} else {
				$('#surveyTable').modal('show', true);
			}
		});

		// Segmentaciones
		$('#searchSegmentation').on('click', function() {
			if(self.segmentations === '') {
				self.getAllSegmentaciones(false);
			} else {
				$('#segmentationTable').modal('show', true);
			}
		});

		// Modal de misiones
		$('#searchMissions').on('click', function() {
			if(self.allMissions === '') {
				self.requestAllMissions();
			} else {
				$('#modalMissions').modal('show', true);
			}
		});

		// Videollamada
		$('#videocall').off().on('click', function() {
			if(self.leader == '') {
				let errorTitle = pf.const.language.RSC1616;
				let errorContent = pf.const.language.RSC1728;
				pf.utils.showInfoDialog(errorTitle, errorContent);
			} else {
				if(self.missionsWhitVideocall.length == 1) {
					let timestamp = new Date().getTime();
					sessionStorage.setItem('idProjectTimestamp', btoa(self.idProject + timestamp));
					sessionStorage.setItem('projectName', btoa(self.project.NombreProyecto));
					sessionStorage.setItem('videocallJID', btoa(self.leader.id));
					sessionStorage.setItem('videocallNoParticipants', '0');
					// Nuevo valores
					sessionStorage.setItem('stamMissionVideocall', btoa(self.missionsWhitVideocall[0].stampMision));
					window.location.href = '#!proyectos_videocall';
				} else {
					// Modal con misiones de videollamada
					self.renderMissionsWhitVideocall();
				}
			}
		});

		// Videollamada sin participantes
		$('#videocallNoParticipants').off().on('click', function() {
			if(self.leader == '') {
				let errorTitle = pf.const.language.RSC1616;
				let errorContent = pf.const.language.RSC1728;
				pf.utils.showInfoDialog(errorTitle, errorContent);
			} else {
				let timestamp = new Date().getTime();
				sessionStorage.setItem('idProjectTimestamp', btoa(self.idProject + timestamp));
				sessionStorage.setItem('projectName', btoa(self.project.NombreProyecto));
				sessionStorage.setItem('videocallJID', btoa(self.leader.id));
				sessionStorage.setItem('videocallNoParticipants', '1');
				window.location.href = '#!proyectos_videocall';
			}
		});

		// Videollamada externa
		$('#externalVideocall').off().on('click', function() {
			let content = `
				<div class="form-group">
					<label for="externalLink" class="fw-500">${pf.const.language.RSC1954}</label>
					<input id="externalLink" type="text" class="form-control" value="">
					<p class="pt-1">${pf.const.language.RSC2222}</p>
				</div>
			`;

			let objInfo = {
				accept: {
					text: pf.const.language.RSC377
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC1953;
			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				let externalLink = $('#externalLink').val().trim();
				if(externalLink == '') {
					return;
				}

				// Servicio de envío del enlace de la videollamada externa
				self.postMessageMultiple(externalLink);
			}, function() {});
		});

		// Control de chat grupal para misiones que lo necesiten
		$('#groupChat').on('change', function() {
			let size = self.projectMissions.length;
			for(let i = 0; i < size; i++) {
				if(self.projectMissions[i].objetivo == 'ConversacionChatGrupal' || self.projectMissions[i].objetivo == 'FotoChatGrupal' || self.projectMissions[i].objetivo == 'VideoChatGrupal') {
					$('#groupChat').prop('checked', true);

					let warningTitle = pf.const.language.RSC10;
					let warningContent = pf.const.language.RSC1733;
					pf.utils.showInfoDialog(warningTitle, warningContent);
					break;
				}
			}
		});

		// Aceptar encuestas
		$('#selectSurveys').on('click', function() {
			$('#surveyClose').trigger('click');
			//Limpieza de arrays de encuestas de perfilación
			// Objeto
			self.targetsSurvey = [];
			// Identificadores
			self.targetsSurveySID = [];
			// Nombres
			self.profilingName = [];
			// Relaciones
			self.sidRelations = [];
			//Limpieza de elementos html
			$('#resultTableTabs').html('');
			$('#resultTableTabsContent').html('');

			if(self.selectedSurveys.length > 0) {
				// Inclusividad
				if(self.selectedSurveys.length > 1) {
					$('#inclusiveContainer').show();
				} else {
					$('#inclusiveContainer').hide();
				}

				self.requestTargetsSurvey(0, false);
			} else {
				$('#inclusiveContainer').hide();
				$('#surveyProfiling').val('');
			}
		});

		// Aceptar segmentaciones
		$('#selectSegmentations').on('click', function() {
			$('#segmentationClose').trigger('click');

			//Limpieza de elementos html
			$('#resultTableTabs').html('');
			$('#resultTableTabsContent').html('');

			if(self.selectedSegmentations.length > 0) {
				// Inclusividad
				if(self.selectedSegmentations.length > 1) {
					$('#inclusiveContainer').show();
				} else {
					$('#inclusiveContainer').hide();
				}

				// Lanza la creación de las tablas de objetivos
				for(let r = 0; r < self.selectedSegmentations.length; r++) {
					self.renderSegmentationSegments(r);
				}

				$('#segmentation').val(self.selectedIDSegmentations.toString());
				$('#segmentation').attr('title', self.selectedIDSegmentations.toString());
			} else {
				$('#inclusiveContainer').hide();
				$('#segmentation').val('');
				$('#segmentation').attr('title', '');
			}
		});

		// Restricciones de carácteres por tecla
		$('.ovSpecChars').off().on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1762);

			return result;
		});

		// Restricciones de carácteres por pegado
		$('.ovSpecChars').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1762);
		});

		// Añadir registro videollamada externa
		$('#importVideoLlamadas').off().on('click', function() {
			let content = `
				<div class="mb-0">
					<label for="externalVideo" class="form-label fw-500">${pf.const.language.RSC1958}</label>
					<input id="externalVideo" type="file" class="form-control pa-bo-36" accept="video/*">
				</div>

				<script>
					$('#externalVideo').change(function(evt) {
						let file = evt.target.files[0];
						if(file.size > ${self.maxSize}) {
							let successTitle = (pf.const.language.RSC1959);
							let successContent = (pf.const.language.RSC1337);
							pf.utils.showInfoDialog(successTitle, successContent);
							document.getElementById('externalVideo').value = '';
						}
					});
				</script>
			`;

			let objInfo = {
				accept: {
					text: pf.const.language.RSC377
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC1957;
			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				let inputElement = document.getElementById('externalVideo');
				self.videoFile = inputElement.files[0];

				if(!self.videoFile) {
					$('#externalVideo').addClass('is-invalid');
					$('[for="externalVideo"]').addClass('is-invalid');
					return false;
				}

				// Servicio de guardado de videollamada externa
				setTimeout(function() {
					// Spinner añadido
					addLoader();
					self.setFileRecordedExternal();
				}, 400);
			}, function() {});
		});

		// Añadir registro documento externo
		$('#importAdditionalDocuments').off().on('click', function() {
			let content = `
				<div class="mb-3">
					<label for="externalFile" class="form-label fw-500">${pf.const.language.RSC167}</label>
					<input id="externalFile" type="file" class="form-control pa-bo-36">
				</div>

				<div class="mb-0">
					<label for="externalFileDesc" class="form-label fw-500">${pf.const.language.RSC178}</label>
					<input id="externalFileDesc" type="text" class="form-control">
				</div>

				<script>
					$('#externalFile').change(function(evt) {
						let file = evt.target.files[0];
						if(file.size > ${self.maxSize}) {
							let successTitle = (pf.const.language.RSC1959);
							let successContent = (pf.const.language.RSC1337);
							pf.utils.showInfoDialog(successTitle, successContent);
							document.getElementById('externalFile').value = '';
						}
					});
				</script>
			`;

			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2064;
			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				let inputElement = document.getElementById('externalFile');
				let inputElementDesc = $('#externalFileDesc').val();

				if(!inputElement.files[0]) {
					$('#externalFile').addClass('is-invalid');
					$('[for="externalFile"]').addClass('is-invalid');
					return false;
				}

				self.fileToUpload = inputElement.files[0];
				self.fileToUploadDesc = inputElementDesc;

				self.insertCMBPProjectsFile();
			}, function() {});
		});
	},

	clickEvents(data, dType = null) {
		let self = this;

		if(dType) {
			self.requestType = dType;
		}

		switch(self.requestType) {
			case 'leader':
				self.leader = data;
				$('#projectLeader').val(self.leader.nameUser + ' ' + self.leader.userApellidos + ' ' + self.leader.userApellidos2);
				break;
			case 'country':
				self.country = data;
				self.countryFilter = data.isocode;
				self.leaderModal.data = null;
				$('#projectCountry').val(self.country.isocode);
				break;
		}
	},

	renderMissionsWhitVideocall() {
		let self = this;

		$('#videocallModal').modal('show');

		let table = `
			<table id="tableVideocall" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
						<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
						<th scope="col" title="${pf.const.language.RSC118}">${pf.const.language.RSC118}</th>
					</tr>
				</thead>

				<thead class="filtersVideocall">
					<tr>
						<td>idmision</td>
						<td>fechahorainicio</td>
						<td>fechahorafin</td>
						<td>importe</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.missionsWhitVideocall.length;
		for(let i = 0; i < size; i++) {
			let startDateTime = self.missionsWhitVideocall[i].fechahorainicio.split(' ');
			let startDateArray = startDateTime[0].split('/');
			let startDate = startDateArray[2] + '-' + startDateArray[1] + '-' + startDateArray[0];
			let startTimeArray = startDateTime[1].split(':');
			let startTime = startTimeArray[0] + ':' + startTimeArray[1];

			let endDateTime = self.missionsWhitVideocall[i].fechahorafin.split(' ');
			let endDateArray = endDateTime[0].split('/');
			let endDate = endDateArray[2] + '-' + endDateArray[1] + '-' + endDateArray[0];
			let endTimeArray = endDateTime[1].split(':');
			let endTime = endTimeArray[0] + ':' + endTimeArray[1];

			table += `
				<tr class="c-pointer videocall-selected" data-stampmission="${self.missionsWhitVideocall[i].missionStamp}">
					<td class="text-truncate" title="${self.missionsWhitVideocall[i].idmision}">${self.missionsWhitVideocall[i].idmision}</td>
					<td class="text-truncate" title="${startDate} ${startTime}">${startDate} ${startTime}</td>
					<td class="text-truncate" title="${endDate} ${endTime}">${endDate} ${endTime}</td>
					<td class="text-truncate" title="${self.missionsWhitVideocall[i].importe}">${self.missionsWhitVideocall[i].importe}</td>
				</tr>
			`;
		}

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

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

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

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

		let tableVideocall = $('#tableVideocall').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '115px', targets: 1},
				{width: '115px', targets: 2},
				{width: '115px', targets: 3}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			tableVideocall.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableVideocall, 'filtersVideocall');

		// Selección de misión
		$('.videocall-selected').off().on('click', function() {
			let missionStamp = $(this).data('stampmission');

			$('#closeVideocallModal').trigger('click');

			let timestamp = new Date().getTime();
			sessionStorage.setItem('idProjectTimestamp', btoa(self.idProject + timestamp));
			sessionStorage.setItem('projectName', btoa(self.project.NombreProyecto));
			sessionStorage.setItem('videocallJID', btoa(self.leader.id));
			sessionStorage.setItem('videocallNoParticipants', '0');
			// Nuevo valores
			sessionStorage.setItem('stamMissionVideocall', btoa(missionStamp));

			setTimeout(function() {
				window.location.href = '#!proyectos_videocall';
			}, 200);
		});
	},

	// Cambiado para que salgan todas las encuestas
	requestSurveysProfiling() {
		let self = this;

		ajaxComunCallWithCallback('getAllSurveys', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.surveysProfiling = ajaxReturn.result;
				self.renderSurveysProfiling();
				self.surveysProfilingFlag = true;
			}
		});
	},

	renderSurveysProfiling() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title=""></th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
					<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
					<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
					<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
					<th scope="col" title="${pf.const.language.RSC118}">${pf.const.language.RSC118}</th>
				</tr>
			</thead>

			<thead class="filters">
				<tr>
					<td>selector</td>
					<td>id</td>
					<td>name</td>
					<td>dateCreation</td>
					<td>enabled</td>
					<td>startDate</td>
					<td>endDate</td>
					<td>remuneration</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.surveysProfiling.length;
		for(let i = 0; i < size; i++) {
			let checked = '';
			for(let j = 0; j < self.selectedSurveys.length; j++) {
				if(self.selectedSurveys[j].sid == self.surveysProfiling[i].sid) {
					checked = 'checked';
				}
			}

			// Formato de fechas, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let datecreated = '';
			let datecreatedOrder = '';
			if(self.surveysProfiling[i].datecreated != '') {
				// Para ordenación en columna
				datecreatedOrder = self.surveysProfiling[i].datecreated.replace(' ', '');

				let dateTimeArrayStart = self.surveysProfiling[i].datecreated.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					datecreated = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				} else {
					datecreated = dateStart + ' ' + dateTimeArrayStart[1];
				}
			}

			let startdate = '';
			let startdateOrder = '';
			if(self.surveysProfiling[i].startdate != '') {
				// Para ordenación en columna
				startdateOrder = self.surveysProfiling[i].startdate.replace(' ', '');

				let dateTimeArrayStart = self.surveysProfiling[i].startdate.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					startdate = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				} else {
					startdate = dateStart + ' ' + dateTimeArrayStart[1];
				}
			}

			let expires = '';
			let expiresOrder = '';
			if(self.surveysProfiling[i].expires != '') {
				// Para ordenación en columna
				expiresOrder = self.surveysProfiling[i].expires.replace(' ', '');

				let dateTimeArrayStart = self.surveysProfiling[i].expires.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					expires = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				} else {
					expires = dateStart + ' ' + dateTimeArrayStart[1];
				}
			}

			table += `
				<tr id="sid-${self.surveysProfiling[i].sid}" class="c-pointer" data-active="${self.surveysProfiling[i].active}" data-id="${i}" data-sid="${self.surveysProfiling[i].sid}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selectionSurvey" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].sid}" data-id="${i}" data-sid="${self.surveysProfiling[i].sid}">
						${self.surveysProfiling[i].sid}
					</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].surveyls_title}">${self.surveysProfiling[i].surveyls_title}</td>
					<td class="text-truncate" title="${datecreated}">
						<span class="d-none">${datecreatedOrder}</span>
						${datecreated}
					</td>
					<td class="text-center">
						<span class="d-none">${(self.surveysProfiling[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveysProfiling[i].active == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${startdate}">
						<span class="d-none">${startdateOrder}</span>
						${startdate}
					</td>
					<td class="text-truncate" title="${expires}">
						<span class="d-none">${expiresOrder}</span>
						${expires}
					</td>
					<td class="text-center" title="${self.surveysProfiling[i].remuneracion}">${self.surveysProfiling[i].remuneracion}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'enabled') {
				value = optionsSelectAllYesNo();
			} else if(title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm disabled">`;
			}

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

		let ObjetiveTable = $('#tableSurvey').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '50px', targets: 1},
				{width: '60px', targets: 4},
				{width: '110px', targets: 7}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			ObjetiveTable.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filters');

		self.eventsSurveysProfiling();

		$('#tableSurvey').on('draw.dt', function() {
			self.eventsSurveysProfiling();
		});
	},

	eventsSurveysProfiling() {
		let self = this;

		// Seleccionar encuesta por tr
		$('#tableSurvey tbody tr').off().on('click', function() {
			let index = $(this).data('id');
			let id = $(this).data('sid');
			let selSurSize = self.selectedSurveys.length;
			let checked = $(this).find('.selectionSurvey').prop('checked');

			if(!checked) {
				$(this).find('.selectionSurvey').prop('checked', true);
				if(selSurSize >= self.maxSurveysProfiling) {
					let alertTitle = pf.const.language.RSC398;
					let alertText = pf.const.language.RSC1735;
					pf.utils.showInfoDialog(alertTitle, alertText);
					$(this).find('.selectionSurvey').prop('checked', false);
					return false;
				}

				if(self.surveysProfiling[index].active != '1') {
					let alertTitle = pf.const.language.RSC398;
					let alertText = pf.const.language.RSC1365;
					pf.utils.showInfoDialog(alertTitle, alertText);
					$(this).find('.selectionSurvey').prop('checked', false);
					return false;
				}

				self.selectedSurveys.push(self.surveysProfiling[index]);
			} else {
				$(this).find('.selectionSurvey').prop('checked', false);
				for(let i = 0; i < selSurSize; i++) {
					if(self.selectedSurveys[i].sid == id) {
						self.selectedSurveys.splice(i, 1);
						break;
					}
				}
			}
		});

		// Seleccionar encuesta por checbox
		$('.selectionSurvey').off().on('click', function() {
			let checked = $(this).prop('checked');

			if(checked) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}
		});
	},

	requestTargetsSurvey(index, prev) {
		let self = this;

		let parameters = {
			survey: self.selectedSurveys[index].sid
		};
		if(!prev) {
			addLoader();
		}
		ajaxComunCallWithCallback('getTargetsSurvey', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(ajaxReturn.result[i].type == 'K' || ajaxReturn.result[i].type == 'A' || ajaxReturn.result[i].type == 'B' || ajaxReturn.result[i].type == ';') {
						ajaxReturn.result[i].value = {};
						ajaxReturn.result[i].code = {};
						let sizeK = ajaxReturn.result[i].valuesSQ.length;
						for(let j = 0; j < sizeK; j++) {
							let columnNameKArray = ajaxReturn.result[i].valuesSQ[j].split('|');
							let columnNameK = columnNameKArray[0];
							ajaxReturn.result[i].value[columnNameK] = [];
							ajaxReturn.result[i].code[columnNameK] = [];
						}
					} else {
						ajaxReturn.result[i].value = [];
						ajaxReturn.result[i].code = [];
					}
				}
				self.targetsSurvey.push(ajaxReturn.result);
				if(!prev) {
					self.targetsSurveySID.push(self.selectedSurveys[index].sid);
					self.profilingName.push(self.selectedSurveys[index].surveyls_title);
					self.sidRelations.push('&');
					self.renderTargetsSurvey(index);

					index++;
					if(index < self.selectedSurveys.length) {
						self.requestTargetsSurvey(index, prev);
					} else {
						$('#surveyProfiling').val(self.targetsSurveySID.toString());
					}
				} else {
					self.requestPrevTargetsSurvey(index, self.idProject, self.selectedSurveys[index].sid);
				}

				if(!prev) {
					removeLoader();
				}
			}
		}, false);
	},

	renderTargetsSurvey(index) {
		let self = this;

		let active = '';
		let show = '';
		if(index == 0) {
			active = 'active';
			show = 'show';
		}

		let relation = '';
		if(index != 0) {
			let selecAnd = 'selected';
			let selecOr = '';
			if(self.sidRelations[index] === '|') {
				selecAnd = '';
				selecOr = 'selected';
			}
			relation = `
				<select id="relation${index}" class="form-control form-control-sm relations d-none" data-index="${index}">
					<option value="&" ${selecAnd}>AND</option>
					<option value="|" ${selecOr}>OR</option>
				</select>
			`;
		}

		let relSymbol = '';
		if(index != 0) {
			relSymbol = `
				<span id="relSymbol${index}" class="d-none">
					${self.sidRelations[index]}
				</span>
			`;
		}

		let tab = `
			<li>
				<a href="#survey${index}" class="nav-link ${active} perfTabs" data-toggle="tab">
					${relSymbol + self.selectedSurveys[index].surveyls_title}
					<svg class="bi bi-x icon-color remTab" width="1.2em" height="1.2em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" data-index="${index}">
						<path fill-rule="evenodd" d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/>
						<path fill-rule="evenodd" d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/>
					</svg>
				</a>
			</li>
		`;
		$('#resultTableTabs').append(tab);

		let table = `
			<div id="survey${index}" class="tab-pane fade ${show} ${active} basicTable">
				${relation}
				<table id="registers${index}" class="table table-hover">
					<thead>
						<tr>
							<th scope="col" title="${pf.const.language.RSC122}">${pf.const.language.RSC122}</th>
							<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
							<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
							<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
							<th scope="col" title="${pf.const.language.RSC438}">${pf.const.language.RSC438}</th>
						</tr>
					</thead>

					<thead class="filtersResult${index}">
						<tr>
							<td>section</td>
							<td>question</td>
							<td>value</td>
							<td>code</td>
							<td>type</td>
						</tr>
					</thead>

					<tbody>
		`;

		let size = self.targetsSurvey[index].length;
		for(let i = 0; i < size; i++) {
			let qidArray = self.targetsSurvey[index][i].columnName.split('X');
			let qid = qidArray.pop();

			// Array de tipos respuesta que no saldrán en la tabla
			let answersArray = ['T', '|', '7', 'J', '8'];
			if(answersArray.indexOf(self.targetsSurvey[index][i].type) != -1 || self.targetsSurvey[index][i].question.includes('SOCIAL_LABS_')) {
				continue;
			}

			let value = '';
			let code = '';
			let valueCodeSize = 0;
			if(self.valueCode[index] !== undefined) {
				valueCodeSize = self.valueCode[index].length;
			}
			for(let j = 0; j < valueCodeSize; j++) {
				if(self.targetsSurvey[index][i].type != 'K' && self.targetsSurvey[index][i].type != 'A' && self.targetsSurvey[index][i].type != 'B' && self.targetsSurvey[index][i].type != ';') {
					if(self.valueCode[index][j].ColumnName == self.targetsSurvey[index][i].columnName) {
						value = self.valueCode[index][j].Value.split(',');
						self.targetsSurvey[index][i].value = value;
						code = self.valueCode[index][j].ValueCodes.split(',');
						self.targetsSurvey[index][i].code = code;
					}
				}
			}

			let valueInput = `
				<div class="input-group new-input-style">
					<input type="text" class="form-control-sm inputGrid inputValue" title="${value}" placeholder="${pf.const.language.RSC349}" aria-label="Valores" value="${value}" disabled>
					<div class="input-group-append">
						<button type="button" class="btn btn-outline-secondary searchValues py-0 px-1" data-toggle="modal" data-target="#valuesTable" data-qid="${qid}" data-columnName="${self.targetsSurvey[index][i].columnName}" data-type="${self.targetsSurvey[index][i].type}" data-index="${index}">
							${stcmbackend.svg.threeDotsSmall}
						</button>
					</div>
				</div>
			`;

			// Array de tipos sin botón
			// PREGUNTAR TIPO 'Q'
			let typeArray = ['S', 'D', '2', 'Q', '6', 'N', 'U'];
			if(typeArray.indexOf(self.targetsSurvey[index][i].type) != -1) {
				valueInput = `
					<div class="form-group mb-0">
						<input type="text" class="form-control-sm inputGrid inputValue w-100 typeValues" title="${value}" value="${value}" data-columnName="${self.targetsSurvey[index][i].columnName}" data-type="${self.targetsSurvey[index][i].type}" data-index="${index}">
					</div>
				`;
			} else if(self.targetsSurvey[index][i].type == '5') {
				valueInput = `
					<div class="input-group new-input-style">
						<input type="text" class="form-control-sm inputGrid inputValue" title="${value}" placeholder="${pf.const.language.RSC349}" aria-label="Valores" value="${value}" disabled>
						<div class="input-group-append">
							<button type="button" class="btn btn-outline-secondary fiveValues py-0 px-1" data-toggle="modal" data-target="#valuesTable" data-qid="${qid}" data-columnName="${self.targetsSurvey[index][i].columnName}" data-index="${index}">
								${stcmbackend.svg.threeDotsSmall}
							</button>
						</div>
					</div>
				`;
			}

			// Limpieza de marcas de html
			let textWithTags = self.targetsSurvey[index][i].question;
			let tagsWithoutTags = textWithTags.replace(/<[^>]*>?/g, '');

			// Pregunta tipo 'K'
			if(self.targetsSurvey[index][i].type == 'K' || self.targetsSurvey[index][i].type == 'A' || self.targetsSurvey[index][i].type == 'B' || self.targetsSurvey[index][i].type == ';') {
				let sizeK = self.targetsSurvey[index][i].valuesSQ.length;
				for(let j = 0; j < sizeK; j++) {
					let valuesSQArray = self.targetsSurvey[index][i].valuesSQ[j].split('|');
					let columnNameK = valuesSQArray[0];
					let questionKTitle = tagsWithoutTags.trim() + '\n' + valuesSQArray[1].replace(';', ' ');
					let questionK = tagsWithoutTags.trim() + '<br>' + valuesSQArray[1].replace(';', '');

					let valueCodeSize = 0;
					if(self.valueCode[index] !== undefined) {
						valueCodeSize = self.valueCode[index].length;
					}
					for(let m = 0; m < valueCodeSize; m++) {
						if(self.valueCode[index][m].ColumnName == columnNameK) {
							value = self.valueCode[index][m].Value.split(',');
							self.targetsSurvey[index][i].value[columnNameK] = value;
							code = self.valueCode[index][m].ValueCodes.split(',');
							self.targetsSurvey[index][i].code[columnNameK] = code;
						}
					}

					if(self.targetsSurvey[index][i].type == ';') {
						valueInput = `
							<div class="form-group mb-0">
								<input type="text" class="form-control-sm inputGrid inputValue w-100 typeValues" title="${value}" value="${value}" data-columnName="${self.targetsSurvey[index][i].columnName}" data-type="${self.targetsSurvey[index][i].type}" data-index="${index}">
							</div>
						`;
					} else {
						valueInput = `
							<div class="input-group new-input-style">
								<input type="text" class="form-control-sm inputGrid inputValue" title="${value}" placeholder="${pf.const.language.RSC349}" aria-label="Valores" value="${value}" disabled>
								<div class="input-group-append">
									<button type="button" class="btn btn-outline-secondary KValues py-0 px-1" data-toggle="modal" data-target="#valuesTable" data-qid="${qid}" data-columnName="${self.targetsSurvey[index][i].columnName}" data-columnNameK="${columnNameK}" data-index="${index}">
										${stcmbackend.svg.threeDotsSmall}
									</button>
								</div>
							</div>
						`;
					}

					table += `
						<tr id="${columnNameK}" data-inputCode="">
							<td class="align-middle" title="${self.targetsSurvey[index][i].group_name}">${self.targetsSurvey[index][i].group_name}</td>
							<td class="align-middle" title="${questionKTitle}">${questionK}</td>
							<td>
								${valueInput}
							</td>
							<td class="align-middle" title="">
								<input type="text" class="form-control-sm inputGrid inputCode" title="${code}" aria-label="Códigos" value="${code}" disabled>
							</td>
							<td class="align-middle text-center" title="${self.targetsSurvey[index][i].type}">${self.targetsSurvey[index][i].type}</td>
						</tr>
					`;
				}
			} else {
				// El atributo data-inputCode suplira a la columna de código
				table += `
					<tr id="${self.targetsSurvey[index][i].columnName}" data-inputCode="">
						<td class="align-middle" title="${self.targetsSurvey[index][i].group_name}">${self.targetsSurvey[index][i].group_name}</td>
						<td class="align-middle" title="${tagsWithoutTags.trim()}">${tagsWithoutTags.trim()}</td>
						<td>
							${valueInput}
						</td>
						<td class="align-middle" title="">
							<input type="text" class="form-control-sm inputGrid inputCode" title="${code}" aria-label="Códigos" value="${code}" disabled>
						</td>
						<td class="align-middle text-center" title="${self.targetsSurvey[index][i].type}">${self.targetsSurvey[index][i].type}</td>
					</tr>
				`;
			}
		}

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

		$('#resultTableTabsContent').append(table);

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

			if(title === 'section' || title === 'question') {
				value = `<input type="text" class="form-control form-control-sm">`;
			}

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

		let dataTable = $('#registers' + index).DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '200px', targets: 0},
				{width: '130px', targets: 2},
				{width: '100px', targets: 3},
				{width: '40px', targets: 4}
			],
			aaSorting: []
		});

		// Ocultar botones de tabla
		hideTableButtons('registers' + index);

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		// Relaciones entre encuestas de perfilación
		$('.relations').on('change', function() {
			let index = $(this).data('index');
			let value = $('#relation' + index).val();
			self.sidRelations[index] = value;
			$('#relSymbol' + index).text(value + ' ');
		});

		// Eliminar pestaña
		$('.remTab').off().on('click', function() {
			// Recoge el indice de la pestaña
			let index = $(this).data('index');

			// Elimina el elemento de los array
			self.selectedSurveys.splice(index, 1);
			self.sidRelations.splice(index, 1);
			self.targetsSurvey.splice(index, 1);
			self.targetsSurveySID.splice(index, 1);
			self.valueCode.splice(index, 1);

			// Recrea la tabla de encuestas
			if(self.surveysProfilingFlag) {
				$('#tableSurvey').dataTable().fnDestroy();
				self.renderSurveysProfiling();
			}

			//Limpieza de elementos html
			$('#resultTableTabs').html('');
			$('#resultTableTabsContent').html('');

			// Lanza la creación de las tablas de objetivos
			for(let r = 0; r < self.selectedSurveys.length; r++) {
				self.renderTargetsSurvey(r);
			}

			$('#surveyProfiling').val(self.targetsSurveySID.toString());
		});

		self.eventTargetsSurvey();

		$('#registers' + index).on('draw.dt', function() {
			self.eventTargetsSurvey();
		});
	},

	eventTargetsSurvey() {
		let self = this;

		// Valores de modal
		$('.searchValues').off().on('click', function() {
			let qid = $(this).attr('data-qid');
			let type = $(this).attr('data-type');
			let index = $(this).data('index');
			let survey = self.selectedSurveys[index].sid;
			self.columnName = $(this).attr('data-columnName');
			self.requestSurveyValues(qid, survey, type, index);
		});

		// Valores de modal para preguntas tipo '5'
		$('.fiveValues').off().on('click', function() {
			let index = $(this).data('index');
			self.surveyValues = [
				{code: '1', answer: '1'},
				{code: '2', answer: '2'},
				{code: '3', answer: '3'},
				{code: '4', answer: '4'},
				{code: '5', answer: '5'}
			];
			self.columnName = $(this).attr('data-columnName');

			stcmbackend.proyectos.renderSurveyValues(index, self);
		});

		// Valores de modal para preguntas tipo 'K'
		$('.KValues').off().on('click', function() {
			let index = $(this).data('index');
			self.columnName = $(this).attr('data-columnName');
			self.columnNameK = $(this).attr('data-columnNameK');
			let size = self.targetsSurvey[index].length;
			for(let i = 0; i < size; i++) {
				if(self.targetsSurvey[index][i].columnName == self.columnName) {
					self.surveyValues = self.targetsSurvey[index][i].values;
					break;
				}
			}

			stcmbackend.proyectos.renderSurveyValues(index, self);
		});

		// Valores de texto
		$('.typeValues').off().on('change', function() {
			let columnName = $(this).attr('data-columnName');
			let index = $(this).data('index');
			let type = $(this).attr('data-type');

			let size = self.targetsSurvey[index].length;
			let code = [];
			let value = [$(this).val()];
			$('#' + columnName).find('.inputValue').attr('title', $(this).val());
			if($(this).val().indexOf('-') != -1) {
				let valueArray = $(this).val().split('-');

				for(let i = parseInt(valueArray[0]); i <= valueArray[1]; i++) {
					code.push(i);
				}

				$('#' + columnName).attr('data-inputCode', code);
				$('#' + columnName).find('.inputCode').val(code);
				$('#' + columnName).find('.inputCode').attr('title', code);

				for(let i = 0; i < size; i++) {
					if(columnName == self.targetsSurvey[index][i].columnName) {
						self.targetsSurvey[index][i].value = value;
						self.targetsSurvey[index][i].code = code;
					}
				}
			} else {
				code.push(value[0]);
				$('#' + columnName).attr('data-inputCode', code);
				$('#' + columnName).find('.inputCode').val(code);
				$('#' + columnName).find('.inputCode').attr('title', code);

				for(let i = 0; i < size; i++) {
					if(columnName == self.targetsSurvey[index][i].columnName) {
						self.targetsSurvey[index][i].value = value;
						self.targetsSurvey[index][i].code = code;
					}
				}
			}
		});
	},

	requestSurveyValues(qid, survey, type, index) {
		let self = this;

		let parameters = {
			survey: survey,
			qid: qid
		};
		ajaxComunCallWithCallback('getTargetsSurveyByQID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.surveyValues = ajaxReturn.result;

				if(type === ':' || type === 'F') {
					self.getOptionsFor2PointsTypeQuetsion(qid, survey, index);
				} else {
					stcmbackend.proyectos.renderSurveyValues(index, self);
				}
			}
		});
	},

	getOptionsFor2PointsTypeQuetsion(parent_qid, survey, index) {
		let self = this;

		let parameters = {
			survey: survey,
			parent_qid: parent_qid
		};
		ajaxComunCallWithCallbackOne('getOptionsFor2PointsTypeQuetsion', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				let questionOptions = resp;

				let values = self.surveyValues;
				let newSurveyValues = []
				questionOptions.forEach(qo => {
					values.forEach(value => {
						let qoCode = qo.title || qo.code;
						let vCode = value.title || value.code;
						let qoQuestion = qo.question || qo.answer;
						let vQuestion = value.question || value.answer;

						let newVal = {
							code: qoCode + '#' + vCode,
							answer: qoQuestion + ' / ' + vQuestion 
						}
						newSurveyValues.push(newVal)
					});
				});
				self.surveyValues = newSurveyValues;
				
				stcmbackend.proyectos.renderSurveyValues(index, self);
			}
		});
	},

	getAllSegmentaciones(start) {
		let self = this;

		ajaxComunCallWithCallback('getAllSegmentaciones', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.segmentations = ajaxReturn.result;

				if(start) {
					// Añadir catalogación y clave de incluido a los segmentos con los valores de proyecto
					let sizeS = self.segmentations.length;
					for(let i = 0; i < sizeS; i++) {
						self.segmentations[i]['catalogacion'] = [];
						let controlArray = [];
						let sizeA = self.segmentations[i].segmentos.length;
						let included = false;
						for(let j = 0; j < sizeA; j++) {
							if(controlArray.indexOf(self.segmentations[i].segmentos[j].Descripcion) === -1) {
								controlArray.push(self.segmentations[i].segmentos[j].Descripcion);

								let obj = {};
								if(self.segmentationsData[self.segmentations[i].idSegmentacion] !== undefined) {
									for(let h = 0; h < self.segmentationsData[self.segmentations[i].idSegmentacion].length; h++) {
										if(self.segmentationsData[self.segmentations[i].idSegmentacion][h].Segmentacion == self.segmentations[i].segmentos[j].Descripcion) {
											obj = {
												name: self.segmentations[i].segmentos[j].Descripcion,
												include: self.segmentationsData[self.segmentations[i].idSegmentacion][h].Value
											};
											self.segmentations[i]['catalogacion'].push(obj);
											included = true;
											break;
										}
									}
								} else {
									obj = {
										name: self.segmentations[i].segmentos[j].Descripcion,
										include: '0'
									};
									self.segmentations[i]['catalogacion'].push(obj);
								}
							}
						}

						if(included) {
							self.selectedSegmentations.push(self.segmentations[i]);
						}
					}
				} else {
					// Añadir catalogación y clave de incluido a los segmentos
					let sizeS = self.segmentations.length;
					for(let i = 0; i < sizeS; i++) {
						self.segmentations[i]['catalogacion'] = [];
						let controlArray = [];
						let sizeA = self.segmentations[i].segmentos.length;
						for(let j = 0; j < sizeA; j++) {
							if(controlArray.indexOf(self.segmentations[i].segmentos[j].Descripcion) === -1) {
								controlArray.push(self.segmentations[i].segmentos[j].Descripcion);
								let obj = {
									name: self.segmentations[i].segmentos[j].Descripcion,
									include: '0'
								};

								self.segmentations[i]['catalogacion'].push(obj);
							}
						}
					}
				}

				// Tabla de resultados
				self.renderSegmentations();

				// Input de segmentaciones
				$('#segmentation').val(self.selectedIDSegmentations.toString());
				$('#segmentation').attr('title', self.selectedIDSegmentations.toString());

				// Tablas de Objetivos de investigación
				for(let r = 0; r < self.selectedSegmentations.length; r++) {
					self.renderSegmentationSegments(r);
				}
			}
		});
	},

	renderSegmentations() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title=""></th>
					<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
					<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
					<th scope="col" title="${pf.const.language.RSC346}">${pf.const.language.RSC346}</th>
				</tr>
			</thead>

			<thead class="filtersSegmentations">
				<tr>
					<td>selector</td>
					<td>descripción</td>
					<td>encuesta</td>
					<td>descEncuesta</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.segmentations.length;
		for(let i = 0; i < size; i++) {
			let checked = '';
			for(let j = 0; j < self.selectedSegmentations.length; j++) {
				if(self.selectedSegmentations[j].idSegmentacion == self.segmentations[i].idSegmentacion) {
					checked = 'checked';
				}
			}

			table += `
				<tr class="c-pointer" data-index="${i}" data-idseg="${self.segmentations[i].idSegmentacion}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selectionSegmentation" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.segmentations[i].Descripcion}" data-idseg="${self.segmentations[i].idSegmentacion}" data-index="${i}">
						${self.segmentations[i].Descripcion}
					</td>
					<td class="text-truncate" title="${self.segmentations[i].surveyls_title}">${self.segmentations[i].surveyls_title}</td>
					<td class="text-truncate" title="${self.segmentations[i].surveyls_description}">${self.segmentations[i].surveyls_description}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm disabled">`;
			}

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

		let ObjetiveTable = $('#tableSegmentation').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			ObjetiveTable.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filtersSegmentations');

		self.eventsSegmentations();

		$('#tableSegmentation').on('draw.dt', function() {
			self.eventsSegmentations();
		});
	},

	eventsSegmentations() {
		let self = this;

		// Seleccionar segmentación por tr
		$('#tableSegmentation tbody tr').off().on('click', function() {
			let index = $(this).data('index');
			let idseg = $(this).data('idseg');
			let selSegSize = self.selectedSegmentations.length;
			let checked = $(this).find('.selectionSegmentation').prop('checked');

			if(!checked) {
				$(this).find('.selectionSegmentation').prop('checked', true);
				if(selSegSize >= self.maxSurveysProfiling) {
					let alertTitle = pf.const.language.RSC1741;
					let alertText = pf.const.language.RSC1785;
					pf.utils.showInfoDialog(alertTitle, alertText);
					$(this).find('.selectionSegmentation').prop('checked', false);
					return false;
				}

				self.selectedSegmentations.push(self.segmentations[index]);
				self.selectedIDSegmentations.push(self.segmentations[index].idSegmentacion);
			} else {
				$(this).find('.selectionSegmentation').prop('checked', false);
				for(let i = 0; i < selSegSize; i++) {
					if(self.selectedSegmentations[i].idSegmentacion == idseg) {
						self.selectedSegmentations.splice(i, 1);
						self.selectedIDSegmentations.splice(i, 1);
						break;
					}
				}
			}
		});

		// Seleccionar segmentación por checbox
		$('.selectionSegmentation').off().on('click', function() {
			let checked = $(this).prop('checked');

			if(checked) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}
		});
	},

	renderSegmentationSegments(index) {
		let self = this;

		let SegmentSeg = self.selectedSegmentations[index].catalogacion;

		let active = '';
		let show = '';
		if(index == 0) {
			active = 'active';
			show = 'show';
		}

		let tab = `
			<li id="li_tab_${index}">
				<a href="#survey${index}" class="nav-link ${active} perfTabs" data-toggle="tab">
					${self.selectedSegmentations[index].Descripcion}
					<svg class="bi bi-x icon-color remTab" width="1.2em" height="1.2em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg" data-index="${index}">
						<path fill-rule="evenodd" d="M11.854 4.146a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708-.708l7-7a.5.5 0 0 1 .708 0z"/>
						<path fill-rule="evenodd" d="M4.146 4.146a.5.5 0 0 0 0 .708l7 7a.5.5 0 0 0 .708-.708l-7-7a.5.5 0 0 0-.708 0z"/>
					</svg>
				</a>
			</li>
		`;
		$('#resultTableTabs').append(tab);

		let table = `
			<div id="survey${index}" class="tab-pane fade ${show} ${active} basicTable">
				<table id="registers${index}" class="table table-hover mt-0">
					<thead>
						<tr>
							<th scope="col" title="${pf.const.language.RSC1748}">${pf.const.language.RSC1748}</th>
							<th scope="col" title="${pf.const.language.RSC1786}">${pf.const.language.RSC1786}</th>
						</tr>
					</thead>

					<thead class="filtersSegResult${index}">
						<tr>
							<td>segmento</td>
							<td>incluir</td>
						</tr>
					</thead>

					<tbody>
		`;

		let size = SegmentSeg.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="${self.selectedSegmentations[index].idSegmentacion}">
					<td class="align-middle" title="${SegmentSeg[i].name}">${SegmentSeg[i].name}</td>
					<td>
						<span class="d-none">${(SegmentSeg[i].include == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="i_${index}_${i}" type="checkbox" class="custom-control-input uSwitch attrInclude" ${(SegmentSeg[i].include == 1 ? 'checked' : '')} data-index="${index}" data-seg="${i}">
							<label for="i_${index}_${i}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

		$('#resultTableTabsContent').append(table);

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

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

		let dataTable = $('#registers' + index).DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '60px', targets: 1}
			],
			aaSorting: []
		});

		// Ocultar botones de tabla
		hideTableButtons('registers' + index);

		// Apply the search
		applyTheSearch(dataTable, 'filtersSegResult');

		// Eliminar pestaña
		$('.remTab').off().on('click', function() {
			// Recoge el indice de la pestaña
			let index = $(this).data('index');

			// Elimina el elemento de los array
			self.selectedSegmentations.splice(index, 1);
			self.selectedIDSegmentations.splice(index, 1);

			// Recrea la tabla de encuestas
			$('#tableSegmentation').dataTable().fnDestroy();
			self.renderSegmentations();

			//Limpieza de elementos html
			$('#resultTableTabs').html('');
			$('#resultTableTabsContent').html('');

			// Lanza la creación de las tablas de objetivos
			for(let r = 0; r < self.selectedSegmentations.length; r++) {
				self.renderSegmentationSegments(r);
			}

			$('#segmentation').val(self.selectedIDSegmentations.toString());
			$('#segmentation').attr('title', self.selectedIDSegmentations.toString());
		});

		self.eventSegmentationsSegments(index);

		$('#resultTable' + index).on('draw.dt', function() {
			self.eventSegmentationsSegments(index);
		});
	},

	eventSegmentationsSegments() {
		let self = this;

		$('.attrInclude').off().on('click', function() {
			let checked = $(this).prop('checked');
			let index = $(this).data('index');
			let seg = $(this).data('seg');

			if(checked) {
				self.selectedSegmentations[index].catalogacion[seg].include = '1';
			} else {
				self.selectedSegmentations[index].catalogacion[seg].include = '0';
			}
		});
	},

	requestAllMissions() {
		let self = this;

		// Parámetro de cliente
		let parameters = {
			idCliente: self.idCliente
		}
		ajaxComunCallWithCallback('getAllMisiones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.allMissions = ajaxReturn.result;

				self.renderAllMissions();
			}
		});
	},

	renderAllMissions() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC26}">${pf.const.language.RSC26}</th>
					<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
					<th scope="col" title="${pf.const.language.RSC171}">${pf.const.language.RSC171}</th>
					<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
					<th scope="col" title="${pf.const.language.RSC172}">${pf.const.language.RSC172}</th>
					<th scope="col" title="${pf.const.language.RSC145}">${pf.const.language.RSC145}</th>
					<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
				</tr>
			</thead>

			<thead class="filters">
				<tr>
					<td>idmision</td>
					<td>tipomision</td>
					<td>fechainicio</td>
					<td>horainicio</td>
					<td>fechafin</td>
					<td>horafin</td>
					<td>importe</td>
					<td>encuesta</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let size = self.allMissions.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos o si se trata de una misión anidada
			if(allowedCountries.indexOf(self.allMissions[i].country) == -1 || self.allMissions[i].tipoAnidada == '1') {
				continue;
			}

			let startDateTime = self.allMissions[i].fechahorainicio.split('#');
			let startDateArray = startDateTime[0].split('/');
			let startDate = startDateArray[2] + '-' + startDateArray[1] + '-' + startDateArray[0];
			let startTimeArray = startDateTime[2].split(':');
			let startTime = startDateTime[1] + ':' + startTimeArray[0];

			let endDateTime = self.allMissions[i].fechahorafin.split('#');
			let endDateArray = endDateTime[0].split('/');
			let endDate = endDateArray[2] + '-' + endDateArray[1] + '-' + endDateArray[0];
			let endTimeArray = endDateTime[2].split(':');
			let endTime = endDateTime[1] + ':' + endTimeArray[0];

			// Reloj - Zona horaria
			let timeZone = sessionStorage['STCMBackEnd:timeZone'];
			let date = new Date();
			let renderTimeNow = moment.tz(date, timeZone).format('YYYY-MM-DD HH:mm:ss');

			let nowDate = new Date(renderTimeNow);
			let dateEnd = new Date(endDate + ' ' + endTime);

			let color = '';
			if(nowDate >= dateEnd) {
				color = 'text-muted';
			}

			table += `
				<tr id="${self.allMissions[i].idmision}" class="c-pointer ${color}">
					<td class="text-truncate" title="${self.allMissions[i].idmision}">${self.allMissions[i].idmision}</td>
					<td class="text-truncate" title="${self.allMissions[i].tipomision}">${self.allMissions[i].tipomision}</td>
					<td class="text-truncate" title="${startDate}">${startDate}</td>
					<td class="text-truncate" title="${startTime}">${startTime}</td>
					<td class="text-truncate" title="${endDate}">${endDate}</td>
					<td class="text-truncate" title="${endTime}">${endTime}</td>
					<td class="text-truncate" title="${self.allMissions[i].importe}">${self.allMissions[i].importe}</td>
					<td class="text-center">
						<span class="d-none">${(self.allMissions[i].encuesta == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(self.allMissions[i].encuesta == '1' ? 'checked' : '')}>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'encuesta') {
				value = optionsSelectAllYesNo();
			}

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

		let allMissionsTable = $('#tableSelectMissions').DataTable({
			language: self.language,
			scrollY: 300,
			scrollCollapse: true,
			pageLength: 25,
			autoWidth: false,
			order: [[2, 'desc'], [3, 'desc']]
		});

		setTimeout(function() {
			allMissionsTable.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(allMissionsTable, 'filters');

		$('#tableSelectMissions tbody').off().on('click', 'tr', function() {
			let id = $(this).prop('id');

			for(let i = 0; i < size; i++) {
				if(id == self.allMissions[i].idmision) {
					// Comprobación de que la misión no esté en el proyecto
					let missionOut = true;
					let projectMissionsSize = self.projectMissions.length;
					for(let j = 0; j < projectMissionsSize; j++) {
						if(id == self.projectMissions[j].idmision) {
							missionOut = false;
						}
					}

					if(self.allMissions[i].objetivo == 'ConversacionChatGrupal' || self.allMissions[i].objetivo == 'FotoChatGrupal' || self.allMissions[i].objetivo == 'VideoChatGrupal') {
						$('#groupChat').prop('checked', true);
					}

					// Añadido de misión al proyecto
					if(missionOut) {
						let obj = {
							idProject: self.idProject,
							idmision: self.allMissions[i].idmision,
							descripcion: self.allMissions[i].descripcion,
							fechahorafin: self.allMissions[i].fechahorafinexec,
							fechahorainicio: self.allMissions[i].fechahorainicioexec,
							inicionotificado: 0,
							finnotificado: 0,
							importe: self.allMissions[i].importe,
							stampMision: self.allMissions[i].stampMision,
							isSurvey: self.allMissions[i].isSurvey,
							sid: self.allMissions[i].sid,
							objetivo: self.allMissions[i].objetivo,
							finmisioncupo: self.allMissions[i].finmisioncupo
						};
						self.projectMissions.push(obj);
					}
				}
			}

			$('#closeMissions').trigger('click');

			// Recargar tabla de misiones
			$('#tableMissions').dataTable().fnDestroy();
			self.renderProjectsMissions();
		});
	},

	editProject(action) {
		let self = this;
		
		// Control de repartición de misiones
		let missionDelivery = null;
		if(self.project.proyectoReparticion == '1') {
			missionDelivery = self.acceptDeliveryMissionsControl();
			if(!missionDelivery) {
				return false;
			}
		}

		let id = self.idProject;
		let useSegmentation = '0';
		let sidPerfilacion = '';
		let surveyProfilingValidator = true;
		let idSegmentation = '';
		let segmentationValidator = true;
		let targetTotalPanel = '0';
		if($('#searchAlgorithmSurvey').prop('checked')) {
			sidPerfilacion = $('#surveyProfiling').val();
			// Validación id encuesta de perfilación
			if(sidPerfilacion === '') {
				$('#surveyProfiling').addClass('is-invalid');
				$('#surveyProfiling-group').addClass('group-invalid');
				$('[for="surveyProfiling"]').addClass('is-invalid');
				surveyProfilingValidator = false;
			} else {
				$('#surveyProfiling').removeClass('is-invalid');
				$('#surveyProfiling-group').removeClass('group-invalid');
				$('[for="surveyProfiling"]').removeClass('is-invalid');
				surveyProfilingValidator = true;
			}
		} else if($('#searchAlgorithmSegmentation').prop('checked')) {
			useSegmentation = '1';
			idSegmentation = $('#segmentation').val();
			// Validación segmentación
			if(idSegmentation === '') {
				$('#segmentation').addClass('is-invalid');
				$('#segmentation-group').addClass('group-invalid');
				$('[for="segmentation"]').addClass('is-invalid');
				segmentationValidator = false;
			} else {
				$('#segmentation').removeClass('is-invalid');
				$('#segmentation-group').removeClass('group-invalid');
				$('[for="segmentation"]').removeClass('is-invalid');
				segmentationValidator = true;
			}

			// Limpieza de valores de encuesta
			self.targetsSurvey = [];
			self.targetsSurveySID = [];
			self.profilingName = [];
		} else if($('#searchAlgorithmTotal').prop('checked')) {
			targetTotalPanel = '1';

			// Limpieza de valores de encuesta
			self.targetsSurvey = [];
			self.targetsSurveySID = [];
			self.profilingName = [];
		} else {
			return false;
		}

		let NombreProyecto = $('#projectName').val().trim();
		let projectNameValidator = true;
		// Validación nombre de proyecto
		if(NombreProyecto === '') {
			$('#projectName').addClass('is-invalid');
			$('[for="projectName"]').addClass('is-invalid');
			projectNameValidator = false;
		} else {
			$('#projectName').removeClass('is-invalid');
			$('[for="projectName"]').removeClass('is-invalid');
			projectNameValidator = true;
		}

		let country = self.country.isocode;
		// Validación país de proyecto
		let projectCountryValidator = true;
		if(country === undefined) {
			$('#projectCountry').addClass('is-invalid');
			$('[for="projectCountry"]').addClass('is-invalid');
			projectCountryValidator = false;
		} else {
			$('#projectCountry').removeClass('is-invalid');
			$('[for="projectCountry"]').removeClass('is-invalid');
			projectCountryValidator = true;
		}

		let LiderProyecto = self.leader.nameUser;
		let LiderProyectoEmail = self.leader.email;
		let projectLeaderValidator = true;
		// Validación líder de proyecto
		if(LiderProyecto == 'undefined' || LiderProyecto == undefined) {
			$('#projectLeader').addClass('is-invalid');
			$('[for="projectLeader"]').addClass('is-invalid');
			projectLeaderValidator = false;
		} else {
			$('#projectLeader').removeClass('is-invalid');
			$('[for="projectLeader"]').removeClass('is-invalid');
			projectLeaderValidator = true;
		}

		let ChatGrupal = ($('#groupChat').prop('checked') === true ? 1 : 0);
		let VideoIndividual = 0;
		let VideoGrupal = 0;

		let notificarInclusion = ($('#greeting').prop('checked') === true ? 1 : 0);

		let numberRecordsValidator = true;
		let numberRecords = $('#numberRecords').val();
		if(numberRecords == '') {
			$('#numberRecords').addClass('is-invalid');
			$('[for="numberRecords"]').addClass('is-invalid');
			numberRecordsValidator = false;
		} else {
			$('#numberRecords').removeClass('is-invalid');
			$('[for="numberRecords"]').removeClass('is-invalid');
			numberRecordsValidator = true;
		}

		// Control de uso de CPG
		let cpgValidator = true;
		if(self.useCPG == '1' && sessionStorage['STCMBackEnd:idCPG'] == '0') {
			if(self.cpgList == '') {
				$('#cpgList').addClass('is-invalid');
				$('#cpgList-group').addClass('group-invalid');
				$('[for="cpgList"]').addClass('is-invalid');
				cpgValidator = false;
			} else {
				$('#cpgList').removeClass('is-invalid');
				$('#cpgList-group').removeClass('group-invalid');
				$('[for="cpgList"]').removeClass('is-invalid');
				cpgValidator = true;
			}
		}

		if(!projectCountryValidator || !surveyProfilingValidator || !segmentationValidator || !projectNameValidator || !projectLeaderValidator || !numberRecordsValidator || !cpgValidator) {
			if(self.leader == '') {
				let errorTitle = pf.const.language.RSC1616;
				let errorContent = pf.const.language.RSC1728;
				pf.utils.showInfoDialog(errorTitle, errorContent);
			} else {
				pf.utils.alerts.showCompleteAllFields();
			}
			return false;
		}

		// Relación de encuestas
		let sidRelations = '';
		let size = self.targetsSurveySID.length;
		for(let i = 0; i < size; i++) {
			if(i === 0) {
				sidRelations += self.targetsSurveySID[i];
			} else {
				sidRelations += ',' + self.targetsSurveySID[i];
			}
		}

		// Segmentaciones
		let segSize = self.selectedSegmentations.length;
		let idSegmentations = [];
		let nameSegmentations = [];
		let segSegmentations = [];
		if($('#searchAlgorithmSegmentation').prop('checked')) {
			for(let i = 0; i < segSize; i++) {
				idSegmentations.push(self.selectedSegmentations[i].idSegmentacion);
				nameSegmentations.push(self.selectedSegmentations[i].Descripcion);

				let catSize = self.selectedSegmentations[i].catalogacion.length;
				for(let j = 0; j < catSize; j++) {
					let string = j + '#' + self.selectedSegmentations[i].idSegmentacion + '#' + self.selectedSegmentations[i].Descripcion + '#' + self.selectedSegmentations[i].catalogacion[j].name + '#' + self.selectedSegmentations[i].catalogacion[j].include;
					segSegmentations.push(string);
				}
			}
		}

		let parameters = {
			country: country,
			id: id,
			//FechaProyecto: endDate,
			FechaProyecto: self.project.FechaProyecto,
			sidPerfilacion: JSON.stringify(self.targetsSurveySID),
			NombreProyecto: NombreProyecto,
			LiderProyecto: LiderProyecto,
			ClienteInterno: $('#brandsInvolved').val(),
			ObjetivoProyecto: $('#businessObjective').val(),
			DecisionATomar: $('#actionStandard').val(),
			Resultados: $('#resultsFavorable').val(),
			ChatIndividual: 0,
			ChatGrupal: ChatGrupal,
			VideoIndividual: VideoIndividual,
			VideoGrupal: VideoGrupal,
			LiderProyectoEmail: LiderProyectoEmail,
			ListaDistribucion: 1,
			IdPerfilacion: JSON.stringify(self.profilingName),
			IdPerfilacionDesc: JSON.stringify(self.profilingName),
			notificarInclusion: notificarInclusion,
			inclusivo: $('#inclusive').val(),
			useSegmentation: useSegmentation,
			sidRelations: sidRelations,
			targetsSurvey: JSON.stringify(self.targetsSurvey),
			sidRelationsSegmentation: JSON.stringify(idSegmentations),
			IdSegmentacion: JSON.stringify(nameSegmentations),
			IdSegmentacionDesc: JSON.stringify(nameSegmentations),
			segSegmentations: JSON.stringify(segSegmentations),
			projectMissions: JSON.stringify(self.projectMissions),
			applicantName: $('#ApplicantName').val(),
			brandsInvolved: $('#brandsInvolved').val(),
			projectDescription: $('#projectDescription').val(),
			background: $('#background').val(),
			businessObjective: $('#businessObjective').val(),
			investigationObjective: $('#investigationObjective').val(),
			actionStandard: $('#actionStandard').val(),
			favorableResults: $('#resultsFavorable').val(),
			notFavorableResults: $('#resultsNotFavorable').val(),
			cpgList: self.cpgList,
			modifiedQuota: self.modifiedQuota,
			quotaElementsArrayMissions: JSON.stringify(self.quotaElementsArrayMissions),
			targetTotalPanel: targetTotalPanel
		};
		ajaxComunCallWithCallback('updateCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(self.project.proyectoReparticion == '1') {
					// Guardar repartición de misiones
					let parameters = {
						missions: JSON.stringify(missionDelivery)
					};
					ajaxComunCallWithCallback('setCMBPProjectsMisionesCuotaReparto', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							//
						}
					}, false);
				}

				self.saveProjectRotations(action);
			}
		});
	},

	spAddFieldsPerf() {
		let self = this;

		let parameters = {
			country: self.country.isocode
		};
		ajaxComunCallWithCallback('spAddFieldsPerf', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				//
			}
		});
	},

	getAllMotivosExpulsionProject() {
		let self = this;

		ajaxComunCallWithCallback('getAllMotivosExpulsionProject', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.motivosExpulsion = ajaxReturn.result;

				if(self.motivosExpulsion == 'No reason defined') {
					// Mensaje de acción conseguida
					let successTitle = pf.const.language.RSC10;
					let successContent = self.motivosExpulsion;
					pf.utils.showInfoDialog(successTitle, successContent);
				} else {
					self.renderMotivosExpulsion();
				}
			}
		});
	},

	renderMotivosExpulsion() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC382}">${pf.const.language.RSC382}</th>
				</tr>
			</thead>

			<thead class="filters">
				<tr>
					<td>motivo</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.motivosExpulsion.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-id="${self.motivosExpulsion[i].id}" data-motivo="${self.motivosExpulsion[i].motivo}">
					<td class="text-truncate" title="${self.motivosExpulsion[i].motivo}">${self.motivosExpulsion[i].motivo}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let tableMotivosExpProject = $('#tableMotivosExpProject').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false
		});

		setTimeout(function() {
			tableMotivosExpProject.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableMotivosExpProject, 'filters');

		$('#motivosExpProjectTable').modal('toggle');

		$('#tableMotivosExpProject tbody').off().on('click', 'tr', function() {
			let motivoID = $(this).data('id');
			let motivo = $(this).data('motivo');

			$('#motivosExpProjectClose').trigger('click');

			self.deleteCMBPProjectsParticipantes(motivoID, motivo);
		});
	},

	deleteCMBPProjectsParticipantes(motivoID, motivo) {
		let self = this;

		let message = pf.const.language.RSC1256 + ' ' + self.project.NombreProyecto + '\n' + pf.const.language.RSC382 + ': ' + motivo;
		let parameters = {
			id: self.idProject,
			participants: self.participantsIDExp,
			motivoExclusion: motivoID,
			from: self.leader.id,
			message: message
		};
		ajaxComunCallWithCallback('deleteCMBPProjectsParticipantes', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = self.participants.length;
				for(let i = 0; i < size; i++) {
					if(self.participantsIDExp == self.participants[i].idUser) {
						self.participants.splice(i, 1);
						break;
					}
				}

				// Recargar tabla de participantes
				$('#tableParticipants').dataTable().fnDestroy();
				self.renderProjectParticipants();

				// Mensaje de acción conseguida
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC1257;
				pf.utils.showInfoDialog(successTitle, successContent);
			}
		});
	},

	getFilesRecordedByProject() {
		let self = this;

		let parameters = {
			idProject: self.idProject
		};
		ajaxComunCallWithCallback('getFilesRecordedByProject', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.filesRecorded = ajaxReturn.result;

				// Tabla de video llamadas
				self.renderFilesRecorded();

				// Control de spinner
				self.loaders.getFilesRecordedByProject = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	renderFilesRecorded() {
		let self = this;

		let table = `
			<table id="tableVideoLlamadas" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
						<th scope="col" title="${pf.const.language.RSC1311}">${pf.const.language.RSC1311}</th>
						<th scope="col" title="${pf.const.language.RSC2000}">${pf.const.language.RSC2000}</th>
						<th scope="col" title="${pf.const.language.RSC2001}">${pf.const.language.RSC2001}</th>
						<th scope="col" title="${pf.const.language.RSC1312}">${pf.const.language.RSC1312}</th>
						<th scope="col" title="${pf.const.language.RSC1313}">${pf.const.language.RSC1313}</th>
					</tr>
				</thead>

				<thead class="filtersRecorded">
					<tr>
						<td>fecha</td>
						<td>grabacion</td>
						<td>audio</td>
						<td>transcripcion</td>
						<td>duracion</td>
						<td>tamaño</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.filesRecorded.length;
		for(let i = 0; i < size; i++) {
			let url = self.filesRecorded[i].recordedFilePath + '/' + self.filesRecorded[i].recordedFileName;
			let size = self.filesRecorded[i].recordedFileTotalSize + ' ' + self.filesRecorded[i].recordedFileTotalSizeUnit;

			let camara = `<span class="d-none">${pf.const.language.RSC121}</span>`;
			let altavoz = `<span class="d-none">${pf.const.language.RSC121}</span>`;
			let lapiz = `<span class="d-none">${pf.const.language.RSC121}</span>`;

			if(self.filesRecorded[i].recorded == '1') {
				camara = `
					<span class="d-none">${pf.const.language.RSC120}</span>
					<span class="c-pointer viewVideo" data-url="${url}" data-file="${self.filesRecorded[i].recordedFileName}">
						<svg class="bi bi-camera-video-fill" width="1em" height="1em" fill="rgb(${self.color1RGB})" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
							<path fill-rule="evenodd" d="M0 5a2 2 0 0 1 2-2h7.5a2 2 0 0 1 1.983 1.738l3.11-1.382A1 1 0 0 1 16 4.269v7.462a1 1 0 0 1-1.406.913l-3.111-1.382A2 2 0 0 1 9.5 13H2a2 2 0 0 1-2-2V5z"/>
						</svg>
					</span>
				`;

				if(self.filesRecorded[i].Aux01 != '') {
					// Altavoz relleno / Audio
					altavoz = `
						<span class="d-none">${pf.const.language.RSC120}</span>
						<span class="c-pointer listenAudio" data-url="${self.filesRecorded[i].recordedFilePath}" data-file="${self.filesRecorded[i].Aux01}">
							<svg class="bi bi-volume-up-fill" width="18" height="18" fill="rgb(${self.color1RGB})" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
								<path d="M11.536 14.01A8.473 8.473 0 0 0 14.026 8a8.473 8.473 0 0 0-2.49-6.01l-.708.707A7.476 7.476 0 0 1 13.025 8c0 2.071-.84 3.946-2.197 5.303l.708.707z"/>
								<path d="M10.121 12.596A6.48 6.48 0 0 0 12.025 8a6.48 6.48 0 0 0-1.904-4.596l-.707.707A5.483 5.483 0 0 1 11.025 8a5.483 5.483 0 0 1-1.61 3.89l.706.706z"/>
								<path d="M8.707 11.182A4.486 4.486 0 0 0 10.025 8a4.486 4.486 0 0 0-1.318-3.182L8 5.525A3.489 3.489 0 0 1 9.025 8 3.49 3.49 0 0 1 8 10.475l.707.707zM6.717 3.55A.5.5 0 0 1 7 4v8a.5.5 0 0 1-.812.39L3.825 10.5H1.5A.5.5 0 0 1 1 10V6a.5.5 0 0 1 .5-.5h2.325l2.363-1.89a.5.5 0 0 1 .529-.06z"/>
							</svg>
						</span>
					`;

					if(self.filesRecorded[i].transcription == '1') {
						// Lapiz relleno / Transcripción
						lapiz = `
							<span class="d-none">${pf.const.language.RSC120}</span>
							<span class="c-pointer viewTranscription" data-url="${self.filesRecorded[i].recordedFilePath}" data-file="${self.filesRecorded[i].Aux01}" data-call="${self.filesRecorded[i].idCall}">
								<svg class="bi bi-pencil-fill" width="16" height="16" fill="rgb(${self.color1RGB})" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
									<path d="M12.854.146a.5.5 0 0 0-.707 0L10.5 1.793 14.207 5.5l1.647-1.646a.5.5 0 0 0 0-.708l-3-3zm.646 6.061L9.793 2.5 3.293 9H3.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.207l6.5-6.5zm-7.468 7.468A.5.5 0 0 1 6 13.5V13h-.5a.5.5 0 0 1-.5-.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.5-.5V10h-.5a.499.499 0 0 1-.175-.032l-.179.178a.5.5 0 0 0-.11.168l-2 5a.5.5 0 0 0 .65.65l5-2a.5.5 0 0 0 .168-.11l.178-.178z"/>
								</svg>
							</span>
						`;
					} else {
						lapiz = `
							<span class="d-none">${pf.const.language.RSC121}</span>
							<span class="c-pointer transcription" data-url="${self.filesRecorded[i].recordedFilePath}" data-file="${self.filesRecorded[i].Aux01}" data-call="${self.filesRecorded[i].idCall}">
								<svg class="bi bi-pencil" width="16" height="16" fill="rgb(${self.color1RGB})" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
									<path d="M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325z"/>
								</svg>
							</span>
						`;
					}
				} else if(self.filesRecorded[i].recordedFileTotalSize != '0') {
					altavoz = `
						<span class="d-none">${pf.const.language.RSC121}</span>
						<span class="c-pointer audio" data-url="${self.filesRecorded[i].recordedFilePath}" data-file="${self.filesRecorded[i].recordedFileName}" data-call="${self.filesRecorded[i].idCall}">
							<svg class="bi bi-volume-up" width="18" height="18" fill="rgb(${self.color1RGB})" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
								<path d="M11.536 14.01A8.473 8.473 0 0 0 14.026 8a8.473 8.473 0 0 0-2.49-6.01l-.708.707A7.476 7.476 0 0 1 13.025 8c0 2.071-.84 3.946-2.197 5.303l.708.707z"/>
								<path d="M10.121 12.596A6.48 6.48 0 0 0 12.025 8a6.48 6.48 0 0 0-1.904-4.596l-.707.707A5.483 5.483 0 0 1 11.025 8a5.483 5.483 0 0 1-1.61 3.89l.706.706z"/>
								<path d="M10.025 8a4.486 4.486 0 0 1-1.318 3.182L8 10.475A3.489 3.489 0 0 0 9.025 8c0-.966-.392-1.841-1.025-2.475l.707-.707A4.486 4.486 0 0 1 10.025 8zM7 4a.5.5 0 0 0-.812-.39L3.825 5.5H1.5A.5.5 0 0 0 1 6v4a.5.5 0 0 0 .5.5h2.325l2.363 1.89A.5.5 0 0 0 7 12V4zM4.312 6.39 6 5.04v5.92L4.312 9.61A.5.5 0 0 0 4 9.5H2v-3h2a.5.5 0 0 0 .312-.11z"/>
							</svg>
						</span>
					`;
				}
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.filesRecorded[i].stampServer}">${self.filesRecorded[i].stampServer}</td>
					<td class="text-truncate text-center">
						${camara}
					</td>
					<td class="text-truncate text-center">
						${altavoz}
					</td>
					<td class="text-truncate text-center">
						${lapiz}
					</td>
					<td class="text-truncate" title="${self.filesRecorded[i].recordedFilePartDuration}">${self.filesRecorded[i].recordedFilePartDuration}</td>
					<td class="text-truncate" title="${size}">${size}</td> 
				</tr>
			`;
		}

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

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

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

			if(title === 'grabacion' || title === 'audio' || title === 'transcripcion') {
				value = optionsSelectAllYesNo();
			}

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

		let recordedTable = $('#tableVideoLlamadas').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 5,
			autoWidth: false,
			columnDefs: [
				{width: '80px', targets: 1},
				{width: '80px', targets: 2},
				{width: '110px', targets: 3}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC194,
				className: 'd-none',
				title: pf.const.language.RSC194,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(recordedTable, 'filtersRecorded');

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

		self.tableVideoLlamadasEvents();

		$('#tableVideoLlamadas').on('draw.dt', function() {
			self.tableVideoLlamadasEvents();
		});
	},

	tableVideoLlamadasEvents() {
		let self = this;

		// Visualizar video
		$('.viewVideo').off().on('click', function() {
			let url = $(this).data('url');
			let file = $(this).data('file');

			$('#attachmentViewer').show();
			$('.attachmentContainer').html('');
			$('#downloadAttachment').show();
			$('#reTranscription').hide();
			$('#iframeWordcloud').html('');
			$('#iframeWordcloud').hide();

			content = `
				<video id="elementRep" controls>
					<source src="${url}">
				</video>
			`;

			$('.attachmentContainer').html(content);

			$('#downloadAttachment').off().on('click', function(e) {
				e.preventDefault();
				self.createFileServer(url, file);
			});

			$('#closeAttachment').off().on('click', function() {
				let element = document.getElementById('elementRep');
				element.pause();
				$('#attachmentViewer').hide();
			});
		});

		// Escuchar audio
		$('.listenAudio').off().on('click', function() {
			let url = $(this).data('url') + '/' + $(this).data('file');
			let file = $(this).data('file');

			$('#attachmentViewer').show();
			$('.attachmentContainer').html('');
			$('#downloadAttachment').show();
			$('#reTranscription').hide();
			$('#iframeWordcloud').html('');
			$('#iframeWordcloud').hide();

			content = `
				<audio id="elementRep" controls>
					<source src="${url}">
				</audio>
			`;

			$('.attachmentContainer').html(content);

			$('#downloadAttachment').off().on('click', function(e) {
				e.preventDefault();
				self.createFileServer(url, file);
			});

			$('#closeAttachment').off().on('click', function() {
				let element = document.getElementById('elementRep');
				element.pause();
				$('#attachmentViewer').hide();
			});
		});

		// Convertir video (MP4) a audio (WAV)
		$('.audio').off().on('click', function() {
			let url = $(this).data('url');
			let file = $(this).data('file');
			let call = 'CODE#' + $(this).data('call');

			self.convertMP4ToWAV(url, file, call);
		});

		// Comenzar transcripción
		$('.transcription').off().on('click', function() {
			let path = $(this).data('url');
			let fileName = $(this).data('file');
			let idCall = 'CODE#' + $(this).data('call');

			// Valores de configuración
			let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
			let azureCognitiveLenguajeKEY = config.azureCognitiveLenguajeKEY;
			let azureCognitiveLenguajeRegion = config.azureCognitiveLenguajeRegion;

			if(azureCognitiveLenguajeKEY == '' || azureCognitiveLenguajeKEY == null || azureCognitiveLenguajeKEY == undefined) {
				let errorTitle = pf.const.language.RSC2001;
				let errorContent = pf.const.language.RSC2102;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				return false;
			}

			let values = {
				idProject: self.idProject,
				idCall: idCall,
				path: path,
				fileName: fileName,
				audioFile: '',
				azureCognitiveLenguajeKEY: azureCognitiveLenguajeKEY,
				azureCognitiveLenguajeRegion: azureCognitiveLenguajeRegion,
				reTranscription: '0'
			}

			let audioTranscription = new Transcription(values);
			audioTranscription.sendAudioTranscription();
		});

		// Visualizar transcripción
		$('.viewTranscription').off().on('click', function() {
			let path = $(this).data('url');
			let fileName = $(this).data('file');
			let idCall = 'CODE#' + $(this).data('call');
			self.viewTranscription = {
				idCall: idCall,
				path: path,
				fileName: fileName
			};

			$('#attachmentViewerTranscription').show();
			$('.attachmentContainerTranscription').html('');
			$('#reTranscription').show();
			$('#iframeWordcloud').hide();
			$('#downloadAttachmentTranscription').hide();
			$('#returnToText').hide();
			$('#fullscreenWordcloudTranscription').show();

			// Descargar wordcloud
			$('#downloadAttachmentTranscription').hide();

			window.addEventListener('message', function(event) {
				self.wordCloudImg = event.data;
			});

			$('#downloadAttachmentTranscription').off().on('click', function() {
				let a = document.getElementById('downloadAttachmentTranscription');
				a.href = self.wordCloudImg;
			});

			$('#downloadAttachmentTranscriptionText').off().on('click', function() {
				let date = Date.now()
				let element = document.createElement('a');

				let text = '';

				for(let i = 0; i < self.transcriptionText.length; i++) {
					let element = self.transcriptionText[i].text;
					text += element + '\n\n';
				}

				let content = `
					<div class="form-group">
						<label for="externalLink">${pf.const.language.RSC2043}</label>

						<div class="d-flex form-check">
							<label for="formatoWord" class="form-check-label">Word</label>
							<input id="formatoWord" type="radio" class="form-check-input" name="formatoDescargaTranscripcion" checked>
						</div>

						<div class="d-flex form-check">
							<label for="formatoExcel" class="form-check-label">Excel</label>
							<input id="formatoExcel" type="radio" class="form-check-input" name="formatoDescargaTranscripcion">
						</div>
					</div>
				`;

				let objInfo = {
					accept: {
						text: pf.const.language.RSC141
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC2042;
				pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
					if($('#formatoWord').is(':checked') == true) {
						element.setAttribute('href', 'data:application/msword;charset=utf-8,' + encodeURIComponent(text));
						element.setAttribute('download', 'transcription' + date);
						element.style.display = 'none';
						document.body.appendChild(element);
						element.click();
						document.body.removeChild(element);
					} else {
						element.setAttribute('href', 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(text));
						element.setAttribute('download', 'transcription' + date);
						element.style.display = 'none';
						document.body.appendChild(element);
						element.click();
						document.body.removeChild(element);
					}
				}, function() {});
			});

			$('#closeAttachmentTranscription').off().on('click', function() {
				$('#attachmentViewerTranscription').hide();
				$('#iframeWordcloud').hide();
				$('#downloadAttachmentTranscriptionText').show();
				$('#downloadAttachmentTranscription').hide();
				$('#returnToText').hide();
				$('#fullscreenWordcloudTranscription').show();
				$('#downloadAttachmentTranscription').hide();
				setTimeout(function() {
					$('#downloadAttachmentTranscription').hide();
				}, 3000);
			});

			$('#reTranscription').off().on('click', function() {
				$('#attachmentViewerTranscription').hide();
				// Valores de configuración
				let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
				let azureCognitiveLenguajeKEY = config.azureCognitiveLenguajeKEY;
				let azureCognitiveLenguajeRegion = config.azureCognitiveLenguajeRegion;

				if(azureCognitiveLenguajeKEY == '' || azureCognitiveLenguajeKEY == null || azureCognitiveLenguajeKEY == undefined) {
					let errorTitle = pf.const.language.RSC2001;
					let errorContent = pf.const.language.RSC2102;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					return false;
				}

				let values = {
					idProject: self.idProject,
					idCall: self.viewTranscription.idCall,
					path: self.viewTranscription.path,
					fileName: self.viewTranscription.fileName,
					audioFile: '',
					azureCognitiveLenguajeKEY: azureCognitiveLenguajeKEY,
					azureCognitiveLenguajeRegion: azureCognitiveLenguajeRegion,
					reTranscription: '1'
				}

				let audioTranscription = new Transcription(values);
				audioTranscription.sendAudioTranscription();
			});

			// Petición de transcripción por proyecto e idCall
			self.getFilesTranscriptionByProject();
		});

		$('#fullscreenWordcloudTranscription').off().on('click', function() {
			$('.attachmentContainerTranscription').hide();
			$('#contentTextContainer').hide();
			$('#iframeWordcloud').show();
			$('#downloadAttachmentTranscriptionText').hide();

			$('#fullscreenWordcloudTranscription').hide();
			$('#returnToText').show();
			setTimeout(function() {
				$('#downloadAttachmentTranscription').show();
			}, 3000);
		});

		$('#returnToText').off().on('click', function() {
			$('.attachmentContainerTranscription').show();
			$('#contentTextContainer').show();
			$('#iframeWordcloud').hide();
			$('#downloadAttachmentTranscriptionText').show();

			$('#fullscreenWordcloudTranscription').show();
			$('#returnToText').hide();
			$('#downloadAttachmentTranscription').hide();

			setTimeout(function() {
				$('#downloadAttachmentTranscription').hide();
			}, 3000);
		});
	},

	createFileServer(url, file) {
		let self = this;

		let client = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let mail = client.email.split('@');
		let user = mail[0].replace('.', '_');

		let parameters = {
			url: url,
			file: file,
			user: user
		};
		ajaxComunCallWithCallbackOne('getAttachedConversation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				let src = stcm.const.downloads + resp.file
				let link = document.createElement('a');
				link.href = src;
				link.download = file;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);
				self.deleteFile(resp.file);
			}
		});
	},

	convertMP4ToWAV(url, file, call) {
		let self = this;

		let parameters = {
			fileNameUpload: file,
			recordedFilePath: url,
			idCall: call
		};
		ajaxComunCallWithCallback('convertMP4ToWAV', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC2004;
				pf.utils.showInfoDialog(successTitle, successContent);

				self.getFilesRecordedByProject();
			}
		});
	},

	// Borrado de archivo
	deleteFile(file) {
		let parameters = {
			filename: file
		};
		ajaxComunCallWithCallbackVoid('deleteFile', parameters);
	},

	addRotationToMision(stampMision, rotationArray, rotationsObject) {
		let self = this;

		let mision = self.projectMissions.find(mision => {
			return (mision.stampMision === stampMision)
		})
		if(mision) {
			mision.rotation = rotationArray;
			mision.rotationObject = rotationsObject;
			self.renderProjectParticipants();
		}
	},

	saveProjectRotations(action) {
		let self = this;

		let rotationsArray = [];
		self.projectMissions.forEach(mision => {
			if(mision.rotation) {
				rotationsArray = [
					...rotationsArray,
					...mision.rotation
				]
			}
		});
		if(rotationsArray.length > 0) {
			let parameters = {
				values: JSON.stringify(rotationsArray)
			};
			ajaxComunCallWithCallback('setProjectMisionRotaciones', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					self.saveParticipantRotations(action);
				}
			});
		} else {
			self.afterSaveFunction(action);
		}
	},

	saveParticipantRotations(action) {
		let self = this;

		let rotationArray =self.createUserRotationArray();
		if(self.updateRotations && rotationArray.length > 0) {
			let parameters = {
				values: JSON.stringify(rotationArray)
			};
			ajaxComunCallWithCallback('setUserRotacion', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					self.afterSaveFunction(action);
				}
			});
		} else {
			self.afterSaveFunction(action);
		}
	},

	afterSaveFunction(action) {
		let self = this;

		if(action === 'edit') {
			let successTitle = pf.const.language.RSC10;
			let successContent = pf.const.language.RSC453;
			pf.utils.showInfoDialog(successTitle, successContent);
			window.location.href = '#!proyectos';
		} else if(action === 'getResults') {
			sessionStorage.setItem('idProject', self.idProject);
			sessionStorage.setItem('numberRecords', $('#numberRecords').val());
			sessionStorage.setItem('cpgList', self.cpgList);

			if($('#searchAlgorithmSegmentation').prop('checked')) {
				sessionStorage.setItem('searchAlgorithm', 'segmentation');
				// Encuestas
				sessionStorage.setItem('idProfiling', '');
				sessionStorage.setItem('targetsSurvey', '{}');
				// Segmentaciones
				sessionStorage.setItem('segmentation', $('#segmentation').val());
				sessionStorage.setItem('selectedSegmentations', JSON.stringify(self.selectedSegmentations));
			} else if($('#searchAlgorithmSurvey').prop('checked')) {
				sessionStorage.setItem('searchAlgorithm', 'survey');
				// Encuestas
				sessionStorage.setItem('idProfiling', $('#surveyProfiling').val());
				sessionStorage.setItem('targetsSurvey', JSON.stringify(self.targetsSurvey));
				// Segmentaciones
				sessionStorage.setItem('segmentation', '');
				sessionStorage.setItem('selectedSegmentations', '{}');
			} else if($('#searchAlgorithmTotal').prop('checked')) {
				sessionStorage.setItem('searchAlgorithm', 'total');
				// Encuestas
				sessionStorage.setItem('idProfiling', '');
				sessionStorage.setItem('targetsSurvey', '{}');
				// Segmentaciones
				sessionStorage.setItem('segmentation', '');
				sessionStorage.setItem('selectedSegmentations', '{}');
			}

			sessionStorage.setItem('leader', JSON.stringify(self.leader));
			sessionStorage.setItem('missionsCount', self.projectMissions.length);
			sessionStorage.setItem('projectMisions', JSON.stringify(self.projectMissions));
			sessionStorage.setItem('countryFilter', self.countryFilter);
			sessionStorage.setItem('proyect_inclusive', $('#inclusive').val());

			window.location.href = '#!proyectos_objectives';
		}
	},

	getSelectedUsersRotacionesProject: async function() {
		let self = this;

		let misionsParams = [];
		for(let mision of self.projectMissions) {
			misionsParams.push({
				'survey': mision.sid,
				'idProject': self.idProject,
				'mision': mision.stampMision
			});
		};

		let parameters = {
			misions: JSON.stringify(misionsParams)
		};
		ajaxComunCallWithCallback('getAllAsignedProjectRotaciones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.length != 0) {
					ajaxReturn.result.forEach(mision => {
						mision.rotations.forEach(rotation => {
							let participant = self.participants.find(par => par.email == rotation.token);
							if(!participant) {
								return;
							} else {
								if(!participant.rotations) {
									participant.rotations = [];
								}

								participant.rotations.push(rotation);
							}
						});
					});

				}
				self.renderProjectParticipants();
				self.renderProjectsMissions();
				self.getAllRotacionesProject();
			}
		}, false);
	},

	assignRotation(rotIdx, usrIdx, rotArray, stampMision) {
		let self = this;

		moduledRotIndex = rotIdx % rotArray.length;

		rotation = rotArray[moduledRotIndex];
		if(rotation.toAssign <= 0) {
			//condición de parada para evitar loop infinito (no debería darse el caso but anyway)
			if(usrIdx%rotArray.length -1 === moduledRotIndex) {
				return false;
			}

			return(self.assignRotation(rotIdx+1, usrIdx, rotArray, stampMision));
		} else {
			if(!self.participants[usrIdx].rotations) {
				self.participants[usrIdx].rotations =[]
			}

			--rotation.toAssign;
			self.participants[usrIdx].rotations.push({...rotArray[moduledRotIndex], stampMision: stampMision});

			return true;
		}
	},

	assignRotationsToUsers() {
		let self = this;

		if(self.loaded) {
			self.projectMissions.forEach(mision => {
				if(mision.rotationObject) {
					this.calculatePercentage(mision.rotationObject);
				}
			});
			for(let i = 0; i < self.participants.length; i++) {
				self.participants[i].rotations = [];
				for(let j = 0; j < self.projectMissions.length; j++) {
					if(self.projectMissions[j].rotationObject) {
						let valid = self.assignRotation(i,i,self.projectMissions[j].rotationObject, self.projectMissions[j].stampMision);
						if(!valid) {
							return false;
						}
					}
				}
			}
			self.updateRotations = true;
		} else {
			self.loaded = true;
		}

		return true;
	},

	calculatePercentage(rotations) {
		let self = this;

		function u(c, total) {
			let real, natural;
			real = c * total + amortized;
			natural = Math.floor(real); // just to be on the safe side
			amortized = real - natural;
			return natural;
		}
		let total = self.participants.length;
		let sum = 0;
		let amortized = 0;
		let i = 0;
		for(i = 0; i < rotations.length - 1; i++) {
			let percentatge = parseFloat(((rotations[i].porcentaje)/100).toFixed(2));
			numberToAssign = u(percentatge,total);
			rotations[i].assign = numberToAssign;
			rotations[i].toAssign = numberToAssign;
			sum += numberToAssign;
		}

		rotations[i].assign = total - sum;
		rotations[i].toAssign = total - sum;
	},

	createUserRotationArray() {
		let self = this;

		let resultArray = [];
		self.participants.forEach(participant => {
			participant.rotations.forEach(rotation => {
				let rotString = `${self.idProject}#${rotation.stampMision}#${rotation.idrotation}#${rotation.sid}#${participant.email}`;
				resultArray.push(rotString)
			});
		});
		return resultArray;
	},

	getAllRotacionesProject() {
		let self = this;

		let misionsParams = [];
		self.projectMissions.forEach(mision => {
			misionsParams.push({
				'survey':mision.surveyId,
				'idProject':self.idProject,
				'mision':mision.stampMision
			})
		});

		let parameters = {
			misions: JSON.stringify(misionsParams)
		};
		ajaxComunCallWithCallback('getAllRotacionesProject', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				ajaxReturn.result.forEach(misonRotacion => {
					let mision = self.projectMissions.find(mision => {
						return (mision.stampMision === misonRotacion.mision)
					})
					if(mision) {
						mision.rotation = self.generateRotationArray(misonRotacion.rotations);
						mision.rotationObject = misonRotacion.rotations;
					}
				});

				// Control de spinner
				self.loaders.getAllRotacionesProject = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	generateRotationArray(rotations) {
		let self = this;

		let rotationArray = [];
		rotations.forEach(rotation => {
			let rotationString = `${self.idProject}#${rotation.stampMision}#${rotation.idrotation}#${rotation.sid}#${rotation.porcentaje}`;
			rotationArray.push(rotationString);
		});
		return rotationArray;
	},

	postMessageMultiple(externalLink) {
		let self = this;

		// A continuación le compartimos el enlace a la videocall a la que ha sido invitado/a:
		let message = pf.const.language.RSC1955 + ' ' + externalLink;

		let parameters = {
			from: self.leader.id,
			emailsToSend: '',
			message: message,
			idlist: self.project.ListaDistribucionID
		};
		ajaxComunCallWithCallback('postMessageMultiple', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC1956;
				pf.utils.showInfoDialog(successTitle, successContent);
			}
		});
	},

	setFileRecordedExternal() {
		let self = this;

		let timestamp = new Date().getTime();
		let idcall = self.idProject + timestamp;

		let parameters = {
			userName: self.userName,
			jid: self.leader.id,
			dateArmed: '',
			folderRecorded: '',
			fileRecorded: self.videoFile,
			idProject: self.idProject,
			stamp: timestamp,
			idcall: 'CODE#' + idcall
		};
		ajaxComunCallWithCallback('setFileRecordedExternal', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Spinner añadido fin
				removeLoader();

				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC1960;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/proyectos/proyectos_edit.html', 'wrapper', ProyectosEditController);
			}
		});
	},

	getFilesTranscriptionByProject() {
		let self = this;

		let parameters = {
			idProject: self.idProject,
			idcall: self.viewTranscription.idCall
		};
		ajaxComunCallWithCallback('getFilesTranscriptionByProject', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let paragraphs = '';
				self.transcriptionText = ajaxReturn.result;
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					paragraphs += `<p>${ajaxReturn.result[i].text}</p>`;
				}

				let idCallK = self.viewTranscription.idCall.slice(5, self.viewTranscription.idCall.length);

				let url = self.wordCloudURL;
				let wordcloud = url + '/?a=&b=&c=' + self.idProject +'&d=&e=&f=&g=' + self.primaryColor + '&h=' + self.secundaryColor + '&i=2&j=' + self.numberWordsWordcloud + '&k=' + idCallK + '&l=&m=&n=&o=';

				let content = `
					<div id="contentTextContainer">
						<div id="pageTextContainer">
							${paragraphs}
						<div> 
					</div>
				`;
				let iframehtml = `<iframe id="wordcloudTranscription" src="${wordcloud}" class="iframeTranscription embed-responsive-item vh-50 border-0"></iframe>`;

				$('.attachmentContainerTranscription').html(content);
				$('#iframeWordcloud').html(iframehtml);
			}
		});
	},

	additionalDocumentsTable() {
		let self = this;

		let excelTitle = pf.const.language.RSC2062;

		let table = `
			<table id="tableAdditionalDocuments" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC225}"></th>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC1313}">${pf.const.language.RSC1313}</th>
						<th scope="col" title="${pf.const.language.RSC56}">${pf.const.language.RSC56}</th>
						<th scope="col" title="${pf.const.language.RSC95}"></th>
					</tr>
				</thead>

				<thead class="filtersAdditionalDocuments">
					<tr>
						<td>editar</td>
						<td>fecha</td>
						<td>documento</td>
						<td>descripcion</td>
						<td>tamaño</td>
						<td>descargar</td>
						<td>borrar</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.filesToUploadInfo.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate text-center" title="${pf.const.language.RSC225}">
						<span class="c-pointer editDescription" data-id="${self.filesToUploadInfo[i].id}" data-description="${self.filesToUploadInfo[i].descripcion}">
							${stcmbackend.svg.pencil}
						</span>
					</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].fecha}">${self.filesToUploadInfo[i].fecha}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].documento}">${self.filesToUploadInfo[i].documento}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].descripcion}">${self.filesToUploadInfo[i].descripcion}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].tamano}">${self.filesToUploadInfo[i].tamano}</td>
					<td class="text-truncate text-center">
						<a href="${stcm.const.downloads + 'projects/' + self.idProject + '/' + self.filesToUploadInfo[i].documento}" class="btn btn-eye loadFile" download>
							${stcmbackend.svg.bigDownloadWithoutColor}
						</a>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteFilesToUpload" data-id="${self.filesToUploadInfo[i].id}" data-name="${self.filesToUploadInfo[i].documento}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

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

			if(title === 'descargar' || title === 'borrar' || title === 'editar') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let recordedTable = $('#tableAdditionalDocuments').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 5,
			autoWidth: false,
			columnDefs: [
				{width: '30px', orderable: false, targets: 0},
				{width: '135px', targets: 2},
				{width: '70px', targets: 4},
				{width: '85px', orderable: false, targets: 5},
				{width: '30px', orderable: false, targets: 6}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(recordedTable, 'filtersAdditionalDocuments');

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

		self.tableAdditionalDocumentsEvents();

		$('#tableAdditionalDocuments').on('draw.dt', function() {
			self.tableAdditionalDocumentsEvents();
		});
	},

	tableAdditionalDocumentsEvents() {
		let self = this;

		// Eliminar registro
		$('.deleteFilesToUpload').off().on('click', function() {
			let id = $(this).data('id');
			let filename = $(this).data('name');

			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC10;
			let alertText = pf.const.language.RSC2066;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteCMBPProjectsFileById(id, filename);
			}, function() {});
		});

		// Editar descripción
		$('.editDescription').off().on('click', function() {
			let id = $(this).data('id');

			// Alert con input
			let alertTitle = pf.const.language.RSC2062;

			let content = `
				<div class="form-group">
					<label for="documentDescription" class="fw-500">${pf.const.language.RSC178}</label>
					<input id="documentDescription" type="text" class="form-control" value="">
				</div>
			`;
			let objInfo = {
				accept: {
					text: pf.const.language.RSC225
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				let documentDescription = $('#documentDescription').val();

				self.updateCMBPProjectsFilesDesc(id, documentDescription);
			}, function() {});
		});
	},

	insertCMBPProjectsFile() {
		let self = this;

		addLoader();
		let parameters = {
			id: self.idProject,
			admin: self.userMail,
			fileToUpload: self.fileToUpload,
			fileToUploadDesc: self.fileToUploadDesc
		};
		ajaxComunCallWithCallback('insertCMBPProjectsFile', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Archivo subido con éxito
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC2065;
				pf.utils.showInfoDialog(successTitle, successContent);

				// Vaciar variable de archivo
				self.fileToUpload = null;

				// Petición de archivos de proyecto
				self.getCMBPProjectsFiles();
			}
		}, false);
	},

	getCMBPProjectsFiles() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjectsFiles', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Archivos de proyecto
				self.filesToUploadInfo = [];
					
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						id: ajaxReturn.result[i].id,
						fecha: ajaxReturn.result[i].stampServer,
						admin: ajaxReturn.result[i].admin,
						documento: ajaxReturn.result[i].fileName,
						descripcion: ajaxReturn.result[i].descripcion,
						tamano: ajaxReturn.result[i].fileSize
					};
					self.filesToUploadInfo.push(obj);
				}

				self.additionalDocumentsTable();

				removeLoader();
			}
		}, false);
	},

	deleteCMBPProjectsFileById(id, filename) {
		let self = this;

		addLoader();
		let parameters = {
			id: self.idProject,
			projectFiles: id,
			filename: filename
		};
		ajaxComunCallWithCallback('deleteCMBPProjectsFileById', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Documento eliminado con éxito
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC2067;
				pf.utils.showInfoDialog(successTitle, successContent);

				// Vaciar variable de archivo
				self.fileToUpload = null;

				// Petición de archivos de proyecto
				self.getCMBPProjectsFiles();
			}
		}, false);
	},

	updateCMBPProjectsFilesDesc(id, documentDescription) {
		let self = this;

		let parameters = {
			id: id,
			descripcion: documentDescription,
			admin: self.userMail
		};
		ajaxComunCallWithCallback('updateCMBPProjectsFilesDesc', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Documento editado con éxito
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC2112;
				pf.utils.showInfoDialog(successTitle, successContent);

				// Petición de archivos de proyecto
				self.getCMBPProjectsFiles();
			}
		});
	},

	//TODO: refactor segmentation quota
	// renderQuotaTables(quota, segmentations, stampMision) {
	// 	let self = this;

	// 	// Elemento general
	// 	let surveyOrSegmentation = '';
	// 	let totalSaved = 0;
	// 	let surveySelected = false;
	// 	self.quotaElementsArray = [];

	// 	// Si lo seleccionado como algoritmo es una encuesta se emula el funcionamiento de una segmentación de un solo segmento
	// 	let size = segmentations.length;
	// 	if(size === 0) {
	// 		surveySelected = true;

	// 		let obj = [{
	// 			surveys: $('#surveyProfiling').val(),
	// 			Descripcion: pf.const.language.RSC2206,
	// 			idSegmentacion: 0,
	// 			idSegmento: 0
	// 		}];
	// 		segmentations.push(obj);

	// 		size = 1;
	// 	}

	// 	// Bucle por cada segmentación
	// 	let indexArray = 0;
	// 	for(let i = 0; i < size; i++) {
	// 		let sizeE = segmentations[i].length;
	// 		// Bucle por cada segmento
	// 		for(let n = 0; n < sizeE; n++) {
	// 			let profilingElement = '';
	// 			let value = 0;
	// 			if(surveySelected) {
	// 				value = quota;
	// 			}

	// 			let sizeSaved = self.previousQuotaAllocation.length;
	// 			for(let e = 0; e < sizeSaved; e++) {
	// 				if(self.previousQuotaAllocation[e].segmento == segmentations[i][n].idSegmento) {
	// 					value = parseInt(self.previousQuotaAllocation[e].segmentoValue);
	// 					totalSaved += parseInt(self.previousQuotaAllocation[e].segmentoValue);
	// 				}
	// 			}

	// 			let objFirst = {
	// 				stampMision: stampMision,
	// 				surveys: segmentations[i][n].surveys || '0',
	// 				idSegmentacion: segmentations[i][n].idSegmentacion,
	// 				idSegmento: segmentations[i][n].idSegmento,
	// 				id: 'firstLevelQ_' + i + '_' + n,
	// 				childs: [],
	// 				childClass: 'firstLevelQ_' + i + '_' + n,
	// 				value: value
	// 			};
	// 			self.quotaElementsArray.push(objFirst);

	// 			// Bucle de secciones de perfilación
	// 			let indexProf = 0;
	// 			for(let section in self.profilingSections) {
	// 				let value = 0;
	// 				if(surveySelected) {
	// 					value = quota;
	// 				}
	// 				let genderSaved = 0;
	// 				let ageSaved = 0;
	// 				let regionSaved = 0;
	// 				let secSaved = 0;
	// 				let name = '';
	// 				let idSection = '';
	// 				let data = [];

	// 				if(sizeSaved > 0) {
	// 					for(let e = 0; e < sizeSaved; e++) {
	// 						if(self.previousQuotaAllocation[e].segmento == segmentations[i][n].idSegmento) {
	// 							genderSaved += parseInt(self.previousQuotaAllocation[e].generoValue);
	// 							ageSaved += parseInt(self.previousQuotaAllocation[e].rangoEdadValue);
	// 							regionSaved += parseInt(self.previousQuotaAllocation[e].regionValue);
	// 							secSaved += parseInt(self.previousQuotaAllocation[e].rangoNSEValue);
	// 						}
	// 					}

	// 					switch(section) {
	// 						case 'genero':
	// 							value = (genderSaved == 0 && surveySelected ? quota : objFirst.value);
	// 						break;
	// 						case 'edad':
	// 							value = (ageSaved == 0 && surveySelected ? quota : objFirst.value);
	// 						break;
	// 						case 'region':
	// 							value = (regionSaved == 0 && surveySelected ? quota : objFirst.value);
	// 						break;
	// 						case 'sec':
	// 							value = (secSaved == 0 && surveySelected ? quota : objFirst.value);
	// 						break;
	// 					}
	// 				}

	// 				let obj = {
	// 					id: 'secondLevelQ_' + i + '_' + n + '_' + section,
	// 					childs: [],
	// 					childClass: 'secondLevelQ_' + i + '_' + n + '_' + section,
	// 					value: value
	// 				};
	// 				self.quotaElementsArray[indexArray].childs.push(obj);

	// 				switch(section) {
	// 					case 'genero':
	// 						name = pf.const.language.RSC151;
	// 						idSection = 'sectionGender_' + i + '_' + n;
	// 						for(let i = 0; i < self.profilingSections[section].length; i++) {
	// 							data.push(self.profilingSections[section][i].genero);
	// 						}
	// 					break;
	// 					case 'edad':
	// 						name = pf.const.language.RSC1917;
	// 						idSection = 'sectionAge_' + i + '_' + n;
	// 						for(let i = 0; i < self.profilingSections[section].length; i++) {
	// 							data.push(self.profilingSections[section][i].edad);
	// 						}
	// 					break;
	// 					case 'region':
	// 						name = pf.const.language.RSC597;
	// 						idSection = 'sectionRegion_' + i + '_' + n;
	// 						for(let region in self.profilingSections[section]) {
	// 							data.push(region);
	// 						}
	// 					break;
	// 					case 'sec':
	// 						name = pf.const.language.RSC1990;
	// 						idSection = 'sectionNse_' + i + '_' + n;
	// 						for(let i = 0; i < self.profilingSections[section].length; i++) {
	// 							data.push(self.profilingSections[section][i].sec);
	// 						}
	// 					break;
	// 				}

	// 				// Elementos de perfilación - Inicialmente ocultos
	// 				let profilingSection = '';
	// 				let valueTotal = 0;
	// 				for(let j = 0; j < data.length; j++) {
	// 					let value = 0;
	// 					if(sizeSaved > 0) {
	// 						for(let e = 0; e < sizeSaved; e++) {
	// 							if(self.previousQuotaAllocation[e].segmento == segmentations[i][n].idSegmento) {
	// 								switch(section) {
	// 									case 'genero':
	// 										if(self.previousQuotaAllocation[e].genero == data[j]) {
	// 											value = self.previousQuotaAllocation[e].generoValue;
	// 										}
	// 									break;
	// 									case 'edad':
	// 										if(self.previousQuotaAllocation[e].rangoEdad == data[j]) {
	// 											value = self.previousQuotaAllocation[e].rangoEdadValue;
	// 										}
	// 									break;
	// 									case 'region':
	// 										if(self.previousQuotaAllocation[e].region == data[j]) {
	// 											value = self.previousQuotaAllocation[e].regionValue;
	// 										}
	// 									break;
	// 									case 'sec':
	// 										if(self.previousQuotaAllocation[e].rangoNSE == data[j]) {
	// 											value = self.previousQuotaAllocation[e].rangoNSEValue;
	// 										}
	// 									break;
	// 								}
	// 							}
	// 						}
	// 					}

	// 					let obj = {
	// 						name: data[j],
	// 						id: 'thirdLevelQ_' + i + '_' + n + '_' + section + '_' + j,
	// 						value: value
	// 					};
	// 					self.quotaElementsArray[indexArray].childs[indexProf].childs.push(obj);

	// 					valueTotal += parseInt(value);

	// 					profilingSection += `
	// 						<div class="card border-0">
	// 							<div class="card-body d-flex align-items-center border-0 collapse py-2 pa-le-5rem">
	// 								<span>${data[j]}</span>

	// 								<input id="thirdLevelQ_${i}_${n}_${section}_${j}" type="number" class="form-control ml-auto imputQuota thirdLevelQ secondLevelQ_${i}_${n}_${section} wi-100" value="${value}" title="${value}" data-group="secondLevelQ_${i}_${n}_${section}" data-span="secondLevelSpan_${i}_${n}_${section}">
	// 							</div>
	// 						</div>
	// 					`;
	// 				}
	// 				indexProf++;

	// 				// Perfilaciónes - Inicialmente ocultos
	// 				profilingElement += `
	// 					<div class="card border-0">
	// 						<div class="card-header d-flex align-items-center pl-5">
	// 							<span class="title-secondary">${name}</span>

	// 							<button type="button" class="btn btn-link text-body text-decoration-none arrowQuota py-0" data-toggle="collapse" data-target="#${idSection}" data-arrow="right" data-sub="2">
	// 								${stcmbackend.svg.chevronRight}
	// 							</button>

	// 							<span class="ml-auto">	
	// 								<span id="secondLevelSpan_${i}_${n}_${section}">${valueTotal}</span> / 
	// 								<span id="secondLevelQ_${i}_${n}_${section}" class="ml-auto spanQuota secondLevelQ firstLevelQ_${i}_${n} pr-3" data-group="firstLevelQ_${i}_${n}">${value}</span>
	// 							</span>
	// 						</div>

	// 						<div id="${idSection}" class="card-body p-0 border-0 collapse">
	// 							${profilingSection}
	// 						</div>
	// 					</div>
	// 				`;
	// 			}
	// 			indexArray++;

	// 			// Segmentos
	// 			let firstElement = `
	// 				<input id="firstLevelQ_${i}_${n}" type="number" class="form-control ml-auto imputQuota firstLevelQ wi-100" value="${value}" title="${value}">
	// 			`;
	// 			if(surveySelected) {
	// 				firstElement = '';
	// 			}

	// 			surveyOrSegmentation += `
	// 				<div class="card border-0">
	// 					<div class="card-header d-flex align-items-center">
	// 						<span class="title-secondary">${segmentations[i][n].Descripcion}</span>

	// 						<button type="button" class="btn btn-link text-body text-decoration-none arrowQuota py-0" data-toggle="collapse" data-target="#header_${i}_${n}" data-arrow="down" data-sub="2">
	// 							${stcmbackend.svg.chevronDown}
	// 						</button>

	// 						${firstElement}
	// 					</div>

	// 					<div id="header_${i}_${n}" class="card-body border-0 p-0 collapse show">
	// 						${profilingElement}
	// 					</div>
	// 				</div>
	// 			`;
	// 		}
	// 	}

	// 	if(surveySelected) {
	// 		$('#quotaValue').addClass('d-none');
	// 	} else {
	// 		$('#quotaValue').removeClass('d-none');
	// 		$('#usedQuota').text(totalSaved);
	// 		$('#usedQuota').removeClass('text-danger');
	// 	}

	// 	$('#tableQuotaContainer').html(surveyOrSegmentation);

	// 	// Collapse
	// 	$('.arrowQuota').on('click', function() {
	// 		let arrow = $(this).attr('data-arrow');
	// 		let direction = '';
	// 		if(arrow == 'right') {
	// 			direction = stcmbackend.svg.chevronDown;
	// 			$(this).attr('data-arrow', 'down');
	// 		} else {
	// 			direction = stcmbackend.svg.chevronRight;
	// 			$(this).attr('data-arrow', 'right');
	// 		}
	// 		$(this).html(direction);
	// 		let target = $(this).data('target');
	// 		$(target).collapse('toggle');
	// 	});

	// 	// Suma de los inputs de primer nivel al valor de cupo asignado solo para segmentaciones
	// 	$('.firstLevelQ').off().on('blur', function() {
	// 		if(!surveySelected) {
	// 			self.firstLevelQuotaControl(quota, $(this));
	// 		}
	// 	});

	// 	// Suma de los inputs de tercer nivel al valor de perfilación
	// 	$('.thirdLevelQ').off().on('blur', function() {
	// 		self.thirdLevelQuotaControl($(this));
	// 	});

	// 	// Aceptar Cupo
	// 	$('#acceptQuota').off().on('click', function() {
	// 		let allocable = parseInt(quota);

	// 		// Título de alertas
	// 		let titel = pf.const.language.RSC2126;
	// 		let content = '';

	// 		// Control de segmentos
	// 		let segmentsValue = 0;
	// 		for(let i = 0; i < self.quotaElementsArray.length; i++) {
	// 			segmentsValue += parseInt(self.quotaElementsArray[i].value);
	// 		}

	// 		if(segmentsValue !== allocable) {
	// 			if(segmentsValue > allocable) {
	// 				content = pf.const.language.RSC2146;
	// 			} else if(segmentsValue < allocable) {
	// 				content = pf.const.language.RSC2147;
	// 			}

	// 			pf.utils.showInfoDialog(titel, content);
	// 			return false;
	// 		}

	// 		let thirdLevelQControl = $('#tableQuotaContainer .is-invalid').length;
	// 		if(thirdLevelQControl > 0) {
	// 			content = pf.const.language.RSC2207;
	// 			pf.utils.showInfoDialog(titel, content);
	// 			return false;
	// 		}

	// 		self.modifiedQuota = true;
	// 		let newElement = true;
	// 		let size = self.quotaElementsArrayMissions.length;
	// 		for(let i = 0; i < size; i++) {
	// 			if(self.quotaElementsArrayMissions[i][0].stampMision == self.quotaElementsArray[0].stampMision) {
	// 				self.quotaElementsArrayMissions[i] = self.quotaElementsArray;
	// 				newElement = false;
	// 			}
	// 		}

	// 		if(newElement) {
	// 			self.quotaElementsArrayMissions.push(self.quotaElementsArray);
	// 		}

	// 		$('#modalQuota').modal('hide');
	// 	});
	// },

	renderQuotaTablesSurvey(quota, stampMision) {
		let self = this;

		var name = '';
		var idSection = '';
		
		let profilingElement = '';

		let objFirst = {
			stampMision: stampMision,
			surveys: $('#surveyProfiling').val(),
			idSegmentacion: 0,
			idSegmento: 0,
			id: 'firstLevelQ_0_0',
			childs: [],
			childClass: 'firstLevelQ_0_0',
			value: quota
		};
		self.quotaElementsArray.push(objFirst);

		var index = 0;
		for (var section in self.quota_details) {
			let data = [];
			let profilingSection = '';
			let value = 0;
			let sectionName = '';

			switch (section) {
				case 'gender':
					name = pf.const.language.RSC151;
					idSection = 'sectionGender_0_0';
					data = self.quota_details.gender;
					sectionName = 'genero';
					break;
				case 'age':
					name = pf.const.language.RSC1917;
					idSection = 'sectionAge_0_0';
					data = self.quota_details.age;
					sectionName = 'edad';
					break;
				case 'region':
					name = pf.const.language.RSC597;
					idSection = 'sectionRegion_0_0';
					data = self.quota_details.region;
					sectionName = 'region';
					break;
				case 'nse':
					name = pf.const.language.RSC1990;
					idSection = 'sectionNse_0_0';
					data = self.quota_details.nse;
					sectionName = 'sec';
					break;
			}

			let obj = {
				id: 'secondLevelQ_0_0_' + sectionName,
				childs: [],
				childClass: 'secondLevelQ_0_0_' + sectionName,
				value: quota
			};
			self.quotaElementsArray[0].childs.push(obj);

			var j = 0;
			let valueTotal = 0;
			for (var objData in data) {
				profilingSection += `
							<div class="card border-0">
								<div class="card-body d-flex align-items-center border-0 collapse py-2 pa-le-5rem">
									<span>${objData}</span>

									<input id="thirdLevelQ_0_0_${sectionName}_${j}" type="number" class="form-control ml-auto imputQuota thirdLevelQ secondLevelQ_0_0_${sectionName} wi-100" value="${data[objData].value}" title="${data[objData].value}" data-group="secondLevelQ_0_0_${sectionName}" data-span="secondLevelSpan_0_0_${sectionName}" data-max="${data[objData].max}">
									<div class="pl-2" style="width: 100px; text-align: right;"><strong>max. ${data[objData].max}</strong></div>
								</div>
							</div>
						`;

				valueTotal += data[objData].value;

				let obj = {
					name: objData,
					id: 'thirdLevelQ_0_0_' + sectionName + '_' + j,
					value: data[objData].value
				};
				self.quotaElementsArray[0].childs[index].childs.push(obj);
				j++;
			}

			value = quota;
			profilingElement += `
						<div class="card border-0">
							<div class="card-header d-flex align-items-center pl-5">
								<span class="title-secondary">${name}</span>

								<button type="button" class="btn btn-link text-body text-decoration-none arrowQuota py-0" data-toggle="collapse" data-target="#${idSection}" data-arrow="right" data-sub="2">
									${stcmbackend.svg.chevronRight}
								</button>

								<span class="ml-auto">	
									<span id="secondLevelSpan_0_0_${sectionName}">${valueTotal}</span> / 
									<span id="secondLevelQ_0_0_${sectionName}" class="ml-auto spanQuota secondLevelQ firstLevelQ_0_0 pr-3" data-group="firstLevelQ_0_0">${value}</span>
								</span>
							</div>

							<div id="${idSection}" class="card-body p-0 border-0 collapse">
								${profilingSection}
							</div>
						</div>
			`;
			
			index++;
		}
	
		let surveyOrSegmentation = `
					<div class="card border-0">
						<div class="card-header d-flex align-items-center">
							<span class="title-secondary">${pf.const.language.RSC2206}</span>

							<button type="button" class="btn btn-link text-body text-decoration-none arrowQuota py-0" data-toggle="collapse" data-target="#header_0_0" data-arrow="down" data-sub="2">
								${stcmbackend.svg.chevronDown}
							</button>
						</div>

						<div id="header_0_0" class="card-body border-0 p-0 collapse show">
							${profilingElement}
						</div>
					</div>
		`;

		$('#quotaValue').addClass('d-none');
		$('#tableQuotaContainer').html(surveyOrSegmentation);

		// Collapse
		$('.arrowQuota').on('click', function() {
			let arrow = $(this).attr('data-arrow');
			let direction = '';
			if(arrow == 'right') {
				direction = stcmbackend.svg.chevronDown;
				$(this).attr('data-arrow', 'down');
			} else {
				direction = stcmbackend.svg.chevronRight;
				$(this).attr('data-arrow', 'right');
			}
			$(this).html(direction);
			let target = $(this).data('target');
			$(target).collapse('toggle');
		});

		// Suma de los inputs de tercer nivel al valor de perfilación
		$('.thirdLevelQ').off().on('blur', function() {
			self.thirdLevelQuotaControl($(this));
		});

		// Aceptar Cupo
		$('#acceptQuota').off().on('click', function() {
			// Título de alertas
			let titel = pf.const.language.RSC2126;
			let content = '';

			let thirdLevelQControl = $('#tableQuotaContainer .is-invalid').length;
			if(thirdLevelQControl > 0) {
				content = pf.const.language.RSC2207;
				pf.utils.showInfoDialog(titel, content);
				return false;
			}

			self.modifiedQuota = true;
			let newElement = true;
			let size = self.quotaElementsArrayMissions.length;
			for(let i = 0; i < size; i++) {
				if(self.quotaElementsArrayMissions[i][0].stampMision == self.quotaElementsArray[0].stampMision) {
					self.quotaElementsArrayMissions[i] = self.quotaElementsArray;
					newElement = false;
				}
			}

			if(newElement) {
				self.quotaElementsArrayMissions.push(self.quotaElementsArray);
			}

			$('#modalQuota').modal('hide');
		});
	},

	firstLevelQuotaControl(quota, element) {
		let self = this;

		let id = element.attr('id');
		let inputValue = element.val();
		let allocable = parseInt(quota);

		// Control para input vacío
		if(inputValue === '') {
			inputValue = 0;
		}
		let value = parseInt(inputValue);

		// Control para números no enteros
		if(value < 0 || value === NaN) {
			value = 0;
		}

		$(this).val(value);
		$('.' + id).text(value);

		let totalUsed = 0;
		$('.firstLevelQ').each(function() {
			let inputValue = $(this).val();
			// Control para input vacío
			if(inputValue === '') {
				inputValue = 0;
			}

			totalUsed += parseInt(inputValue);
		});

		$('#usedQuota').text(totalUsed);

		// Control de valores generales
		if(totalUsed !== allocable) {
			$('#usedQuota').addClass('text-danger');
			$('.firstLevelQ').addClass('is-invalid');
		} else {
			$('#usedQuota').removeClass('text-danger');
			$('.firstLevelQ').removeClass('is-invalid');
		}

		// Control de valores inferiores
		$('.' + id).each(function() {
			let goup = $(this).attr('id');
			let sectionUsed = 0;
			$('.' + goup).each(function() {
				let spanValue = $(this).val();

				sectionUsed += parseInt(spanValue);
			});

			if(sectionUsed !== value && sectionUsed !== 0) {
				$('.' + goup).addClass('is-invalid');
			} else {
				$('.' + goup).removeClass('is-invalid');
			}
		});

		let sizeA = self.quotaElementsArray.length;
		for(let i = 0; i < sizeA; i++) {
			if(self.quotaElementsArray[i].id == id) {
				self.quotaElementsArray[i].value = value;
				break;
			}
		}
	},

	thirdLevelQuotaControl(element) {
		let self = this;

		let id = element.attr('id');
		let group = element.data('group');
		let span = element.data('span');
		let inputValue = element.val();
		let parentValue = parseInt($('#' + group).text());

		// Control para input vacío
		if(inputValue === '') {
			inputValue = 0;
		}
		let value = parseInt(inputValue);

		// Control para números no enteros
		if(value < 0 || value === NaN) {
			value = 0;
		}

		$(this).val(value);

		let totalUsed = 0;
		let arrayMax = [];
		$('.' + group).each(function() {
			let inputValue = $(this).val();
			let inputMax = $(this).data('max');
			// Control para input vacío
			if(inputValue === '') {
				inputValue = 0;
			}

			totalUsed += parseInt(inputValue);

			if (inputValue > inputMax) {
				arrayMax.push($(this));
			}
		});

		$('#' + span).text(totalUsed);

		// Control de valores específicos
		if(totalUsed !== parentValue && totalUsed !== 0) {
			$('.' + group).addClass('is-invalid');
		} else {
			$('.' + group).removeClass('is-invalid');
		}
		
		//control max values
		arrayMax.forEach(element => {
			element.addClass('is-invalid');
		});

		let sizeA = self.quotaElementsArray.length;
		for(let i = 0; i < sizeA; i++) {
			let sizeB = self.quotaElementsArray[i].childs.length;
			for(let j = 0; j < sizeB; j++) {
				if(self.quotaElementsArray[i].childs[j].id == group) {
					self.quotaElementsArray[i].childs[j].value = totalUsed;

					let siceC = self.quotaElementsArray[i].childs[j].childs.length;
					for(let n = 0; n < siceC; n++) {
						if(self.quotaElementsArray[i].childs[j].childs[n].id == id) {
							self.quotaElementsArray[i].childs[j].childs[n].value = value;
							break;
						}
					}
				}
			}
		}
	},

	deliveryMissionsModal(advisers) {
		let self = this;

		$('#modalDeliveryMissions').modal('show');

		let table = `
			<table id="tableDeliveryMissions" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					</tr>
				</thead>

				<thead class="filtersDeliveryMissions">
					<tr>
						<td>nombre</td>
						<td>mail</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = advisers.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${advisers[i].idUser}">${advisers[i].idUser}</td>
					<td class="text-truncate" title="${advisers[i].emailUser}">${advisers[i].emailUser}</td>
				</tr>
			`;
		}

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

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

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

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

		let deliveryMissionsTable = $('#tableDeliveryMissions').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2229,
				className: 'd-none',
				title: pf.const.language.RSC2229,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

		setTimeout(function() {
			deliveryMissionsTable.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(deliveryMissionsTable, 'filtersDeliveryMissions');

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

	// Control de repartición de misiones
	acceptDeliveryMissionsControl() {
		let total = 0;

		$('#tableMissions .percentageDelivery').each(function() {
			let inputValue = $(this).val();

			// Control para input vacío
			if(inputValue === '') {
				inputValue = 0;
			}

			total += parseInt(inputValue);
		});

		if(total != 100) {
			$('#tableMissions .percentageDelivery').addClass('is-invalid');

			let titel = pf.const.language.RSC2229;
			let content = pf.const.language.RSC2230;

			pf.utils.showInfoDialog(titel, content);

			return false;
		} else {
			$('#tableMissions .percentageDelivery').removeClass('is-invalid');

			let missionDelivery = [];
			$('#tableMissions .percentageDelivery').each(function() {
				let stampMision = $(this).data('stampmision');
				let inputValue = $(this).val();

				// Control para input vacío
				if(inputValue === '') {
					inputValue = 0;
				}

				let obj = {
					missionStamp: stampMision,
					cuotaReparto: inputValue
				};

				missionDelivery.push(obj);
			});

			return missionDelivery;
		}
	}
};