let StepByStepMissionNewController = {
	pageName: 'StepByStepMissionNewController',
	language: '',
	typeOptions: [],
	objetive: '',
	index: '',
	surveys: '',
	templates: '',
	products: '',
	today: '',
	country: '',
	requestType: '',
	market: 0,
	productsModal: '',
	productsAmountModal: '',
	remindersTableArray: [],
	usuarioQueNotifica: '',
	descUsuarioQueNotifica: '',
	userMail: '',
	// 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: '',
	isInclusive: false,
	dateFormat: '',
	// Misiones anidadas
	isSurvey: false,
	nestableMissions: [],
	nestedMission: null,
	// Step by step
	stampMissionSBS: '',
	selectNewSurvey: false,

	reset() {
		let self = this;

		self.language = pf.const.language_table;
		self.typeOptions = [];
		self.objetive = '';
		self.index = '';
		self.surveys = '';
		self.templates = '';
		self.products = '';
		self.today = '';
		self.country = [];
		self.requestType = '';
		self.market = sessionStorage['STCMBackEnd:config_market'];
		self.productsModal = '';
		self.productsAmountModal = '';
		self.remindersTableArray = [];
		self.usuarioQueNotifica = '';
		self.descUsuarioQueNotifica = '';
		self.userMail = '';
		// 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 = '';
		self.isInclusive = false;
		self.dateFormat = '';
		// Misiones anidadas
		self.isSurvey = false;
		self.nestableMissions = [];
		self.nestedMission = null;
		// Step by step
		self.stampMissionSBS = '';
		self.selectNewSurvey = false;
	},

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

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

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

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

		// Fecha y hora
		let now = new Date();
		let nYear = now.getFullYear();
		let nMonth = now.getMonth() + 1;
		if(nMonth < 10) {
			nMonth = '0' + nMonth;
		}
		let nDay = now.getDate();
		if(nDay < 10) {
			nDay = '0' + nDay;
		}
		self.today = nYear + '-' + nMonth + '-' + nDay;

		$('#startDate').val(self.today);
		$('#startTime').val('00:00');
		$('#endDate').val(self.today);
		$('#endTime').val('23:59');

		// Nombre de proyecto puesto a la misión
		$('#missionName').val(sessionStorage['nameProjectSBS']);

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

		ajaxComunCallWithCallback('getPaisesEnabled', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				// Obtener países permitidos
				let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
				let noDefault = true;
				let firstCountry = true;

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

					if(ajaxReturn.result[i].isocode == sessionStorage['countryProjectSBS']) {
						noDefault = false;
						self.country = ajaxReturn.result[i];

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

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

						$('#projectCountry').val(self.country.isocode);

						firstCountry = false;
					} else if(firstCountry) {
						self.country = ajaxReturn.result[i];

						firstCountry = false;
					}
				}

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

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

					$('#projectCountry').val(self.country.isocode);
				}
			}
		});

		StepByStepSharedController.tableRecordatorios(self);

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

		// Ocultar de inicio la sección de Misión anidada
		$('#nestedMissionDivContainer').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);

		// Restricciones de carácteres por tecla para el nombre de misión
		$('#missionName').off().on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1972, /[a-z0-9_-\s.]/i);

			return result;
		});

		// Restricciones de carácteres por pegado para el nombre de misión
		$('#missionName').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1972, /[^a-z0-9_-\s.]/gi);
		});

		// 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.length > 0) {
					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();
				$('#startDate').val(self.today);
				$('#endDate').val(self.today);

				// Para las encuestas
				if(self.typeOptions.length > 0 && self.index != '') {
					if(self.typeOptions[self.index].isSurvey == '1') {
						$('#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 = [];

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

						StepByStepSharedController.renderTypes(self);
					}
				});
			}

			$('#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();
				$('#startDate').val(self.today);
				$('#startTime').val('00:00');
				$('#endDate').val(self.today);
				$('#endTime').val('23:59');
			}
		});

		// Guardar nueva misión
		$('#nextSBS').on('click', function() {
			// Comprobación de misiones referidas
			if(self.typeOptions[self.index] != undefined) {
				let tipomision = self.typeOptions[self.index].idTipoMision;
				if(tipomision == 'Referidos') {
					StepByStepSharedController.existsMisionBetweenDates(self);
				} else {
					self.createMission();
				}
			}
		});
	},

	renderObjetives() {
		let self = this;

		// 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" 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 {
			//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">
								</td>
								<td id="tdCurrency" class="text-truncate align-middle" title="${self.country.currency}">${self.country.currency}</td>
								<td class="text-truncate align-middle">
									<input type="number" class="form-control inputGrid percent">
								</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">
								</td>
								<td class="text-truncate align-middle">
									<input type="number" class="form-control inputGrid percent">
								</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" 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}</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 objetiveTimes" value="1">
							</td>
							<td class="text-truncate align-middle">
								<select class="form-control objetivePeriod selectGrid he-26 p-0">
									<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">
							</td>
							<td class="text-truncate align-middle">
								<select class="form-control objetivePeriod selectGrid he-26 p-0">
									<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);

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

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

		// Encuestas
		$('.searchSurvey').on('click', function() {
			if(self.surveys === '') {
				let JSONuser = sessionStorage['STCMBackEnd:user'];
				let user = JSON.parse(JSONuser);
				let idCliente = user.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, 'StepByStepMissionNewController');
		$('.searchProduct').off().on('click', function() {
			self.requestType = 'addProducts';
			self.productsModal.setEvents(self.products);
		});

		// Productos / importe
		self.productsAmountModal = new TableProducts(1, 'StepByStepMissionNewController');
		$('.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="${pf.const.language.RSC366}">${pf.const.language.RSC366}</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: self.language,
			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);

			$('#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') {
			let parameters = {
				tipomision: self.typeOptions[self.index].idTipoMision
			};
			ajaxComunCallWithCallback('getAllTipoMisionObjetivos', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					self.objetive = ajaxReturn.result;

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

					if(!self.selectNewSurvey) {
						self.renderObjetives();
					}
				}
			});
		} else {
			$('#registers').html('');
		}

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

		if(self.typeOptions[self.index].isSurvey == '1' && !$('#alwaysCurrent').prop('checked')) {
			$('#answersLimitContainer').removeClass('d-none');
			$('#numMaxUsers').prop('disabled', false);
			$('#missionClosed').prop('disabled', false);
		} else {
			$('#answersLimitContainer').addClass('d-none');
			$('#numMaxUsers').val('');
			$('#numMaxUsers').prop('disabled', true);
			$('#missionClosed').val('');
			$('#missionClosed').prop('disabled', true);
		}
	},

	createMission() {
		let self = this;

		let noValidate = false;

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

		// 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') {
			$('#missionTypeInput').addClass('is-invalid');
			$('[for="missionTypeInput"]').addClass('is-invalid');
			noValidate = true;
		} else {
			$('#missionTypeInput').removeClass('is-invalid');
			$('[for="missionTypeInput"]').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 = {
			missionSBS: '1',
			id: sessionStorage['idProjectSBS'],
			idmision: idmision,
			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,
			currencyinterno: $('#currencyCommission').val(),
			needValidation: ($('#needValidation').prop('checked') ? '1' : '0'),
			misionQuestionsArray: JSON.stringify(self.selectedQuestions),
			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),
			selectNewSurveySBS: self.selectNewSurvey,
			isAuditoria: ($('#isAuditoria').prop('checked') ? '1' : '0')
		};
		ajaxComunCallWithCallback('createMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				sessionStorage.setItem('stampMissionSBS', ajaxReturn.result);
				sessionStorage.setItem('idMisionSBS', idmision);
				sessionStorage.setItem('surveySBS', '');

				if(self.selectNewSurvey) {
					sessionStorage.setItem('selectNewSurveySBS', '1');
					window.location.href = '#!step_by_step_survey';
				} else {
					sessionStorage.setItem('selectNewSurveySBS', '0');
					window.location.href = '#!step_by_step_criterion_new';
				}
			}
		});
	},

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

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

		switch(self.requestType) {
			case 'addProducts':
				self.products = data;
				TableProductsMision.setEvents(self.products, 'divProductsTable', 'newMissionSBS');
				break;

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

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

			case 'removeProductAmount':
				self.products.splice(data, 1);
				TableProductsMision.setEvents(self.products, 'divProductsTable', 'newMissionAmountSBS', 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;
		});

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

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

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

	// Petición de valores de encuesta
	getTargetsSurvey() {
		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'];
					//let texto = ['S', 'D', '2', 'Q', '6', 'N'];

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

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

	// 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: self.language,
			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 btn-table-selected-rel searchValues" 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" data-toggle="modal" data-target="#valuesTable" data-qid="${qid}" data-columnName="${self.selectedQuestions[i].columnName}" data-index="${i}">
							${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" 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" 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" 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);

		// 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: self.language,
			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" class="align-middle" ${(false ? 'checked' : '')}>
						</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 controlChecksInclusive = [];
		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(surveyValue.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: self.language,
			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');
				}
			}
		});
	}
};