let StepByStepSharedController = {
	commonTitles() {
		// TITLES
		// Navegador
		$('#backSBS').attr('title', pf.const.language.RSC2602);
		$('#taskEditorSBS').attr('title', pf.const.language.RSC2095);
		$('#dataEntrySBS').attr('title', pf.const.language.RSC2094);
		$('#surveySBS').attr('title', pf.const.language.RSC110);
		$('#taskCriteriaSBS').attr('title', pf.const.language.RSC2096);
		$('#summarySBS').attr('title', pf.const.language.RSC2097);
		$('#nextSBS').attr('title', pf.const.language.RSC1530);
		// Botones
		$('.addTitle').attr('title', pf.const.language.RSC93);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
		$('#importAdditionalDocuments').attr('title', pf.const.language.RSC2063);
		// Añadir textos
		$('#continuingMissionTooltip').attr('title', pf.const.language.RSC2504);
		$('#greetingTooltip').attr('title', pf.const.language.RSC1258);
	},

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

			return result;
		});

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

	sharedEventsProjects(self) {
		// Valores de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.userMail = user.email;

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

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

			countryModal.setEvents();
		});

		// Modal de CPG's
		$('#searchCPG').off().on('click', function() {
			if(self.cpgActive === null) {
				ajaxComunCallWithCallback('getAllCPG', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						if(ajaxReturn.result == 'No CPG defined') {
							self.cpgActive = [];
						} else {
							self.cpgActive = ajaxReturn.result;
						}

						// Tabla de resultados
						StepByStepSharedController.renderAllCPG(self);
					}
				});
			} else {
				$('#cpgTable').modal('show', true);
			}
		});

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

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

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

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

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

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

				if(self.pageName === 'StepByStepProjectNewController') {
					let obj = {
						admin: self.userMail,
						documento: inputElement.files[0].name,
						tamano: inputElement.files[0].size,
						descripcion: inputElementDesc
					};
					self.filesToUploadInfo.push(obj);
					self.filesToUpload.push(inputElement.files[0]);

					self.additionalDocumentsTable();
				} else {
					self.fileToUpload = inputElement.files[0];
					self.fileToUploadDesc = inputElementDesc;

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

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

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

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

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

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

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

		// Restricciones de carácter # por tecla para el Texto inicio de misión
		$('#missionStartText').off().on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1999, /[^#]/i);

			return result;
		});

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

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

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

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

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

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

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

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

					StepByStepSharedController.renderNestableMissions(self);
				}
			});

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

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

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

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

		// Volver al proyecto creado
		$('#backSBS').on('click', function() {
			sessionStorage.setItem('stampMissionSBS', self.stampMissionSBS);

			window.location.href = '#!step_by_step_project_edit';
		});
	},

	sharedEventsCriterion(self) {
		// Volver a la misión creada
		$('#backSBS').on('click', function() {
			if(sessionStorage['selectNewSurveySBS'] == '1') {
				window.location.href = '#!step_by_step_survey';
			} else {
				window.location.href = '#!step_by_step_mission_edit';
			}
		});

		// Guardar Criterio
		$('#nextSBS').off().on('click', function() {
			if($('#searchAlgorithmSurvey').prop('checked')) {
				StepByStepSharedController.productSetCMBPProjectsTargets(self);
			} else if($('#searchAlgorithmSegmentation').prop('checked')) {
				StepByStepSharedController.productSetCMBPProjectsTargetsSegmentation(self);
			} else if($('#searchAlgorithmTotal').prop('checked')) {
				StepByStepSharedController.productSetCMBPProjectsTargetsTotal(self);
			}
		});
	},

	renderAllCPG(self) {
		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title="">
						<div class="div-global-selection">
							<input type="checkbox" class="globalSelectionCPG">
						</div>
					</th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC1540}">${pf.const.language.RSC1540}</th>
					<th scope="col" title="${pf.const.language.RSC1541}">${pf.const.language.RSC1541}</th>
					<th scope="col" title="${pf.const.language.RSC1542}">${pf.const.language.RSC1542}</th>
				</tr>
			</thead>

			<thead class="filtersCPG">
				<tr>
					<td>selector</td>
					<td>id</td>
					<td>pais</td>
					<td>razonSocial</td>
					<td>nombreComercial</td>
					<td>identFiscal</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Array de CPG's seleccionado
		let cpgListArray = self.cpgList.split(',');

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.cpgActive.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if((self.cpgActive[i].country != '' && allowedCountries.indexOf(self.cpgActive[i].country) == -1) || self.cpgActive[i].activo == '0') {
				continue;
			}

			let checked = '';
			if(cpgListArray.indexOf(self.cpgActive[i].idCPG) != -1) {
				checked = 'checked';
			}

			table += `
				<tr class="c-pointer check-select-cpg" data-id="${self.cpgActive[i].idCPG}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selectionCPG" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.cpgActive[i].idCPG}">${self.cpgActive[i].idCPG}</td>
					<td class="text-truncate" title="${self.cpgActive[i].country}">${self.cpgActive[i].country}</td>
					<td class="text-truncate" title="${self.cpgActive[i].razonSocial}">${self.cpgActive[i].razonSocial}</td>
					<td class="text-truncate" title="${self.cpgActive[i].nombreComercial}">${self.cpgActive[i].nombreComercial}</td>
					<td class="text-truncate" title="${self.cpgActive[i].identFiscal}">${self.cpgActive[i].identFiscal}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableCPG, 'filtersCPG');

		StepByStepSharedController.multiSelectTableEventsCPG();

		$('#tableCPG').on('draw.dt', function() {
			StepByStepSharedController.multiSelectTableEventsCPG();
		});

		$('#addCPG').off().on('click', function() {
			let addCPG = [];
			$('#tableCPG tr').each(function() {
				let cheked = $(this).find('.selectionCPG');
				if(cheked.prop('checked')) {
					let idCPG = $(this).data('id');
					addCPG.push(idCPG);
				}
			});

			self.cpgList = addCPG.toString();
			if(self.cpgList == '') {
				self.cpgList = sessionStorage['STCMBackEnd:idCPG'];
			}

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

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

	multiSelectTableEventsCPG() {
		inputControl();

		// Selección por tr
		$('#tableCPG tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selectionCPG').prop('checked');
			if(checkedComp) {
				$(this).find('.selectionCPG').prop('checked', false);
			} else {
				$(this).find('.selectionCPG').prop('checked', true);
			}

			inputControl();
		});

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

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelectionCPG').off().on('change', function() {
			if($('.globalSelectionCPG').prop('checked')) {
				$('.selectionCPG').prop('checked', true);
			} else {
				$('.selectionCPG').prop('checked', false);
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selectionCPG').length == $('.selectionCPG:checked').length && $('.selectionCPG').length > 0) {
				$('.globalSelectionCPG').prop('checked', true);
			} else {
				$('.globalSelectionCPG').prop('checked', false);
			}
		}
	},

	renderTemplates(self) {
		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
				</tr>
			</thead>

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

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

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

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

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

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

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

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

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

			<tbody>
		`;

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

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

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

			if(type == 'Encuesta' || type == 'Tracking de compra' || type == 'Tracking de precios' || type == 'Tracking de productos' || type == 'Auditoría') {
				$('#continuingMission').prop('disabled', false);

				// Iniciar selección de encuesta
				$('#modalStepByStepSurvey').modal('toggle');

				// Nueva encuesta
				$('#newSurvey').off().on('click', function() {
					$('#modalStepByStepSurvey').modal('toggle');
					self.selectNewSurvey = true;
					self.preRenderObjetives();
				});

				// Encuesta existente
				$('#existingSurvey').off().on('click', function() {
					$('#modalStepByStepSurvey').modal('toggle');
					self.selectNewSurvey = false;
					self.preRenderObjetives();
				});
			} else {
				$('#continuingMission').prop('disabled', true);

				self.preRenderObjetives();
			}

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

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

	renderNestableMissions(self) {
		let table = `
			<table id="nestableMissionsTable" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
						<th scope="col" title="${pf.const.language.RSC171}">${pf.const.language.RSC171}</th>
						<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
						<th scope="col" title="${pf.const.language.RSC172}">${pf.const.language.RSC172}</th>
						<th scope="col" title="${pf.const.language.RSC145}">${pf.const.language.RSC145}</th>
					</tr>
				</thead>

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

				<tbody>
		`;

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

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

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

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

			table += `
				<tr class="c-pointer" data-index="${i}" data-idmision="${self.nestableMissions[i].idmision}" data-stampmision="${self.nestableMissions[i].stampMision}">
					<td class="text-truncate" title="${self.nestableMissions[i].idmision}">${self.nestableMissions[i].idmision}</td>
					<td class="text-truncate" title="${startDate}">${startDate}</td>
					<td class="text-truncate" title="${startTime}">${startTime}</td>
					<td class="text-truncate" title="${endDate}">${endDate}</td>
					<td class="text-truncate" title="${endTime}">${endTime}</td>
					<td class="text-truncate" title="${self.nestableMissions[i].importe}">${self.nestableMissions[i].importe}</td>
				</tr>
			`;
		}

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

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

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

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

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

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

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

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

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

			self.nestedMission = self.nestableMissions[index];

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

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

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

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

		let country = $('#projectCountry').val();
		let tipomision = self.typeOptions[self.index].idTipoMision;

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

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

				<tbody>
		`;

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

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

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

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

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

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

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

		self.tableRecordatoriosEvents();
	},

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

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

			<tbody>
		`;

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

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

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

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

		StepByStepSharedController.eventsSurveysProfiling(self);

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

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

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

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

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

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

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

	renderSurveyValues(index, self) {
		if(self.renderSurveyValuesFlag) {
			$('#tableValues').dataTable().fnDestroy();
		} else {
			self.renderSurveyValuesFlag = true;
		}

		// Nombre/code sacado del modal
		let table = `
			<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 typeK = false;
		let questionSize = self.targetsSurvey[index].length;
		for(let i = 0; i < questionSize; i++) {
			if(self.targetsSurvey[index][i].columnName == self.columnName && self.targetsSurvey[index][i].type != 'K' && self.targetsSurvey[index][i].type != 'A' && self.targetsSurvey[index][i].type != 'B') {
				controlChecks = self.targetsSurvey[index][i].code;
			} else if(self.targetsSurvey[index][i].columnName == self.columnName && (self.targetsSurvey[index][i].type == 'K' || self.targetsSurvey[index][i].type == 'A' || self.targetsSurvey[index][i].type == 'B')) {
				typeK = true;
				controlChecks = self.targetsSurvey[index][i].code[self.columnNameK];
			}
		}
		let size = self.surveyValues.length;
		for(let i = 0; i < size; i++) {
			let checked = false;
			if(typeK) {
				checked = (controlChecks.indexOf(String(self.surveyValues[i].code)) != -1 ? true : false);
			} else {
				checked = (controlChecks.indexOf(self.surveyValues[i].code) != -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;

			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>
		`;

		$('#tableValues').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: []
		});

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

		// 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
		StepByStepSharedController.selectionMult(index, self, ObjetiveTable);

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

	selectionMult(index, self, ObjetiveTable) {
		// 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() {
			ObjetiveTable.destroy();

			let valueArray = [];
			let codeArray = [];
			let nameArray = [];

			$('#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.targetsSurvey[index].length;
			for(let i = 0; i < size; i++) {
				if(self.columnName == self.targetsSurvey[index][i].columnName && self.targetsSurvey[index][i].type != 'K') {
					self.targetsSurvey[index][i].value = valueArray;
					self.targetsSurvey[index][i].code = codeArray;
				} else if(self.columnName == self.targetsSurvey[index][i].columnName && self.targetsSurvey[index][i].type == 'K') {
					typeK = true;
					self.targetsSurvey[index][i].value[self.columnNameK] = valueArray;
					self.targetsSurvey[index][i].code[self.columnNameK] = codeArray;
				}
			}

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

	// Guardar objetivos
	productSetCMBPProjectsTargets(self) {
		let useSegmentation = '0';
		let surveyProfilingValidator = true;
		let sidPerfilacion = $('#surveyProfiling').val();
		// Validación id encuesta de perfilación
		if(sidPerfilacion === '') {
			$('#surveyProfiling').addClass('is-invalid');
			$('#surveyProfiling-group').addClass('group-invalid');
			$('[for="surveyProfiling"]').addClass('is-invalid');
			surveyProfilingValidator = false;
		} else {
			$('#surveyProfiling').removeClass('is-invalid');
			$('#surveyProfiling-group').removeClass('group-invalid');
			$('[for="surveyProfiling"]').removeClass('is-invalid');
			surveyProfilingValidator = true;
		}

		if(!surveyProfilingValidator) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

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

		let parameters = {
			delete: '1',
			id: self.idProject,
			useSegmentation: useSegmentation,
			sidPerfilacion: JSON.stringify(self.targetsSurveySID),
			IdPerfilacion: JSON.stringify(self.profilingName),
			IdPerfilacionDesc: JSON.stringify(self.profilingName),
			sidRelations: sidRelations,
			inclusivo: $('#inclusive').val(),
			targetsSurvey: JSON.stringify(self.targetsSurvey),
			sidRelationsSegmentation: '',
			IdSegmentacion: '',
			IdSegmentacionDesc: '',
			targetTotalPanel: '0'
		};
		ajaxComunCallWithCallback('productSetCMBPProjectsTargets', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Criterios guardados
				sessionStorage.setItem('criterionSBS', '1');
				sessionStorage.setItem('searchAlgorithmSBS', 'survey');
				sessionStorage.setItem('idProfilingSBS', $('#surveyProfiling').val());
				sessionStorage.setItem('targetsSurveySBS', JSON.stringify(self.targetsSurvey));
				sessionStorage.setItem('segmentationSBS', '');
				sessionStorage.setItem('selectedSegmentationsSBS', '{}');
				sessionStorage.setItem('proyect_inclusiveSBS', $('#inclusive').val());

				window.location.href = '#!step_by_step_summary';
			}
		});
	},

	productSetCMBPProjectsTargetsSegmentation(self) {
		let useSegmentation = '1';
		let segmentationValidator = true;
		let idSegmentation = $('#segmentation').val();
		// Validación segmentación
		if(idSegmentation === '') {
			$('#segmentation').addClass('is-invalid');
			$('#segmentation-group').addClass('group-invalid');
			$('[for="segmentation"]').addClass('is-invalid');
			segmentationValidator = false;
		} else {
			$('#segmentation').removeClass('is-invalid');
			$('#segmentation-group').removeClass('group-invalid');
			$('[for="segmentation"]').removeClass('is-invalid');
			segmentationValidator = true;
		}

		if(!segmentationValidator) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		// Segmentaciones
		let segSize = self.selectedSegmentations.length;
		let idSegmentations = [];
		let nameSegmentations = [];
		let segSegmentations = [];
		for(let i = 0; i < segSize; i++) {
			idSegmentations.push(self.selectedSegmentations[i].idSegmentacion);
			nameSegmentations.push(self.selectedSegmentations[i].Descripcion);

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

		let parameters = {
			delete: '1',
			id: self.idProject,
			useSegmentation: useSegmentation,
			sidPerfilacion: '',
			IdPerfilacion: '',
			IdPerfilacionDesc: '',
			sidRelations: '',
			inclusivo: '',
			sidRelationsSegmentation: JSON.stringify(idSegmentations),
			IdSegmentacion: JSON.stringify(nameSegmentations),
			IdSegmentacionDesc: JSON.stringify(nameSegmentations),
			segSegmentations: JSON.stringify(segSegmentations),
			targetTotalPanel: '0'
		};
		ajaxComunCallWithCallback('productSetCMBPProjectsTargetsSegmentation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Criterios guardados
				sessionStorage.setItem('criterionSBS', '1');
				sessionStorage.setItem('searchAlgorithmSBS', 'segmentation');
				sessionStorage.setItem('idProfilingSBS', '');
				sessionStorage.setItem('targetsSurveySBS', '{}');
				sessionStorage.setItem('segmentationSBS', $('#segmentation').val());
				sessionStorage.setItem('selectedSegmentationsSBS', JSON.stringify(self.selectedSegmentations));
				sessionStorage.setItem('proyect_inclusiveSBS', $('#inclusive').val());

				window.location.href = '#!step_by_step_summary';
			}
		});
	},

	productSetCMBPProjectsTargetsTotal(self) {
		let parameters = {
			delete: '1',
			id: self.idProject,
			useSegmentation: '0',
			sidPerfilacion: '',
			IdPerfilacion: '',
			IdPerfilacionDesc: '',
			sidRelations: '',
			inclusivo: '',
			sidRelationsSegmentation: '',
			IdSegmentacion: '',
			IdSegmentacionDesc: '',
			targetTotalPanel: '1'
		};
		ajaxComunCallWithCallback('productSetCMBPProjectsTargetsTotal', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Criterios guardados
				sessionStorage.setItem('criterionSBS', '1');
				sessionStorage.setItem('searchAlgorithmSBS', 'total');
				sessionStorage.setItem('idProfilingSBS', '');
				sessionStorage.setItem('targetsSurveySBS', '{}');
				sessionStorage.setItem('segmentationSBS', '');
				sessionStorage.setItem('selectedSegmentationsSBS', '{}');
				sessionStorage.setItem('proyect_inclusiveSBS', $('#inclusive').val());

				window.location.href = '#!step_by_step_summary';
			}
		});
	}
};