let MisionesEditController = {
	userJSON: null,
	user: null,
	idMission: '',
	data: '',
	objectives: '',
	typeOptions: [],
	objetive: '',
	index: '',
	surveys: '',
	templates: '',
	country: '',
	requestType: '',
	products: '',
	productsModal: '',
	productsAmountModal: '',
	remindersTableArray: [],
	usuarioQueNotifica: '',
	descUsuarioQueNotifica: '',
	userMail: '',
	remindersChange: false,
	remindersId: [],
	missionState: '',
	stamp: '',
	loaders: {},
	// Todos los valores devueltos por getTargetsSurvey
	questionDiscriminatoryArray: [],
	// Preguntas seleccionadas
	selectedQuestions: [],
	// ID de preguntas seleccionadas
	selectedQuestionsID: [],
	// Valores para crear el selector de respuestas
	surveyValues: '',
	// Valores de control de pregunta
	columnName: '',
	columnNameK: '',
	// Control de si ya hay exclusiones
	misionQuestionsArrayControl: '0',
	manualClosing: '0',
	manualClosingText: '',
	isInclusive: false,
	button: null,
	projectList: [],
	isSurvey: false,
	missionCompleted: 0,
	reopeningMessage: '',
	projectListID: [],
	ListaDistribucionID: '',
	dateFormat: '',
	// Misiones anidadas
	nestableMissions: [],
	nestedMission: null,
	nestedMissionOld: '',
	// Archivos .js de otras secciones
	samplingFile: null,
	samplingDetailedFile: null,
	samplingDynamicFile: null,
	complianceFile: null,

	reset() {
		let self = this;

		self.userJSON = null;
		self.user = null;
		self.idMission = atob(sessionStorage.getItem('idMission'));
		self.data = '';
		self.objectives = '';
		self.typeOptions = [];
		self.objetive = '';
		self.index = '';
		self.surveys = '';
		self.templates = '';
		self.country = '';
		self.requestType = '';
		self.products = '';
		self.productsModal = '';
		self.productsAmountModal = '';
		self.remindersTableArray = [];
		self.usuarioQueNotifica = '';
		self.descUsuarioQueNotifica = '';
		self.userMail = '';
		self.remindersChange = false;
		self.remindersId = [];
		self.missionState = atob(sessionStorage.getItem('idMissionState'));
		self.stamp = atob(sessionStorage.getItem('idMissionStamp'));
		self.loaders = {
			getAllTipoMision: false,
			getMision: false,
			getMisionesObjetivos: false,
			getMisionRemember: false,
			getPaisesEnabled: false,
			getMisionesProjects: false,
			getAllTipoMisionObjetivos: false,
			getMisionQuestionNoAccomplish: false
		};
		// Todos los valores devueltos por getTargetsSurvey
		self.questionDiscriminatoryArray = [];
		// Preguntas seleccionadas
		self.selectedQuestions = [];
		// ID de preguntas seleccionadas
		self.selectedQuestionsID = [];
		// Valores para crear el selector de respuestas
		self.surveyValues = '';
		// Valores de control de pregunta
		self.columnName = '';
		self.columnNameK = '';
		// Control de si ya hay exclusiones
		self.misionQuestionsArrayControl = '0';
		self.manualClosing = '0';
		self.manualClosingText = '';
		self.isInclusive = false;
		self.button = null;
		self.projectList = [];
		self.isSurvey = false;
		self.missionCompleted = 0;
		self.reopeningMessage = '';
		self.projectListID = [];
		self.ListaDistribucionID = '';
		self.dateFormat = '';
		// Misiones anidadas
		self.nestableMissions = [];
		self.nestedMission = null;
		self.nestedMissionOld = '';
		// Archivos .js de otras secciones
		self.samplingFile = null;
		self.samplingDetailedFile = null;
		self.samplingDynamicFile = null;
		self.complianceFile = null;
	},

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

		// Información de administrador
		self.userJSON = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let userMail = self.userJSON.email;
		self.userMail = userMail;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');
		self.dateFormat = self.userJSON.formatoFecha;

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.usuarioQueNotifica = config.SYSNotifUser;
		self.descUsuarioQueNotifica = config.SYSNotifUserName;

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

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

		// Opciones de header
		let jsonsubopt = {
			back: 'backMissions',
			save: 'saveMission',
			close: 'closeMission'
		};

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

			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

		// Botones secundarios
		$('#backMissions').addClass('secondary-button');
		$('#closeMission').addClass('secondary-button');

		// Pestañas y contenedores de inicio ocultas
		$('#editMissionTabs .tab-button').hide();
		$('#samplingContainer').hide();
		$('#samplingDetailedContainer').hide();
		$('#samplingDynamicContainer').hide();
		$('#complianceContainer').hide();

		// Mostrar pestaña de información
		$('#infoTab').show();

		// Estado de la misión
		let stateText = atob(sessionStorage.getItem('idMissionStateText'));
		$('#missionState').val(stateText);
		$('#missionState').attr('title', stateText);

		// Candado
		$('#endMissionPermitsContainer').hide();

		// Misión cerrada manualmente oculto
		$('#manualClosing').hide();

		/* Estados de mision
			0 -> No empezada
			1 -> En curso
			2 -> Finalizada
		*/
		// Desabilitación para misiones en curso y finalizadas
		if(self.missionState === '0') {
			$('.state').prop('disabled', false);
			$('#searchCustomer').prop('disabled', false);
		} else {
			$('.state').prop('disabled', true);
			$('#searchCustomer').prop('disabled', true);
			$('#endTime').parent().addClass('div-disabled');

			// Mostrar pestaña de cumplimiento
			$('#complianceTab').show();

			if(self.missionState === '1') {
				self.missionCompleted = 0;
			} else {
				self.missionCompleted = 1;
			}

			// Candado
			$('#endMissionPermitsContainer').show();
		}

		// Si la misión está en curso mostrar el boton de cerrar misión
		if(self.missionState != '1') {
			$('#closeMission').removeClass('d-flex');
			$('#closeMission').addClass('d-none');
		}

		// Ocultar elemento si no se trabaja con clientes
		if(sessionStorage['STCMBackEnd:globalWorkingwithClients'] == 'false') {
			$('#customersContainer').hide();
		}

		addLoader();
		ajaxComunCallWithCallback('getAllTipoMision', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.typeOptions = ajaxReturn.result;

				self.renderTypes();
				self.getMision();

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

		self.loadLang();
		self.applyEvents();

		// Ocultar de inicio sección de respuestas de auto no cumplimiento
		$('#selfNonComplianceContainer').hide();
		$('#responseControl').hide();
		$('#responseControlMessage').hide();

		// Collapse
		addEventArrowTableHeader();

		// Pintar texto de label
		changeLabelsColor();

		// Archivos .js de otras secciones
		// Muestreo
		self.samplingFile = MuestreoController;
		self.samplingFile.setEvents('-me-sam');
		// Muestreo detallado
		self.samplingDetailedFile = MuestreoDetalladoController;
		self.samplingDetailedFile.setEvents('-me-sam-det');
		// Muestreo dinámico
		self.samplingDynamicFile = MuestreoDinamicoController;
		self.samplingDynamicFile.setEvents('-me-sam-dyn');
		// Cumplimiento
		self.complianceFile = CumplimientosController;
		self.complianceFile.setEvents('-me-com');
	},

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

		// TITLES
		$('.addTitle').attr('title', pf.const.language.RSC93);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
		$('#infoTab').attr('title', pf.const.language.RSC1314);
		$('#samplingTab').attr('title', pf.const.language.RSC35);
		$('#samplingDetailedTab').attr('title', pf.const.language.RSC963);
		$('#samplingDynamicTab').attr('title', pf.const.language.RSC2426);
		$('#complianceTab').attr('title', pf.const.language.RSC33);

		// Añadir textos
		$('#continuingMissionTooltip').attr('title', pf.const.language.RSC2504);
	},

	applyEvents() {
		let self = this;

		// Cambio de pestañas
		$('#editMissionTabs .tab-button').on('click', function() {
			$('#editMissionTabs .tab-button').removeClass('activeTB');
			$(this).addClass('activeTB');

			// Ocultar todas las secciones
			$('.tabContainer').hide();

			// Mostrar la sección activa
			let id = $(this).data('id');
			$('#' + id).show();

			// Carga de gráfica en la pestaña de cumplimiento
			if(id === 'complianceContainer') {
				self.complianceFile.idProject = self.projectListID[0];
				self.complianceFile.idMission = self.idMission;
				addLoader();
				ajaxComunCallWithCallback('getCMBPProjects', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						CumplimientosController.project = ajaxReturn.result;
					}
				}, false);
				self.complianceFile.getSnapAcualMisionCumplimiento();
			} else if(id === 'samplingContainer') {
				// Misión continua
				self.samplingFile.isContinuing = self.data.continuingMission;
				if(self.data.continuingMission == '1') {
					$('#startDate' + self.suffix).parent().show();
					$('#endDate' + self.suffix).parent().show();
				} else {
					$('#startDate' + self.suffix).parent().hide();
					$('#endDate' + self.suffix).parent().hide();
				}

				self.samplingFile.idPoll = $('.survey').val();
				self.samplingFile.isPerf = '0';
				self.samplingFile.idMission = self.idMission;
				self.samplingFile.stampMision = self.stamp;
				self.samplingFile.project = self.projectListID[0];
			} else if(id === 'samplingDetailedContainer') {
				$('#poll-me-sam-det').val(self.idMission);
				self.samplingDetailedFile.idPoll = $('.survey').val();
				self.samplingDetailedFile.isPerf = '0';
				self.samplingDetailedFile.country = self.country.isocode;
			} else if(id === 'samplingDynamicContainer') {
				self.samplingDynamicFile.getPlantillaReportesByDefault();

				// Misión continua
				self.samplingDynamicFile.isContinuing = self.data.continuingMission;
				if(self.samplingDynamicFile.isContinuing == '1') {
					$('#startDate' + self.suffix).parent().show();
					$('#endDate' + self.suffix).parent().show();
				} else {
					$('#startDate' + self.suffix).parent().hide();
					$('#endDate' + self.suffix).parent().hide();
				}
				
				// Datos de misión
				self.samplingDynamicFile.idPoll = $('.survey').val();
				self.samplingDynamicFile.isPerf = '0';
				self.samplingDynamicFile.idMission = self.idMission;
				self.samplingDynamicFile.stampMision = self.stamp;
				self.samplingDynamicFile.project = self.projectListID[0];
			}
		});

		// Uso de comisión
		$('#usaComision').off().on('change', function() {
			if($('#usaComision').prop('checked')) {
				$('.commission').prop('disabled', false);
			} else {
				$('.commission').prop('disabled', true);
				$('#missionCommission').val('');
			}
		});

		// Misión inicial
		$('#initialMission').off().on('change', function() {
			if($('#initialMission').prop('checked')) {
				// Si es inicial tambien es siempre vigente
				$('#alwaysCurrent').prop('checked', true);
				$('#alwaysCurrent').prop('disabled', true);
				$('#alwaysCurrent').trigger('change');
			} else {
				$('#alwaysCurrent').prop('disabled', false);

				if(!$('#alwaysCurrent').prop('checked')) {
					// Se reactiva la opción de misión anidada
					$('#nestedMission').prop('disabled', false);
				}
			}
		});

		// Misión continua
		$('#continuingMission').off().on('change', function() {
			if($('#continuingMission').prop('checked')) {
				$('#alwaysCurrent').prop('checked', false);
				$('#alwaysCurrent').trigger('change');
				$('#alwaysCurrent').prop('disabled', true);
				$('#needValidation').prop('checked', true);
				$('#needValidation').trigger('change');
			} else {
				$('#alwaysCurrent').prop('disabled', false);
			}
		});

		// Siempre vigente
		$('#alwaysCurrent').off().on('change', function() {
			if($('#alwaysCurrent').prop('checked')) {
				$('#dateTimeContainer').hide();
				$('#startDate').val('1982-06-19');
				$('#endDate').val('2700-12-31');

				// Para las encuestas
				if(self.typeOptions[self.index].isSurvey == '1') {
					$('#answersLimitContainer').addClass('d-none');
					$('#answersQuotaContainer').addClass('d-none');
					$('#answersLimit').prop('checked', false);
					$('#numMaxUsers').val('');
					$('#numMaxUsers').prop('disabled', true);
					$('#missionClosed').val('');
					$('#missionClosed').prop('disabled', true);
				}

				// No puede ser misión anidada
				$('#nestedMission').prop('checked', false);
				$('#nestedMission').prop('disabled', true);
				$('#nestableQuests').val('');
				$('#nestableQuestsStamp').text('');
			} else {
				$('#dateTimeContainer').show();
				let dateTimeStartArray = self.data.fechahorainicio.split('#');
				let dateStartArray = dateTimeStartArray[0].split('/');
				$('#startDate').val(dateStartArray[2] + '-' + dateStartArray[1] + '-' + dateStartArray[0]);
				$('#startTime').val(dateTimeStartArray[1] + ':' + dateTimeStartArray[2]);

				let dateTimeEndArray = self.data.fechahorafin.split('#');
				let dateEndArray = dateTimeEndArray[0].split('/');
				$('#endDate').val(dateEndArray[2] + '-' + dateEndArray[1] + '-' + dateEndArray[0]);
				$('#endTime').val(dateTimeEndArray[1] + ':' + dateTimeEndArray[2]);

				// Para las encuestas
				if(self.typeOptions[self.index].isSurvey == '1' && self.index != '') {
					$('#answersLimitContainer').removeClass('d-none');
					$('#answersQuotaContainer').removeClass('d-none');
					$('#numMaxUsers').prop('disabled', false);
					$('#missionClosed').prop('disabled', false);
				}

				// Se reactiva la opción de misión anidada
				$('#nestedMission').prop('disabled', false);
			}
		});

		// 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);
		});

		// Restricciones del carácter # por tecla para el Texto inicio de misión
		$('#missionStartText').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.RSC1999, /[^#]/i);

			return result;
		});

		// Restricciones del carácter # por pegado para el Texto inicio de misión
		$('#missionStartText').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1999, /[#]/gi);
		});

		//tipo misión 
		$('#searchMisionType').off().on('click', function() {
			// Ocultar sección de respuestas de auto no cumplimiento y borrar tabla de preguntas
			$('#selfNonComplianceContainer').hide();
			$('#responseControl').hide();
			$('#responseControlContainer').html('');
			$('#responseControlMessage').hide();
			$('#autoNonComplianceMessage').val('');
			$('#importenocumplimiento').val('');
			self.questionDiscriminatoryArray = [];
			self.selectedQuestions = [];
			self.selectedQuestionsID = [];

			$('#missionTypeTable').modal('show', true);
		});

		$('#missionTypeTable').on('show.bs.modal', function(e) {
			setTimeout(function() {
				$($.fn.dataTable.tables(true)).DataTable().columns.adjust();
			}, 200);
		});

		// Vover a Listas de misiones
		$('#backMissions').on('click', function() {
			window.location.href = '#!misiones';
		});

		// Editar misión
		$('#saveMission').on('click', function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC14;
			let alertText = pf.const.language.RSC317;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				// Comprobación de misiones referidas
				let tipomision = self.typeOptions[self.index].idTipoMision;
				if(tipomision == 'Referidos') {
					self.existsMisionBetweenDates();
				} else {
					// Comprobación cupo/cumplimiento - Edición de misión tipo encuesta
					if($('#numMaxUsers').val() != 0 && self.data.finmisioncupo != $('#numMaxUsers').val() && self.isSurvey) {
						let parameters = {
							stampMision: self.stamp
						};
						ajaxComunCallWithCallback('getMisionesProjects', parameters, function(ajaxReturn) {
							if(ajaxReturn) {
								self.projectList = ajaxReturn.result.map(project => project.id);
								if(self.projectList.length > 0) {
									let parameters = {
										projects: self.projectList,
										mision: self.idMission
									};
									ajaxComunCallWithCallback('getCumplimientoMision', parameters, function(ajaxReturn) {
										if(ajaxReturn) {
											if($('#numMaxUsers').val() != 0 && $('#numMaxUsers').val() < ajaxReturn.result) {
												$('#numMaxUsers').attr('min', ajaxReturn.cumplimiento);
												let alertTitle = pf.const.language.RSC2125;
												let alertText = pf.const.language.RSC2130;
												pf.utils.showInfoDialog(alertTitle, alertText);
											} else {
												self.editMission();
											}
										}
									}, true);
								} else {
									self.editMission();
								}
							}
						}, true);
					} else {
						self.editMission();
					}
				}
			}, function() {});
		});

		// Cambiar el país
		let countryModal = new TableCountries(0, 'editMissionCountry');
		$('#searchCountry').off().on('click', function() {
			self.requestType = 'country';
			countryModal.setEvents();
		});

		// Cliente
		let customerModal = new TableCustomers('editMissionCustomer');
		$('#searchCustomer').off().on('click', function() {
			self.requestType = 'customer';
			customerModal.setEvents();
		});

		// Añadir recordatorio
		$('#newRecordatorio').off().on('click', function() {
			let obj = {
				date: '',
				time: '',
				message: '',
				lastRun: ''
			};
			self.remindersTableArray.push(obj);
			self.tableRecordatorios();
		});

		//Validación
		$('#needValidation').off().on('change', function() {
			let needValidation = $('#needValidation').prop('checked');
			if(needValidation) {
				$('#validation').removeClass('d-none');
			} else {
				$('#continuingMission').prop('checked', false);
				$('#validationText').val('');
				$('#validation').addClass('d-none');
			}
		});

		// Misión anidada
		$('#nestedMission').off().on('change', function() {
			let nestedMission = $('#nestedMission').prop('checked');

			if(nestedMission) {
				$('#nestedMissionDivContainer').show();

				// Programación
				$('#programacionContainer').hide();

				$('#startDate').val('');
				$('#startTime').val('');
				$('#endDate').val('');
				$('#endTime').val('');
			} else {
				$('#nestedMissionDivContainer').hide();
				$('#nestableQuests').val('');
				$('#nestableQuestsStamp').text('');

				// Programación
				$('#programacionContainer').show();

				let dateTimeStartArray = self.data.fechahorainicio.split('#');
				let dateStartArray = dateTimeStartArray[0].split('/');
				$('#startDate').val(dateStartArray[2] + '-' + dateStartArray[1] + '-' + dateStartArray[0]);
				$('#startTime').val(dateTimeStartArray[1] + ':' + dateTimeStartArray[2]);

				let dateTimeEndArray = self.data.fechahorafin.split('#');
				let dateEndArray = dateTimeEndArray[0].split('/');
				$('#endDate').val(dateEndArray[2] + '-' + dateEndArray[1] + '-' + dateEndArray[0]);
				$('#endTime').val(dateTimeEndArray[1] + ':' + dateTimeEndArray[2]);
			}
		});

		// Misiones anidables
		$('#searchNestableQuests').off().on('click', function() {
			self.nestableMissions = [];

			ajaxComunCallWithCallback('getAllMisiones', {}, function(ajaxReturn) {
				if(ajaxReturn) {
					// 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 size = ajaxReturn.result.length;
					for(let i = 0; i < size; i++) {
						// Fecha y hora de inicio de misión
						let dateStart = '';
						if(ajaxReturn.result[i].fechahorainicio != '') {
							let startDateTime = ajaxReturn.result[i].fechahorainicio.split('#');
							let startDateArray = startDateTime[0].split('/');
							dateStart = new Date(startDateArray[2], startDateArray[1]-1, startDateArray[0], startDateTime[1], startDateTime[2].substring(2, 0));
						}

						// Comprobación de misiones de encuestas que no hayan empezado y no sean anidadas
						if(ajaxReturn.result[i].encuesta == '1' && nowDate < dateStart && ajaxReturn.result[i].tipoAnidada == '0') {
							self.nestableMissions.push(ajaxReturn.result[i]);
						}
					}

					self.renderNestableMissions();
				}
			});

			$('#nestableMissionsModal').modal('show', true);
		});

		// Límite de respuestas
		$('#answersLimit').off().on('change', function() {
			let hasAnswerLimit = $('#answersLimit').prop('checked');

			if(hasAnswerLimit) {
				$('.answersQuotaContainer').removeClass('d-none');
			} else {
				$('#numMaxUsers').val('');
				$('#missionClosed').val('');
				$('.answersQuotaContainer').addClass('d-none');
			}
		});

		// Abrir fecha y hora de fin de misión para misiones en curso
		$('#endMissionPermits').off().on('click', function() {
			if(self.missionCompleted == 1) {
				let content = `
					<p>${pf.const.language.RSC2210}</p>
					<input id="textNotifImput" type="text" class="form-control" value="${pf.const.language.RSC2211}" title="${pf.const.language.RSC2211}">
				`;

				$.alert({
					boxWidth: '500px',
					title: '<h3 class="ma-bo-20">' + pf.const.language.RSC14 + '</h3>',
					content: content,
					useBootstrap: false,
					bgOpacity: null,
					theme: 'new-style',
					buttons: {
						accept: {
							text: pf.const.language.RSC141,
							btnClass: 'new-style-accept',
							action() {
								self.reopeningMessage = $('#textNotifImput').val().trim();

								if(self.reopeningMessage != '') {
									if(self.reopeningMessage != pf.const.language.RSC2211) {
										self.editRSC(self.reopeningMessage);
									}

									// Candado
									$('#endMissionPermitsContainer').hide();
									$('#endDate').prop('disabled', false);
									$('#endTime').prop('disabled', false);
									$('#endTime').parent().removeClass('div-disabled');
								} else {
									$('#textNotifImput').addClass('is-invalid');
									$('[for="textNotifImput"]').addClass('is-invalid');
									return false;
								}
							}
						},
						cancel: {
							text: pf.const.language.RSC57,
							btnClass: 'new-style-cancel',
							action() {
								//
							}
						}
					}
				});
			} else {
				let objInfo = {
					accept: {
						text: pf.const.language.RSC141
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC14;
				let alertText = pf.const.language.RSC1802;

				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					// Candado
					$('#endMissionPermitsContainer').hide();
					$('#endDate').prop('disabled', false);
					$('#endTime').prop('disabled', false);
					$('#endTime').parent().removeClass('div-disabled');
				}, function() {});
			}
		});

		// Petición de preguntas y respuestas
		$('#newQuestionAnswers').off().on('click', function() {
			if(self.questionDiscriminatoryArray.length === 0) {
				// Si no hay valores, pedir los valores de la encuesta
				self.getTargetsSurvey(false);
			} else {
				// Si ya hay valores mostrar las preguntas disponibles
				self.renderQuests();
			}

			$('#targetsSurveyModal').modal('show', true);
		});

		// Cerrar misión activa
		$('#closeMission').off().on('click', function() {
			self.showEndReasonAlert(function() {
				let endReason = $('#endReason').val().trim();

				if(endReason != '') {
					// Finalización de misión
					self.manualClosing = '1';
					self.manualClosingText = endReason;
					self.editMission();
				} else {
					$('#endReason').addClass('is-invalid');
					$('[for="endReason"]').addClass('is-invalid');
					return false;
				}
			});
		});
	},

	// Cambios para pedir misión por stampMision
	getMision() {
		let self = this;

		let parameters = {
			stampMision: self.stamp
		};
		ajaxComunCallWithCallback('getMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result[0];
				self.country = {
					isocode: self.data.country,
					currency: self.data.currency,
					defaultCountryCurrency: self.data.defaultCountryCurrency
				}

				let parameters = {
					idmision: self.idMission
				};
				ajaxComunCallWithCallback('getMisionesObjetivos', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.objectives = ajaxReturn.result;

						self.renderData();

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

				self.getMisionRemember();
				$('#projectCountry').val(self.data.country);
				$('#customers').val(self.data.razonSocial);
				$('#customers').data('id', self.data.idCliente);

				self.getPaisesEnabled();

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

	getMisionQuestionNoAccomplish() {
		let self = this;

		let parameters = {
			idmision: self.idMission
		};
		ajaxComunCallWithCallback('getMisionQuestionNoAccomplish', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				let sizeJ = self.questionDiscriminatoryArray.length;
				let mQuests = '';
				let mCode = [];
				let mCodeInclusive = [];
				let mValue = [];
				let mValueInclusive = [];

				for(let i = 0; i < size; i++) {
					// Comprobar si la pregunta es incluye SQ
					if(ajaxReturn.result[i].ColumnName.includes('SQ')) {
						let columNameArray = ajaxReturn.result[i].ColumnName.split('SQ');
						// Comprobar si no hay registro de pregunta con SQ anterior
						if(mQuests === '') {
							// Guardar los valores
							mQuests = columNameArray[0];
							if(ajaxReturn.result[i].Value) {
								mCode.push('SQ' + columNameArray[1]);
								mValue.push(ajaxReturn.result[i].Value);
							}
							if(ajaxReturn.result[i].ValueInc) {
								mCodeInclusive.push('SQ' + columNameArray[1]);
								mValueInclusive.push(ajaxReturn.result[i].ValueInc);
							}
						} else if(mQuests === columNameArray[0]) {
							// Si es igual a la anterior se siguen guardando los valores
							if(ajaxReturn.result[i].Value) {
								mCode.push('SQ' + columNameArray[1]);
								mValue.push(ajaxReturn.result[i].Value);
							}
							if(ajaxReturn.result[i].ValueInc) {
								mCodeInclusive.push('SQ' + columNameArray[1]);
								mValueInclusive.push(ajaxReturn.result[i].ValueInc);
							}
						} else {
							// En caso de cambio de pregunta pero que también tenga SQ
							self.selectedQuestionsID.push(mQuests);

							for(let j = 0; j < sizeJ; j++) {
								if(mQuests == self.questionDiscriminatoryArray[j].columnName) {
									let obj = self.questionDiscriminatoryArray[j];
									if(mCode && mValue) {
										obj.code = mCode;
										obj.value = mValue;
									}
									if(mCodeInclusive && mValueInclusive) {
										obj.codeInclusive = mCodeInclusive;
										obj.valueInclusive = mValueInclusive;
									}
									self.selectedQuestions.push(obj);
								}
							}

							mCode = [];
							mValue = [];
							mCodeInclusive = [];
							mValueInclusive = [];

							mQuests = columNameArray[0];
							
							if(ajaxReturn.result[i].Value) {
								mCode.push('SQ' + columNameArray[1]);
								mValue.push(ajaxReturn.result[i].Value);
							}
							if(ajaxReturn.result[i].ValueInc) {
								mCodeInclusive.push('SQ' + columNameArray[1]);
								mValueInclusive.push(ajaxReturn.result[i].ValueInc);
							}
						}
					} else if(mQuests !== '') {
						// Si la pregunta actual no tiene SQ pero hay una anterior
						self.selectedQuestionsID.push(mQuests);

						for(let j = 0; j < sizeJ; j++) {
							if(mQuests == self.questionDiscriminatoryArray[j].columnName) {
								let obj = self.questionDiscriminatoryArray[j];
								if(mCode && mValue) {
									obj.code = mCode;
									obj.value = mValue;
								}
								if(mCodeInclusive && mValueInclusive) {
									obj.codeInclusive = mCodeInclusive;
									obj.valueInclusive = mValueInclusive;
								}
								self.selectedQuestions.push(obj);
							}
						}

						mQuests = '';
						mCode = [];
						mCodeInclusive = [];
						mValue = [];
						mValueInclusive = [];

						// Pregunta sin SQ
						self.selectedQuestionsID.push(ajaxReturn.result[i].ColumnName);

						for(let j = 0; j < sizeJ; j++) {
							if(ajaxReturn.result[i].ColumnName == self.questionDiscriminatoryArray[j].columnName) {
								let obj = self.questionDiscriminatoryArray[j];

								obj.code = ajaxReturn.result[i].ValueCodes.split(',');
								obj.value = ajaxReturn.result[i].Value.split(',');
								obj.codeInclusive = ajaxReturn.result[i].ValueCodesInc.split(',');
								obj.valueInclusive = ajaxReturn.result[i].ValueInc.split(',');

								self.selectedQuestions.push(obj);
							}
						}
					} else {
						// Pregunta sin SQ
						self.selectedQuestionsID.push(ajaxReturn.result[i].ColumnName);

						for(let j = 0; j < sizeJ; j++) {
							let elementArray = ajaxReturn.result[i].ColumnName.split('M');

							if(elementArray[0].replace('Y', '') == self.questionDiscriminatoryArray[j].columnName) {
								let obj = self.questionDiscriminatoryArray[j];

								obj.code = ajaxReturn.result[i].ValueCodes.split(',');
								obj.value = ajaxReturn.result[i].Value.split(',');
								obj.codeInclusive = ajaxReturn.result[i].ValueCodesInc.split(',');
								obj.valueInclusive = ajaxReturn.result[i].ValueInc.split(',');

								self.selectedQuestions.push(obj);
							}
						}
					}
				}

				// En caso de que la última pregunta fuera la SQ
				if(mQuests !== '') {
					self.selectedQuestionsID.push(mQuests);

					for(let j = 0; j < sizeJ; j++) {
						if(mQuests == self.questionDiscriminatoryArray[j].columnName) {
							let obj = self.questionDiscriminatoryArray[j];
							if(mCode && mValue) {
								obj.code = mCode;
								obj.value = mValue;
							}
							if(mCodeInclusive && mValueInclusive) {
								obj.codeInclusive = mCodeInclusive;
								obj.valueInclusive = mValueInclusive;
							}
							self.selectedQuestions.push(obj);
						}
					}

					mQuests = '';
					mCode = [];
					mCodeInclusive = [];
					mValue = [];
					mValueInclusive = [];
				}

				if(size > 0) {
					self.misionQuestionsArrayControl = '1';
				}

				// Renderizado de tabla de preguntas/respuestas excluyentes
				self.renderTargetsSurvey();

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

	getMisionRemember() {
		let self = this;

		let parameters = {
			stampMision: self.data.stampMision
		};
		ajaxComunCallWithCallback('getMisionRemember', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.length > 0) {
					// Construcción del array de objetos de recordatorios
					let size = ajaxReturn.result.length;
					for(let i = 0; i < size; i++) {
						let dateTimeArray = ajaxReturn.result[i].FechaHoraEjecucionUnica.split('#');
						let dateArray = dateTimeArray[0].split('/');
						let date = dateArray[2] + '-' + dateArray[1] + '-' + dateArray[0];
						let time = dateTimeArray[1] + ':' + dateTimeArray[2];
						let message = ajaxReturn.result[i].MensajeANotificar;

						let obj = {
							date: date,
							time: time,
							message: message,
							lastRun: ajaxReturn.result[i].FechaUltimaEjecucion
						};
						self.remindersTableArray.push(obj);

						if(ajaxReturn.result[i].FechaUltimaEjecucion == '') {
							self.remindersId.push(ajaxReturn.result[i].id);
						}
					}
				}

				self.tableRecordatorios();

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

	renderData() {
		let self = this;

		// Misión cerrada manualmente mostrar/ocultar
		if(self.data.cierreManual == '1') {
			$('#manualClosing').show();
		} else {
			$('#manualClosing').hide();
		}

		$('#missionName').val(self.data.idmision);
		$('#missionBonus').val(self.data.importe);
		$('#missionDesc').val(self.data.descripcion);
		$('#autoNonComplianceMessage').val(self.data.textomisionkoautonocumplimiento);
		$('#importenocumplimiento').val(self.data.importenocumplimiento);
		$('#validationText').val(self.data.textovalidacion);
		$('#missionStartText').val(self.data.textoiniciomision);
		$('#missionEndText').val(self.data.textofinmision);
		$('#missionAccomplished').val(self.data.textomisionok);
		$('#missionNoAccomplished').val(self.data.textomisionko);
		$('#missionCommission').val(self.data.importeinterno);
		// En caso de que la misión no tenga cupo (finmisioncupo == 0), se introduce como campo vacío (añadido check límite de respuestas)
		$('#numMaxUsers').val(self.data.finmisioncupo == 0 ? '' : self.data.finmisioncupo);
		$('#missionClosed').val(self.data.textofinmisioncupo);
		if(self.data.needValidation == '1') {
			$('#needValidation').prop('checked', true);
			$('#validation').removeClass('d-none');
		} else {
			$('#needValidation').prop('checked', false);
			$('#validationText').val('');
			$('#validation').addClass('d-none');
		}

		if(self.data.usaComision == '1') {
			$('#usaComision').prop('checked', true);
			if(self.missionState === '0') {
				$('.commission').prop('disabled', false);
			}
		}

		if(self.data.continuingMission == '1') {
			$('#continuingMission').prop('checked', true);
		}

		if(self.data.misionInicial == '1') {
			$('#initialMission').prop('checked', true);
		}

		if(self.data.misionInfinita == '1') {
			$('#alwaysCurrent').prop('checked', true);
			$('#dateTimeContainer').hide();
		}

		if(self.data.tipoAnidada == '1') {
			$('#nestedMission').prop('checked', true);
		} else {
			$('#nestedMissionDivContainer').hide();
		}

		if(self.data.requiereTracking == '1') {
			$('#activatePassiveTracking').prop('checked', true);
		}

		// Misión de auditoría
		if(self.data.isAuditoria == '1') {
			$('#isAuditoria').prop('checked', true);
		}

		// Si tiene misión anidada
		if(self.data.estadoAnidada != '' && self.data.estadoAnidada != '1') {
			$('#nestableQuests').val(self.data.idMisionAnidada);
			$('#nestableQuestsStamp').text(self.data.estadoAnidada);
			self.nestedMissionOld = self.data.estadoAnidada;
		}

		let dateTimeStartArray = self.data.fechahorainicio.split('#');
		let dateStartArray = dateTimeStartArray[0].split('/');
		$('#startDate').val(dateStartArray[2] + '-' + dateStartArray[1] + '-' + dateStartArray[0]);
		$('#startTime').val(dateTimeStartArray[1] + ':' + dateTimeStartArray[2]);

		let dateTimeEndArray = self.data.fechahorafin.split('#');
		let dateEndArray = dateTimeEndArray[0].split('/');
		$('#endDate').val(dateEndArray[2] + '-' + dateEndArray[1] + '-' + dateEndArray[0]);
		$('#endTime').val(dateTimeEndArray[1] + ':' + dateTimeEndArray[2]);

		let size = self.typeOptions.length;
		for(let i = 0; i < size; i++) {
			if(self.data.tipomision === self.typeOptions[i].idTipoMision) {
				self.index = i;
			}
		}

		// Llamada para el proyecto donde interviene esta misión
		self.getMisionesProjects();

		if(self.index === '') {
			let errorTitle = pf.const.language.RSC14;
			let errorContent = pf.const.language.RSC2103;
			pf.utils.showInfoDialog(errorTitle, errorContent);
			return false;
		}

		$('#missionTypeInput').val(self.data.tipomision);

		if(self.typeOptions[self.index].isSurvey == '1' && self.missionState === '0') {
			$('#numMaxUsers').prop('disabled', false);
			$('#missionClosed').prop('disabled', false);
			// Verificar si tiene límite de respuestas establecido para marcar el check
			$('#answersLimitContainer').removeClass('d-none');
			if(self.data.finmisioncupo > 0) {
				$('#answersLimit').prop('checked', true);
				$('.answersQuotaContainer').removeClass('d-none');
			} else {
				$('#answersLimit').prop('checked', false);
				$('.answersQuotaContainer').addClass('d-none');
			}
			self.isSurvey = true;
		} else if(self.typeOptions[self.index].isSurvey == '1' && self.missionState === '1') {
			$('#numMaxUsers').prop('disabled', false);
			// Ahora sí se podrá editar el texto de fin de misión por cupo
			$('#missionClosed').prop('disabled', false);
			// Verificar si tiene límite de respuestas establecido para marcar el check
			$('#answersLimitContainer').removeClass('d-none');
			if(self.data.finmisioncupo > 0) {
				$('#answersLimit').prop('checked', true);
				$('.answersQuotaContainer').removeClass('d-none');
			} else {
				$('#answersLimit').prop('checked', false);
				$('.answersQuotaContainer').addClass('d-none');
			}
			self.isSurvey = true;
		} else if(self.typeOptions[self.index].isSurvey == '1' && self.missionState === '2') {
			$('#numMaxUsers').prop('disabled', true);
			$('#missionClosed').prop('disabled', true);
			$('#answersLimit').prop('disabled', true);
			// Verificar si tiene límite de respuestas establecido para marcar el check
			$('#answersLimitContainer').removeClass('d-none');
			if(self.data.finmisioncupo > 0) {
				$('#answersLimit').prop('checked', true);
				$('.answersQuotaContainer').removeClass('d-none');
			} else {
				$('#answersLimit').prop('checked', false);
				$('.answersQuotaContainer').addClass('d-none');
			}
			self.isSurvey = true;

			// Mostrar pestaña de muestreo, muestreo detallado y muestreo dinámico
			$('#samplingTab').show();
			$('#samplingDetailedTab').show();
			$('#samplingDynamicTab').show();
		} else {
			$('#numMaxUsers').prop('disabled', true);
			$('#missionClosed').prop('disabled', true);
			// Oculta los valores
			$('#answersLimitContainer').addClass('d-none');
			$('.answersQuotaContainer').addClass('d-none');
			$('#answersLimit').prop('checked', false);
		}

		self.getObjectives();
	},

	getObjectives() {
		let self = this;

		let parameters = {
			tipomision: self.typeOptions[self.index].idTipoMision
		};
		ajaxComunCallWithCallback('getAllTipoMisionObjetivos', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.objetive = ajaxReturn.result;

				self.renderObjetives();

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

	renderObjetives() {
		let self = this;

		if(self.missionState === '0') {
			// Activar check de passive tracking
			$('#activatePassiveTracking').prop('disabled', false);
		}

		let table = `
			<table id="registers" class="table table-hover">
				<thead>
					<tr>
		`;

		let columnDefs = [];

		if(self.typeOptions[self.index].isSurvey == 1) {
			// ENCUESTA
			table += `
						<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</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}<span class="text-danger">*</span></th>
						<th scope="col" title="${pf.const.language.RSC346}">${pf.const.language.RSC346}</th>
						<th scope="col" title="${pf.const.language.RSC568}">${pf.const.language.RSC568}</th>
					</tr>
				</thead>

				<tbody>
			`;

			let size = self.objetive.length;
			for(let i = 0; i < size; i++) {
				table += `
					<tr>
						<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
						<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
						<td>
							<div class="input-group new-input-style">
								<input type="text" class="form-control-sm inputGrid survey" placeholder="${pf.const.language.RSC110}" aria-label="Encuesta" disabled>
								<div class="input-group-append d-block">
									<button type="button" class="btn btn-outline-secondary searchSurvey py-0 px-1 stateObjetive" data-toggle="modal" data-target="#surveyTable">
										${stcmbackend.svg.threeDotsSmall}
									</button>
								</div>
							</div>
						</td>
						<td class="text-truncate descriptionSurv align-middle"></td>
						<td>
							<div class="input-group new-input-style">
								<input type="text" class="form-control-sm inputGrid template" title="${pf.const.language.RSC2352}" value="${pf.const.language.RSC2352}" disabled data-id="0">
								<div class="input-group-append d-block">
									<button type="button" class="btn btn-outline-secondary searchTemplates py-0 px-1" data-toggle="modal" data-target="#templateTable">
										${stcmbackend.svg.threeDotsSmall}
									</button>
								</div>
							</div>
						</td>
					</tr>
				`;
			}

			columnDefs = [
				{width: '150px', targets: 2},
				{width: '150px', targets: 4}
			];
		} else {
			// NO ENCUESTA
			//Objetivo tipo pedido (o order)
			if(self.typeOptions[self.index].isOrder == 1) {
				if(self.objetive[0].objetivo == 'Pedido (Importe)') {
					// Objetivo: Pedido (Importe)
					table += `
								<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
								<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
								<th scope="col" title="${pf.const.language.RSC145}">${pf.const.language.RSC145}<span class="text-danger">*</span></th>
								<th scope="col" title="${pf.const.language.RSC953}">${pf.const.language.RSC953}</th>
								<th scope="col" title="${pf.const.language.RSC1043}">${pf.const.language.RSC1043}</th>
								<th scope="col" title="${pf.const.language.RSC342}">${pf.const.language.RSC342}</th>
							</tr>
						</thead>

						<tbody>
					`;

					let size = self.objetive.length;
					for(let i = 0; i < size; i++) {
						table += `
							<tr>
								<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
								<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
								<td class="text-truncate align-middle">
									<input type="number" class="form-control inputGrid totalImport stateObjetive">
								</td>
								<td id="tdCurrency" class="text-truncate align-middle" title="${self.country.defaultCountryCurrency}">${self.country.defaultCountryCurrency}</td>
								<td class="text-truncate align-middle">
									<input type="number" class="form-control inputGrid percent stateObjetive">
								</td>
								<td class="text-truncate align-middle" title="${pf.const.language.RSC345}">${pf.const.language.RSC345}</td>
							</tr>
						`;
					}

					columnDefs = [
						{width: '120px', targets: 0},
						{width: '150px', targets: 2},
						{width: '50px', targets: 3},
						{width: '90px', targets: 4},
						{width: '60px', targets: 5}
					];
				} else if(self.objetive[0].objetivo == 'Pedido (Num. Pedidos)') {
					// Objetivo: Pedido (Num. Pedidos)
					table += `
								<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
								<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
								<th scope="col" title="${pf.const.language.RSC1239}">${pf.const.language.RSC1239}<span class="text-danger">*</span></th>
								<th scope="col" title="${pf.const.language.RSC1043}">${pf.const.language.RSC1043}</th>
								<th scope="col" title="${pf.const.language.RSC342}">${pf.const.language.RSC342}</th>
							</tr>
						</thead>

						<tbody>
					`;

					let size = self.objetive.length;
					for(let i = 0; i < size; i++) {
						table += `
							<tr>
								<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
								<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
								<td class="text-truncate align-middle">
									<input type="number" class="form-control inputGrid numOrders stateObjetive">
								</td>
								<td class="text-truncate align-middle">
									<input type="number" class="form-control inputGrid percent stateObjetive">
								</td>
								<td class="text-truncate align-middle" title="${pf.const.language.RSC345}">${pf.const.language.RSC345}</td>
							</tr>
						`;
					}

					columnDefs = [
						{width: '120px', targets: 0},
						{width: '135px', targets: 2},
						{width: '120px', targets: 3},
						{width: '60px', targets: 4}
					];
				} else if(self.objetive[0].objetivo == 'Pedido (Artículo/Importe)') {
					// Objetivo: Pedido (Artículo/Importe)
					table += `
								<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
								<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
								<th scope="col" title="${pf.const.language.RSC1044}">${pf.const.language.RSC1044}<span class="text-danger">*</span></th>
								<th scope="col" title="${pf.const.language.RSC342}">${pf.const.language.RSC342}</th>
							</tr>
						</thead>

						<tbody>
					`;

					let size = self.objetive.length;
					for(let i = 0; i < size; i++) {
						table += `
							<tr>
								<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
								<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
								<td>
									<div class="input-group new-input-style">
										<input type="text" class="form-control-sm inputGrid productInput order" placeholder="${pf.const.language.RSC1044}" aria-label="Producto" disabled>
										<div class="input-group-append d-block">
											<button type="button" class="btn btn-outline-secondary searchProductAmount py-0 px-1" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsSmall}
											</button>
										</div>
									</div>
								</td>
								<td class="text-truncate align-middle" title="${pf.const.language.RSC345}">${pf.const.language.RSC345}</td>
							</tr>
						`;
					}

					columnDefs = [
						{width: '90px', targets: 3}
					];
				} else {
					// Objetivo: Pedido (Producto)
					table += `
								<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
								<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
								<th scope="col" title="${pf.const.language.RSC1044}">${pf.const.language.RSC1044}<span class="text-danger">*</span></th>
								<th scope="col" title="${pf.const.language.RSC342}">${pf.const.language.RSC342}</th>
							</tr>
						</thead>

						<tbody>
					`;

					let size = self.objetive.length;
					for(let i = 0; i < size; i++) {
						table += `
							<tr>
								<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
								<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
								<td>
									<div class="input-group new-input-style">
										<input type="text" class="form-control-sm inputGrid productInput order" placeholder="${pf.const.language.RSC1044}" aria-label="Producto" disabled>
										<div class="input-group-append d-block">
											<button type="button" class="btn btn-outline-secondary searchProduct py-0 px-1 stateObjetive" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsSmall}
											</button>
										</div>
									</div>
								</td>
								<td class="text-truncate align-middle" title="${pf.const.language.RSC345}">${pf.const.language.RSC345}</td>
							</tr>
						`;
					}

					columnDefs = [
						{width: '90px', targets: 3}
					];
				}
			} else if(self.typeOptions[self.index].isPassiveTracking == 1) {
				table += `
							<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
							<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						</tr>
					</thead>

					<tbody>
				`;

				let size = self.objetive.length;
				for(let i = 0; i < size; i++) {
					table += `
						<tr>
							<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo }</td>
							<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
						</tr>
					`;
				}

				columnDefs = [];
			} else if(self.objetive[0].objetivo == 'VideoCallGrupal' || self.objetive[0].objetivo == 'VideoCallUnitaria') {
				// Desactivar check de passive tracking
				$('#activatePassiveTracking').prop('checked', false);
				$('#activatePassiveTracking').prop('disabled', true);

				table += `
							<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
							<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
							<th scope="col" title="${pf.const.language.RSC341}">${pf.const.language.RSC341}<span class="text-danger">*</span></th>
							<th scope="col" title="${pf.const.language.RSC342}">${pf.const.language.RSC342}<span class="text-danger">*</span></th>
						</tr>
					</thead>

					<tbody>
				`;

				let size = self.objetive.length;
				for(let i = 0; i < size; i++) {
					table += `
						<tr>
							<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
							<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
							<td class="text-truncate align-middle">
								<input type="number" class="form-control inputGrid objetiveTimes stateObjetive" value="1">
							</td>
							<td class="text-truncate align-middle">
								<select class="form-control objetivePeriod selectGrid he-26 p-0 stateObjetive">
									<option value="-1">${pf.const.language.RSC343}</option>
									<option value="dia">${pf.const.language.RSC344}</option>
									<option value="hora">${pf.const.language.RSC166}</option>
									<option value="total" selected>${pf.const.language.RSC345}</option>
								</select>
							</td>
						</tr>
					`;
				}

				columnDefs = [
					{visible: false, targets: 2},
					{visible: false, targets: 3}
				];
			} else {
				table += `
							<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
							<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
							<th scope="col" title="${pf.const.language.RSC341}">${pf.const.language.RSC341}<span class="text-danger">*</span></th>
							<th scope="col" title="${pf.const.language.RSC342}">${pf.const.language.RSC342}<span class="text-danger">*</span></th>
						</tr>
					</thead>

					<tbody>
				`;

				let size = self.objetive.length;
				for(let i = 0; i < size; i++) {
					table += `
						<tr>
							<td class="text-truncate align-middle" title="${self.objetive[i].objetivo}">${self.objetive[i].objetivo}</td>
							<td class="text-truncate align-middle" title="${pf.const.language['RSC' + self.objetive[i].descripcion]}">${pf.const.language['RSC' + self.objetive[i].descripcion]}</td>
							<td class="text-truncate align-middle">
								<input type="number" class="form-control inputGrid objetiveTimes stateObjetive">
							</td>
							<td class="text-truncate align-middle">
								<select class="form-control objetivePeriod selectGrid he-26 p-0 stateObjetive">
									<option value="-1">${pf.const.language.RSC343}</option>
									<option value="dia">${pf.const.language.RSC344}</option>
									<option value="hora">${pf.const.language.RSC166}</option>
									<option value="total">${pf.const.language.RSC345}</option>
								</select>
							</td>
						</tr>
					`;
				}

				columnDefs = [
					{width: '60px', targets: 2},
					{width: '145px', targets: 3}
				];
			}
		}

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

		$('#missionObjectives').removeClass('d-none');
		$('#resultTable').html(table);

		if(self.missionState === '0') {
			$('.stateObjetive').prop('disabled', false);
		} else {
			$('.stateObjetive').prop('disabled', true);
		}

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			filter: false,
			autoWidth: false,
			columnDefs: columnDefs,
			bInfo: false
		});

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

		if(self.objectives[0]) {
			if(self.typeOptions[self.index].isSurvey == 1) {
				// Encuesta
				$('.survey').val(self.objectives[0].encuesta);
				$('.descriptionSurv').text(self.objectives[0].descencuesta);
				let template = self.data.idPlantillaReportes == '0' ? pf.const.language.RSC2352 : self.data.nombrePlantillaReportes;
				$('.template').val(template);
				$('.template').attr('title', template);
				$('.template').data('id', self.data.idPlantillaReportes);
			} else if(self.typeOptions[self.index].isOrder == 1) {
				if(self.objectives[0].objetivo == 'Pedido (Importe)') {
					$('.totalImport').val(self.objectives[0].orderamount);
					$('.percent').val(self.objectives[0].orderamountporcfinanciated)
				} else if(self.objectives[0].objetivo == 'Pedido (Num. Pedidos)') {
					$('.numOrders').val(self.objectives[0].ordernumtimes);
					$('.percent').val(self.objectives[0].orderamountporcfinanciated)
				} else {
					let products = []
					self.objectives.forEach(obj => {
						let p = {}
						p.code = obj.orderproductitem;
						p.packaging = obj.orderproductunit;
						if(obj.objetivo === 'Pedido (Artículo/Importe)') {
							p.orderproductnumitems = obj.orderproductamount;
						} else {
							p.orderproductnumitems = obj.orderproductnumitems;
						}
						products.push(p);
					});
					self.products = products;
					if(self.objectives[0].objetivo === 'Pedido (Artículo/Importe)') {
						TableProductsMision.setEvents(self.products, 'divProductsTable', 'newMisionEdit', true);
					} else {
						TableProductsMision.setEvents(self.products, 'divProductsTable', 'newMisionEdit');
					}
				}
			} else {
				// No encuesta
				$('.inputGrid').val(self.objectives[0].numveces);
				$('.selectGrid').val((self.objectives[0].periodo ? self.objectives[0].periodo.toLowerCase() : -1));
			}
		}

		if(self.data.encuesta == '1') {
			// Mostrar sección de respuestas de auto no cumplimiento
			$('#selfNonComplianceContainer').show();
			$('#responseControl').show();
			$('#responseControlMessage').show();
			// Pedir información de las preguntas de la encuesta seleccionada
			self.getTargetsSurvey(true);
		} else {
			// Control de spinner
			self.loaders.getMision = true;
			self.loaders.getMisionQuestionNoAccomplish = true;
			spinnerControl(self.loaders);
		}

		// Encuestas
		$('.searchSurvey').on('click', function() {
			if(self.surveys === '') {
				let idCliente = self.userJSON.idCliente;

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

						self.renderSurveys();
					}
				});
			} else {
				$('#surveyTable').modal('show', true);
			}
		});

		// Plantillas
		$('.searchTemplates').on('click', function() {
			if(self.templates === '') {
				ajaxComunCallWithCallback('getPlantillasReportes', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.templates = ajaxReturn.result;

						self.renderTemplates();
					}
				});
			} else {
				$('#templateTable').modal('show', true);
			}
		});

		// Productos / cantidad
		self.productsModal = new TableProducts(1, 'addProductsEdit');
		$('.searchProduct').off().on('click', function() {
			self.requestType = 'addProductsEdit';
			self.productsModal.setEvents(self.products);
		});

		// Productos / importe
		self.productsAmountModal = new TableProducts(1, 'addProductsEdit');
		$('.searchProductAmount').off().on('click', function() {
			self.requestType = 'addProductsAmount';
			self.productsAmountModal.setEvents(self.products);
		});
	},

	renderSurveys() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="ID">ID</th>
					<th scope="col" title="${pf.const.language.RSC112}">${pf.const.language.RSC112}</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.RSC115}">${pf.const.language.RSC115}</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="filtersPoll">
				<tr>
					<td>sid</td>
					<td>surveyls_title</td>
					<td>datecreated</td>
					<td>active</td>
					<td>perfilacion</td>
					<td>startdate</td>
					<td>expires</td>
					<td>remuneracion</td>
				</tr>
			</thead>

			<tbody>
		`;

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

		let size = self.surveys.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.surveys[i].countries != '' && allowedCountries.indexOf(self.surveys[i].countries) == -1) {
				continue;
			}

			let color = '';
			if(self.surveys[i].idmision != '' || self.surveys[i].idProject != '') {
				color = 'text-muted';
				continue;
			}

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let startDate = '-';
			let startDateOrder = '';
			if(self.surveys[i].startdate != '') {
				// Para ordenación en columna
				startDateOrder = self.surveys[i].startdate.replace(' ', '');

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

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

				let dateTimeArrayEnd = self.surveys[i].expires.split(' ');
				let dateEnd = dateTimeArrayEnd[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					endDate = modifyDateFormat(dateEnd);
				} else {
					endDate = dateEnd;
				}
			}

			table += `
				<tr id="sid${self.surveys[i].sid}" class="c-pointer ${color}" data-active="${self.surveys[i].active}" data-mission="" data-project="" data-status="">
					<td class="text-truncate" title="${self.surveys[i].sid}">${self.surveys[i].sid}</td>
					<td class="text-truncate pollName" title="${self.surveys[i].surveyls_title}">${self.surveys[i].surveyls_title}</td>
					<td class="text-truncate" title="${self.surveys[i].datecreated}">${self.surveys[i].datecreated}</td>
					<td class="text-center">
						<span class="d-none">${(self.surveys[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveys[i].active == '1' ? 'checked' : '')}></td>
					<td class="text-center">
						<span class="d-none">${(self.surveys[i].perfilacion == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveys[i].perfilacion == '1' ? 'checked' : '')}></td>
					<td class="text-truncate start-date" title="${startDate}">
						<span class="d-none">${startDateOrder}</span>
						${startDate}
					</td>
					<td class="text-truncate end-date" title="${endDate}">
						<span class="d-none">${endDateOrder}</span>
						${endDate}
					</td>
					<td class="text-truncate remuneracion" title="${self.surveys[i].remuneracion}">${self.surveys[i].remuneracion}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'active' || title == 'perfilacion') {
				value = optionsSelectAllYesNo();
			}

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

		let tablePoll = $('#tablePoll').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

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

		// Apply the search
		applyTheSearch(tablePoll, 'filtersPoll');

		$('#tablePoll tbody').off().on('click', 'tr', function() {
			// Control de encuesta en uso
			if($(this).hasClass('text-muted')) {
				return false;
			}

			let idSurvey = $(this).prop('id').replace('sid', '');
			let active = $(this).data('active');
			if(active != '1') {
				let alertTitle = pf.const.language.RSC14;
				let alertText = pf.const.language.RSC1365;
				pf.utils.showInfoDialog(alertTitle, alertText);
				return false;
			}

			// Mostrar sección de respuestas de auto no cumplimiento y borrar tabla de preguntas
			$('#selfNonComplianceContainer').show();
			$('#responseControl').show();
			$('#responseControlContainer').html('');
			$('#autoNonComplianceMessage').val('');
			$('#importenocumplimiento').val('');
			$('#responseControlMessage').show();
			self.questionDiscriminatoryArray = [];
			self.selectedQuestions = [];
			self.selectedQuestionsID = [];
			// Crear tabla de preguntas y respuestas
			self.renderTargetsSurvey();

			$('.survey').val(idSurvey);
			let name = $(this).find('.pollName').text();
			$('.descriptionSurv').text(name);
			let remuneration = $(this).find('.remuneracion').text();
			let startMission = $(this).find('.start-date').text();
			let endMission = $(this).find('.end-date').text();
			let startArray = startMission.split(' ');
			$('#startDate').val(startArray[0]);
			$('#startTime').val(startArray[1]);
			let endArray = endMission.split(' ');
			$('#endDate').val(endArray[0]);
			$('#endTime').val(endArray[1]);

			$('#tablePoll tbody tr').css('outline-width', 'initial');
			$('#tablePoll tbody tr').css('outline-style', 'none');
			$('#tablePoll tbody tr').css('outline-color', '#000');
			$('#tablePoll tbody tr').css('font-weight', 'normal');
			$(this).css('outline-width', 'thin');
			$(this).css('outline-style', 'solid');
			$(this).css('outline-color', '#f00');
			$(this).css('font-weight', 'bold');
			$('#closePool').trigger('click');
		});
	},

	renderTemplates() {
		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.RSC178}">${pf.const.language.RSC178}</th>
				</tr>
			</thead>

			<thead class="filtersTemplate">
				<tr>
					<td>nombre</td>
					<td>descripcion</td>
				</tr>
			</thead>

			<tbody>
				<tr class="c-pointer" data-id="0">
					<td class="text-truncate" title="${pf.const.language.RSC2352}">${pf.const.language.RSC2352}</td>
					<td class="text-truncate" title="${pf.const.language.RSC2352}">${pf.const.language.RSC2352}</td>
				</tr>
		`;

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

		table += `
			</tbody>
		`;

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

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

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

		let tableTemplate = $('#tableTemplate').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

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

		// Apply the search
		applyTheSearch(tableTemplate, 'filtersTemplate');

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

			if(id == '0') {
				$('.template').val(pf.const.language.RSC2352);
				$('.template').attr('title', pf.const.language.RSC2352);
				$('.template').data('id', '0');
			} else {
				let name = $(this).data('name');
				$('.template').val(name);
				$('.template').attr('title', id);
				$('.template').data('id', id);
			}

			$('#tableTemplate tbody tr').css('outline-width', 'initial');
			$('#tableTemplate tbody tr').css('outline-style', 'none');
			$('#tableTemplate tbody tr').css('outline-color', '#000');
			$('#tableTemplate tbody tr').css('font-weight', 'normal');
			$(this).css('outline-width', 'thin');
			$(this).css('outline-style', 'solid');
			$(this).css('outline-color', '#f00');
			$(this).css('font-weight', 'bold');
			$('#closeTemplates').trigger('click');
		});
	},

	renderTypes() {
		let self = this;

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

			<thead class="filtersMisionType">
				<tr>
					<td>type</td>
					<td>desc</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.typeOptions.length;
		for(let i = 0; i < size; i++) {
			if(self.typeOptions[i].isOrder == '0' || sessionStorage['STCMBackEnd:config_market'] == '1') {
				table += `
					<tr id="${self.typeOptions[i].idTipoMision}" class="c-pointer" index="${i}" data-audit="${self.typeOptions[i].isAuditoria}">
						<td class="text-truncate" title="${self.typeOptions[i].idTipoMision}">${self.typeOptions[i].idTipoMision}</td>
						<td class="text-truncate" title="${self.typeOptions[i].Descripcion}">${self.typeOptions[i].Descripcion}</td>
					</tr>
				`;
			}
		}

		table += `
			</tbody>
		`;

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

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

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

		let tableMisionType = $('#tableMisionType').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(tableMisionType, 'filtersMisionType');

		$('#tableMisionType tbody').off().on('click', 'tr', function() {
			let index = $(this).attr('index');
			let type = $(this).prop('id');
			let isAuditoria = $(this).data('audit');

			if(type == 'Encuesta' || type == 'Tracking de compra' || type == 'Tracking de precios' || type == 'Tracking de productos') {
				$('#continuingMission').prop('disabled', false);
			} else {
				$('#continuingMission').prop('disabled', true);
			}

			if(isAuditoria == '1') {
				$('#isAuditoria').prop('checked', true);
				$('#continuingMission').prop('checked', true);
			} else {
				$('#isAuditoria').prop('checked', false);
			}

			if(type == 'Tracking de compra' || type == 'Tracking de precios' || type == 'Tracking de productos') {
				$('#needValidation').prop('checked', true);
				$('#needValidation').trigger('change');
				$('#continuingMission').prop('checked', true);
				$('#continuingMission').trigger('change');
				$('#activatePassiveTracking').prop('checked', true);
			} else if(isAuditoria == '0') {
				$('#needValidation').prop('checked', false);
				$('#needValidation').trigger('change');
				$('#continuingMission').prop('checked', false);
				$('#continuingMission').trigger('change');
				$('#activatePassiveTracking').prop('checked', false);
			}

			$('#missionTypeInput').val(type)
			$('#tableProducts').html('')
			self.index = index;
			if(self.index != '-1') {
				addLoader();
				self.getObjectives();
			} else {
				$('#registers').html('');
			}

			if(self.typeOptions[self.index].isSurvey == '1') {
				self.isSurvey = true;
			} else {
				self.isSurvey = false;
			}

			if(self.typeOptions[self.index].isSurvey == '1') {
				$('#numMaxUsers').prop('disabled', false);
				$('#missionClosed').prop('disabled', false);
			} else {
				$('#numMaxUsers').val('');
				$('#numMaxUsers').prop('disabled', true);
				$('#missionClosed').val('');
				$('#missionClosed').prop('disabled', true);
			}
			$('#closeMisionType').trigger('click');
		});
	},

	renderNestableMissions() {
		let self = this;

		let table = `
			<table id="nestableMissionsTable" 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.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>
					</tr>
				</thead>

				<thead class="filtersNestableMissions">
					<tr>
						<td>idmision</td>
						<td>fechainicio</td>
						<td>horainicio</td>
						<td>fechafin</td>
						<td>horafin</td>
						<td>importe</td>
					</tr>
				</thead>

				<tbody>
		`;

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

		let size = self.nestableMissions.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.nestableMissions[i].country) == -1) {
				continue;
			}

			let startDateTime = self.nestableMissions[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.nestableMissions[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];

			table += `
				<tr class="c-pointer" data-index="${i}" data-idmision="${self.nestableMissions[i].idmision}" data-stampmision="${self.nestableMissions[i].stampMision}">
					<td class="text-truncate" title="${self.nestableMissions[i].idmision}">${self.nestableMissions[i].idmision}</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.nestableMissions[i].importe}">${self.nestableMissions[i].importe}</td>
				</tr>
			`;
		}

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

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

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

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

		let nestableMissionsTable = $('#nestableMissionsTable').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '120px', targets: 1},
				{width: '110px', targets: 2},
				{width: '120px', targets: 3},
				{width: '110px', targets: 4},
				{width: '70px', targets: 5}
			]
		});

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

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

		// Apply the search
		applyTheSearch(nestableMissionsTable, 'filtersNestableMissions');

		$('#nestableMissionsTable tbody').off().on('click', 'tr', function() {
			let idmision = $(this).data('idmision');
			let stampMision = $(this).data('stampmision');
			let index = $(this).data('index');

			self.nestedMission = self.nestableMissions[index];

			$('#nestableQuests').val(idmision);
			$('#nestableQuestsStamp').text(stampMision);

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

	editMission() {
		let self = this;

		// Control de ampliación de fecha/hora fin para misiones en marcha
		let endDateTimeMod = false;
		if(self.missionState !== '0') {
			// Valores antiguos
			let oldDateTimeArray = self.data.fechahorafin.split('#');
			let oldDateArray = oldDateTimeArray[0].split('/');
			let oldMinSegArray = oldDateTimeArray[2].split(':');
			let oldDate = new Date(oldDateArray[2], oldDateArray[1], oldDateArray[0], oldDateTimeArray[1], oldMinSegArray[0], oldMinSegArray[1]);

			// Valores nuevos
			let newEndDataArray = $('#endDate').val().split('-');
			let newEndTime = $('#endTime').val() + ':00';
			let newEndTimeArray = newEndTime.split(':');
			let newDate = new Date(newEndDataArray[0], newEndDataArray[1], newEndDataArray[2], newEndTimeArray[0], newEndTimeArray[1], newEndTimeArray[2]);

			if(newDate < oldDate) {
				let warningTitle = pf.const.language.RSC14;
				let warningContent = pf.const.language.RSC1803;
				pf.utils.showInfoDialog(warningTitle, warningContent);
				$('#endDate').addClass('is-invalid');
				$('[for="endDate"]').addClass('is-invalid');
				$('#endTime').addClass('is-invalid');
				$('[for="endTime"]').addClass('is-invalid');
				return false;
			} else if(newDate > oldDate) {
				endDateTimeMod = true;
			}
		}

		let noValidate = false;

		let descripcion = $('#missionDesc').val().trim();
		// Validación descripcion
		if(descripcion === '') {
			$('#missionDesc').addClass('is-invalid');
			$('[for="missionDesc"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionDesc').removeClass('is-invalid');
			$('[for="missionDesc"]').removeClass('is-invalid');
		}

		let textoiniciomision = $('#missionStartText').val().trim();
		// Validación texto inicio
		if(textoiniciomision === '') {
			$('#missionStartText').addClass('is-invalid');
			$('[for="missionStartText"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionStartText').removeClass('is-invalid');
			$('[for="missionStartText"]').removeClass('is-invalid');
		}

		let textofinmision = $('#missionEndText').val().trim();
		// Validación texto fin
		if(textofinmision === '') {
			$('#missionEndText').addClass('is-invalid');
			$('[for="missionEndText"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionEndText').removeClass('is-invalid');
			$('[for="missionEndText"]').removeClass('is-invalid');
		}

		let textomisionok = $('#missionAccomplished').val().trim();
		// Validación texto misión cumplida
		if(textomisionok === '') {
			$('#missionAccomplished').addClass('is-invalid');
			$('[for="missionAccomplished"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionAccomplished').removeClass('is-invalid');
			$('[for="missionAccomplished"]').removeClass('is-invalid');
		}

		let textomisionko = $('#missionNoAccomplished').val().trim();
		// Validación texto misión no cumplida
		if(textomisionko === '') {
			$('#missionNoAccomplished').addClass('is-invalid');
			$('[for="missionNoAccomplished"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionNoAccomplished').removeClass('is-invalid');
			$('[for="missionNoAccomplished"]').removeClass('is-invalid');
		}

		// Validación tipomision
		let tipomision = '';
		let desctipomision = '';
		if(self.index === '' || self.index === '-1') {
			$('#missionType').addClass('is-invalid');
			$('[for="missionType"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionType').removeClass('is-invalid');
			$('[for="missionType"]').removeClass('is-invalid');
			tipomision = self.typeOptions[self.index].idTipoMision;
			desctipomision = self.typeOptions[self.index].idTipoMision;
			// Validación tipomision 'encuesta'
			if(self.typeOptions[self.index].isSurvey == 1) {
				// Validación Encuesta
				if($('.survey').val() === '') {
					$('.survey').addClass('is-invalid');
					$('[for="survey"]').addClass('is-invalid');
					noValidate = true;
				} else {
					$('.survey').removeClass('is-invalid');
					$('[for="survey"]').removeClass('is-invalid');
				}
			} else if(self.typeOptions[self.index].isOrder == 1) {
				if(self.objetive[0].objetivo == 'Pedido (Importe)') {
					// Pedido (Importe)
					if($('.totalImport').val() === '' || parseInt($('.totalImport').val()) < 0) {
						$('.totalImport').css('border-color', '#dc3545');
						noValidate = true;
					} else {
						$('.totalImport').css('border-color', '#ced4da');
					}
					if($('.percent').val() === '' || parseInt($('.percent').val()) < 0 || parseInt($('.percent').val()) > 100) {
						$('.percent').css('border-color', '#dc3545');
						noValidate = true;
					} else {
						$('.percent').css('border-color', '#ced4da');
					}
				} else if(self.objetive[0].objetivo == 'Pedido (Num. Pedidos)') {
					// Pedido (Num. Pedidos)
					if($('.numOrders').val() === '' || parseInt($('.numOrders').val()) < 0) {
						$('.numOrders').css('border-color', '#dc3545');
						noValidate = true;
					} else {
						$('.numOrders').css('border-color', '#ced4da');
					}
					if($('.percent').val() === '' || parseInt($('.percent').val()) < 0 || parseInt($('.percent').val()) > 100) {
						$('.percent').css('border-color', '#dc3545');
						noValidate = true;
					} else {
						$('.percent').css('border-color', '#ced4da');
					}
				} else if(self.objetive[0].objetivo == 'Pedido (Artículo/Importe)') {
					// Pedido (Artículo/Importe)
					if($('#tableProducts tbody .user_selected').length == 0) {
						noValidate = true;
					} else {
						$('#tableProducts tbody .user_selected').each(function() {
							// Producto
							if($(this).find('.productCode').attr('title') === '' || $(this).find('.productCode').attr('title') == null || $(this).find('.productCode').attr('title') == undefined) {
								$(this).find('.productCode').addClass('is-invalid');
								noValidate = true;
								return false;
							} else {
								$(this).find('.productCode').removeClass('is-invalid');
							}
							// Importe
							if($(this).find('.numberProducts').val() === '' || parseInt($('.numberProducts').val()) < 0) {
								$(this).find('.numberProducts').css('border-color', '#dc3545');
								noValidate = true;
								return false;
							} else {
								$(this).find('.numberProducts').css('border-color', '#ced4da');
							}
							// Unidad
							if($(this).find('.productUnit').attr('title') === '' || $(this).find('.productUnit').attr('title') == null || $(this).find('.productUnit').attr('title') == undefined) {
								$(this).find('.productUnit').css('border-color', '#dc3545');
								noValidate = true;
								return false;
							} else {
								$(this).find('.productUnit').css('border-color', '#ced4da');
							}
						});
					}
				} else {
					// Pedido (Producto)
					if($('#tableProducts tbody .user_selected').length == 0) {
						noValidate = true;
					} else {
						$('#tableProducts tbody .user_selected').each(function() {
							// Producto
							if($(this).find('.productCode').attr('title') === '' || $(this).find('.productCode').attr('title') == null || $(this).find('.productCode').attr('title') == undefined) {
								$(this).find('.productCode').addClass('is-invalid');
								noValidate = true;
								return false;
							} else {
								$(this).find('.productCode').removeClass('is-invalid');
							}
							// Numero de bultos
							if($(this).find('.numberProducts').val() === '' || parseInt($('.numberProducts').val()) < 0) {
								$(this).find('.numberProducts').css('border-color', '#dc3545');
								noValidate = true;
								return false;
							} else {
								$(this).find('.numberProducts').css('border-color', '#ced4da');
							}
							// Unidad
							if($(this).find('.productUnit').attr('title') === '' || $(this).find('.productUnit').attr('title') == null || $(this).find('.productUnit').attr('title') == undefined) {
								$(this).find('.productUnit').css('border-color', '#dc3545');
								noValidate = true;
								return false;
							} else {
								$(this).find('.productUnit').css('border-color', '#ced4da');
							}
						});
					}
				}
			} else if(self.typeOptions[self.index].isPassiveTracking == 1) {
				//for future compronations
			} else {
				// Validación Nº veces
				if($('.objetiveTimes').val() === '' || $('.objetiveTimes').val() == '0') {
					$('.objetiveTimes').css('border-color', '#dc3545');
					noValidate = true;
				} else {
					$('.objetiveTimes').css('border-color', '#ced4da');
				}
				// Validación Periodo
				if($('.objetivePeriod').val() == '-1') {
					$('.objetivePeriod').css('border-color', '#dc3545');
					noValidate = true;
				} else {
					$('.objetivePeriod').css('border-color', '#ced4da');
				}
			}
		}

		let hasAnswerLimit = $('#answersLimit').prop('checked');
		if(hasAnswerLimit) {
			if($('#numMaxUsers').val() === '' || $('#numMaxUsers').val() <= 0) {
				$('#numMaxUsers').addClass('is-invalid');
				$('[for="numMaxUsers"]').addClass('is-invalid');
				let alertTitle = pf.const.language.RSC654;
				let alertText = pf.const.language.RSC2179;
				pf.utils.showInfoDialog(alertTitle, alertText);
				return false;
			}
		}

		// Control de fecha/hora inicio/fin
		let startDateEmpty = $('#startDate').val() === '' ? true : false;
		let startTimeEmpty = $('#startTime').val() === '' ? true : false;
		let endDateEmpty = $('#endDate').val() === '' ? true : false;
		let endTimeEmpty = $('#endTime').val() === '' ? true : false;

		// Misión anidada
		let tipoAnidada = $('#nestedMission').prop('checked') ? true : false;

		let dateTimeEmpty = false;
		if(startDateEmpty && !tipoAnidada) {
			$('#startDate').addClass('is-invalid');
			$('[for="startDate"]').addClass('is-invalid');
			dateTimeEmpty = true;
		} else {
			$('#startDate').removeClass('is-invalid');
			$('[for="startDate"]').removeClass('is-invalid');
		}
		if(startTimeEmpty && !tipoAnidada) {
			$('#startTime').addClass('is-invalid');
			$('[for="startTime"]').addClass('is-invalid');
			dateTimeEmpty = true;
		} else {
			$('#startTime').removeClass('is-invalid');
			$('[for="startTime"]').removeClass('is-invalid');
		}
		if(endDateEmpty && !tipoAnidada) {
			$('#endDate').addClass('is-invalid');
			$('[for="endDate"]').addClass('is-invalid');
			dateTimeEmpty = true;
		} else {
			$('#endDate').removeClass('is-invalid');
			$('[for="endDate"]').removeClass('is-invalid');
		}
		if(endTimeEmpty && !tipoAnidada) {
			$('#endTime').addClass('is-invalid');
			$('[for="endTime"]').addClass('is-invalid');
			dateTimeEmpty = true;
		} else {
			$('#endTime').removeClass('is-invalid');
			$('[for="endTime"]').removeClass('is-invalid');
		}

		let fechahorainicioexec = '';
		let fechahorainicio = '';
		let fechahorafinexec = '';
		let fechahorafin = '';
		if(!tipoAnidada) {
			let fechahorainicioArray = $('#startDate').val().split('-');
			let startTime = $('#startTime').val()+ ':00';
			startTime = startTime.substring(0,8);
			let fechainicio = fechahorainicioArray[2] + '/' + fechahorainicioArray[1] + '/' + fechahorainicioArray[0];
			fechahorainicioexec = fechainicio + ' ' + startTime;
			fechahorainicio = fechainicio + '#' + startTime.replace(':', '#') + '#';

			let fechahorafinArray = $('#endDate').val().split('-');
			let endTime = $('#endTime').val()+ ':00';
			endTime = endTime.substring(0,8);
			let fechafin = fechahorafinArray[2] + '/' + fechahorafinArray[1] + '/' + fechahorafinArray[0];
			fechahorafinexec = fechafin + ' ' + endTime;
			fechahorafin = fechafin + '#' +endTime.replace(':', '#') + '#';
		}

		if(noValidate || dateTimeEmpty) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let encuesta = self.typeOptions[self.index].isSurvey;
		if(encuesta === undefined) {
			encuesta = '0';
		}

		let order = self.typeOptions[self.index].isOrder;
		if(order === undefined) {
			order = '0';
		}

		let periodo = ($('.objetivePeriod').val() ? $('.objetivePeriod').val() : '');
		if(order) {
			periodo = 'Total';
		}

		// Pedido (Producto)
		let orderproductitem = '';
		if(self.objetive[0].objetivo == 'Pedido (Producto)') {
			let response = '[';
			$('#tableProducts tbody tr').each(function() {
				let productCode = ($(this).find('.productCode').attr('title') ? $(this).find('.productCode').attr('title') : '');
				let numberProducts = ($(this).find('.numberProducts').val() ? $(this).find('.numberProducts').val() : '');
				let productUnit = ($(this).find('.productUnit').attr('title') ? $(this).find('.productUnit').attr('title') : '');
				response += '"' + productCode + '#' + numberProducts + '#' + productUnit + '",';
			});
			orderproductitem = response.substring(0, response.length - 1);
			orderproductitem += ']';
		}

		// Pedido (Artículo/Importe)
		let orderproductAmount = '';
		if(self.objetive[0].objetivo == 'Pedido (Artículo/Importe)') {
			let response = '[';
			$('#tableProducts tbody tr').each(function() {
				let productCode = ($(this).find('.productCode').attr('title') ? $(this).find('.productCode').attr('title') : '');
				let AmountProducts = ($(this).find('.numberProducts').val() ? $(this).find('.numberProducts').val() : '');
				let productUnit = ($(this).find('.productUnit').attr('title') ? $(this).find('.productUnit').attr('title') : '');
				response += '"' + productCode + '#' + AmountProducts + '#' + productUnit + '",';
			});
			orderproductAmount = response.substring(0, response.length - 1);
			orderproductAmount += ']';
		}

		// Para validación de tipos a la hora de hacer recordatorios antes del inicio
		let videoCallTypes = ['Video en chat grupal', 'Video en chat personal', 'Videocall 1-1', 'Videocall grupal'];

		// Validación de Recordatorios
		let dateStartControl = new Date($('#startDate').val() + ' ' + $('#startTime').val());
		let dateEndControl = new Date($('#endDate').val() + ' ' + $('#endTime').val());
		let reminders = false;
		let remindersCheck = true;
		let remindersSize = self.remindersTableArray.length;
		let remindersArray = [];
		for(let i = 0; i < remindersSize; i++) {
			if(self.remindersTableArray[i].date == '' || self.remindersTableArray[i].time == '' || self.remindersTableArray[i].message == '') {
				continue;
			} else {
				reminders = true;
				let reminderControl = new Date(self.remindersTableArray[i].date + ' ' + self.remindersTableArray[i].time);
				if(dateStartControl < reminderControl && reminderControl < dateEndControl) {
					reminderString = self.remindersTableArray[i].date + ' ' + self.remindersTableArray[i].time + '#' + self.remindersTableArray[i].message + '#' + self.remindersTableArray[i].lastRun;
					remindersArray.push(reminderString);
					$('#dateInput' + i).removeClass('is-invalid');
					$('#timeInput' + i).removeClass('is-invalid');
				} else if(videoCallTypes.includes(tipomision) && reminderControl < dateEndControl) {
					reminderString = self.remindersTableArray[i].date + ' ' + self.remindersTableArray[i].time + '#' + self.remindersTableArray[i].message + '#' + self.remindersTableArray[i].lastRun;
					remindersArray.push(reminderString);
					$('#dateInput' + i).removeClass('is-invalid');
					$('#timeInput' + i).removeClass('is-invalid');
				} else {
					remindersCheck = false;
					$('#dateInput' + i).addClass('is-invalid');
					$('#timeInput' + i).addClass('is-invalid');
				}
			}
		}

		// Control de que la fecha de inicio sea anterior a la fecha de fin
		if(dateEndControl <= dateStartControl && !tipoAnidada) {
			let alertTitle = pf.const.language.RSC14;
			let alertText = pf.const.language.RSC1928;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return false;
		}

		if(reminders && !remindersCheck) {
			let alertTitle = pf.const.language.RSC1355;
			let alertText = pf.const.language.RSC1357;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return false;
		}

		let finmisioncupo = $('#numMaxUsers').val();
		let textofinmisioncupo = $('#missionClosed').val().trim();

		let parameters = {
			idmision: $('#missionName').val().trim(),
			descripcion: descripcion,
			textovalidacion: $('#validationText').val().trim(),
			textoiniciomision: textoiniciomision,
			textofinmision: textofinmision,
			textomisionok: textomisionok,
			textomisionko: textomisionko,
			tipomision: tipomision,
			desctipomision: desctipomision,
			fechahorainicio: fechahorainicio,
			fechahorainicioexec: fechahorainicioexec,
			fechahorafin: fechahorafin,
			fechahorafinexec: fechahorafinexec,
			importe: $('#missionBonus').val().trim(),
			encuesta: encuesta,
			objetivo: self.objetive[0].objetivo,
			descobjetivo: self.objetive[0].descripcion,
			idEncuesta: $('.survey').val(),
			descencuesta: ($('.descriptionSurv').text() ? $('.descriptionSurv').text() : ''),
			idPlantillaReportes: ($('.template').data('id') ? $('.template').data('id') : '0'),
			numveces: ($('.objetiveTimes').val() ? $('.objetiveTimes').val() : ''),
			periodo: periodo,
			currency: $('#currency').val(),
			country: self.country.isocode,
			order: order,
			orderamount: ($('.totalImport').val() ? $('.totalImport').val() : ''),
			orderamountporcfinanciated: ($('.percent').val() ? $('.percent').val() : ''),
			orderproductitem: orderproductitem,
			orderproductAmount: orderproductAmount,
			ordernumtimes: ($('.numOrders').val() ? $('.numOrders').val() : ''),
			importeinterno: $('#missionCommission').val(),
			finmisioncupo: finmisioncupo,
			textofinmisioncupo: textofinmisioncupo,
			reminders: JSON.stringify(remindersArray),
			UsuarioQueNotifica: self.usuarioQueNotifica,
			DescUsuarioQueNotifica: self.descUsuarioQueNotifica,
			userMail: self.userMail,
			recordatorios: pf.const.language.RSC1355,
			remindersChange: self.remindersChange,
			stampMision: self.data.stampMision,
			remindersId: JSON.stringify(self.remindersId),
			endDateTimeMod: endDateTimeMod,
			endDateTimeOld: self.data.fechahorafinexec,
			currencyinterno: $('#currencyCommission').val(),
			needValidation: ($('#needValidation').prop('checked') ? '1' : '0'),
			misionQuestionsArray: JSON.stringify(self.selectedQuestions),
			misionQuestionsArrayControl: self.misionQuestionsArrayControl,
			manualClosing: self.manualClosing,
			manualClosingText: self.manualClosingText,
			reopeningMessage: self.reopeningMessage,
			projectListID: self.projectListID,
			ListaDistribucionID: self.ListaDistribucionID,
			textomisionkoAutoNoCumplimiento: $('#autoNonComplianceMessage').val().trim(),
			usaComision: ($('#usaComision').prop('checked') ? '1' : '0'),
			importenocumplimiento: $('#importenocumplimiento').val(),
			currencynocumplimiento: $('#currencynocumplimiento').val(),
			misionInicial: ($('#initialMission').prop('checked') ? '1' : '0'),
			misionInfinita: ($('#alwaysCurrent').prop('checked') ? '1' : '0'),
			idCliente: $('#customers').data('id'),
			tipoAnidada: ($('#nestedMission').prop('checked') ? '1' : '0'),
			estadoAnidadaStamp: $('#nestableQuestsStamp').text(),
			requiereTracking: ($('#activatePassiveTracking').prop('checked') ? '1' : '0'),
			continuingMission: ($('#continuingMission').prop('checked') ? '1' : '0'),
			nestedMission: JSON.stringify(self.nestedMission),
			nestedMissionOld: self.nestedMissionOld,
			isAuditoria: ($('#isAuditoria').prop('checked') ? '1' : '0')
		};
		ajaxComunCallWithCallback('updateMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC14;
				let successContent = pf.const.language.RSC320;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!misiones';
			}
		});
	},

	getPaisesEnabled() {
		let self = this;

		ajaxComunCallWithCallback('getPaisesEnabled', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let selected = '';
					if(self.data.country == ajaxReturn.result[i].isocode) {
						selected = 'selected';
					}

					let options = `
						<option value="${ajaxReturn.result[i].currency}">${ajaxReturn.result[i].currency}</option>
						<option value="points">${pf.const.language.RSC1897}</option>
					`;

					if(i == 0 && selected == '') {
						$('#currency').html(options);
						$('#currencyCommission').html(options);
						$('#currencynocumplimiento').html(options);
					} else if(selected != '') {
						$('#currency').html(options);
						$('#currencyCommission').html(options);
						$('#currencynocumplimiento').html(options);
					}
				}

				$('#currency').val(self.data.currency);
				$('#currencyCommission').val(self.data.currencyinterno);
				$('#currencynocumplimiento').val(self.data.currencynocumplimiento);

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

	existsMisionBetweenDates() {
		let self = this;

		let fechahorainicioArray = $('#startDate').val().split('-');
		let fechainicio = fechahorainicioArray[2] + '/' + fechahorainicioArray[1] + '/' + fechahorainicioArray[0];
		let startTime = $('#startTime').val() + ':00';
		startTime = startTime.substring(0,8);
		let fechahorainicioexec = fechainicio + ' ' + startTime;

		let fechahorafinArray = $('#endDate').val().split('-');
		let fechafin = fechahorafinArray[2] + '/' + fechahorafinArray[1] + '/' + fechahorafinArray[0];
		let endTime = $('#endTime').val() + ':00';
		endTime = endTime.substring(0,8);
		let fechahorafinexec = fechafin + ' ' + endTime;

		let country = $('#projectCountry').val();

		let tipomision = self.typeOptions[self.index].idTipoMision;

		let parameters = {
			fechahorainicioexec: fechahorainicioexec,
			fechahorafinexec: fechahorafinexec,
			country: country,
			tipomision: tipomision
		};
		ajaxComunCallWithCallback('existsMisionBetweenDates', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let idmision = $('#missionName').val();
				if(ajaxReturn.result.length == 0) {
					self.editMission();
				} else if(ajaxReturn.result.length == 1 && ajaxReturn.result[0].idmision == idmision) {
					self.editMission();
				} else {
					let warningTitle = pf.const.language.RSC14;
					let warningContent = pf.const.language.RSC956;
					pf.utils.showInfoDialog(warningTitle, warningContent);
				}
			}
		});
	},

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

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

		switch(self.requestType) {
			case 'country':
				self.country = data;
				$('#tdCurrency').text(self.country.currency);
				$('#tdCurrency').attr('title', self.country.currency);
				$('#projectCountry').val(self.country.isocode);

				let options = `
					<option value="${self.country.currency}">${self.country.currency}</option>
					<option value="points">${pf.const.language.RSC1897}</option>
				`;

				$('#currency').html(options);
				$('#currencyCommission').html(options);
				$('#currencynocumplimiento').html(options);
				break;

			case 'addProductsEdit':
				for(let i = 0; i < data.length; i++) {
					for(let j = 0; j < self.products.length; j++) {
						if(data[i].code == self.products[j].code) {
							data[i]['orderproductnumitems'] = self.products[j].orderproductnumitems;
						}
					}
				}

				self.products = data;
				TableProductsMision.setEvents(self.products, 'divProductsTable', 'newMisionEdit');
				break;

			case 'removeProduct':
				self.products.splice(data, 1);
				TableProductsMision.setEvents(self.products, 'divProductsTable', 'newMisionEdit');
				break;

			case 'addProductsAmount':
				self.products = data;
				TableProductsMision.setEvents(self.products, 'divProductsTable', 'editMisionAmount', true);
				break;

			case 'removeProductAmount':
				self.products.splice(data, 1);
				TableProductsMision.setEvents(self.products, 'divProductsTable', 'editMisionAmount', true);
				break;

			case 'customer':
				$('#customers').val(data.nombreComercial);
				$('#customers').data('id', data.idCustomer);
				break;

			default:
				break;
		}
	},

	tableRecordatorios() {
		let self = this;

		let table = `
			<table id="tableReminders" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC431}">${pf.const.language.RSC431}</th>
						<th scope="col" title="${pf.const.language.RSC432}">${pf.const.language.RSC432}</th>
						<th scope="col" title="${pf.const.language.RSC421}">${pf.const.language.RSC421}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.remindersTableArray.length;
		if(size < 1) {
			let obj = {
				date: '',
				time: '',
				message: '',
				lastRun: ''
			};
			self.remindersTableArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let date = self.remindersTableArray[i].date;
			let time = self.remindersTableArray[i].time;
			let message = self.remindersTableArray[i].message;
			table += `
				<tr data-id="${i}">
					<td class="text-truncate p-1">
						<span id="date${i}" class="d-none">${date}</span>
						<input id="dateInput${i}" type="date" class="form-control dateInput recState" value="${date}" title="${date}">
					</td>
					<td class="text-truncate p-1">
						<span id="time${i}" class="d-none">${time}</span>
						<input id="timeInput${i}" type="time" class="form-control timeInput recState" value="${time}" title="${time}">
					</td>
					<td class="text-truncate p-1">
						<span id="message${i}" class="d-none">${message}</span>
						<input id="messageInput${i}" type="text" class="form-control messageInput recState" value="${message}" title="${message}">
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteReminder">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableReminders = $('#tableReminders').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '160px', targets: 0},
				{width: '90px', targets: 1},
				{width: '30px', targets: 3}
			],
			ordering: false,
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1355,
				className: 'd-none',
				title: pf.const.language.RSC1355,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

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

		if(self.missionState === '2') {
			$('.recState').prop('disabled', true);
		}

		self.tableRecordatoriosEvents();
	},

	tableRecordatoriosEvents() {
		let self = this;

		// Input de fecha
		$('.dateInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('dateInput', '');
			let value = $(this).val();
			self.remindersTableArray[index].date = value;
			self.remindersChange = true;
		});

		// Input de hora
		$('.timeInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('timeInput', '');
			let value = $(this).val();
			self.remindersTableArray[index].time = value;
			self.remindersChange = true;
		});

		// Input de mensaje
		$('.messageInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('messageInput', '');
			let value = $(this).val();
			self.remindersTableArray[index].message = value;
			self.remindersChange = true;
		});

		// Eliminar recordatorio
		$('.deleteReminder').off().on('click', function() {
			let index = $(this).parent().parent().data('id');
			self.remindersTableArray.splice(index, 1);
			self.remindersChange = true;
			self.tableRecordatorios();
		});
	},

	getNumParticipantesNotificados(typeMsg, id, descripcion = '') {
		let self = this;

		let parameters = {
			stampMision: self.stamp,
			project: id,
			typeMsg: typeMsg,
			descripcion: descripcion
		};
		ajaxComunCallWithCallback('getNumParticipantesNotificados', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(descripcion === '') {
					self.participantesNotificadosTable(ajaxReturn.result);
				} else {
					let arrayText = self.button.parent().prev().text().split('/');
					let newText = ajaxReturn.result + '/' + arrayText[1];
					self.button.parent().prev().text(newText);

					if(parseInt(ajaxReturn.result) == parseInt(arrayText[1])) {
						self.button.hide();
					}
				}
			}
		});
	},

	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.RSC176}">${pf.const.language.RSC176}</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>idProject</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].idProject}">${participants[i].idProject}</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>
		`;

		$('#headerModalTitle').text(pf.const.language.RSC1962);
		$('#divTableModal').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: '50px', targets: 4},
			{width: '30px', targets: 5},
			{width: '40px', targets: 6},
			{width: '70px', targets: 8},
			{width: '100px', targets: 9},
			{width: '130px', targets: 11}
		];

		// Control GDPR
		if(gdpr == '1') {
			columnDefs = [
				{width: '50px', targets: 1},
				{width: '30px', targets: 2},
				{width: '40px', targets: 3},
				{width: '70px', targets: 5},
				{width: '100px', targets: 6},
				{width: '130px', targets: 8}
			];
		}

		let tableNotifiedUsers = $('#tableNotifiedUsers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			autoWidth: false,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			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: []
		});

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

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

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

	getMisionesProjects() {
		let self = this;

		let parameters = {
			stampMision: self.stamp
		};
		ajaxComunCallWithCallback('getMisionesProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.projectList = ajaxReturn.result.map(project => project.NombreProyecto);
				self.projectListID = ajaxReturn.result.map(project => project.id);
				self.ListaDistribucionID = ajaxReturn.result.map(project => project.ListaDistribucionID);

				// Control de inclusión en proyecto para mostrar o no la pestaña de cumplimiento
				if(self.projectListID.length === 0) {
					$('#complianceTab').hide();
				}

				// Control para solo encuestas a la hora de reabrir
				let tipomision = self.typeOptions[self.index].idTipoMision;

				let participants = '0'
				if(ajaxReturn.result.length > 0) {
					participants = ajaxReturn.result[0].inicio.participantes;
				}

				// Control para que no se pueda modificar la fecha de una misión que no esté en ningún proyecto, o que este proyecto no tenga usuarios
				if(((self.projectListID.length === 0 || participants == '0') && self.missionState === '2') || (tipomision != 'Encuesta' && self.missionState === '2')) {
					// Candado
					$('#endMissionPermitsContainer').hide();
				}

				self.misionesProjectsTable(ajaxReturn.result);

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

	misionesProjectsTable(projects) {
		let self = this;

		let table = `
			<table id="tableMisionesProjects" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC387}">${pf.const.language.RSC387}</th>
						<th scope="col" title="${pf.const.language.RSC385}">${pf.const.language.RSC385}</th>
						<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
						<th scope="col" title="${pf.const.language.RSC443}">${pf.const.language.RSC133}</th>
						<th scope="col" title="${pf.const.language.RSC2183}">${pf.const.language.RSC2183}</th>
						<th scope="col" title="${pf.const.language.RSC1970}">${pf.const.language.RSC177}</th>
						<th scope="col" title="${pf.const.language.RSC1970}">${pf.const.language.RSC2024}</th>
					</tr>
				</thead>

				<thead class="filtersMisionesProjects">
					<tr>
						<td>LiderProyecto</td>
						<td>NombreProyecto</td>
						<td>id</td>
						<td>Inicio</td>
						<td>notificaciónAbierta</td>
						<td>Misión</td>
						<td>Fin</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = projects.length;
		for(let i = 0; i < size; i++) {
			// Botón inicio
			let buttonInicio = '';
			if(projects[i].inicio.notificados < projects[i].inicio.participantes) {
				buttonInicio += `
					<button id="" type="button" class="alertNotifyUsersInicio btn btn-eye loadFile btn-validate" data-id="${i}" typeMSG="initMision" idProject="${projects[i].id}" data-from="${projects[i].LiderProyectoJID}">
						${stcmbackend.svg.exclamationLgWithoutColor}
					</button>
				`;
			}

			// Botón misión
			let buttonMision = '';

			// Si no es encuesta, no devuelve el parámetro 'mision'
			let misionText = '-';
			if(projects[i].mision != null) {
				if(projects[i].mision.notificados < projects[i].mision.participantes) {
					buttonMision += `
						<button type="button" class="alertNotifyUsersMision btn btn-eye loadFile btn-validate" data-id="${i}" typeMSG="isMision" idProject="${projects[i].id}" data-from="${projects[i].LiderProyectoJID}">
							${stcmbackend.svg.exclamationLgWithoutColor}
						</button>
					`;
				}
				misionText = `
					<div class="d-flex align-items-center">
						<div id="${projects[i].id}" class="mr-auto p-2 clickable_label" type="isMision" data-toggle="modal" data-target="#modalContainer">
							${projects[i].mision.notificados}/${projects[i].mision.participantes}
						</div>
						<div>
							${buttonMision}
						</div>
					</div>
				`;
			}

			// Botón fin
			let buttonFin = '';
			// Si la encuesta no esta finalizada, no debe aparecer el botón para notificar la finalización
			let stateText = atob(sessionStorage.getItem('idMissionState'));
			// 1 - en curso / 2 - finalizada
			if(stateText == 2) {
				if(projects[i].fin.notificados < projects[i].fin.participantes) {
					buttonFin += `
						<button type="button" class="alertNotifyUsersFin btn btn-eye loadFile btn-validate" data-id="${i}" typeMSG="finMision" idProject="${projects[i].id}" data-from="${projects[i].LiderProyectoJID}">
							${stcmbackend.svg.exclamationLgWithoutColor}
						</button>
					`;
				}
			}

			table += `
				<tr>
					<td class="text-truncate" title="${projects[i].LiderProyecto}">${projects[i].LiderProyecto}</td>
					<td class="text-truncate" title="${projects[i].NombreProyecto}">${projects[i].NombreProyecto}</td>
					<td class="text-truncate" title="${projects[i].id}">${projects[i].id}</td>
					<td class="text-truncate" title="${projects[i].id}">
						<div class="d-flex align-items-center">
							<div id="${projects[i].id}" class="mr-auto p-2 clickable_label" type="initMision" data-toggle="modal" data-target="#modalContainer">
								${projects[i].inicio.notificados}/${projects[i].inicio.participantes}
							</div>
							<div>
								${buttonInicio}
							</div>
						</div>
					</td>
					<td class="text-truncate" title="${projects[i].id}">${(projects[i].misionPushOpen == undefined ? '0' : projects[i].misionPushOpen.abrieron)}/${(projects[i].misionPushOpen == undefined ? '0' : projects[i].misionPushOpen.participantes)}</td>
					<td class="text-truncate" title="${projects[i].id}">
						${misionText}
					</td>
					<td class="text-truncate" title="${projects[i].id}">
						<div class="d-flex align-items-center">
							<div id="${projects[i].id}" class="mr-auto p-2 clickable_label" type="finMision" data-toggle="modal" data-target="#modalContainer">
								${projects[i].fin.notificados}/${projects[i].fin.participantes}
							</div>
							<div>
								${buttonFin}
							</div>
						</div>
					</td>
				</tr>
			`;
		}

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

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

		$('.clickable_label').off().on('click', function() {
			let typeMsg = $(this).attr('type');
			let id = $(this).attr('id');
			self.getNumParticipantesNotificados(typeMsg, id);
		});

		// Alert button diferencia nº Participantes <-> nº Notificados / Inicio
		$('.alertNotifyUsersInicio').off().on('click', function() {
			self.button = $(this);
			let typeMsg = $(this).attr('typeMSG');
			let idProject = $(this).attr('idProject');
			let from = $(this).data('from');
			let message = self.data.textoiniciomision;
			let objInfo = {
				accept: {
					text: pf.const.language.RSC1242
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2023;
			let alertText = pf.const.language.RSC2022;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.sendNotificationsToUnnotifiedUsers(typeMsg, idProject, message, 0, from);
			}, function() {});
		});

		// Alert button diferencia nº Participantes <-> nº Notificados / Misión
		$('.alertNotifyUsersMision').off().on('click', function() {
			self.button = $(this);
			let typeMsg = $(this).attr('typeMSG');
			let idProject = $(this).attr('idProject');
			let from = $(this).data('from');
			let message = self.data.textoiniciomision;
			let objInfo = {
				accept: {
					text: pf.const.language.RSC1242
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2023;
			let alertText = pf.const.language.RSC2022;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				let surveyId = self.data.sid;
				self.sendNotificationsToUnnotifiedUsers(typeMsg, idProject, message, 1, from, surveyId);
			}, function() {});
		});

		// Alert button diferencia nº Participantes <-> nº Notificados / Fin
		$('.alertNotifyUsersFin').off().on('click', function() {
			self.button = $(this);
			let typeMsg = $(this).attr('typeMSG');
			let idProject = $(this).attr('idProject');
			let from = $(this).data('from');
			let message = self.data.textofinmision;
			// Si se cierra por cupo, se utiliza el texto de finalización por cupo
			if(self.data.finmisioncupo != 0) {
				message = self.data.textofinmisioncupo;
			}

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

			let alertTitle = pf.const.language.RSC2023;
			let alertText = pf.const.language.RSC2022;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.sendNotificationsToUnnotifiedUsers(typeMsg, idProject, message, 0, from);
			}, function() {});
		});

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

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

		let tableMisionesProjects = $('#tableMisionesProjects').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			autoWidth: false,
			columnDefs: [
				{width: '100px', targets: 2}
			],
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1963,
				className: 'd-none',
				title: pf.const.language.RSC1963,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Apply the search
		applyTheSearch(tableMisionesProjects, 'filtersMisionesProjects');

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

	sendNotificationsToUnnotifiedUsers(typeMsg, idProject, message, postSurvey, from, surveyId) {
		let self = this;

		let parameters = {
			stampMision: self.stamp,
			project: idProject,
			typeMsg: typeMsg
		};
		ajaxComunCallWithCallback('sendMisionMessageUsersNotNotified', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(postSurvey == 1) {
					self.postSurvey(typeMsg, idProject, message, from, ajaxReturn.result, surveyId);
				} else {
					self.notificarListaDeDifusion(idProject, ajaxReturn.result, typeMsg, message, from);
				}
			}
		});
	},

	notificarListaDeDifusion(idProject, idListaDeDifusion, typeMsg, message, from) {
		let self = this;

		let initMision = 0;
		let finMision = 0;
		let silent = 0;
		if(typeMsg == 'initMision' && self.data.encuesta == 1) {
			silent = 1; // 1 si es inicio y encuesta
		}

		if(typeMsg == 'initMision') {
			initMision = 1;
			finMision = 0;
		} else {
			initMision = 0;
			finMision = 1;
		}

		let cupoMision = 0;
		if(self.data.finmisioncupo != 0) {
			cupoMision = 1;
		}

		let parameters = {
			from: from,
			emailsToSend: '',
			message: message,
			idlist: idListaDeDifusion,
			silent: silent,
			misionStamp: self.stamp,
			idProject: idProject,
			initMision: initMision,
			finMision: finMision,
			isMision: 0,
			typeMsg: 1,
			cupoMision: cupoMision
		};
		ajaxComunCallWithCallback('postMessageMultiple', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.getNumParticipantesNotificados(typeMsg, idProject, 'number');
			}
		}, false);
	},

	getCMBPProjectInfo(idProject, idListaDeDifusion, typeMsg, message, postSurvey, surveyId) {
		let self = this;

		if(postSurvey == 1) {
			self.postSurvey(typeMsg, idProject, message, from, idListaDeDifusion, surveyId);
		} else {
			self.notificarListaDeDifusion(idProject, idListaDeDifusion, typeMsg, message, from);
		}
	},

	postSurvey(typeMsg, idProject, message, from, idListaDeDifusion, surveyId) {
		let self = this;

		let parameters = {
			from: from,
			emailsToSend: '',
			message: surveyId,
			idlist: idListaDeDifusion,
			misionStamp: self.stamp,
			idProject: idProject,
			textToNotify: message,
			isMision: 1
		};
		ajaxComunCallWithCallback('postSurveyMisiones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.getNumParticipantesNotificados(typeMsg, idProject, 'number');
			}
		});
	},

	// Petición de valores de encuesta
	getTargetsSurvey(init) {
		let self = this;

		let survey = $('.survey').val();

		let parameters = {
			survey: survey
		};
		ajaxComunCallWithCallback('getTargetsSurvey', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
					for(let j = 0; j < size; j++) {
					// Tipos no permitidos
					let typesNotAllowed = ['1', '2', '3', '4', '6', '7', 'J', '8', ':', ';', '*', '|', 'A', 'B', 'C', 'D', 'E', 'H', 'I', 'K', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'X'];

					if(typesNotAllowed.indexOf(ajaxReturn.result[j].type) !== -1 || ajaxReturn.result[j].question.includes('SOCIAL_LABS_')) {
						continue;
					}

					// Si la pregunta es de tipo K se crean valores correspondientes al array de preguntas
					if(ajaxReturn.result[j].type == 'K') {
						ajaxReturn.result[j].value = {};
						ajaxReturn.result[j].code = {};
						let sizeK = ajaxReturn.result[j].valuesSQ.length;
						for(let f = 0; f < sizeK; f++) {
							let columnNameKArray = ajaxReturn.result[j].valuesSQ[f].split('|');
							let columnNameK = columnNameKArray[0];
							ajaxReturn.result[j].value[columnNameK] = [];
							ajaxReturn.result[j].code[columnNameK] = [];
							ajaxReturn.result[j].valueInclusive[columnNameK] = [];
							ajaxReturn.result[j].codeInclusive[columnNameK] = [];
						}
					} else {
						ajaxReturn.result[j].value = [];
						ajaxReturn.result[j].code = [];
						ajaxReturn.result[j].valueInclusive = [];
						ajaxReturn.result[j].codeInclusive = [];
					}

					// Array de preguntas que pueden utilizarse para discriminar
					self.questionDiscriminatoryArray.push(ajaxReturn.result[j]);
				}

				if(init) {
					// Pedir información de preguntas/respuestas excluidas
					self.getMisionQuestionNoAccomplish();
				}

				// Modal con tabla de preguntas
				self.renderQuests();
			}
		}, false);
	},

	// renderizado de modal con tabla de preguntas
	renderQuests() {
		let self = this;

		let table = `
			<table id="tableTargetsSurvey" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
						<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
					</tr>
				</thead>

				<thead class="filtersQuest">
					<tr>
						<td>columnName</td>
						<td>question</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.questionDiscriminatoryArray.length;
		for(let i = 0; i < size; i++) {
			// Si la pregunta ya ha sido seleccionada no aparece
			if(self.selectedQuestionsID.indexOf(self.questionDiscriminatoryArray[i].columnName) !== -1) {
				continue;
			}

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

			table += `
				<tr class="c-pointer" data-index="${i}">
					<td id="${self.questionDiscriminatoryArray[i].columnName}" class="columnName selectQ">${self.questionDiscriminatoryArray[i].columnName}</td>
					<td class="question selectQ">${tagsWithoutTags}</td>
				</tr>
			`;
		}

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

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableTargetsSurvey, 'filtersQuest');

		$('#tableTargetsSurvey tr').on('click', function() {
			let index = $(this).data('index');

			// La pregunta seleccionad se guarda en self.selectedQuestions y su ID en self.selectedQuestionsID
			self.selectedQuestions.push(self.questionDiscriminatoryArray[index]);
			self.selectedQuestionsID.push(self.questionDiscriminatoryArray[index].columnName);

			// Añadido de array valores inclusivos en caso de que no exista
			if(self.questionDiscriminatoryArray[index].valueInclusive == null && self.questionDiscriminatoryArray[index].codeInclusive == null) {
				self.questionDiscriminatoryArray[index].valueInclusive = [];
				self.questionDiscriminatoryArray[index].codeInclusive = [];
			}

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

			// Renderizado de las preguntas seleccionadas
			self.renderTargetsSurvey();
		});
	},

	renderTargetsSurvey() {
		let self = this;

		let table = `
			<table id="targetsSurveyTable" class="table table-hover mt-0">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
						<th scope="col" title="${pf.const.language.RSC2127}">${pf.const.language.RSC2127}</th>
						<th scope="col" title="${pf.const.language.RSC2128}">${pf.const.language.RSC2128}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<thead class="filtersTargetsSurvey">
					<tr>
						<td>question</td>
						<td>value</td>
						<td>valueInclusive</td>
						<td>trash</td>
					</tr>
				</thead>

				<tbody>
		`;

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

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

			let valueInputInclusive = `
				<div class="input-group new-input-style">
					<input type="text" class="form-control inputValueInclusive" title="${self.selectedQuestions[i].valueInclusive}" placeholder="${pf.const.language.RSC127}" aria-label="Valores" value="${self.selectedQuestions[i].valueInclusive}" disabled>
					<div class="input-group-append">
						<button type="button" class="btn btn-outline-secondary btn-table-selected-rel searchValuesInclusive stateObjetive" data-toggle="modal" data-target="#valuesTable" data-qid="${qid}" data-columnName="${self.selectedQuestions[i].columnName}" data-index="${i}" disabled>
							${stcmbackend.svg.threeDotsSmall}
						</button>
					</div>
				</div>
			`;

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

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

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

					valueInput = `
						<div class="input-group new-input-style">
							<input type="text" class="form-control inputValue" title="${self.selectedQuestions[i].value}" placeholder="${pf.const.language.RSC127}" aria-label="Valores" value="${self.selectedQuestions[i].value}" disabled>
							<div class="input-group-append">
								<button type="button" class="btn btn-outline-secondary KValues btn-table-selected-rel stateObjetive" data-toggle="modal" data-target="#valuesTable" data-qid="${qid}" data-columnName="${self.selectedQuestions[i].columnName}" data-columnNameK="${columnNameK}" data-index="${i}">
									${stcmbackend.svg.threeDotsSmall}
								</button>
							</div>
						</div>
					`;

					table += `
						<tr id="cn_${columnNameK}" data-inputCode="">
							<td class="align-middle" title="${questionKTitle}">${questionK}</td>
							<td>
								${valueInput}
							</td>
							<td>
								${valueInputInclusive}
							</td>
							<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
								<span class="c-pointer deleteTargetsSurvey" data-id="${self.selectedQuestions[i].columnName}">
									${stcmbackend.svg.bigTrash}
								</span>
							</td>
						</tr>
					`;
				}
			} else {
				// El atributo data-inputCode suplira a la columna de código
				table += `
					<tr id="cn_${self.selectedQuestions[i].columnName}" data-inputCode="">
						<td class="align-middle" title="${tagsWithoutTags.trim()}">${tagsWithoutTags.trim()}</td>
						<td>
							${valueInput}
						</td>
						<td>
							${valueInputInclusive}
						</td>
						<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
							<span class="c-pointer deleteTargetsSurvey" data-id="${self.selectedQuestions[i].columnName}">
								${stcmbackend.svg.bigTrash}
							</span>
						</td>
					</tr>
				`;
			}
		}

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

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

		if(self.missionState === '0') {
			$('.stateObjetive').prop('disabled', false);
		} else {
			$('.stateObjetive').prop('disabled', true);
		}

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

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

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

		let dataTable = $('#targetsSurveyTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '35%', targets: 1},
				{width: '35%', targets: 2},
				{width: '30px', targets: 3}
			],
			aaSorting: []
		});

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

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

		self.eventTargetsSurvey();
		
		$('#targetsSurveyTable').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 index = $(this).data('index');
			let survey = $('.survey').val();
			self.columnName = $(this).attr('data-columnName');
			self.requestSurveyValues(qid, survey, index);
		});

		// Valores de modal
		$('.searchValuesInclusive').off().on('click', function() {
			let qid = $(this).attr('data-qid');
			let index = $(this).data('index');
			let survey = $('.survey').val();
			self.columnName = $(this).attr('data-columnName');
			self.requestSurveyValues(qid, survey, index, true);
		});

		// 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');
			self.renderSurveyValues(index);
		});

		// 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.selectedQuestions.length;
			for(let i = 0; i < size; i++) {
				if(self.selectedQuestions[i].columnName == self.columnName) {
					self.surveyValues = self.selectedQuestions[i].values;
					break;
				}
			}

			self.renderSurveyValues(index);
		});

		// 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.selectedQuestions.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.selectedQuestions[i].columnName) {
						self.selectedQuestions[i].value = value;
						self.selectedQuestions[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.selectedQuestions[i].columnName) {
						self.selectedQuestions[i].value = value;
						self.selectedQuestions[i].code = code;
					}
				}
			}
		});

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

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

			let indexSelectedQuestionsID = self.selectedQuestionsID.indexOf(id);
			self.selectedQuestionsID.splice(indexSelectedQuestionsID, 1);

			self.renderTargetsSurvey();
		});
	},

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

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

				self.renderSurveyValues(index, inclusiveModal);
			}
		});
	},

	renderSurveyValues(index, inclusiveModal) {
		let self = this;

		// Nombre/code sacado del modal
		let table = `
			<table id="tableValues" class="table table-hover tv-80">
				<thead>
					<tr>
						<th scope="col">
							${pf.const.language.RSC406}
							<input id="selectionAll" type="checkbox" ${(false ? 'checked' : '')} class="align-middle">
						</th>
						<th scope="col">${pf.const.language.RSC127}</th>
					</tr>
				</thead>

				<thead class="filtersValue">
					<tr>
						<td>checkbox</td>
						<td>answerName</td>
					</tr>
				</thead>

				<tbody>
		`;

		let controlChecks = [];
		let typeK = false;
		let questionSize = self.selectedQuestions.length;
		for(let i = 0; i < questionSize; i++) {
			if(self.selectedQuestions[i].columnName == self.columnName && self.selectedQuestions[i].type != 'K') {
				if(inclusiveModal) {
					controlChecksInclusive = self.selectedQuestions[i].codeInclusive;
				} else {
					controlChecks = self.selectedQuestions[i].code;
				}
			} else if(self.selectedQuestions[i].columnName == self.columnName && self.selectedQuestions[i].type == 'K') {
				typeK = true;
				controlChecks = self.selectedQuestions[i].code[self.columnNameK];
			}
		}

		let size = self.surveyValues.length;
		for(let i = 0; i < size; i++) {
			let checked = false;
			let surveyValue = self.surveyValues[i];
			if(typeK) {
				checked = (controlChecks.indexOf(String(self.surveyValues[i].code)) != -1 ? true : false);
			} else {
				let value = surveyValue.title || surveyValue.code;
				if(inclusiveModal) {
					checked = (controlChecksInclusive.indexOf(value) != -1 ? true : false);
				} else {
					checked = (controlChecks.indexOf(value) != -1 ? true : false);
				}
			}

			let answer = self.surveyValues[i].answer;
			switch(answer) {
				case 'Y':
					answer = pf.const.language.RSC120;
					break;
				case 'N':
					answer = pf.const.language.RSC121;
					break;
				case 'M':
					answer = pf.const.language.RSC556;
					break;
				case 'F':
					answer = pf.const.language.RSC557;
					break;
			}
			let code = self.surveyValues[i].code || self.surveyValues[i].title;

			// Si los elementos se encuentran en la lista contraria, no se cargan en la tabla
			if(inclusiveModal) {
				if(self.selectedQuestions[index].code.includes(code)) {
					continue;
				}
			} else {
				if(self.selectedQuestions[index].codeInclusive.includes(code)) {
					continue;
				}
			}

			table += `
				<tr class="c-pointer check-select" data-value="${self.surveyValues[i].answer}" data-code="${code}">
					<td class="text-center">
						<span class="d-none">${(checked ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="selection" ${(checked ? 'checked' : '')}>
					</td>
					<td class="value">${answer}</td>
				</tr>
			`;
		}

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

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

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

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

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

		let ObjetiveTable = $('#tableValues').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '130px', targets: 0}
			],
			ordering: false,
			aaSorting: []
		});

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

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

		if($('.selection').length == $('.selection:checked').length) {
			$('#selectionAll').prop('checked', true);
		} else {
			$('#selectionAll').prop('checked', false);
		}

		// Selección de múltiples encuestas
		self.selectionMult(index, inclusiveModal);

		$('#tableValues').on('draw.dt', function() {
			self.selectionMult(index, inclusiveModal);
		});
	},

	selectionMult(index, inclusiveModal) {
		let self = this;

		self.isInclusive = inclusiveModal;

		// Selección por tr
		$('.check-select').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			if($('.selection').length == $('.selection:checked').length) {
				$('#selectionAll').prop('checked', true);
			} else {
				$('#selectionAll').prop('checked', false);
			}
		});

		// Selección por input
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			if($('.selection').length == $('.selection:checked').length) {
				$('#selectionAll').prop('checked', true);
			} else {
				$('#selectionAll').prop('checked', false);
			}
		});

		// La id del elemento principal modifica los elementos secundarios a través de su clase
		$('#selectionAll').on('click', function() {
			$('.selection').prop('checked', this.checked);
		});

		$('#selectValues').off().on('click', function() {
			let valueArray = [];
			let codeArray = [];
			let nameArray = [];

			let valueArrayFiltered = [];
			let codeArrayFiltered = [];

			$('#tableValues tr').each(function() {
				let cheked = $(this).find('.selection');
				if(cheked.prop('checked')) {
					valueArray.push($(this).attr('data-value'));
					codeArray.push($(this).attr('data-code'));
					nameArray.push($(this).find('.value').text());
				}
			});

			let typeK = false;
			let size = self.selectedQuestions.length;
			for(let i = 0; i < size; i++) {
				if(self.columnName == self.selectedQuestions[i].columnName && self.selectedQuestions[i].type != 'K') {
					if(self.isInclusive) {
						// Una pregunta Inclusiva no puede estar en la array de preguntas Exclusivas
						for(let j = 0; j < valueArray.length; j++) {
							if(!self.selectedQuestions[i].value.includes(valueArray[j])) {
								valueArrayFiltered.push(valueArray[j]);
							}
						}
						for(let j = 0; j < codeArray.length; j++) {
							if(!self.selectedQuestions[i].code.includes(codeArray[j])) {
								codeArrayFiltered.push(codeArray[j]);
							}
						}
						self.selectedQuestions[i].valueInclusive = valueArrayFiltered;
						self.selectedQuestions[i].codeInclusive = codeArrayFiltered;
					} else {
						// Una pregunta Exclusiva no puede estar en la array de preguntas Inclusivas
						for(let j = 0; j < valueArray.length; j++) {
							if(!self.selectedQuestions[i].valueInclusive.includes(valueArray[j])) {
								valueArrayFiltered.push(valueArray[j]);
							}
						}

						for(let j = 0; j < codeArray.length; j++) {
							if(!self.selectedQuestions[i].codeInclusive.includes(codeArray[j])) {
								codeArrayFiltered.push(codeArray[j]);
							}
						}
						self.selectedQuestions[i].value = valueArrayFiltered;
						self.selectedQuestions[i].code = codeArrayFiltered;
					}
				} else if(self.columnName == self.selectedQuestions[i].columnName && self.selectedQuestions[i].type == 'K') {
					typeK = true;
					self.selectedQuestions[i].value[self.columnNameK] = valueArray;
					self.selectedQuestions[i].code[self.columnNameK] = codeArray;
				}
			}

			if(typeK) {
				$('#cn_' + self.columnNameK).find('.inputValue').val(nameArray);
				$('#cn_' + self.columnNameK).find('.inputValue').attr('title', nameArray);
				$('#cn_' + self.columnNameK).attr('data-inputCode', codeArray);
				$('#closeValues').trigger('click');
			} else {
				if(self.isInclusive) {
					$('#cn_' + self.columnName).find('.inputValueInclusive').val(nameArray);
					$('#cn_' + self.columnName).find('.inputValueInclusive').attr('title', nameArray);
					$('#cn_' + self.columnName).attr('data-inputCode', codeArrayFiltered);
					$('#closeValues').trigger('click');
				} else {
					$('#cn_' + self.columnName).find('.inputValue').val(nameArray);
					$('#cn_' + self.columnName).find('.inputValue').attr('title', nameArray);
					$('#cn_' + self.columnName).attr('data-inputCode', codeArrayFiltered);
					$('#closeValues').trigger('click');
				}
			}
		});
	},

	showEndReasonAlert(callback) {
		let content = `
			<div class="form-group">
				<label for="endReason" class="fw-500">${pf.const.language.RSC331}</label>
				<input id="endReason" type="text" class="form-control" value="">
			</div>
		`;

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

		let alertTitle = pf.const.language.RSC14;
		pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
			callback();
		}, function() {});
	},

	editRSC(textNotifImput) {
		let objectRSC = null;
		let lenguage = sessionStorage['STCMBackEnd:lenguage'];

		let parameters = {
			rsc: '2211'
		};
		ajaxComunCallWithCallback('getRSC', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				objectRSC = ajaxReturn.result[0];
				objectRSC[lenguage] = textNotifImput;

				let parameters = {
					rsc: '2211',
					system: objectRSC.system,
					country: objectRSC.country,
					app: objectRSC.app
				};

				for(let element in objectRSC) {
					if(element == 'idRSC' || element == 'system' || element == 'country' || element == 'app' || element == 'idTenant' || element == 'idCPG') {
						continue;
					}

					let key = element.toLowerCase();

					parameters[key] = objectRSC[element];
				}

				ajaxComunCallWithCallback('updateRSC', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						//
					}
				}, false);
			}
		}, false);
	}
};