let ProyectosNewController = {
	user: null,
	language: '',
	leader: {},
	todayEndDate: '',
	requestType: '',
	surveysProfiling: '',
	profilingName: [],
	targetsSurvey: [],
	targetsSurveySID: [],
	columnName: '',
	columnNameK: '',
	surveyValues: '',
	renderSurveyValuesFlag: false,
	country: '',
	leaderModal: null,
	countryFilter: '',
	selectedSurveys: [],
	maxSurveysProfiling: 5,
	sidRelations: [],
	segmentations: '',
	selectedSegmentations: [],
	selectedIDSegmentations: [],
	maxSize: 0,
	filesToUpload: [],
	filesToUploadInfo: [],
	userMail: '',
	useCPG: '',
	cpgList: '0',
	cpgActive: null,
	dateFormat: '',
	catalogingValues: [],
	catalogingIdSelected: [],

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.leader = {};
		self.todayEndDate = '';
		self.requestType = '';
		self.surveysProfiling = '';
		self.profilingName = [];
		self.targetsSurvey = [];
		self.targetsSurveySID = [];
		self.columnName = '';
		self.columnNameK = '';
		self.surveyValues = '';
		self.renderSurveyValuesFlag = false;
		self.country = '';
		self.leaderModal = null;
		self.countryFilter = '';
		self.selectedSurveys = [];
		self.maxSurveysProfiling = 5;
		self.sidRelations = [];
		self.segmentations = '';
		self.selectedSegmentations = [];
		self.selectedIDSegmentations = [];
		self.maxSize = 0;
		self.filesToUpload = [];
		self.filesToUploadInfo = [];
		self.userMail = '';
		self.useCPG = sessionStorage['STCMBackEnd:multicpg'];
		self.cpgList = '0';
		self.cpgActive = null;
		self.dateFormat = '';
		self.catalogingValues = [];
		self.catalogingIdSelected = [];
	},

	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('.', '_');
		self.dateFormat = user.formatoFecha;

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.maxSize = config.upload_max_filesize_bytes;

		// Lider de proyecto
		if(config.SYSMisionsUserName != '' && config.SYSMisionsUser != '') {
			self.leader = {
				nameUser: config.SYSMisionsUserName,
				userApellidos: null,
				userApellidos2: null,
				email: config.SYSMisionsUser
			}
			$('#projectLeader').val(self.leader.nameUser);
		}

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

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

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

		// Opciones de header
		let jsonsubopt = {
			back: 'back',
			save: 'save'
		};

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionBack(jsonsubopt.back)}
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		// Botón principal
		$('#save').addClass('main-button');

		// Botones secundarios
		$('#back').addClass('secondary-button');

		// Control de uso de CPG
		if(self.useCPG == '0' || sessionStorage['STCMBackEnd:idCPG'] != '0') {
			self.cpgList = sessionStorage['STCMBackEnd:idCPG'];
			$('#searchCPG').prop('disabled', true);
			$('#cpgList').val(self.cpgList);
			$('#cpgList').attr('title', self.cpgList);
		}

		// Añadir textos
		$('#greetingTooltip').attr('title', pf.const.language.RSC1258);
		$('#inclusiveContainer').hide();

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

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

		self.additionalDocumentsTable();

		// Control de países permitidos por el administrador si solo hay uno
		let countries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		if(countries.length === 1) {
			self.country = {
				isocode: countries[0]
			};
			self.countryFilter = countries[0];
			$('#projectCountry').val(self.country.isocode);
		}

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

		// 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.proyectos.sharedEvents(self);

		// Guardar Proyecto
		$('#save').on('click', function() {
			self.createProject();
		});

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

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

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

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

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

		/* TTT En proceso JIRA 3252 */
		// Input radio catalogación
		$('#searchAlgorithmCataloging').on('click', function() {
			// Petición de tabla de catalogación
			stcmbackend.proyectos.getCatalogacionesM(self);

			$('#algorithmSurvey').css('visibility', 'hidden');
			$('#algorithmSegmentation').css('visibility', 'hidden');

			$('.option-box-check').removeClass('option-box-check-selected');
			$(this).parent().addClass('option-box-check-selected');
		});
		/* TTT En proceso JIRA 3252 */

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

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

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

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

			countryModal.setEvents();
		});

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

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

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

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

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

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

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

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

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

		if(data == undefined || data == '') {
			return false;
		}

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

		switch(self.requestType) {
			case 'leader':
				self.leader = data;
				$('#projectLeader').val(self.leader.nameUser + ' ' + self.leader.userApellidos + ' ' + self.leader.userApellidos2);
				
				break;
			case 'country':
				self.country = data;
				self.countryFilter = data.isocode;
				self.leaderModal.data = null;
				$('#projectCountry').val(self.country.isocode);

				break;
		}
	},

	renderSurveysProfiling() {
		let self = this;

		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';
				}
			}

			// Formato de fechas, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let datecreated = '';
			let datecreatedOrder = '';
			if(self.surveysProfiling[i].datecreated != '') {
				// Para ordenación en columna
				datecreatedOrder = self.surveysProfiling[i].datecreated.replace(' ', '');

				let dateTimeArrayStart = self.surveysProfiling[i].datecreated.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					datecreated = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				} else {
					datecreated = dateStart + ' ' + dateTimeArrayStart[1];
				}
			}

			let startdate = '';
			let startdateOrder = '';
			if(self.surveysProfiling[i].startdate != '') {
				// Para ordenación en columna
				startdateOrder = self.surveysProfiling[i].startdate.replace(' ', '');

				let dateTimeArrayStart = self.surveysProfiling[i].startdate.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					startdate = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				} else {
					startdate = dateStart + ' ' + dateTimeArrayStart[1];
				}
			}

			let expires = '';
			let expiresOrder = '';
			if(self.surveysProfiling[i].expires != '') {
				// Para ordenación en columna
				expiresOrder = self.surveysProfiling[i].expires.replace(' ', '');

				let dateTimeArrayStart = self.surveysProfiling[i].expires.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					expires = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				} else {
					expires = dateStart + ' ' + dateTimeArrayStart[1];
				}
			}

			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="${datecreated}">
						<span class="d-none">${datecreatedOrder}</span>
						${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="${startdate}">
						<span class="d-none">${startdateOrder}</span>
						${startdate}
					</td>
					<td class="text-truncate" title="${expires}">
						<span class="d-none">${expiresOrder}</span>
						${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');

		self.eventsSurveysProfiling();

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

	eventsSurveysProfiling() {
		let self = this;

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

	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.profilingName.push(self.selectedSurveys[index].surveyls_title);
				self.sidRelations.push('&');
				self.renderTargetsSurvey(index);

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

	renderTargetsSurvey(index) {
		let self = this;

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

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

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

		let tab = `
			<li id="li_tab_${index}">
				<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} basicTable">
				${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 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();
			self.renderSurveysProfiling();

			//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(index);
		
		$('#registers' + index).on('draw.dt', function() {
			self.eventTargetsSurvey(index);
		});
	},

	eventTargetsSurvey(index) {
		let self = this;

		// Valores de modal
		$('.searchValues').off().on('click', function() {
			let qid = $(this).attr('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');
			
			stcmbackend.proyectos.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;
				}
			}

			stcmbackend.proyectos.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;

				stcmbackend.proyectos.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;

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

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

		let relation = '';

		let relSymbol = '';

		let tab = `
			<li id="li_tab_${index}">
				<a href="#survey${index}" class="nav-link ${active} perfTabs" data-toggle="tab">
					${relSymbol + 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} basicTable">
				${relation}
				<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: '260px', 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';
			}
		});
	},

	createProject() {
		let self = this;

		// El ID se genera en servidor

		let useSegmentation = '0';
		let sidPerfilacion = '';
		let surveyProfilingValidator = true;
		let idSegmentation = '';
		let segmentationValidator = true;
		let targetTotalPanel = '0';
		let targetCataloging = '0'
		if($('#searchAlgorithmSurvey').prop('checked')) {
			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;
			}
		} else if($('#searchAlgorithmSegmentation').prop('checked')) {
			useSegmentation = '1';
			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;
			}
		} else if($('#searchAlgorithmTotal').prop('checked')) {
			targetTotalPanel = '1';
		} else if($('#searchAlgorithmCataloging').prop('checked')) {
			targetCataloging = '1';

			if(self.catalogingIdSelected.length == 0) {
				let alertTitle = pf.const.language.RSC187;
				let alertText = pf.const.language.RSC2639;
				pf.utils.showInfoDialog(alertTitle, alertText);

				return false;
			}
		} else {
			return false;
		}

		let NombreProyecto = $('#projectName').val().trim();
		let projectNameValidator = true;
		// Validación nombre de proyecto
		if(NombreProyecto === '') {
			$('#projectName').addClass('is-invalid');
			$('[for="projectName"]').addClass('is-invalid');
			projectNameValidator = false;
		} else {
			$('#projectName').removeClass('is-invalid');
			$('[for="projectName"]').removeClass('is-invalid');
			projectNameValidator = true;
		}

		let surname1 = self.leader.userApellidos ? ' ' + self.leader.userApellidos : '';
		let surname2 = self.leader.userApellidos2 ? ' ' + self.leader.userApellidos2 : '';
		let LiderProyecto = self.leader.nameUser + surname1 + surname2;
		let LiderProyectoEmail = self.leader.email;

		let country = self.country.isocode;
		// Validación país de proyecto
		let projectCountryValidator = true;
		if(country === undefined) {
			$('#projectCountry').addClass('is-invalid');
			$('#projectCountry-group').addClass('group-invalid');
			$('[for="projectCountry"]').addClass('is-invalid');
			projectCountryValidator = false;
		} else {
			$('#projectCountry').removeClass('is-invalid');
			$('#projectCountry-group').removeClass('group-invalid');
			$('[for="projectCountry"]').removeClass('is-invalid');
			projectCountryValidator = true;
		}

		let projectLeaderValidator = true;
		// Validación líder de proyecto
		if(LiderProyecto == 'undefined' || LiderProyecto == undefined) {
			$('#projectLeader').addClass('is-invalid');
			$('#projectLeader-group').addClass('group-invalid');
			$('[for="projectLeader"]').addClass('is-invalid');
			projectLeaderValidator = false;
		} else {
			$('#projectLeader').removeClass('is-invalid');
			$('#projectLeader-group').removeClass('group-invalid');
			$('[for="projectLeader"]').removeClass('is-invalid');
			projectLeaderValidator = true;
		}

		let ChatGrupal = ($('#groupChat').prop('checked') === true ? 1 : 0);
		let VideoIndividual = 0;
		let VideoGrupal = 0;

		let notificarInclusion = ($('#greeting').prop('checked') === true ? 1 : 0);

		// Control de uso de CPG
		let cpgValidator = true;
		if(self.useCPG == '1' && sessionStorage['STCMBackEnd:idCPG'] == '0') {
			if(self.cpgList == '') {
				$('#cpgList').addClass('is-invalid');
				$('#cpgList-group').addClass('group-invalid');
				$('[for="cpgList"]').addClass('is-invalid');
				cpgValidator = false;
			} else {
				$('#cpgList').removeClass('is-invalid');
				$('#cpgList-group').removeClass('group-invalid');
				$('[for="cpgList"]').removeClass('is-invalid');
				cpgValidator = true;
			}
		}

		if(!projectCountryValidator || !surveyProfilingValidator || !segmentationValidator || !projectNameValidator || !projectLeaderValidator || !cpgValidator) {
			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];
			}
		}

		// 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 = {
			sidPerfilacion: JSON.stringify(self.targetsSurveySID),
			NombreProyecto: NombreProyecto,
			FechaProyecto: self.todayEndDate,
			LiderProyecto: LiderProyecto,
			ClienteInterno: $('#brandsInvolved').val(),
			ObjetivoProyecto: $('#businessObjective').val(),
			DecisionATomar: $('#actionStandard').val(),
			Resultados: $('#resultsFavorable').val().trim(),
			country: country,
			ChatIndividual: 0,
			ChatGrupal: ChatGrupal,
			VideoIndividual: VideoIndividual,
			VideoGrupal: VideoGrupal,
			LiderProyectoEmail: LiderProyectoEmail,
			ListaDistribucion: 1,
			IdPerfilacion: JSON.stringify(self.profilingName),
			IdPerfilacionDesc: JSON.stringify(self.profilingName),
			notificarInclusion: notificarInclusion,
			inclusivo: $('#inclusive').val(),
			useSegmentation: useSegmentation,
			sidRelations: sidRelations,
			targetsSurvey: JSON.stringify(self.targetsSurvey),
			sidRelationsSegmentation: JSON.stringify(idSegmentations),
			IdSegmentacion: JSON.stringify(nameSegmentations),
			IdSegmentacionDesc: JSON.stringify(nameSegmentations),
			segSegmentations: JSON.stringify(segSegmentations),
			applicantName: $('#ApplicantName').val().trim(),
			brandsInvolved: $('#brandsInvolved').val().trim(),
			projectDescription: $('#projectDescription').val().trim(),
			background: $('#background').val().trim(),
			businessObjective: $('#businessObjective').val().trim(),
			investigationObjective: $('#investigationObjective').val().trim(),
			actionStandard: $('#actionStandard').val().trim(),
			favorableResults: $('#resultsFavorable').val().trim(),
			notFavorableResults: $('#resultsNotFavorable').val().trim(),
			admin: self.userMail,
			filesToUploadInfo: JSON.stringify(self.filesToUploadInfo),
			cpgList: self.cpgList,
			proyectoReparticion: $('#proyectoReparticion').prop('checked') ? '1' : '0',
			targetTotalPanel: targetTotalPanel,
			/* TTT En proceso JIRA 3252 */
			// targetCataloging: targetCataloging,
			// catalogingIdSelected: JSON.stringify(self.catalogingIdSelected)
			/* TTT En proceso JIRA 3252 */
		};

		// Documentos
		let elementSize = self.filesToUpload.length;
		for(let i = 0; i < elementSize; i++) {
			parameters['element' + i] = self.filesToUpload[i];
		}

		ajaxComunCallWithCallback('insertCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				sessionStorage.setItem('idProject', ajaxReturn.result);
				sessionStorage.setItem('numberRecords', $('#numberRecords').val());

				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC435;
				pf.utils.showInfoDialog(successTitle, successContent);

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

	additionalDocumentsTable() {
		let self = this;

		let excelTitle = pf.const.language.RSC2062;

		let table = `
			<table id="tableAdditionalDocuments" 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.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC1313}">${pf.const.language.RSC1313}</th>
						<th scope="col" title="${pf.const.language.RSC95}"></th>
					</tr>
				</thead>

				<thead class="filtersAdditionalDocuments">
					<tr>
						<td>documento</td>
						<td>descripcion</td>
						<td>tamaño</td>
						<td>borrar</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.filesToUploadInfo.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].documento}">${self.filesToUploadInfo[i].documento}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].descripcion}">${self.filesToUploadInfo[i].descripcion}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].tamano}">${self.filesToUploadInfo[i].tamano}</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteFilesToUpload" data-index="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

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

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

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

		let recordedTable = $('#tableAdditionalDocuments').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 5,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 3}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(recordedTable, 'filtersAdditionalDocuments');

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

		self.tableAdditionalDocumentsEvents();

		$('#tableAdditionalDocuments').on('draw.dt', function() {
			self.tableAdditionalDocumentsEvents();
		});
	},

	tableAdditionalDocumentsEvents() {
		let self = this;

		// Eliminar registro
		$('.deleteFilesToUpload').off().on('click', function() {
			let index = $(this).data('index');
			self.filesToUploadInfo.splice(index, 1);
			self.filesToUpload.splice(index, 1);
			self.additionalDocumentsTable();
		});
	}
};