let StepByStepMissionEditController = {
	pageName: 'StepByStepMissionEditController',
	userJSON: 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',
	isInclusive: false,
	button: null,
	projectList: [],
	isSurvey: false,
	missionCompleted: 0,
	reopeningMessage: '',
	projectListID: [],
	ListaDistribucionID: '',
	dateFormat: '',
	// Misiones anidadas
	nestableMissions: [],
	nestedMission: null,
	nestedMissionOld: '',
	// Step by step
	stampMissionSBS: '',
	selectNewSurvey: false,

	reset() {
		let self = this;

		self.userJSON = null;
		self.idMission = sessionStorage.getItem('idMisionSBS');
		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 = '0';
		self.stamp = sessionStorage.getItem('stampMissionSBS');
		self.loaders = {
			getAllTipoMision: false,
			getMision: false,
			getMisionesObjetivos: false,
			getMisionRemember: false,
			getPaisesEnabled: 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.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 = '';
		// Step by step
		self.stampMissionSBS = '';
		self.selectNewSurvey = false;
	},

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

		// Información de administrador
		self.userJSON = JSON.parse(sessionStorage['STCMBackEnd:user']);
		self.userMail = self.userJSON.email;
		self.dateFormat = self.userJSON.formatoFecha;

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

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

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

				StepByStepSharedController.renderTypes(self);
				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();

		// Imagenes para selección de encuesta
		let srcImgNewSurvey = stcm.const.downloads + 'svg_new/black_cross.svg';
		$('#newSurveyIMG').attr('src', srcImgNewSurvey);
		let srcImgExistingSurvey = stcm.const.downloads + 'svg_new/file.svg';
		$('#existingSurveyIMG').attr('src', srcImgExistingSurvey);

		// Collapse
		addEventArrowTableHeader();

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

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

		// Títulos comunes
		StepByStepSharedController.commonTitles();
	},

	applyEvents() {
		let self = this;

		StepByStepSharedController.sharedEventscommon(self);
		StepByStepSharedController.sharedEventsMissions(self);

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

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

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

		// Editar misión
		$('#nextSBS').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') {
					StepByStepSharedController.existsMisionBetweenDates(self);
				} 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() {});
		});
	},

	// 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.getMision = true;
						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();
			}
		}, 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
						};
						self.remindersTableArray.push(obj);
						self.remindersId.push(ajaxReturn.result[i].id);
					}
				}

				StepByStepSharedController.tableRecordatorios(self);

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

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

	renderData() {
		let self = this;

		$('#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;
			}
		}

		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;

				sessionStorage.setItem('misionObjectiveSBS', self.objetive);
				sessionStorage.setItem('descMisionObjectiveSBS', pf.const.language['RSC' + self.objetive.descripcion]);

				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
				if(self.objectives[0].encuesta != 'undefined') {
					$('.survey').val(self.objectives[0].encuesta);
				} else {
					self.selectNewSurvey = true;
				}
				$('.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;

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

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

		// Productos / importe
		self.productsAmountModal = new TableProducts(1, 'StepByStepMissionEditController');
		$('.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 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');
		});
	},

	preRenderObjetives() {
		let self = this;

		$('#tableProducts').html('')
		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);
			}
	},

	editMission() {
		let self = this;

		let noValidate = false;

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

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

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

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

		// Validación texto misión no cumplida
		let textomisionko = $('#missionNoAccomplished').val().trim();
		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() === '' && !self.selectNewSurvey) {
					$('.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;
					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;
					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: false,
			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,
			selectNewSurveySBS: self.selectNewSurvey,
			isAuditoria: ($('#isAuditoria').prop('checked') ? '1' : '0')
		};
		ajaxComunCallWithCallback('updateMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(self.selectNewSurvey) {
					sessionStorage.setItem('selectNewSurveySBS', '1');
					sessionStorage.setItem('surveySBS', '');
					window.location.href = '#!step_by_step_survey';
				} else {
					sessionStorage.setItem('selectNewSurveySBS', '0');
					// Control nuevo / editar
					if(sessionStorage['criterionSBS'] == '1') {
						window.location.href = '#!step_by_step_criterion_edit';
					} else {
						window.location.href = '#!step_by_step_criterion_new';
					}
				}
			}
		});
	},

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

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

		switch(self.requestType) {
			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', 'editMissionSBS');
				break;

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

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

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

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

			default:
				break;
		}
	},

	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;
			StepByStepSharedController.tableRecordatorios(self);
		});
	},

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

			// 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 = [];
			}

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

			$('#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');
				}
			}
		});
	}
};