let CumplimientosController = {
	typeColors: null,
	fontSize: null,
	fontName: null,
	colorsRGB: [],
	colorsHex: [],
	project: '',
	idProject: '',
	mission: '',
	missionFlag: false,
	idMission: '',
	complianceChart: {},
	graphData: {},
	dataOKKO: [],
	data: '',
	dataFlag: false,
	projectObj: {},
	total: 0,
	dateFormat: '',
	suffix: '',

	reset() {
		let self = this;

		self.typeColors = null;
		self.fontSize = null;
		self.fontName = null;
		self.colorsRGB = [];
		self.colorsHex = [];
		self.project = '';
		self.idProject = '';
		self.mission = '';
		self.missionFlag = false;
		self.idMission = '';
		self.complianceChart = {};
		self.graphData = {};
		self.dataOKKO = [];
		self.data = '';
		self.dataFlag = false;
		self.projectObj = {};
		self.total = 0;
		self.dateFormat = '';
		self.suffix = '';
	},

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

		// Información de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.dateFormat = user.formatoFecha;

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

		if(self.suffix === '') {
			// Añadir titulo
			$('#page-title').text(pf.const.language.RSC33);
		

			// Opciones de header
			let jsonsubopt = {
				project: 'project',
				mision: 'mission',
				distributionlist: 'diffusion'
			};

			let nav = `
				<div class="d-flex justify-content-end">
					${createSubOptionProject(jsonsubopt.project)}
					${createSubOptionMision(jsonsubopt.mision)}
					${createSubOptionDistributionList(jsonsubopt.distributionlist)}
				</div>
			`;

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

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

			self.applyEvents();
		} else if(self.suffix === '-me-com') {
			// Opciones de header
			let jsonsubopt = {
				distributionlist: 'diffusion'
			};

			let nav = `
				<div class="d-flex justify-content-end">
					${createSubOptionDistributionList(jsonsubopt.distributionlist)}
				</div>
			`;

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

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

		// Añadir textos
		$('.RSC-compGraph').text(pf.const.language.RSC154 + ' (%)');

		self.loadLang();

		$('#mGraphs' + self.suffix).hide();
		$('#resultTableC').hide();

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

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

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Proyectos
		$('#searchProject').on('click', function() {
			// Objeto project
			if(self.project === '') {
				ajaxComunCallWithCallback('getCMBPProjects', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.project = ajaxReturn.result;

						self.renderProject();
					}
				});
			} else {
				$('#projectTable').modal('show', true);
			}
		});

		// Misiones
		$('#searchMission').on('click', function() {
			// Objeto mision
			if(self.mission === '') {
				let parameters = {
					project: self.idProject
				};
				ajaxComunCallWithCallback('getAllMisionesByProject', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.mission = ajaxReturn.result;

						self.renderMissions();
					}
				});
			} else {
				$('#missionTable').modal('show', true);
			}
		});

		let idProject = atob(sessionStorage.getItem('mission_idProject'));
		let idMission = atob(sessionStorage.getItem('mission_idMission'));
		let nameProject = atob(sessionStorage.getItem('mission_nameProject'));
		// Caracteres extraños
		if(idProject == 'ée' || idMission == 'ée') {
			idProject = '';
			idMission = '';
			// Limpieza de sessionStorage
			sessionStorage.setItem('mission_idMission', btoa(''));
			sessionStorage.setItem('mission_idProject', btoa(''));
			sessionStorage.setItem('mission_nameProject', btoa(''));
		}

		if(idProject != '' && idMission != '') {
			self.idProject = idProject;
			self.idMission = idMission;
			$('#project').val(nameProject);
			$('#mission').val(idMission);

			// Limpieza de sessionStorage
			sessionStorage.setItem('mission_idMission', btoa(''));
			sessionStorage.setItem('mission_idProject', btoa(''));
			sessionStorage.setItem('mission_nameProject', btoa(''));

			// Creación de gráficas
			addLoader();
			self.getSnapAcualMisionCumplimiento();
		}
	},

	getSnapAcualMisionCumplimiento() {
		let self = this;

		let parameters = {
			project: self.idProject,
			idmision: self.idMission
		};
		ajaxComunCallWithCallback('getSnapAcualMisionCumplimiento', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let parameters = {
					project: self.idProject,
					mision: self.idMission
				};
				ajaxComunCallWithCallback('getAnalyticsMisiones', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						let compliance = ajaxReturn.result;
						let totalOK = compliance.totalOK[0].resultadoOK;
						let totalKO = compliance.totalKO[0].resultadoKO;

						$('#mGraphs' + self.suffix).show();
						let complianceData = [];

						let sizeOK = compliance.desgloseOK.length;
						for(let i = 0; i < sizeOK; i++) {
							let user = {
								name: compliance.desgloseOK[i].userNombre || '',
								surname1: compliance.desgloseOK[i].userApellidos || '',
								surname2: compliance.desgloseOK[i].userApellidos2 || '',
								email: compliance.desgloseOK[i].userEmail || '',
								compliance: 'Cumplido',
								cpg: compliance.desgloseOK[i].cpgName || '',
								cpgId: compliance.desgloseOK[i].cpgId || '',
								date: compliance.desgloseOK[i].submitdate || '',
								username: compliance.desgloseOK[i].username
							};
							complianceData.push(user);
						}

						let sizeKO = compliance.desgloseKO.length;
						for(let i = 0; i < sizeKO; i++) {
							let user = {
								name: compliance.desgloseKO[i].userNombre || '',
								surname1: compliance.desgloseKO[i].userApellidos || '',
								surname2: compliance.desgloseKO[i].userApellidos2 || '',
								email: compliance.desgloseKO[i].userEmail || '',
								compliance: 'No Cumplido',
								cpg: compliance.desgloseKO[i].cpgName || '',
								cpgId: compliance.desgloseKO[i].cpgId || '',
								date: compliance.desgloseKO[i].submitdate || '',
								username: compliance.desgloseKO[i].username
							};
							complianceData.push(user);
						}

						// Gráfica
						self.complianceGraph(totalOK, totalKO);
						self.graphsEvents();

						// Tabla de resultados
						self.data = complianceData;
						self.renderData();

						removeLoader();
					}
				}, false);
			}
		}, false);
	},

	renderProject() {
		let self = this;

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

			<thead class="filtersProject">
				<tr>
					<td>FechaAlta</td>
					<td>NombreProyecto</td>
					<td>LiderProyecto</td>
					<td>ClienteInterno</td>
				</tr>
			</thead>

			<tbody>
		`;

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

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let dateTime = '';
			let dateTimeArray = self.project[i].FechaDeAlta.split(' ');
			let date = dateTimeArray[0].replace(/-/g, '/');
			if(self.dateFormat === 'DDMMAAAA') {
				dateTime = modifyDateFormat(date);
			} else {
				dateTime = date;
			}

			table += `
				<tr id="id${self.project[i].id}" class="c-pointer">
					<td title="${dateTime}">${dateTime}</td>
					<td class="projectName" title="${self.project[i].NombreProyecto}">${self.project[i].NombreProyecto}</td>
					<td title="${self.project[i].LiderProyecto}">${self.project[i].LiderProyecto}</td>
					<td title="${self.project[i].ClienteInterno}">${self.project[i].ClienteInterno}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableProject, 'filtersProject');

		$('#tableProject tbody').off().on('click', 'tr', function() {
			$('#searchMission').prop('disabled', false);

			//Limpieza de mission
			self.mission = '';
			self.idMission = '';
			$('#mission').val(pf.const.language.RSC14);

			self.idProject = $(this).prop('id').replace('id', '');
			let name = $(this).find('.projectName').text();
			$('#project').val(name);
			$('#tableProject tbody tr').css('outline-width', 'initial');
			$('#tableProject tbody tr').css('outline-style', 'none');
			$('#tableProject tbody tr').css('outline-color', '#000');
			$('#tableProject tbody tr').css('font-weight', 'normal');
			$(this).css('outline-width', 'thin');
			$(this).css('outline-style', 'solid');
			$(this).css('outline-color', '#f00');
			$(this).css('font-weight', 'bold');
			$('#closeProject').trigger('click');
		});
	},

	renderMissions() {
		let self = this;

		if(self.missionFlag) {
			$('#tableMission').dataTable().fnDestroy();
		} else {
			self.missionFlag = 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.RSC26}">${pf.const.language.RSC26}</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.RSC145}">${pf.const.language.RSC145}</th>
				</tr>
			</thead>

			<thead class="filtersMission">
				<tr>
					<td>idmision</td>
					<td>tipomision</td>
					<td>fechahorainicio</td>
					<td>fechahorafin</td>
					<td>importe</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.mission.length;
		for(let i = 0; i < size; i++) {
			// Formato de fecha, el servicio devuelve DD/MM/AAAA HH:MM:SS
			let dateTimeStart = '';
			let dateTimeEnd = '';
			let dateTimeStartArray = self.mission[i].fechahorainicio.split(' ');
			let dateTimeEndArray = self.mission[i].fechahorafin.split(' ');
			let dateStart = dateTimeStartArray[0];
			let dateEnd = dateTimeEndArray[0];
			if(self.dateFormat === 'AAAAMMDD') {
				dateTimeStart = modifyDateFormat(dateStart) + ' ' + dateTimeStartArray[1];
				dateTimeEnd = modifyDateFormat(dateEnd) + ' ' + dateTimeEndArray[1];
			} else {
				dateTimeStart = dateStart + dateTimeStartArray[1];
				dateTimeEnd = dateEnd + dateTimeEndArray[1];
			}

			table += `
				<tr class="c-pointer" data-order="${(i + 1)}">
					<td id="${self.mission[i].idmision}" class="columnName" title="${self.mission[i].idmision}">${self.mission[i].idmision}</td>
					<td title="${self.mission[i].tipomision}">${self.mission[i].tipomision}</td>
					<td title="${dateTimeStart}">${dateTimeStart}</td>
					<td title="${dateTimeEnd}">${dateTimeEnd}</td>
					<td title="${self.mission[i].importe}">${self.mission[i].importe}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

		// Setup - add a text input to each footer cell
		$('#tableMission .filtersMission td').each(function() {
			$(this).html('<input type="text" class="form-control form-control-sm">');
		});

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

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

		// Apply the search
		applyTheSearch(tableMission, 'filtersMission');

		$('#missionTable table tbody').on('click', 'tr', function() {
			$('#exportCompliance').prop('disabled', true);
			$('#diffusion').prop('disabled', true);
			let mission = $(this).find('.columnName').text();
			self.idMission = $(this).find('.columnName').text();
			$('#mission').val(mission);
			$('#missionTable tbody tr').css('outline-width', 'initial');
			$('#missionTable tbody tr').css('outline-style', 'none');
			$('#missionTable tbody tr').css('outline-color', '#000');
			$('#missionTable tbody tr').css('font-weight', 'normal');
			$(this).css('outline-width', 'thin');
			$(this).css('outline-style', 'solid');
			$(this).css('outline-color', '#f00');
			$(this).css('font-weight', 'bold');
			$('#closeMission').trigger('click');

			// Cargar tabla
			addLoader();
			self.getSnapAcualMisionCumplimiento();
		});
	},

	complianceGraph(totalOK, totalKO) {
		let self = this;

		let labels = [pf.const.language.RSC157, pf.const.language.RSC158];

		// Datos en porcentaje
		let total = totalOK + totalKO;
		self.total = total;
		let data = [];
		let valueOK = (totalOK * 100 / total).toFixed(1);
		if(valueOK == Math.floor(valueOK)) {
			data.push(Math.floor(valueOK));
		} else {
			data.push(valueOK);
		}
		let valueKO = (totalKO * 100 / total).toFixed(1);
		if(valueKO == Math.floor(valueKO)) {
			data.push(Math.floor(valueKO));
		} else {
			data.push(valueKO);
		}
		self.dataOKKO = data;

		// COLORES
		let gradient = [self.colorsHex[0], self.colorsHex[1]];

		if(!$.isEmptyObject(self.complianceChart)) {
			self.complianceChart.destroy();
		}

		let ctx = document.getElementById('graphCompliance').getContext('2d');

		Chart.defaults.global.defaultFontSize = parseInt(self.fontSize, 10);
		Chart.defaults.global.defaultFontFamily = self.fontName;

		let titleText = pf.const.language.RSC32 + ': ' + total;

		self.graphData = {
			type: 'pie',
			data: {
				datasets: [{
					data: data,
					backgroundColor: gradient
				}],
				labels: labels
			},
			options: {
				layout: {
					padding: {
						top: -20
					}
				},
				responsive: true,
				maintainAspectRatio: false,
				legend: {
					display: true,
					position: 'right',
					onClick: false
				},
				title: {
					display: true,
					text: titleText,
					padding: 26
				},
				tooltips: {
					enabled: false
				},
				plugins: {
					datalabels: {
						color: 'white',
						font: {
							weight: 'bold'
						},
						formatter(value, context) {
							return value;
						}
					}
				}
			}
		};

		let graph = new Chart(ctx, self.graphData);

		self.complianceChart = graph;
	},

	// TABLA DE RESULTADOS
	renderData() {
		let self = this;

		if(self.dataFlag) {
			$('#registers' + self.suffix).dataTable().fnDestroy();
		} else {
			self.dataFlag = true;
		}

		$('#resultTableC').show();
		let excelTitle = self.idMission;

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
			<th scope="col" title="${pf.const.language.RSC1626}">${pf.const.language.RSC1626}</th>
			<th scope="col" title="${pf.const.language.RSC1627}">${pf.const.language.RSC1627}</th>
		`;
		let nameSurnameFilter = `
			<td>name</td>
			<td>surname1</td>
			<td>surname2</td>
		`;

		// Control GDPR
		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		// Control de market
		let marketHead = '';
		let marketFilter = '';
		if(sessionStorage['STCMBackEnd:config_market'] == '1') {
			marketHead = `
				<th scope="col" title="CPG">CPG</th>
				<th scope="col" title="CPG - ID">CPG - ID</th>
			`;
			marketFilter = `
				<td>cpg</td>
				<td>cpgid</td>¡
			`;
		}

		let table = `
			<thead>
				<tr>
					${marketHead}
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC33}">${pf.const.language.RSC33}</th>
					<th scope="col" title="${pf.const.language.RSC2344}">${pf.const.language.RSC2344}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					${marketFilter}
					${nameSurnameFilter}
					<td>email</td>
					<td>compliance</td>
					<td>dateCompliance</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let nameSurnameBody = `
				<td class="text-truncate" title="${self.data[i].name}">${self.data[i].name}</td>
				<td class="text-truncate" title="${self.data[i].surname1}">${self.data[i].surname1}</td>
				<td class="text-truncate" title="${(self.data[i].surname2 == null ? '-' : self.data[i].surname2)}">${(self.data[i].surname2 == null ? '-' : self.data[i].surname2)}</td>
			`;

			// Control GDPR
			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			// Control de market
			let marketBody = '';
			if(sessionStorage['STCMBackEnd:config_market'] == '1') {
				marketBody = `
					<td class="text-truncate" title="${self.data[i].cpg}">${self.data[i].cpg}</td>
					<td class="text-truncate" title="${self.data[i].cpgId}">${self.data[i].cpgId}</td>
				`;
			}

			// Para ordenación en columna
			let dateOrder = self.data[i].date.replace(' ', '');

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let dateTime = '';
			if(self.data[i].date != '') {
				let dateTimeArray = self.data[i].date.split(' ');
				let date = dateTimeArray[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					dateTime = modifyDateFormat(date) + ' ' + dateTimeArray[1];
				} else {
					dateTime = date + ' ' + dateTimeArray[1];
				}
			}

			table += `
				<tr>
					${marketBody}
					${nameSurnameBody}
					<td class="text-truncate" title="${self.data[i].email}">${self.data[i].email}</td>
					<td class="text-truncate" title="${(self.data[i].compliance == 'Cumplido' ? pf.const.language.RSC120 : pf.const.language.RSC121)}">${(self.data[i].compliance == 'Cumplido' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</td>
					<td class="text-truncate" title="${dateTime}">
						<span class="d-none">${dateOrder}</span>
						${dateTime}
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#registers' + self.suffix).html(table);

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

			if(title == 'compliance') {
				value = optionsSelectAllYesNo();
			}

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

		let columnOrder = 5;
		if(gdpr == '1' && sessionStorage['STCMBackEnd:config_market'] == '1') {
			columnOrder = 4;
		} else if(gdpr == '1') {
			columnOrder = 2;
		} else if(sessionStorage['STCMBackEnd:config_market'] == '1') {
			columnOrder = 4;
		}

		let dataTable = $('#registers' + self.suffix).DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: excelTitle,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === columnOrder) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		// Ocultar botones de tabla
		hideTableButtons('registers' + self.suffix);

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

		dataTable.rowGroup().disable().draw();

		// Exportar tabla
		$('#exportCompliance').prop('disabled', false);
		$('#exportCompliance').off().on('click', function() {
			$('#registersContainer' + self.suffix + ' .buttons-excel').trigger('click');
		});

		// Activación de botón de creación de lista de difusión
		$('#diffusion').prop('disabled', false);
		$('#diffusion').off().on('click', function() {
			let content = `
				<select id="mailingLists" class="form-control">
					<option value="OK">${pf.const.language.RSC157}</option>
					<option value="KO">${pf.const.language.RSC158}</option>
				</select>
			`;

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

			let alertTitle = pf.const.language.RSC12;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, content, objInfo, function() {
				let type = $('#mailingLists').val();
				self.requestMailingList(type);
			}, function() {});
		});
	},

	// Gráfica a pantalla completa
	graphsEvents() {
		let self = this;

		let graph;
		$('#mGraphs' + self.suffix + ' .section-body').off().on('click', function() {
			$('#graphicsViewer').show();

			let labels = [pf.const.language.RSC157, pf.const.language.RSC158];

			// COLORES
			let gradient = [self.colorsHex[0], self.colorsHex[1]];

			let ctx = document.getElementById('graphViewer').getContext('2d');

			Chart.defaults.global.defaultFontSize = parseInt(self.fontSize, 10);
			Chart.defaults.global.defaultFontFamily = self.fontName;

			if(screen.width < 380) {
				data.options.scales.xAxes[0].ticks.fontSize = 12;
			}

			let titleText = pf.const.language.RSC32 + ': ' + self.total;

			let dataChart = {
				type: 'pie',
				data: {
					datasets: [{
						data: self.dataOKKO,
						backgroundColor: gradient
					}],
					labels: labels
				},
				options: {
					layout: {
						padding: {
							top: 6
						}
					},
					responsive: true,
					maintainAspectRatio: false,
					legend: {
						display: true,
						position: 'right',
						onClick: false
					},
					title: {
						display: true,
						text: titleText,
						fontSize: 20
					},
					tooltips: {
						enabled: false
					},
					plugins: {
						datalabels: {
							color: 'white',
							font: {
								weight: 'bold'
							},
							formatter(value, context) {
								return value;
							}
						}
					}
				}
			};

			graph = new Chart(ctx, dataChart);
		});

		$('#downloadGraph').off().on('click', function() {
			/*Get image of canvas element*/
			let url_base64jp = document.getElementById('graphViewer').toDataURL('image/jpg');
			/*get download button (tag: <a></a>) */
			let a = document.getElementById('downloadGraph');
			/*insert chart image url to download button (tag: <a></a>) */
			a.href = url_base64jp;
		});

		$('#closeGraphic').off().on('click', function() {
			graph.destroy();
			$('#graphicsViewer').hide();
		});
	},

	requestMailingList(type) {
		let self = this;

		let size = self.project.length;
		for(let i = 0; i < size; i++) {
			if(self.project[i].id === self.idProject) {
				self.projectObj = self.project[i];
			}
		}

		let parameters = {
			NombreProyecto: self.projectObj.NombreProyecto + ' - ' + type,
			LiderProyecto: self.projectObj.LiderProyectoJID
		};
		ajaxComunCallWithCallback('getDistributionList', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.length > 0) {
					let id = ajaxReturn.result[0].id;
					self.updateDistributionList(type, id);
				} else {
					self.createDistributionList(type);
				}
			}
		});
	},

	createDistributionList(type) {
		let self = this;

		let recipients = [];
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(type === 'OK') {
				if(self.data[i].compliance === 'Cumplido') {
					let email = self.data[i].username;
					let domainArray = self.projectObj.LiderProyectoJID.split('@');
					recipients.push(email + '@' + domainArray[1]);
				}
			} else if(type === 'KO') {
				if(self.data[i].compliance === 'No Cumplido') {
					let email = self.data[i].username;
					let domainArray = self.projectObj.LiderProyectoJID.split('@');
					recipients.push(email + '@' + domainArray[1]);
				}
			}
		}

		let parameters = {
			country: self.projectObj.country,
			admin: self.projectObj.LiderProyectoJID,
			activa: 1,
			description: self.projectObj.NombreProyecto + ' - ' + type,
			destinatarios: recipients,
			idProject: self.idProject,
			idMision: self.idMission,
			aux01: type
		};
		ajaxComunCallWithCallback('createDistributionListOKKO', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successCreateTitle = pf.const.language.RSC12;
				let successCreateContent = pf.const.language.RSC159;
				pf.utils.showInfoDialog(successCreateTitle, successCreateContent);
			}
		});
	},

	updateDistributionList(type, id) {
		let self = this;

		let recipients = [];
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(type === 'OK') {
				if(self.data[i].compliance === 'Cumplido') {
					let email = self.data[i].username;
					let domainArray = self.projectObj.LiderProyectoJID.split('@');
					recipients.push(email + '@' + domainArray[1]);
				}
			} else if(type === 'KO') {
				if(self.data[i].compliance === 'No Cumplido') {
					let email = self.data[i].username;
					let domainArray = self.projectObj.LiderProyectoJID.split('@');
					recipients.push(email + '@' + domainArray[1]);
				}
			}
		}

		let parameters = {
			idList: id,
			admin: self.projectObj.LiderProyectoJID,
			activa: 1,
			description: self.projectObj.NombreProyecto + ' - ' + type,
			destinatarios: recipients,
			idProject: self.idProject,
			idMision: self.idMission,
			aux01: type
		};
		ajaxComunCallWithCallback('updateDistributionListOKKO', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successUpdateTitle = pf.const.language.RSC12;
				let successUpdateContent = pf.const.language.RSC160;
				pf.utils.showInfoDialog(successUpdateTitle, successUpdateContent);
			}
		});
	}
};