let StepByStepCriterionEditController = {
	language: '',
	idProject: null,
	project: null,
	surveysProfiling: '',
	segmentations: '',
	targetsSurvey: [],
	targetsSurveySID: [],
	profilingName: [],
	sidRelations: [],
	selectedSurveys: [],
	surveyValues: '',
	selectedSegmentations: [],
	selectedIDSegmentations: [],
	columnName: '',
	columnNameK: '',
	renderSurveyValuesFlag: false,
	maxSurveysProfiling: 5,

	reset() {
		let self = this;

		self.language = pf.const.language_table;
		self.idProject = sessionStorage['idProjectSBS'];
		self.project = null;
		self.surveysProfiling = '';
		self.segmentations = '';
		self.targetsSurvey = [];
		self.targetsSurveySID = [];
		self.profilingName = [];
		self.sidRelations = [];
		self.selectedSurveys = [];
		self.surveyValues = '';
		self.selectedSegmentations = [];
		self.selectedIDSegmentations = [];
		self.columnName = '';
		self.columnNameK = '';
		self.renderSurveyValuesFlag = false;
		self.maxSurveysProfiling = 5;
	},

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

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

		// Encuestas Vs Segmentacione
		// Input radio toda la comunidad de inicio
		$('#algorithmSurvey').css('visibility', 'hidden');
		$('#algorithmSegmentation').hide();
		$('#algorithmSegmentation').css('visibility', 'hidden');
		$('#inclusiveContainer').hide();

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

		// Collapse
		addEventArrowTableHeader();

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

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

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

	applyEvents() {
		let self = this;

		StepByStepSharedController.sharedEventsCriterion(self);

		// Input radio encuesta
		$('#searchAlgorithmSurvey').on('click', function() {
			$('#algorithmSurvey').css('visibility', 'visible');
			$('#algorithmSurvey').show();
			$('#algorithmSegmentation').hide();
			$('#selectSurveys').click();
			$('#investigationObjectives').addClass('d-none');

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

		// Input radio segmentación
		$('#searchAlgorithmSegmentation').on('click', function() {
			$('#algorithmSurvey').hide();
			$('#algorithmSegmentation').css('visibility', 'visible');
			$('#algorithmSegmentation').show();
			$('#selectSegmentations').click();
			$('#investigationObjectives').addClass('d-none');

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

		// Input radio toda la comunidad
		$('#searchAlgorithmTotal').on('click', function() {
			$('#algorithmSurvey').css('visibility', 'hidden');
			$('#algorithmSegmentation').css('visibility', 'hidden');
			$('#investigationObjectives').addClass('d-none');

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

		// Encuesta de perfilación
		$('#searchSurvey').on('click', function() {
			if(self.surveysProfiling === '') {
				ajaxComunCallWithCallback('getAllSurveys', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.surveysProfiling = ajaxReturn.result;

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

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

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

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

				self.requestTargetsSurvey(0);
			} else {
				$('#inclusiveContainer').hide();
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');
				$('#surveyProfiling').val('');
			}
		});

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

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

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

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

				$('#segmentation').val(self.selectedIDSegmentations.toString());
				$('#segmentation').attr('title', self.selectedIDSegmentations.toString());
			} else {
				$('#inclusiveContainer').hide();
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');
				$('#segmentation').val('');
				$('#segmentation').attr('title', '');
			}
		});
	},

	getCMBPProjects() {
		let self = this;

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

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

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

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

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

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

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

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

						// Petición inicial
						self.targetsSurveySID = [];
						self.requestTargetsSurvey(0, true);
					}
				}
			}
		});
	},

	requestTargetsSurvey(index) {
		let self = this;

		let parameters = {
			survey: self.selectedSurveys[index].sid
		};
		ajaxComunCallWithCallback('getTargetsSurvey', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let j = 0; j < size; j++) {
					if(ajaxReturn.result[j].type == 'K' || ajaxReturn.result[j].type == 'A' || ajaxReturn.result[j].type == 'B' || ajaxReturn.result[j].type == ';') {
						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] = [];
						}
					} else {
						ajaxReturn.result[j].value = [];
						ajaxReturn.result[j].code = [];
					}
				}
				self.targetsSurvey.push(ajaxReturn.result);
				self.targetsSurveySID.push(self.selectedSurveys[index].sid);
				self.renderTargetsSurvey(index);

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

	renderTargetsSurvey(index) {
		let self = this;

		// Visualizar objetivos de investigación
		$('#investigationObjectives').removeClass('d-none');

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

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

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

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

					<tbody>
		`;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

			// Recrea la tabla de encuestas
			$('#tableSurvey').dataTable().fnDestroy();
			StepByStepSharedController.renderSurveysProfiling(self);

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

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

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

		self.eventTargetsSurvey();

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

	eventTargetsSurvey() {
		let self = this;

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

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

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

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

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

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

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

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

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

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

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

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

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

	getAllSegmentaciones() {
		let self = this;

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

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

							let obj = {
								name: self.segmentations[i].segmentos[j].Descripcion,
								include: '0'
							};

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

				// Tabla de resultados
				self.renderSegmentations();
			}
		});
	},

	renderSegmentations() {
		let self = this;

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

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

			<tbody>
		`;

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

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

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

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

		self.eventsSegmentations();

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

	eventsSegmentations() {
		let self = this;

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

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

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

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

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

	renderSegmentationSegments(index) {
		let self = this;

		// Visualizar objetivos de investigación
		$('#investigationObjectives').removeClass('d-none');

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

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

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

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

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

					<tbody>
		`;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		self.eventSegmentationsSegments(index);

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

	eventSegmentationsSegments() {
		let self = this;

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

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