let MisionesController = {
	user: null,
	language: '',
	data: '',
	projects:null,
	market: 0,
	projectsFlag: false,
	reportObject: {},
	arrayDelMult: [],
	numPregPerf: '',
	colorsRGB: [],
	colorsHex: [],
	typeColors: null,
	fontName: null,
	fontSize: null,
	wordCloudURL: null,
	primaryColor: null,
	secundaryColor: null,
	numberWordsWordcloud: null,
	timestamp: '',
	reports: null,
	excelDataOpt: 0,
	generatingReports: [],
	plantillaReportes: null,
	idCliente: '',
	dateFormat: '',
	isContinuing: '0',

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = '';
		self.projects = null;
		self.market = sessionStorage['STCMBackEnd:config_market'];
		self.projectsFlag = false;
		self.reportObject = {};
		self.arrayDelMult = [];
		self.numPregPerf = '';
		self.colorsRGB = [];
		self.colorsHex = [];
		self.typeColors = null;
		self.fontName = null;
		self.fontSize = null;
		self.wordCloudURL = null;
		self.primaryColor = null;
		self.secundaryColor = null;
		self.numberWordsWordcloud = null;
		self.timestamp = Date.now();
		self.reports = {
			word: false,
			ppt: false,
			excel: false,
			wc: false,
			images: false
		};
		self.excelDataOpt = 0;
		self.generatingReports = [];
		self.plantillaReportes = null;
		self.idCliente = '';
		self.dateFormat = '';
		self.isContinuing = '0';
	},

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

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

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

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

		// Opciones de header
		let jsonsubopt = {
			new: 'new'
		};

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

		// Desactivar el botón de nueva misión si no se tienen permisos
		if(sessionStorage['STCMBackEnd:newMission'] == 0) {
			$('#new').attr('disabled', true);
		}

		// Parámetro de cliente
		let parameters = {
			idCliente: self.idCliente
		}
		ajaxComunCallWithCallback('getAllMisiones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				// Tabla de resultados
				self.renderData();
			}
		});

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.typeColors = config.UsarColorDegradado;
		self.fontSize = config.SizeFontAnalytics;
		self.fontName = config.FontAnalytics;
		self.wordCloudURL = config.URLWordCloud;
		self.primaryColor = config.tenant[0].colorPrimario.replace('#', '');
		self.secundaryColor = config.tenant[0].colorSecundario.replace('#', '');
		self.numPregPerf = config.numPregPerfEnMostreo;
		self.numberWordsWordcloud = config.numWordSentenceWordCloud;

		// Rango de colores
		if(!config.RGBFin || config.RGBFin === '') {
			self.colorsRGB[0] = '000,000,255';
			self.colorsHex[0] = rgb2hex('rgb(000,000,255)');
		} else {
			if(self.typeColors == 1) {
				self.colorsRGB[0] = config.RGBFin;
				self.colorsHex[0] = rgb2hex('rgb(' + config.RGBFin + ')');
			} else {
				self.colorsRGB = [];
				for(let i = 0; i < config.colores.length; i++) {
					self.colorsRGB.push(config.colores[i].color);
				}
			}
		}
		if(!config.RGBInicio || config.RGBInicio === '') {
			self.colorsRGB[1] = '255,000,000';
			self.colorsHex[1] = rgb2hex('rgb(255,000,000)');
		} else {
			if(self.typeColors == 1) {
				self.colorsRGB[1] = config.RGBInicio;
				self.colorsHex[1] = rgb2hex('rgb(' + config.RGBInicio + ')');
			} else {
				self.colorsHex = [];
				for(let i = 0; i < config.colores.length; i++) {
					self.colorsHex.push(rgb2hex('rgb(' + config.colores[i].color + ')'));
				}
			}
		}

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

		// Collapse
		addEventArrowTableHeader();
	},

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

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('.deleteMultTitle').attr('title', pf.const.language.RSC95);
	},

	applyEvents() {
		let self = this;

		self.projects = new TableProjects();

		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!misiones_new';
		});
	},

	renderData() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title="">
						<div class="div-global-selection">
							<input type="checkbox" class="globalSelection">
						</div>
					</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC26}">${pf.const.language.RSC26}</th>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</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.RSC2331}">${pf.const.language.RSC2331}</th>
					<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
					<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
					<th scope="col" title="${pf.const.language.RSC572}">${pf.const.language.RSC572}</th>
					<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>selector</td>
					<td>idmision</td>
					<td>tipomision</td>
					<td>pais</td>
					<td>fechainicio</td>
					<td>fechafin</td>
					<td>sincierre</td>
					<td>estado</td>
					<td>encuesta</td>
					<td>validate</td>
					<td>acciones</td>
				</tr>
			</thead>

			<tbody>
		`;

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

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

			let startDateTime = self.data[i].fechahorainicio.split('#');
			let startDateArray = startDateTime[0].split('/');
			let startDate = startDateArray[2] + '-' + startDateArray[1] + '-' + startDateArray[0];
			let startTime = startDateTime[1] + ':' + startDateTime[2];
			if(startTime.length == 5) {
				startTime += ':00';
			} else if(startTime == ':') {
				startTime = '-';
			}

			let endDateTime = self.data[i].fechahorafin.split('#');
			let endDateArray = endDateTime[0].split('/');
			let endDate = endDateArray[2] + '-' + endDateArray[1] + '-' + endDateArray[0];
			let endTime = endDateTime[1] + ':' + endDateTime[2];
			if(endTime.length == 5) {
				endTime += ':00';
			} else if(endTime == ':') {
				endTime = '-';
			}

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

			let nowDate = new Date(renderTimeNow);
			let dateStart = '';
			let dateEnd = '';
			if(self.data[i].fechahorainicio != '' && self.data[i].fechahorafin != '') {
				dateStart = new Date(startDateArray[2], startDateArray[1]-1, startDateArray[0], startDateTime[1], startDateTime[2].substring(2, 0));
				dateEnd = new Date(endDateArray[2], endDateArray[1]-1, endDateArray[0], endDateTime[1], endDateTime[2].substring(2, 0));
			}

			// Para ordenación en columna
			let startDateOrder = startDate + startTime;
			let endDateOrder = endDate + endTime;

			// Estado en curso
			let estado = pf.const.language.RSC977;
			let estateVal = 1;
			let estadoClass = 'text-warning';
			if(self.data[i].misionInfinita == '1' || (self.data[i].fechahorainicio == '' && self.data[i].fechahorafin == '' && self.data[i].tipoAnidada == '1')) {
				startDate = '-';
				startTime = '';
				endDate = '-';
				endTime = '';

				// Para ordenación en columna
				startDateOrder = startDate + startTime;
				endDateOrder = endDate + endTime;
			} else {
				if(nowDate < dateStart) {
					// Estado no empezada
					estado = pf.const.language.RSC976;
					estateVal = 0;
					estadoClass = 'text-secondary';
				}

				if(nowDate > dateEnd) {
					// Estado finalizada
					estado = pf.const.language.RSC978;
					estateVal = 2;
					estadoClass = 'text-success';
				}

				// Formato de fecha, el servicio devuelve DD/MM/AAAA HH:MM:SS
				let dateTimeStartArray = self.data[i].fechahorainicioexec.split(' ');
				let dateTimeEndArray = self.data[i].fechahorafinexec.split(' ');
				if(self.dateFormat === 'AAAAMMDD') {
					startDate = modifyDateFormat(dateTimeStartArray[0]);
					endDate = modifyDateFormat(dateTimeEndArray[0]);
				} else {
					startDate = dateTimeStartArray[0];
					endDate = dateTimeEndArray[0];
				}
			}

			let validate = '<span class="d-none">-</span>';
			if(self.data[i].needValidation == 1) {
				validate += `
					<button type="button" class="btn table-button main-color-text btn-validate" data-id="${i}" data-toggle="modal">
						${stcmbackend.svg.bigEyeWithoutColor}
					</button>
				`;
			}

			let reports = '';
			if(self.data[i].isSurvey == '1' && self.data[i].misionInfinita == '0') {
				reports = `
					<p class="dropdown-item ddreport">
						${stcmbackend.svg.fileEarmarkTextWithoutColor}
						<span>${pf.const.language.RSC1941}</span>
					</p>
				`;
			}

			table += `
				<tr data-id="${self.data[i].idmision}" data-state="${estateVal}" data-statetext="${estado}" data-stamp="${self.data[i].stampMision}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${self.data[i].idmision}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${(self.data[i].idmision || '-')}">${(self.data[i].idmision || '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${(self.data[i].tipomision || '-')}">${(self.data[i].tipomision || '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${(self.data[i].country || '-')}">${(self.data[i].country || '-')}</td>
					<td class="text-truncate c-pointer editRow" title="${startDate + ' ' + startTime}">
						<span class="d-none">${startDateOrder}</span>
						${startDate + ' ' + startTime}
					</td>
					<td class="text-truncate c-pointer editRow" title="${endDate + ' ' + endTime}">
						<span class="d-none">${endDateOrder}</span>
						${endDate + ' ' + endTime}
					</td>
					<td class="text-truncate text-center c-pointer editRow">
						<span class="d-none">${(self.data[i].misionInfinita == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(self.data[i].misionInfinita == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate c-pointer editRow font-weight-bold ${estadoClass}" title="${estado}"> ${estado} </td>
					<td class="text-truncate text-center c-pointer editRow">
						<span class="d-none">${(self.data[i].encuesta == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(self.data[i].encuesta == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						${validate}
					</td>
					<td class="text-center">
						<div id="dropdownActions${i}" class="div-dd-actions c-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							${stcmbackend.svg.threeDotsVertical18}
						</div>

						<div class="dropdown-menu dropdown-menu-right shadow menu-actions" aria-labelledby="dropdownActions${i}" data-id="${self.data[i].idmision}" data-state="${estateVal}" data-statetext="${estado}" data-stamp="${self.data[i].stampMision}" data-index="${i}" data-survey="${self.data[i].sid}">
							${reports}
							<p class="dropdown-item btn-cumplimiento" data-toggle="modal">
								<svg class="bi bi-bar-chart-line" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
									<path d="M11 2a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v12h.5a.5.5 0 0 1 0 1H.5a.5.5 0 0 1 0-1H1v-3a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v3h1V7a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v7h1V2zm1 12h2V2h-2v12zm-3 0V7H7v7h2zm-5 0v-3H2v3h2z"/>
								</svg>
								<span>${pf.const.language.RSC33}</span>
							</p>
							<p class="dropdown-item editRow">
								${stcmbackend.svg.pencilWithoutColor}
								<span>${pf.const.language.RSC225}</span>
							</p>
							<p class="dropdown-item deleteRow">
								${stcmbackend.svg.trashWithoutColor}
								<span>${pf.const.language.RSC95}</span>
							</p>
						</div>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title === 'encuesta' || title === 'order' || title === 'sincierre') {
				value = optionsSelectAllYesNo();
			} else if(title === 'selector' || title === 'validate' || title === 'acciones') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let order = 6;

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '150px', targets: 1},
				{'max-width': '50px', targets: 3},
				{'max-width': '105px', targets: 4},
				{'max-width': '105px', targets: 5},
				{'max-width': '65px', targets: 6},
				{width: '80px', targets: 7},
				{'max-width': '55px', targets: 8},
				{width: '65px', targets: 9},
				{width: '60px', orderable: false, targets: 10}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC14,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 4 || column === 5) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			order: [[order, 'desc'], [4, 'desc']]
		});

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

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

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

		self.tableEvents(dataTable);

		// Eventos con cambio de página de tabla
		$('#registers').on('draw.dt', function() {
			self.tableEvents(dataTable);
		});
	},

	tableEvents(dataTable) {
		let self = this;

		// Edición solo activa si se tienen permisos
		if(sessionStorage['STCMBackEnd:editMission'] != 0) {
			// Editar misión
			$('.editRow').off().on('click', function() {
				let id = $(this).parent().data('id');
				let stamp = $(this).parent().data('stamp');
				let state = $(this).parent().data('state');
				let stateText = $(this).parent().data('statetext');

				sessionStorage.setItem('idMission', btoa(id));
				sessionStorage.setItem('idMissionStamp', btoa(stamp));
				sessionStorage.setItem('idMissionState', btoa(state));
				sessionStorage.setItem('idMissionStateText', btoa(stateText));
				window.location.href = '#!misiones_edit';
			});
		}

		// Eliminación solo activa si se tienen permisos
		if(sessionStorage['STCMBackEnd:deleteMission'] != 0) {
			// Eventos del input global
			globalSelectionInputActions();

			// Borrar mision
			$('.deleteRow').off().on('click', function() {
				let id = $(this).parent().data('id');

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

				let alertTitle = pf.const.language.RSC14;
				let alertText = pf.const.language.RSC318;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.deleteMission(id);
				}, function() {});
			});

			// Array de eliminado múltiple
			$('.deleteSelection').off().on('change', function() {
				let value = $(this).prop('checked');
				let id = $(this).parent().data('id');

				if(value) {
					self.arrayDelMult.push(id);
				} else {
					let index = self.arrayDelMult.indexOf(id);
					self.arrayDelMult.splice(index, 1);
				}

				// Eventos de los inputs individuales
				deleteSelectionInputActions(self.arrayDelMult);
			});

			// Función de borrado múltiple
			$('#multSelecDelete').off().on('click', function() {
				// Aviso de borrado múltiple
				let objInfo = {
					accept: {
						text: pf.const.language.RSC95
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC14;
				let alertText = pf.const.language.RSC1694;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.deleteMission();
				}, function() {});
			});
		}

		// Validar
		$('.btn-validate').off().on('click', function() {
			let id = $(this).data('id');
			sessionStorage.setItem('validationSource', 'missions');
			self.projects.setEvents(self.data[id], false);
		});

		// Ver Cumplimiento
		$('.btn-cumplimiento').off().on('click', function() {
			let idMission = $(this).parent().data('id');
			self.getProjectsByMision(idMission);
		});

		// Selección de reportes a generar
		$('.ddreport').off().on('click', function() {
			self.reportObject = {
				type: 'total',
				mision: $(this).parent().data('id'),
				stampMision: $(this).parent().data('stamp'),
				survey: $(this).parent().data('survey'),
				element: $(this)
			};

			let index = $(this).parent().data('index');

			self.timestamp = Date.now();

			self.reports = {
				word: false,
				ppt: false,
				excel: false,
				wc: false,
				images: false
			};

			let content = `
				<p>${pf.const.language.RSC59}</p>

				<div class="row mt-3 mx-0 mb-0">
					<div class="col-6 mb-3 pl-0">
						<!-- Word -->
						<label for="cbword" class="form-check form-check-inline option-box-check w-100 h-100 c-pointer">
							<input id="cbword" type="checkbox" class="form-check-input reportCheck" name="cbword">

							<div class="ml-2">
								<span class="fw-500">${pf.const.language.RSC536}</span><br>
								<span class="fs-14">${pf.const.language.RSC537}</span>
							</div>
						</label>
					</div>

					<div class="col-6 mb-3 pr-0">
						<!-- Wordcloud -->
						<label for="cbwc" class="form-check form-check-inline option-box-check w-100 h-100 c-pointer">
							<input id="cbwc" type="checkbox" class="form-check-input reportCheck" name="cbwc">

							<div class="ml-2">
								<span class="fw-500">${pf.const.language.RSC542}</span><br>
								<span class="fs-14">${pf.const.language.RSC543}</span>
							</div>
						</label>
					</div>

					<div class="col-6 mb-3 pl-0">
						<!-- Powerpoint -->
						<label for="cbppt" class="form-check form-check-inline option-box-check w-100 h-100 c-pointer">
							<input id="cbppt" type="checkbox" class="form-check-input reportCheck" name="cbppt">

							<div class="ml-2">
								<span class="fw-500">${pf.const.language.RSC2512}</span><br>
								<span class="fs-14">${pf.const.language.RSC539}</span>
							</div>
						</label>
					</div>

					<div class="col-6 mb-3 pr-0">
						<!-- Multimedia -->
						<label for="cbimages" class="form-check form-check-inline option-box-check w-100 h-100 c-pointer">
							<input id="cbimages" type="checkbox" class="form-check-input reportCheck" name="cbimages">

							<div class="ml-2">
								<span class="fw-500">${pf.const.language.RSC544}</span><br>
								<span class="fs-14">${pf.const.language.RSC545}</span>
							</div>
						</label>
					</div>

					<div class="col-6 mb-0 pl-0">
						<!-- Data -->
						<label for="cbexcel" class="form-check form-check-inline option-box-check w-100 h-100 c-pointer">
							<input id="cbexcel" type="checkbox" class="form-check-input reportCheck" name="cbexcel">

							<div class="ml-2">
								<span class="fw-500">${pf.const.language.RSC540}</span><br>
								<span class="fs-14">${pf.const.language.RSC541}</span>

								<div id="dataOptions" class="d-none">
									<div class="form-check p-0">
										<input id="cbexcelAnswers" type="radio" class="form-check-input" name="excelDataOpt" value="1" checked>
										<label for="cbexcelAnswers" class="form-check-label">
											${pf.const.language.RSC150}
										</label>
									</div>
									<div class="form-check p-0">
										<input id="cbexcelCodePrefix" type="radio" class="form-check-input" name="excelDataOpt" value="2">
										<label for="cbexcelCodePrefix" class="form-check-label">
											${pf.const.language.RSC997}
										</label>
									</div>
									<div class="form-check p-0">
										<input id="cbexcelCode" type="radio" class="form-check-input" name="excelDataOpt" value="3">
										<label for="cbexcelCode" class="form-check-label">
											${pf.const.language.RSC998}
										</label>
									</div>
								</div>
							</div>
						</label>
					</div>

					<div class="col-6 mb-0 pr-0">
						<!-- Todos -->
						<label for="allReports" class="form-check form-check-inline option-box-check w-100 c-pointer">
							<input id="allReports" type="checkbox" class="form-check-input" name="allReports">

							<div class="ml-2">
								<span class="fw-500">${pf.const.language.RSC119}</span><br>
								<span class="fs-14">${pf.const.language.RSC2513}</span>
							</div>
						</label>
					</div>
				</div>

				<script>
					$('#cbexcel').on('change', function() {
						if($('#cbexcel').prop('checked') == true) {
							$('#dataOptions').removeClass('d-none');
						} else {
							$('#dataOptions').addClass('d-none');
						}
					});
					$('#allReports').on('change', function() {
						if($('#allReports').prop('checked') == true) {
							$('#allReports').parent().addClass('option-box-check-selected');
							$('.reportCheck').prop('checked', true);
							$('.reportCheck').parent().addClass('option-box-check-selected');
							$('#dataOptions').removeClass('d-none');
						} else {
							$('#allReports').parent().removeClass('option-box-check-selected');
							$('.reportCheck').prop('checked', false);
							$('.reportCheck').parent().removeClass('option-box-check-selected');
							$('#dataOptions').addClass('d-none');
						}
					});
					$('.reportCheck').on('click', function() {
						if($(this).prop('checked') == false) {
							$('#allReports').prop('checked', false);
							$('#allReports').parent().removeClass('option-box-check-selected');
							$(this).parent().removeClass('option-box-check-selected');
						} else {
							$(this).parent().addClass('option-box-check-selected');
						}
					});
				</script>
			`;

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

			let title = pf.const.language.RSC48;
			self.alert = pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(title, content, objInfo, '750px', function() {
				self.reports.word = $('#cbword').prop('checked') ? true : false;
				self.reports.ppt = $('#cbppt').prop('checked') ? true : false;
				self.reports.excel = $('#cbexcel').prop('checked') ? true : false;
				self.reports.wc = $('#cbwc').prop('checked') ? true : false;
				self.reports.images = $('#cbimages').prop('checked') ? true : false;

				let noReports = true;
				for(let report in self.reports) {
					if(self.reports[report]) {
						noReports = false;
					}
				}
				if(noReports) {
					let warningTitle = pf.const.language.RSC1941;
					let warningContent = pf.const.language.RSC2391;
					pf.utils.showInfoDialog(warningTitle, warningContent);
					return false;
				}

				let excelDataOpt = $('input:radio[name=excelDataOpt]:checked').val();
				if(excelDataOpt != undefined) {
					self.excelDataOpt = excelDataOpt;
				} else {
					self.excelDataOpt = 0;
				}

				self.projects.setEvents(self.data[index], true);
			}, function() {});
		});
	},

	getMision(project) {
		let self = this;

		// Parámetros para datos de misión
		parameters = {
			stampMision: self.reportObject.stampMision
		};
		ajaxComunCallWithCallback('getMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let idPlantillaReportes = ajaxReturn.result[0].idPlantillaReportes;
				self.isContinuing = ajaxReturn.result[0].continuingMission;

				if(idPlantillaReportes != '0') {
					// Parámetros para datos de plantilla
					parameters = {
						id: idPlantillaReportes
					};
					ajaxComunCallWithCallback('getPlantillaReportesByID', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							let values = ajaxReturn.result[0];

							self.plantillaReportes = {
								rangoColores: values.rangoColores,
								colorInicio: values.colorInicio,
								colorFinal: values.colorFinal,
								coloresComponenRango: values.coloresComponenRango,
								tipoFuente: values.tipoFuente,
								tamanoFuente: values.tamanoFuente,
								colorTituloPortada: values.colorTituloPortada,
								colorTitulo: values.colorTitulo,
								plantillaPortada: values.plantillaPortada,
								plantilla: values.plantilla,
								logo: values.logo,
								// Valores de tipo de gráfica
								type3: values.type3,
								type4: values.type4,
								type5: values.type5,
								typeINTERROGANTE: values['type!'],
								typeL: values.typeL,
								typeO: values.typeO,
								typeY: values.typeY,
								typeM: values.typeM
							}

							self.generateReports(project);
						}
					});
				} else {
					// Plantilla por defecto
					ajaxComunCallWithCallback('getPlantillaReportesByDefault', {}, function(ajaxReturn) {
						if(ajaxReturn) {
							let values = ajaxReturn.result[0];

							self.plantillaReportes = {
								rangoColores: values.rangoColores,
								colorInicio: values.colorInicio,
								colorFinal: values.colorFinal,
								coloresComponenRango: values.coloresComponenRango,
								tipoFuente: values.tipoFuente,
								tamanoFuente: values.tamanoFuente,
								colorTituloPortada: values.colorTituloPortada,
								colorTitulo: values.colorTitulo,
								plantillaPortada: values.plantillaPortada,
								plantilla: values.plantilla,
								logo: values.logo,
								// Valores de tipo de gráfica
								type3: values.type3,
								type4: values.type4,
								type5: values.type5,
								typeINTERROGANTE: values['type!'],
								typeL: values.typeL,
								typeO: values.typeO,
								typeY: values.typeY,
								typeM: values.typeM
							}

							self.generateReports(project);
						}
					});
				}
			}
		});
	},

	generateReports(project) {
		let self = this;

		self.reportObject.project = project.id;
		let timestamp = Date.now();

		let briefingObject = [];
		if(self.reports.ppt || self.reports.word) {
			// Valores y títulos de briefing
			briefingObject = {
				actionStandard: {
					title: pf.const.language.RSC2059,
					text: project.briefing[0].actionStandard
				},
				applicantName: {
					title: pf.const.language.RSC2053,
					text: project.briefing[0].applicantName
				},
				background: {
					title: pf.const.language.RSC2056,
					text: project.briefing[0].background
				},
				brandsInvolved: {
					title: pf.const.language.RSC2054,
					text: project.briefing[0].brandsInvolved
				},
				businessObjective: {
					title: pf.const.language.RSC2057,
					text: project.briefing[0].businessObjective
				},
				favorableResults: {
					title: pf.const.language.RSC2060,
					text: project.briefing[0].favorableResults
				},
				investigationObjective: {
					title: pf.const.language.RSC2058,
					text: project.briefing[0].investigationObjective
				},
				notFavorableResults: {
					title: pf.const.language.RSC2061,
					text: project.briefing[0].notFavorableResults
				},
				projectDescription: {
					title: pf.const.language.RSC2055,
					text: project.briefing[0].projectDescription
				}
			}
		}

		let headersExcel = '';
		// En el caso de excel preparar los valores básicos de cabeceras
		if(self.reports.excel) {
			if(self.numPregPerf < 4) {
				/*
					RSC1436 = Rotación
					RSC123 = Nombre
					RSC999 = Folio
				*/
				headersExcel = pf.const.language.RSC1436 + ',' + pf.const.language.RSC123 + ',' + pf.const.language.RSC999 + ',Submit date,Date,Time,';

				/*
					RSC564 = Estado
					RSC601 = Región ABI
					RSC607 = Ciudad
					RSC565 = Edad
					RSC1917 = Rango de edad
					RSC151 = Género
					RSC1948 = Segmentación
					RSC560 = Asesor
					RSC126 = Activo
					RSC572 = Validación
				*/
				headersExcel += pf.const.language.RSC564 + ',' + pf.const.language.RSC601 + ',' + pf.const.language.RSC607 + ',' + pf.const.language.RSC565 + ',' + pf.const.language.RSC1917 + ',' + pf.const.language.RSC151 + ',' + pf.const.language.RSC1948 + ',' + pf.const.language.RSC560 + ',' + pf.const.language.RSC126 + ',' + pf.const.language.RSC572
			} else {
				/*
					RSC1436 = Rotación
					RSC123 = Nombre
					RSC999 = Folio
				*/
				headersExcel = pf.const.language.RSC1436 + ',' + pf.const.language.RSC123 + ',' + pf.const.language.RSC999 + ',Submit date,Date,Time,';

				/*
					RSC564 = Estado
					RSC601 = Región ABI
					RSC607 = Ciudad
					RSC565 = Edad
					RSC1917 = Rango de edad
					RSC151 = Género
					RSC598 = NSE
					RSC1990 = Rango NSE
					RSC1948 = Segmentación
					RSC560 = Asesor
					RSC126 = Activo
					RSC572 = Validación
				*/
				headersExcel += pf.const.language.RSC564 + ',' + pf.const.language.RSC601 + ',' + pf.const.language.RSC607 + ',' + pf.const.language.RSC565 + ',' + pf.const.language.RSC1917 + ',' + pf.const.language.RSC151 + ',' + pf.const.language.RSC598 + ',' + pf.const.language.RSC1990 + ',' + pf.const.language.RSC1948 + ',' + pf.const.language.RSC560 + ',' + pf.const.language.RSC126 + ',' + pf.const.language.RSC572
			}

			if(sessionStorage['STCMBackEnd:Consumer'] == 1) {
				headersExcel += ',' + pf.const.language.RSC1899; // Consumidor
			}
		}

		let parameters = {
			idTenant: sessionStorage['STCMBackEnd:idTenant'],
			user: self.user,
			timestamp: timestamp,
			survey: self.reportObject.survey,
			idmision: self.reportObject.mision,
			nameMission: self.reportObject.mision.replace(/\//g, '-'),
			stampMision: self.reportObject.stampMision,
			project: self.reportObject.project,
			numPregPerf: self.numPregPerf,
			// Excel
			excelDataOpt: self.excelDataOpt,
			headersExcel: headersExcel,
			consumo: sessionStorage['STCMBackEnd:Consumer'],
			isContinuing: self.isContinuing,
			// Word y Powerpoint
			isPerf: '',
			colorsRGB: self.colorsRGB,
			colorsHex: self.colorsHex,
			typeColors: self.typeColors,
			fontName: self.fontName,
			fontSize: self.fontSize,
			wordCloudURL: self.wordCloudURL,
			primaryColor: self.primaryColor,
			secundaryColor: self.secundaryColor,
			numberWordsWordcloud: self.numberWordsWordcloud,
			// Datos briefing
			briefing: JSON.stringify(briefingObject),
			questionIdOut: [],
			// Datos de plantilla
			plantillaReportes: self.plantillaReportes ? JSON.stringify(self.plantillaReportes) : '0'
		};

		let reportGenerator = new ReportGeneratorController(self.reports, parameters);
		reportGenerator.executeReports();
		self.generatingReports.push(reportGenerator);
	},

	deleteMission(id = false) {
		let self = this;

		let missions = [];
		if(id !== false) {
			let obj = {
				id: id
			}
			missions.push(obj);
		} else {
			let delSize = self.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				let obj = {
					id: self.arrayDelMult[i]
				}
				missions.push(obj);
			}
			self.arrayDelMult = [];
		}

		let parameters = {
			missions: JSON.stringify(missions)
		};
		ajaxComunCallWithCallback('dropMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC14;
				let successContent = pf.const.language.RSC319;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/misiones/misiones.html', 'wrapper', MisionesController);
			}
		});
	},

	getProjectsByMision(idMission) {
		let self = this;

		let parameters = {
			idmision: idMission
		};
		ajaxComunCallWithCallback('getProjectsByMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let idProject = '';
				let idProjectArray = [];
				let size = ajaxReturn.result.length;

				if(size == 1) {
					idProject = ajaxReturn.result[0].id;
					sessionStorage.setItem('mission_idMission', btoa(idMission));
					sessionStorage.setItem('mission_idProject', btoa(idProject));
					sessionStorage.setItem('mission_nameProject', btoa(ajaxReturn.result[0].NombreProyecto));
					window.location.href = '#!cumplimientos';
				} else {
					idProjectArray = ajaxReturn.result;
					sessionStorage.setItem('mission_idMission', btoa(idMission));
					self.modalProjectsByMission(idProjectArray);
				}
			}
		});
	},

	modalProjectsByMission(idProjectArray) {
		let self = this;

		if(self.projectsFlag) {
			$('#tableProjects').dataTable().fnDestroy();
		} else {
			self.projectsFlag = true;
		}

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC143}">${pf.const.language.RSC143}</th>
					<th scope="col" title="${pf.const.language.RSC144}">${pf.const.language.RSC144}</th>
					<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
				</tr>
			</thead>

			<thead class="filtersProjects">
				<tr>
					<td>name</td>
					<td>leader</td>
					<td>client</td>
					<td>creationDate</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = idProjectArray.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-name="${idProjectArray[i].NombreProyecto}" data-id="${idProjectArray[i].id}">
					<td class="text-truncate" title="${idProjectArray[i].NombreProyecto}">${idProjectArray[i].NombreProyecto}</td>
					<td class="text-truncate" title="${idProjectArray[i].LiderProyecto}">${idProjectArray[i].LiderProyecto}</td>
					<td class="text-truncate" title="${idProjectArray[i].ClienteInterno}">${idProjectArray[i].ClienteInterno}</td>
					<td class="text-truncate" title="${idProjectArray[i].FechaDeAlta}">${idProjectArray[i].FechaDeAlta}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#tableProjects').html(table);
		$('#modalProjects').modal('toggle');

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

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

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

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

		// Apply the search
		applyTheSearch(tableProjects, 'filtersProjects');

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

			$('#closeProjects').trigger('click');

			sessionStorage.setItem('mission_idProject', btoa(idProject));
			sessionStorage.setItem('mission_nameProject', btoa(nameProject));

			setTimeout(function() {
				window.location.href = '#!cumplimientos';
			}, 300);
		});
	}
};