let MuestreoComparativoController = {
	ajax: false,
	generalCharts: null,
	paramsWc: [],
	typeColors: null,
	fontSize: null,
	fontName: null,
	colorsRGB: [],
	colorsHex: [],
	poll: '',
	idPollArray: [],
	idPollNameArray: [],
	idProjectsArray: [],
	idMissionsArray: [],
	NameArrayIndex: 0,
	question: '',
	questionOrder: '',
	questionFlag: false,
	questionTitle: '',
	questionColumnName: '',
	answersChart: {},
	answersData: '',
	wordCloud: false,
	wordCloudURL: '',
	primaryColor: '',
	secundaryColor: '',
	wordCloudImg: '',
	genderChart: {},
	genderData: '',
	ageChart: {},
	ageData: '',
	statesChart: {},
	statesData: '',
	NSEChart: {},
	NSEData: '',
	data: '',
	dataFlag: false,
	resultDataFlag: false,
	alert: null,
	iChart: 0,
	QuestQuantity: 0,
	arrayPpt: [],
	dataPpt: null,
	wcPpt: null,
	questionsPpt: null,
	user: null,
	encuestasPpt: null,
	timestamp: '',
	reports: null,
	errorsReports: null,
	numPregPerf: '',
	namePoll: '',
	columnName: ',',
	idTenant: '',
	questionId: [],
	questionIdOut: [],
	quest_type: '',
	numberWordsWordcloud: 0,
	dateFormat: '',

	reset() {
		let self = this;

		self.typeColors = null;
		self.fontSize = null;
		self.fontName = null;
		self.colorsRGB = [];
		self.colorsHex = [];
		self.poll = '';
		self.idPollArray = [];
		self.idPollNameArray = [];
		self.idProjectsArray = [];
		self.idMissionsArray = [];
		self.NameArrayIndex = 0;
		self.question = '';
		self.questionOrder = '';
		self.questionFlag = false;
		self.questionTitle = '';
		self.questionColumnName = '';
		self.answersChart = {};
		self.answersData = '';
		self.wordCloud = false;
		self.wordCloudURL = '';
		self.primaryColor = '';
		self.secundaryColor = '';
		self.wordCloudImg = '';
		self.genderChart = {};
		self.genderData = '';
		self.ageChart = {};
		self.ageData = '';
		self.statesChart = {};
		self.statesData = '';
		self.NSEChart = {};
		self.NSEData = '';
		self.data = '';
		self.dataFlag = false;
		self.resultDataFlag = false;
		self.iChart = 0;
		self.QuestQuantity = 0;
		self.arrayPpt = [];
		self.timestamp = Date.now();
		self.reports = {
			word: false,
			ppt: false,
			excel: false,
			wc: false
		};
		self.errorsReports = {
			word: false,
			ppt: false,
			excel: false,
			wc: false
		};
		self.numPregPerf = '';
		self.namePoll = '';
		self.columnName = '';
		self.idTenant = '';
		self.questionId = [];
		self.questionIdOut = [];
		self.quest_type = '';
		self.numberWordsWordcloud = 0;
		self.dateFormat = '';
	},

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

		// Información de administrador
		self.user = sessionStorage['STCMBackEnd:user'];
		let userA = JSON.parse(self.user);
		let user = userA.email;
		let user_split = user.split('@');
		self.user = user_split[0].replace('.', '_');
		self.dateFormat = userA.formatoFecha;
		self.idTenant = sessionStorage['STCMBackEnd:idTenant'];

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

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

		// Opciones de header
		let jsonsubopt = {
			survey: 'poll',
			question: 'question',
			report: 'ddreport'
		};

		let nav = `
			<div class="d-flex justify-content-end row m-0">
				${createSubOptionSurvey(jsonsubopt.survey)}
				${createSubOptionQuestion(jsonsubopt.question)}
				${createSubOptionGetReport(jsonsubopt.report)}
			</div>
		`;

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

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

		$('#poll').attr('placeholder', pf.const.language.RSC177);

		self.loadLang();

		$('#mGraphs').hide();
		$('#resultTableM').hide();

		$('#ddreport').click(function() {
			self.timestamp = Date.now();
			self.reports = {
				word: false,
				ppt: false,
				excel: false,
				wc: false
			};
			self.errorsReports = {
				word: false,
				ppt: false,
				excel: false,
				wc: 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 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 alertTitle = pf.const.language.RSC48;
			self.alert = pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, 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;

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

				self.executeReports();
			}, function() {});
		});

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

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

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

		self.applyEvents();
	},

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

		let arrayPercent = ['RSC499', 'RSC147', 'RSC148', 'RSC149'];
		pf.rsc.translateByTagHTMLFormat('percent', arrayPercent);

		// TITLES
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
	},

	executeReports() {
		let self = this;

		self.ajax = false;
		let values = {
			ajax: self.ajax,
			generalCharts: self.generalCharts,
			paramsWc: self.paramsWc,
			typeColors: self.typeColors,
			fontSize: self.fontSize,
			fontName: self.fontName,
			colorsRGB: self.colorsRGB,
			colorsHex: self.colorsHex,
			poll: self.poll,
			idPollArray: self.idPollArray,
			idPollNameArray: self.idPollNameArray,
			idProjectsArray: self.idProjectsArray,
			idMissionsArray: self.idMissionsArray,
			NameArrayIndex: self.NameArrayIndex,
			question: self.question,
			questionOrder: self.questionOrder,
			questionFlag: self.questionFlag,
			questionTitle: self.questionTitle,
			wordCloud: self.wordCloud,
			wordCloudURL: self.wordCloudURL,
			primaryColor: self.primaryColor,
			secundaryColor: self.secundaryColor,
			data: self.data,
			language: pf.const.language_table,
			iChart: self.iChart,
			QuestQuantity: self.QuestQuantity,
			arrayPpt: self.arrayPpt,
			dataPpt: self.dataPpt,
			wcPpt: self.wcPpt,
			questionsPpt: self.questionsPpt,
			user: self.user,
			encuestasPpt: self.encuestasPpt,
			timestamp: self.timestamp,
			reports: self.reports,
			errorsReports: self.errorsReports,
			numPregPerf: self.numPregPerf,
			namePoll: self.namePoll,
			columnName: self.columnName,
			excelDataOpt: self.excelDataOpt,
			questionIdOut: self.questionIdOut,
			numberWordsWordcloud: self.numberWordsWordcloud
		}
		let generator = new DocumentComparativoGeneratorController(values);
		generator.start();
		// Retraso para poder cambiar mensaje del alert en el primer reporte
	},

	applyEvents() {
		let self = this;

		// Encuestas
		$('#searchPoll').on('click', function() {
			// Objeto poll
			if(self.poll === '') {
				let JSONuser = sessionStorage['STCMBackEnd:user'];
				let user = JSON.parse(JSONuser);
				let idCliente = user.idCliente;

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

						self.renderPoll(self.poll);
					}
				});
			} else {
				$('#pollTable').modal('show', true);
			}
		});

		// Preguntas
		$('#searchQuestion').on('click', function() {
			// Objeto question
			if(self.question === '') {
				let parameters = {
					survey: self.idPollArray[self.idPollArray.length - 1]
				};
				ajaxComunCallWithCallback('getQuestionsSurvey', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.question = ajaxReturn.result;

						self.renderQuests(self.question);
					}
				});
			} else {
				$('#questTable').modal('show', true);
			}
		});
	},

	renderPoll(poll) {
		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.RSC177}">${pf.const.language.RSC177}</th>
					<th scope="col" title="${pf.const.language.RSC176}">${pf.const.language.RSC176}</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.RSC549}">${pf.const.language.RSC549}</th>
				</tr>
			</thead>

			<thead class="filtersPoll">
				<tr>
					<td>selector</td>
					<td>mision</td>
					<td>proyecto</td>
					<td>active</td>
					<td>startdate</td>
					<td>expires</td>
					<td>country</td>
				</tr>
			</thead>

			<tbody>
		`;

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

		let size = poll.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(poll[i].countries != '' && allowedCountries.indexOf(poll[i].countries) == -1) {
				continue;
			}

			if(poll[i].idmision == '') {
				continue;
			}

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let startDate = '-';
			let startDateOrder = '';
			if(poll[i].startdate != '') {
				// Para ordenación en columna
				startDateOrder = poll[i].startdate.replace(' ', '');

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

			let endDate = '-';
			let endDateOrder = '';
			if(poll[i].expires != '') {
				// Para ordenación en columna
				endDateOrder = poll[i].expires.replace(' ', '');

				let dateTimeArrayEnd = poll[i].expires.split(' ');
				let dateEnd = dateTimeArrayEnd[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					endDate = modifyDateFormat(dateEnd);
				} else {
					endDate = dateEnd;
				}
			}

			table += `
				<tr id="sid${poll[i].sid}" class="check-select c-pointer" data-project="${poll[i].idProject}" data-mission="${poll[i].idmision}">
					<td class="text-center">
							<div class="div-single-selection">
								<input type="checkbox" class="selection">
							</div>
						</td>
					<td class="text-truncate" title="${poll[i].idmision}">${poll[i].idmision}</td>
					<td class="text-truncate" title="${poll[i].NombreProyecto}">${poll[i].NombreProyecto}</td>
					<td class="text-center">
						<span class="d-none">${(poll[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(poll[i].active == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${startDate}">
						<span class="d-none">${startDateOrder}</span>
						${startDate}
					</td>
					<td class="text-truncate" title="${endDate}">
						<span class="d-none">${endDateOrder}</span>
						${endDate}
					</td>
					<td class="country text-truncate" title="${poll[i].countries}">${poll[i].countries}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let tablePoll = $('#tablePoll').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '60px', targets: 3}
			],
			autoWidth: false,
			aaSorting: []
		});

		// Ajuste de tabla
		setTimeout(function() {
			tablePoll.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tablePoll, 'filtersPoll');

		// Selección de múltiples encuestas
		self.selectionMult();

		$('#tablePoll').on('draw.dt', function() {
			self.selectionMult();
		});
	},

	selectionMult() {
		let self = this;

		inputControl();

		// Selección por tr
		$('#tablePoll tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			inputControl();
		});

		// Selección por input check
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelection').off().on('change', function() {
			if($('.globalSelection').prop('checked')) {
				$('.selection').prop('checked', true);
			} else {
				$('.selection').prop('checked', false);
			}
		});

		$('#multSurvey').off().on('click', function() {
			$('#searchQuestion').prop('disabled', false);
			$('#ddreport').prop('disabled', false);
			self.idPollArray = [];
			self.idPollNameArray = [];
			self.idProjectsArray = [];
			self.idMissionsArray = [];
			// Limpieza de question
			self.question = '';
			self.questionOrder = '';
			self.questionTitle = '';
			self.questionColumnName = '';
			self.columnName = '';
			$('#question').val('Pregunta');

			let obj = [];
			$('#tablePoll tr').each(function() {
				let cheked = $(this).find('.selection');
				if(cheked.prop('checked')) {
					let idMission = $(this).data('mission');
					let idProject = $(this).data('project');
					let date = $(this).find('.dateCreated').text();
					let sid = $(this).attr('id');
					let name = $(this).find('.pollName').text();
					self.namePoll = name;
					let o = {};
					o['mission'] = idMission;
					o['project'] = idProject;
					o['date'] = date;
					sid = sid.replace('sid', '');
					o['sid'] = sid;
					o['name'] = name;
					obj.push(o);
				}
			});

			obj.sort(function(a, b) {
				if(a.date > b.date) {
					return 1;
				}
				if(a.date < b.date) {
					return -1;
				}
				return 0;
			});

			for(let i = 0; i < obj.length; i++) {
				self.idPollArray.push(obj[i].sid);
				self.idPollNameArray.push(obj[i].name);
				self.idProjectsArray.push(obj[i].project);
				self.idMissionsArray.push(obj[i].mission);
			}

			let numbers = self.idPollArray.join().replace(',', ', ');
			$('#poll').val(numbers);
			$('#closePool').trigger('click');
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	},

	renderQuests(quests) {
		let self = this;

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

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

			<thead class="filtersQuest">
				<tr>
					<td>reports</td>
					<td>columnName</td>
					<td>section</td>
					<td>question</td>
				</tr>
			</thead>

			<tbody>
		`;

		let section = $('#poll').val();
		// IDs de preguntas
		self.questionId = [];

		let size = quests.length;
		for(let i = 0; i < size; i++) {
			let question = quests[i].question.replace('/...', '');

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

			if(quests[i].type == '6' || quests[i].type == 'A' || quests[i].type == 'B' || quests[i].type == 'C' || quests[i].type == 'E' || quests[i].type == 'H' || quests[i].type == 'K' || (quests[i].type == 'F' && quests[i].valuesSQ.length > 0)) {
				let sizeK = quests[i].valuesSQ.length;
				for(let j = 0; j < sizeK; j++) {
					let valuesSQArray = quests[i].valuesSQ[j].split('|');
					let columnNameK = valuesSQArray[0];
					let questionK = tagsWithoutTags.trim() + '<br>' + valuesSQArray[1].replace(';', '');
					table += `
						<tr data-order="j${(i + 1)}" data-type="normal" data-quest_type="${quests[i].type}">
							<td class="text-center">
								<input type="checkbox" class="selectionReport" data-quest="${columnNameK}" checked>
							</td>
							<td id="${quests[i].title}" class="columnName selectQ">${columnNameK}</td>
							<td class="selectQ">${quests[i].group_name}</td>
							<td class="question selectQ">${questionK}</td>
						</tr>
					`;

					self.questionId.push(columnNameK);
				}
			} else if(quests[i].type == '6') {
				let sizeK = quests[i].valuesSQ.length - 1;
				let valuesSQArray = quests[i].valuesSQ[sizeK].split('|');
				let columnNameK = valuesSQArray[0];
				let questionK = tagsWithoutTags.trim() + '<br>' + valuesSQArray[1].replace(';', '');
				table += `
					<tr class="c-pointer" data-order="j${(i + 1)}" data-type="normal" data-quest_type="${quests[i].type}">
						<td class="text-center">
							<input type="checkbox" class="selectionReport" data-quest="${columnNameK}" checked>
						</td>
						<td id="${quests[i].title}" class="columnName selectQ">${columnNameK}</td>
						<td class="selectQ">${quests[i].group_name}</td>
						<td class="question selectQ">${questionK}</td>
					</tr>
				`;
				self.questionId.push(columnNameK);
			} else if(quests[i].type == ':') {
				table += `
					<tr class="c-pointer" data-order="${(i + 1)}" data-type="twoPoints" data-quest_type="${quests[i].type}">
						<td class="text-center">
							<input type="checkbox" class="selectionReport" data-quest="${quests[i].columnName}" checked>
						</td>
						<td id="${quests[i].title}" class="columnName selectQ">${quests[i].columnName}</td>
						<td class="selectQ">${quests[i].group_name}</td>
						<td class="question selectQ">${question}</td>
					</tr>
				`;
				self.questionId.push(quests[i].columnName);
			} else {
				table += `
					<tr class="c-pointer" data-order="${(i + 1)}" data-type="normal" data-quest_type="${quests[i].type}">
						<td class="text-center">
							<input type="checkbox" class="selectionReport" data-quest="${quests[i].columnName}" checked>
						</td>
						<td id="${quests[i].title}" class="columnName selectQ">${quests[i].columnName}</td>
						<td class="selectQ">${quests[i].group_name}</td>
						<td class="question selectQ">${question}</td>
					</tr>
				`;
				self.questionId.push(quests[i].columnName);
			}
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let tableQuest = $('#tableQuest').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '30px', orderable: false, targets: 0},
				{width: '40px', targets: 1}
			],
			autoWidth: false,
			aaSorting: []
		});

		// Prueba de reparación para Beb
		setTimeout(function() {
			tableQuest.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableQuest, 'filtersQuest');

		$('.selectQ').on('click', function() {
			self.columnName = $(this).parent().find('.columnName').text();
			let question = $(this).parent().find('.question').text();
			let questionObj = $(this).parent();
			self.quest_type = $(this).parent().data('quest_type');
			self.questionOrder = questionObj[0].dataset.order;
			let type = $(this).parent().attr('data-type');
			if(type == 'twoPoints') {
				self.questionType = ':';
				self.getOptionsFor2PointsTypeQuetsion();
				$('#selectByType').removeClass('d-none');
				$('#selectByType').addClass('d-inline-block');
				$('#twoPointsElement').val('');
			} else {
				$('#selectByType').removeClass('d-inline-block');
				$('#selectByType').addClass('d-none');
				$('#twoPointsElement').val('');
				self.preguntaSQ = '';
				self.preguntaSQText = '';
				$('#exportSurvey').prop('disabled', true);
			}

			self.questionTitle = $(this).parent().find('.columnName').attr('id');
			$('#question').val(question);
			$('#resp').text(question + ' (%)');
			$('#questTable tbody tr').css('outline-width', 'initial');
			$('#questTable tbody tr').css('outline-style', 'none');
			$('#questTable tbody tr').css('outline-color', '#000');
			$('#questTable tbody tr').css('font-weight', 'normal');
			$(this).parent().css('outline-width', 'thin');
			$(this).parent().css('outline-style', 'solid');
			$(this).parent().css('outline-color', '#f00');
			$(this).parent().css('font-weight', 'bold');
			$('#closeQuest').trigger('click');

			// Cargar tabla
			self.getAnalyticsMuestraComparativa();
		});

		$('#accept').off().on('click', function() {
			$('#closeQuest').trigger('click');
		});

		$('#uncheckRows').off().on('click', function() {
			self.questionIdOut = [];

			let size = self.questionId.length;
			for(let i = 0; i < size; i++) {
				self.questionIdOut.push(self.questionId[i]);
			}

			$('.selectionReport').prop('checked', false);
		});

		$('#checkRows').off().on('click', function() {
			self.questionIdOut = [];

			$('.selectionReport').prop('checked', true);
		});

		$('.selectionReport').off().on('click', function() {
			let quest = $(this).data('quest');
			if($(this).prop('checked')) {
				let index = self.questionIdOut.indexOf(quest);
				self.questionIdOut.splice(index, 1);
			} else {
				self.questionIdOut.push(quest);
			}
		});
	},

	// Petición de datos para comparativa
	getAnalyticsMuestraComparativa() {
		let self = this;

		let surveys = self.idPollArray;
		let surveysString = '[';
		for(let i = 0; i < surveys.length; i++) {
			surveysString += '"' + surveys[i] + '",';
		}
		surveysString = surveysString.substring(0, surveysString.length - 1);
		surveysString += ']';

		let parameters = {
			surveys: surveysString,
			question: self.questionTitle,
			param4: self.numPregPerf,
			columnName: self.questionColumnName
		};
		ajaxComunCallWithCallback('getAnalyticsMuestraComparativa', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				$('#mGraphs').show();
				$('#respChart').show();
				$('#answerTable').show();
				$('#respWordCloud').hide();

				let result = ajaxReturn.result.result;
				let data = [];
				let answer = [];
				let gender = [];
				let age = [];
				let states = [];
				self.NameArrayIndex = 0;

				for(let i = 0; i < result.length; i++) {
					if(result[i] === false) {
						self.NameArrayIndex++;
					} else {
						data.push(result[i].data);
						answer.push(result[i].answers);
						gender.push(result[i].gender);
						age.push(result[i].age);
						states.push(result[i].states);
					}
				}

				if(answer[answer.length - 1].labels[0] === 'Others' && answer[answer.length - 1].labels.length === 1) {
					// WordCloud
					$('#respChart').hide();
					$('#answerTable').hide();
					$('#respWordCloud').show();
					self.wordCloud = true;
					if(!$.isEmptyObject(self.answersChart)) {
						self.answersChart.destroy();
						self.answersData = '';
					}
					let answerType = $('#resp').text();
					answerType = answerType.replace(' (%)', ' (WordCloud)');
					$('#titleWordCloud').text(answerType);
					self.printWordCloud();
				} else {
					self.createGraphs(answer, 0);
					self.createResultTable(answer);
				}

				self.createGraphs(gender, 1);
				self.createGraphs(age, 2);
				self.createGraphs(states, 3);
				// Tabla de resultados
				let tableData = data[0];
				for(let i = 1; i < data.length; i++) {
					tableData.push.apply(tableData, data[i]);
				}
				self.data = tableData;
				self.renderData();
				self.graphsEvents();
			}
		});
	},

	createGraphs(result, n) {
		let self = this;

		let ctx;
		let size = result.length;
		let quantity = result[0].labels.length;

		// COLORES
		let gradient = [];
		if(quantity == 2) {
			gradient = [self.colorsHex[0], self.colorsHex[1]];
		} else {
			if(self.typeColors == 1) {
				gradient = generateColors(self.colorsHex[0], self.colorsHex[1], quantity);
			} else {
				gradient = arrayColors(self.colorsHex, quantity);
			}
		}

		let yAxe = [{
			display: false,
			stacked: true,
			ticks: {
				fontSize: 16,
				max: 100
			}
		}];

		switch(n) {
			case 0:
				self.answersData = result;
				if(!$.isEmptyObject(self.answersChart)) {
					self.answersChart.destroy();
				}
				ctx = document.getElementById('graphAnswers').getContext('2d');
				break;
			case 1:
				self.genderData = result;
				if(!$.isEmptyObject(self.genderChart)) {
					self.genderChart.destroy();
				}
				// COLORES con solo 2 opciones
				gradient = [self.colorsHex[0], self.colorsHex[1]];
				yAxe = [{
					display: false,
					stacked: true,
					ticks: {
						fontSize: 16
					}
				}];
				ctx = document.getElementById('graphGender').getContext('2d');
				break;
			case 2:
				self.ageData = result;
				if(!$.isEmptyObject(self.ageChart)) {
					self.ageChart.destroy();
				}
				ctx = document.getElementById('graphAge').getContext('2d');
				break;
			case 3:
				self.statesData = result;
				if(!$.isEmptyObject(self.statesChart)) {
					self.statesChart.destroy();
				}
				ctx = document.getElementById('graphStates').getContext('2d');
				break;
		}

		let data = {};
		data['labels'] = [];
		data['datasets'] = [];

		for(let k = 0; k < size; k++) {
			data['labels'].push(self.idPollNameArray[self.NameArrayIndex + k]);
		}

		let arrayGen = ['Masculino', 'Femenino'];

		for(let i = 0; i < quantity; i++) {
			let label = result[0].labels[i];
			if(n === 1) {
				label = arrayGen[i];
			}

			// COLORES
			let color;
			color = gradient[i];

			let obj = {
				label: label,
				data: [],
				backgroundColor: color,
				borderWidth: 2
			};
			for(let j = 0; j < size; j++) {
				obj.data.push(result[j].datasets.data[i]);
			}
			data['datasets'].push(obj);
		}

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

		let graph = new Chart(ctx, {
			type: 'bar',
			data: data,
			options: {
				responsive: true,
				maintainAspectRatio: false,
				legend: {
					position: 'right',
					onClick: false
				},
				title: {
					display: false,
					text: '',
					fontSize: 16
				},
				scales: {
					xAxes: [{
						stacked: true,
						ticks: {
							display: true,
							autoSkip: false
						}
					}],
					yAxes: yAxe
				},
				tooltips: {
					enabled: false
				},
				plugins: {
					datalabels: {
						color: 'white',
						font: {
							weight: 'bold'
						},
						formatter(value, context) {
							return value;
						}
					}
				}
			}
		});

		switch(n) {
			case 0:
				self.answersChart = graph;
				break;
			case 1:
				self.genderChart = graph;
				break;
			case 2:
				self.ageChart = graph;
				break;
			case 3:
				self.statesChart = graph;
				break;
		}
	},

	createResultTable(data) {
		let self = this;

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

		let excelTitle = $('#question').val();

		let table = `
			<thead>
				<tr>
					<th></th>
		`;

		for(let i = self.NameArrayIndex; i < self.idPollNameArray.length; i++) {
			table += `<th scope="col">${self.idPollNameArray[i]}</th>`;
		}

		table += `
				</tr>
			</thead>

			<tbody>
		`;

		let size = data.length;
		let labelsSize = data[0].labels.length;
		for(let i = 0; i < labelsSize; i++) {
			table += `
				<tr>
					<th>${data[0].labels[i]}</th>
			`;

			for(let j = 0; j < size; j++) {
				table += `<td>${data[j].datasets.data[i]}</td>`;
			}

			table += `
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

		let dataTable = $('#answersRegisters').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,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

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

	// WORDCLOUD
	printWordCloud() {
		let self = this;

		// Los valores de survey y answer los recogerá de los atributos
		let survey = self.idPollArray[self.idPollArray.length - 1];
		let answer = self.questionColumnName;
		let url = self.wordCloudURL;

		// Palabras (1) o frases (2)
		let wordsOrPhrases = 2;

		if(self.quest_type == 'S' || self.quest_type == 'Q') {
			wordsOrPhrases = 1;
		}

		let wordcloud = url + '/?a=' + survey + '&b=' + answer + '&c=&d=&e=&f=&g=' + self.primaryColor + '&h=' + self.secundaryColor + '&i=' + wordsOrPhrases + '&j=' + self.numberWordsWordcloud;

		window.addEventListener('message', function(event) {
			self.wordCloudImg = event.data;
		});

		$('#wordcloud').attr('src', wordcloud);
	},

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

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

		$('#resultTableM').show();
		let excelTitle = self.questionOrder + ' - ' + $('#poll').val() + ' - ' + $('#question').val();

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

		let nameSurnameHead = `<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>`;
		let nameSurnameFilter = `<td>userName</td>`;

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

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC124}">${pf.const.language.RSC124}</th>
					<th scope="col" title="${pf.const.language.RSC309}">${pf.const.language.RSC309}</th>
					<th scope="col" title="${pf.const.language.RSC125}">${pf.const.language.RSC125}</th>
					<th scope="col" title="${pf.const.language.RSC126}">${pf.const.language.RSC126}</th>
					<th scope="col" title="${pf.const.language.RSC127}">${pf.const.language.RSC127}</th>
					<th scope="col" title="${pf.const.language.RSC128}">${pf.const.language.RSC128}</th>
		`;

		$.each(self.data[0], function(key, value) {
			if(key.indexOf('perf') !== -1 && key.indexOf('Desc') !== -1) {
				table += `<th scope="col" title="${value}">${value}</th>`;
			}
		});

		table += `
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					${nameSurnameFilter}
					<td>userEmail</td>
					<td>consejero</td>
					<td>staff</td>
					<td>clabe</td>
					<td>enabled</td>
					<td>answer</td>
					<td>answerothers</td>
		`;

		$.each(self.data[0], function(key, value) {
			if(key.indexOf('perf') !== -1 && key.indexOf('Desc') === -1 && key != 'perf002Range') {
				table += `<td>${key}</td>`;
			}
		});

		table += `
				</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].userName}">${self.data[i].userName}</td>`;

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

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${self.data[i].userEmail}">${self.data[i].userEmail}</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].consejero === '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].consejero === '1' ? 'checked' : '')}></td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].staff === '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].staff === '1' ? 'checked' : '')}></td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].clabe === '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].clabe === '1' ? 'checked' : '')}></td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].enabled === '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].enabled === '1' ? 'checked' : '')}></td>
					<td class="text-truncate" title="${(self.data[i].answer == 'Others' ? '' : self.data[i].answer)}">${(self.data[i].answer == 'Others' ? '-' : self.data[i].answer)}</td>
					<td class="text-truncate" title="${self.data[i].answerothers}">${(self.data[i].answerothers == '' ? '-' : self.data[i].answerothers)}</td>
			`;

			$.each(self.data[i], function(key, value) {
				if(key.indexOf('perf') !== -1 && key.indexOf('Desc') === -1 && key != 'perf002Range') {
					table += `<td class="text-truncate" title="${value}">${value}</td>`;
				}
			});

			table += `
				</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 == 'consejero' || title == 'staff' || title == 'clabe' || title == 'enabled') {
				value = optionsSelectAllYesNo();
			}

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

		let columnDefs = [
			{width: '60px', targets: 2},
			{width: '40px', targets: 3},
			{width: '40px', targets: 4},
			{width: '40px', targets: 5},
			{width: '40px', targets: 9},
			{width: '60px', targets: 10}
		];

		// Control GDPR
		if(gdpr == '1') {
			columnDefs = [
				{width: '60px', targets: 1},
				{width: '40px', targets: 2},
				{width: '40px', targets: 3},
				{width: '40px', targets: 4},
				{width: '40px', targets: 8},
				{width: '60px', targets: 9}
			];
		}

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			rowGroup: {
				endRender(rows, group) {
					return group + ': ' + pf.const.language.RSC146 + ' (' + rows.count() + ')';
				},
				dataSrc: 0
			},
			order: [[0, 'asc']]
		});

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

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

		dataTable.rowGroup().disable().draw();
		$('#nestBy').hide();

		// Creación de select principal de agrupamiento
		// Arrays de datos
		let name = [];

		$.each($('#registers thead th'), function() {
			name.push($(this).text());
		});

		let options1 = `<option value="-1">${pf.const.language.RSC130}</option>`;
		for(let i = 0; i < name.length; i++) {
			options1 += `<option value="${i}">${name[i]}</option>`;
		}
		$('#groupBy').html(options1);

		// Función de agrupamiento anidado
		function nestBy() {
			$('#nestBy').html('');
			let options2 = `<option value="-1">${pf.const.language.RSC131}</option>`;
			for(let i = 0; i < name.length; i++) {
				if(i == $('#groupBy').val()) {
					continue;
				} else {
					options2 += `<option value="${i}">${name[i]}</option>`;
				}
			}
			$('#nestBy').html(options2);

			// Evento de anidado
			$('#nestBy').off().on('change', function() {
				let valueGroup = $('#groupBy').val();

				if($('#nestBy').val() === '-1') {
					dataTable.rowGroup().dataSrc(valueGroup);
					dataTable.order([[valueGroup, 'asc']]).draw();
				} else {
					let valueNest = $('#nestBy').val();
					dataTable.rowGroup().dataSrc([valueGroup, valueNest]);
					dataTable.order([[valueGroup, 'asc'], [valueNest, 'asc']]).draw();
				}
			});
		}

		// Evento de agrupamiento
		$('#groupBy').on('change', function() {
			if($('#groupBy').val() === '-1') {
				dataTable.rowGroup().disable().draw();
				$('#nestBy').hide();
			} else {
				let value = $('#groupBy').val();

				dataTable.rowGroup().enable().draw();
				$('#nestBy').show();

				dataTable.rowGroup().dataSrc(value);
				dataTable.order([[value, 'asc']]).draw();

				// Recreación de agrupamiento secundario
				nestBy();
			}
		});

		// Exportar tabla
		$('#exportSurvey').prop('disabled', false);
		$('#exportSurvey').off().on('click', function() {
			$('#resultTableM .buttons-excel').trigger('click');
		});
	},

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

		$('#mGraphs .card-body').off().on('click', function() {
			let graphName = $(this).find('canvas').prop('id');
			let result = '';
			let title = '';

			if(graphName === undefined && self.wordCloud) {
				$('#wordCloudViewer').show();

				// Los valores de survey y answer los recogerá de los atributos
				let survey = self.idPollArray[self.idPollArray.length - 1];
				let answer = self.questionColumnName;
				let url = self.wordCloudURL;

				// Palabras (1) o frases (2)
				let wordsOrPhrases = 2;

				if(self.quest_type == 'S' || self.quest_type == 'Q') {
					wordsOrPhrases = 1;
				}

				let wordcloud = url + '/?a=' + survey + '&b=' + answer + '&c=&d=&e=&f=&g=' + self.primaryColor + '&h=' + self.secundaryColor + '&i=' + wordsOrPhrases + '&j=' + self.numberWordsWordcloud;

				window.addEventListener('message', function(event) {
					self.wordCloudImg = event.data;
				});

				$('#wordcloudBig').attr('src', wordcloud);

				$('#downloadWordCloud').hide();
				setTimeout(function() {
					$('#downloadWordCloud').show();
				}, 8000);

				$('#downloadWordCloud').off().on('click', function() {
					let a = document.getElementById('downloadWordCloud');
					a.href = self.wordCloudImg;
				});

				$('#closeWordCloud').off().on('click', function() {
					$('#wordCloudViewer').hide();
				});
			} else {
				$('#graphicsViewer').show();
				switch(graphName) {
					case 'graphAnswers':
						result = self.answersData;
						title = $('#resp').text();
						break;
					case 'graphGender':
						result = self.genderData;
						title = pf.const.language.RSC147 + ' (%)';
						break;
					case 'graphAge':
						result = self.ageData;
						title = pf.const.language.RSC148 + ' (%)';
						break;
					case 'graphStates':
						result = self.statesData;
						title = pf.const.language.RSC149 + ' (%)';
						break;
					default:
						$('#graphicsViewer').hide();
						return;
				}

				let ctx = document.getElementById('graphViewer').getContext('2d');
				let size = result.length;
				let quantity = result[0].labels.length;

				// COLORES
				let gradient = [];
				if(quantity == 2) {
					gradient = [self.colorsHex[0], self.colorsHex[1]];
				} else {
					if(self.typeColors == 1) {
						gradient = generateColors(self.colorsHex[0], self.colorsHex[1], quantity);
					} else {
						gradient = arrayColors(self.colorsHex, quantity);
					}
				}

				let yAxe = [{
					display: false,
					stacked: true,
					ticks: {
						fontSize: 16,
						max: 100
					}
				}];
				if(graphName === 'graphGender') {
					// COLORES con solo 2 opciones
					gradient = [self.colorsHex[0], self.colorsHex[1]];
					yAxe = [{
						display: false,
						stacked: true,
						ticks: {
							fontSize: 16
						}
					}];
				}

				let data = {};
				data['labels'] = [];
				data['datasets'] = [];

				for(let k = 0; k < size; k++) {
					data['labels'].push(self.idPollNameArray[k + self.NameArrayIndex]);
				}

				let arrayGen = ['Masculino', 'Femenino'];

				for(let i = 0; i < quantity; i++) {
					let label = result[0].labels[i];
					if(graphName === 'graphGender') {
						label = arrayGen[i];
					}

					// COLORES
					let color;
					color = gradient[i];

					let obj = {
						label: label,
						data: [],
						backgroundColor: color,
						borderWidth: 2
					};
					for(let j = 0; j < size; j++) {
						obj.data.push(result[j].datasets.data[i]);
					}
					data['datasets'].push(obj);
				}

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

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

				let graph = new Chart(ctx, {
					type: 'bar',
					data: data,
					options: {
						responsive: true,
						maintainAspectRatio: false,
						legend: {
							display: true,
							position: 'right',
							onClick: false
						},
						title: {
							display: true,
							text: title,
							padding: 20
						},
						scales: {
							xAxes: [{
								stacked: true,
								ticks: {
									display: true,
									autoSkip: false
								}
							}],
							yAxes: yAxe
						},
						tooltips: {
							enabled: false
						},
						plugins: {
							datalabels: {
								color: 'white',
								font: {
									weight: 'bold'
								},
								clamp: true,
								formatter(value, context) {
									return value;
								}
							}
						}
					}
				});

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