let ProductoCriterioEditController = {
	user: null,
	userMail: '',
	language: '',
	idProduct: null,
	product: null,
	idProject: null,
	project: null,
	surveysProfiling: '',
	segmentations: '',
	targetsSurveyIndex: '',
	targetsSurvey: [],
	targetsSurveySID: [],
	profilingName: [],
	sidRelations: [],
	selectedSurveys: [],
	surveyByQIDIndex: '',
	surveyValues: '',
	selectedSegmentations: [],
	selectedIDSegmentations: [],
	segmentationName: '',
	columnName: '',
	columnNameK: '',
	renderSurveyValuesFlag: false,
	maxSurveysProfiling: 5,
	requestTSInit: true,
	valueCode: [],
	surveysProfilingFlag: false,
	targetsSegmentIndex: '',
	requestASInit: true,
	segmentationsData: {},
	loaders: {},

	reset() {
		let self = this;

		self.user = null;
		self.userMail = '';
		self.language = pf.const.language_table;
		// ID de producto
		self.idProduct = atob(sessionStorage.getItem('idProductToCreate'));
		self.product = null;
		// ID del proyecto
		self.idProject = sessionStorage['idProjectProduct'];
		self.project = null;
		self.surveysProfiling = '';
		self.segmentations = '';
		self.targetsSurveyIndex = '';
		self.targetsSurvey = [];
		self.targetsSurveySID = [];
		self.profilingName = [];
		self.sidRelations = [];
		self.selectedSurveys = [];
		self.surveyByQIDIndex = '';
		self.surveyValues = '';
		self.selectedSegmentations = [];
		self.selectedIDSegmentations = [];
		self.segmentationName = '';
		self.columnName = '';
		self.columnNameK = '';
		self.renderSurveyValuesFlag = false;
		self.maxSurveysProfiling = 5;
		self.requestTSInit = true;
		self.valueCode = [];
		self.surveysProfilingFlag = false;
		self.targetsSegmentIndex = '';
		self.requestASInit = true;
		self.segmentationsData = {};
		self.loaders = {
			getProductsAnaquelByID: false,
			getCMBPProjects: false
		};
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.userMail = user.email;
		let user_split = self.userMail.split('@');
		self.user = user_split[0].replace('.', '_');

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

		let isSurvey = atob(sessionStorage.getItem('productToCreateIsSurvey'));

		// Footer
		// Botón de anterior
		$('#previousStep').show();
		if(isSurvey != '1') {
			$('#previousStep').html(stcmbackend.svg.arrowLeftShortWithoutColor28 + pf.const.language.RSC2094);
			$('#previousStep').attr('title', pf.const.language.RSC2094);
		} else {
			$('#previousStep').html(stcmbackend.svg.arrowLeftShortWithoutColor28 + pf.const.language.RSC110);
			$('#previousStep').attr('title', pf.const.language.RSC110);
		}

		// Pasos
		let footerSteps = `
			<span class="font-weight-bold d-inline-block mx-3">1. ${pf.const.language.RSC2095}</span>
			<span class="font-weight-bold d-inline-block mx-3">2. ${pf.const.language.RSC2094}</span>
			<span class="font-weight-bold d-inline-block mx-3">3. ${pf.const.language.RSC110}</span>
			<span class="font-weight-bold d-inline-block mx-3 text-decoration main-color-text p-2">4. ${pf.const.language.RSC2096}</span>
			<span class="font-weight-bold d-inline-block mx-3">5. ${pf.const.language.RSC2097}</span>
		`;
		if(isSurvey != '1') {
			footerSteps = `
				<span class="font-weight-bold d-inline-block mx-3">1. ${pf.const.language.RSC2095}</span>
				<span class="font-weight-bold d-inline-block mx-3">2. ${pf.const.language.RSC2094}</span>
				<span class="font-weight-bold d-inline-block mx-3 text-decoration main-color-text p-2">3. ${pf.const.language.RSC2096}</span>
				<span class="font-weight-bold d-inline-block mx-3">4. ${pf.const.language.RSC2097}</span>
			`;
		}
		$('#stepContainer').html(footerSteps);

		// Botón de siguiente
		$('#subsequentStep').html(pf.const.language.RSC2097 + stcmbackend.svg.arrowRightShortWithoutColor28);
		$('#subsequentStep').attr('title', pf.const.language.RSC2097);

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

		// Encuestas Vs Segmentacione
		$('#inclusiveContainer').hide();
		$('#algorithmSurvey').hide();
		$('#algorithmSegmentation').hide();

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

		addLoader();
		let parameters = {
			idProduct: self.idProduct
		};
		ajaxComunCallWithCallback('getProductsAnaquelByID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.product = ajaxReturn.result[0];
			}

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

		self.getCMBPProjects();

		// Collapse
		addEventArrowTableHeader();

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

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

		let arrObj = ['RSC393'];
		pf.rsc.translateByTagHTMLFormat(':', arrObj);

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
		$('#importAdditionalDocuments').attr('title', pf.const.language.RSC2063);
	},

	applyEvents() {
		let self = this;

		stcmbackend.productoCriterio.sharedEvents(self);

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

						stcmbackend.productoCriterio.renderSurveysProfiling(self);
						
						self.surveysProfilingFlag = true;
					}
				});
			} else {
				$('#surveyTable').modal('show', true);
			}
		});

		// Segmentaciones
		$('#searchSegmentation').on('click', function() {
			if(self.segmentations === '') {
				self.requestASInit = false;

				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.requestTSInit = false;
				self.requestTargetsSurvey(0);

				// Añadido para Collapse
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');

				let collapseButton = `
					<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#resultTableCollapse" data-arrow="down">
						${stcmbackend.svg.chevronDown}
					</button>
				`;

				$('#targetsSurveyTable').append(collapseButton);

				// Collapse
				$('.arrow').on('click', function() {
					let arrow = $(this).attr('data-arrow');
					let direction = '';
					if(arrow == 'left') {
						direction = stcmbackend.svg.chevronDown;
						$(this).attr('data-arrow', 'down');
					} else {
						direction = stcmbackend.svg.chevronRight;
						$(this).attr('data-arrow', 'left');
					}
					$(this).html(direction);
					$(this).parent().parent().parent().parent().find('.collapse').collapse('toggle');
				});
			} else {
				$('#inclusiveContainer').hide();
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');
				$('#surveyProfiling').val('');
			}
		});
	},

	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') {
					// Segmentación
					$('#searchAlgorithmSegmentation').prop('checked', true);
					$('#algorithmSegmentation').show();
				} else {
					// Encuesta
					$('#searchAlgorithmSurvey').prop('checked', true);
					$('#algorithmSurvey').show();
				}

				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 != '') {
						// Nombres de Segmentaciones
						self.segmentationName = self.project.IdSegmentacion.split(',');

						// 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.requestTargetsSurvey(0, true);
					}
				}
			}

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

	requestTargetsSurvey(index) {
		let self = this;

		self.targetsSurveyIndex = index;

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

				if(!self.requestTSInit) {
					self.targetsSurveySID.push(self.selectedSurveys[self.targetsSurveyIndex].sid);
					self.profilingName.push(self.selectedSurveys[self.targetsSurveyIndex].surveyls_title);
					self.sidRelations.push('&');
					self.renderTargetsSurvey(self.targetsSurveyIndex);

					self.targetsSurveyIndex++;
					if(self.targetsSurveyIndex < self.selectedSurveys.length) {
						self.requestTargetsSurvey(self.targetsSurveyIndex);
					} else {
						$('#surveyProfiling').val(self.targetsSurveySID.toString());
					}
				} else {
					let parameters = {
						id: self.idProject,
						sidPerfilacion: self.selectedSurveys[self.targetsSurveyIndex].sid
					};
					ajaxComunCallWithCallback('getCMBPProjectsTargets', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							self.valueCode.push(ajaxReturn.result);

							self.renderTargetsSurvey(self.targetsSurveyIndex);

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

	getCMBPProjectsTargetsSegmentation(index) {
		let self = this;

		self.targetsSegmentIndex = index;

		let parameters = {
			id: self.project.id,
			sidRelationsSegmentation: self.selectedIDSegmentations[self.targetsSegmentIndex]
		};
		ajaxComunCallWithCallback('getCMBPProjectsTargetsSegmentation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Preparación de json con las diferentes segmentaciones
				self.segmentationsData[self.selectedIDSegmentations[self.targetsSegmentIndex]] = ajaxReturn.result;

				self.targetsSegmentIndex++;
				if(self.targetsSegmentIndex < self.selectedIDSegmentations.length) {
					self.getCMBPProjectsTargetsSegmentation(self.targetsSegmentIndex);
				} else {
					self.getAllSegmentaciones();
				}
			}
		}, false);
	},

	getAllSegmentaciones() {
		let self = this;

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

				if(self.requestASInit) {
					// Añadir catalogación y clave de incluido a los segmentos con los valores de proyecto
					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;
						let included = false;
						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 = {};
								if(self.segmentationsData[self.segmentations[i].idSegmentacion] !== undefined) {
									for(let h = 0; h < self.segmentationsData[self.segmentations[i].idSegmentacion].length; h++) {
										if(self.segmentationsData[self.segmentations[i].idSegmentacion][h].Segmentacion == self.segmentations[i].segmentos[j].Descripcion) {
											obj = {
												name: self.segmentations[i].segmentos[j].Descripcion,
												include: self.segmentationsData[self.segmentations[i].idSegmentacion][h].Value
											};
											self.segmentations[i]['catalogacion'].push(obj);
											included = true;
											break;
										}
									}
								} else {
									obj = {
										name: self.segmentations[i].segmentos[j].Descripcion,
										include: '0'
									};
									self.segmentations[i]['catalogacion'].push(obj);
								}
							}
						}

						if(included) {
							self.selectedSegmentations.push(self.segmentations[i]);
						}
					}
				} else {
					// 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();

				// Input de segmentaciones
				$('#segmentation').val(self.selectedIDSegmentations.toString());
				$('#segmentation').attr('title', self.selectedIDSegmentations.toString());

				// Tablas de Objetivos de investigación
				for(let r = 0; r < self.selectedSegmentations.length; r++) {
					self.renderSegmentationSegments(r);
				}
			}
		});
	},

	renderTargetsSurvey(index) {
		let self = this;

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

		let relation = '';
		if(index != 0) {
			let selecAnd = 'selected';
			let selecOr = '';
			if(self.sidRelations[index] === '|') {
				selecAnd = '';
				selecOr = 'selected';
			}
			relation = `
				<select id="relation${index}" class="form-control form-control-sm relations d-none" data-index="${index}">
					<option value="&" ${selecAnd}>AND</option>
					<option value="|" ${selecOr}>OR</option>
				</select>
			`;
		}

		let relSymbol = '';
		if(index != 0) {
			relSymbol = `
				<span id="relSymbol${index}" class="d-none">
					${self.sidRelations[index]}
				</span>
			`;
		}

		let tab = `
			<li>
				<a href="#survey${index}" class="nav-link ${active} perfTabs" data-toggle="tab">
					${relSymbol + 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 ${show} ${active}">
				${relation}
				<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 value = '';
			let code = '';
			let valueCodeSize = 0;
			if(self.valueCode[index] !== undefined) {
				valueCodeSize = self.valueCode[index].length;
			}
			for(let j = 0; j < valueCodeSize; j++) {
				if(self.targetsSurvey[index][i].type != 'K') {
					if(self.valueCode[index][j].ColumnName == self.targetsSurvey[index][i].columnName) {
						value = self.valueCode[index][j].Value.split(',');
						self.targetsSurvey[index][i].value = value;
						code = self.valueCode[index][j].ValueCodes.split(',');
						self.targetsSurvey[index][i].code = code;
					}
				}
			}

			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}" value="${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="${value}" placeholder="${pf.const.language.RSC349}" aria-label="Valores" value="${value}" 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(';', '');

					let valueCodeSize = 0;
					if(self.valueCode[index] !== undefined) {
						valueCodeSize = self.valueCode[index].length;
					}
					for(let m = 0; m < valueCodeSize; m++) {
						if(self.valueCode[index][m].ColumnName == columnNameK) {
							value = self.valueCode[index][m].Value.split(',');
							self.targetsSurvey[index][i].value[columnNameK] = value;
							code = self.valueCode[index][m].ValueCodes.split(',');
							self.targetsSurvey[index][i].code[columnNameK] = code;
						}
					}

					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}" value="${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="${value}" placeholder="${pf.const.language.RSC349}" aria-label="Valores" value="${value}" 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="${code}" aria-label="Códigos" value="${code}" 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="${code}" aria-label="Códigos" value="${code}" 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);
			self.profilingName.splice(index, 1);

			// Recrea la tabla de encuestas
			if(self.surveysProfilingFlag) {
				$('#tableSurvey').dataTable().fnDestroy();
				stcmbackend.productoCriterio.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());
		});

		stcmbackend.productoCriterio.eventTargetsSurvey(index, self, true);

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

	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;

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

					<thead class="filtersSegResult${index}">
						<tr>
							<td>segmento</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>
						<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: 1}
			],
			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';
			}
		});
	},

	productSetCMBPProjectsTargets() {
		let self = this;

		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: ''
		};
		ajaxComunCallWithCallback('productSetCMBPProjectsTargets', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Criterios guardados
				sessionStorage.setItem('productCriteria', '1');
				sessionStorage.setItem('searchAlgorithm', 'survey');
				sessionStorage.setItem('idProfiling', $('#surveyProfiling').val());
				sessionStorage.setItem('targetsSurvey', JSON.stringify(self.targetsSurvey));
				sessionStorage.setItem('segmentation', '');
				sessionStorage.setItem('selectedSegmentations', '{}');
				sessionStorage.setItem('proyect_inclusive', $('#inclusive').val());

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

	productSetCMBPProjectsTargetsSegmentation() {
		let self = this;

		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)
		};
		ajaxComunCallWithCallback('productSetCMBPProjectsTargetsSegmentation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Criterios guardados
				sessionStorage.setItem('productCriteria', '1');
				sessionStorage.setItem('searchAlgorithm', 'segmentation');
				sessionStorage.setItem('idProfiling', '');
				sessionStorage.setItem('targetsSurvey', '{}');
				sessionStorage.setItem('segmentation', $('#segmentation').val());
				sessionStorage.setItem('selectedSegmentations', JSON.stringify(self.selectedSegmentations));
				sessionStorage.setItem('proyect_inclusive', $('#inclusive').val());

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