let ConfiguracionController = {
	config: null,
	users: null,
	colorsFixed: [],
	myChart: null,
	politics: null,
	surveysProfiling: '',
	genderProfiling: '',
	genderFlag: false,
	stateProfiling: '',
	stateFlag: false,
	ageProfiling: '',
	ageFlag: false,
	plantilla: '',
	plantilla_portada: '',
	logo: '',
	country: [],
	surveys: [],
	iCountry: null,
	genderProfilingABI: '',
	genderFlagABI: false,
	stateProfilingABI: '',
	stateFlagABI: false,
	ageProfilingABI: '',
	ageFlagABI: false,
	nseProfiling: '',
	nseProfilingABI: '',
	nseFlagABI: false,
	nseFlag: false,
	functionalities: '',
	maxSize: 0,
	logoPrimario: null,
	logoSecundario: null,
	favicon: null,
	logoEmail: null,
	logoWallet: null,
	logoWellcome: null,
	logoIcon: null,
	logoLogin: null,
	colorPri: '',
	colorSec: '',
	colorPriOld: '',
	colorSecOld: '',
	tenantParams: {},
	idTenant: '',
	profilingAlgorithms: [],
	userMail: '',
	loaders: {},
	twilioValues: [],
	twilioValuesChange: '0',
	objectRSC: '',
	ckEditors: {},

	reset() {
		let self = this;

		self.config = null;
		self.users = null;
		self.colorsFixed = [];
		self.myChart = null;
		self.politics = null;
		self.surveysProfiling = '';
		self.genderProfiling = '';
		self.genderFlag = false;
		self.stateProfiling = '';
		self.stateFlag = false;
		self.ageProfiling = '';
		self.ageFlag = false;
		self.plantilla = '';
		self.plantilla_portada = '';
		self.logo = '';
		self.country = [];
		self.surveys = [];
		self.iCountry = null;
		self.genderProfilingABI = '';
		self.genderFlagABI = false;
		self.stateProfilingABI = '';
		self.stateFlagABI = false;
		self.ageProfilingABI = '';
		self.ageFlagABI = false;
		self.nseProfiling = '';
		self.nseProfilingABI = '';
		self.nseFlagABI = false;
		self.nseFlag = false;
		self.functionalities = '';
		self.maxSize = 0;
		self.logoPrimario = null;
		self.logoSecundario = null;
		self.favicon = null;
		self.logoEmail = null,
		self.logoWallet = null,
		self.logoWellcome = null,
		self.logoIcon = null,
		self.logoLogin = null,
		self.colorPri = '';
		self.colorSec = '';
		self.colorPriOld = '';
		self.colorSecOld = '';
		self.tenantParams = {
			idTenant: '',
			colorPrimario: '',
			colorSecundario: '',
			favicon: '',
			logoPrimario: '',
			logoSecundario: '',
			logoEmail: '',
			logoWalletApp: '',
			logoWelcomeApp: ''
		};
		self.idTenant = '';
		self.profilingAlgorithms = [];
		self.userMail = '';
		self.loaders = {
			getSystemConfig: false,
			getPoliciesByID: false,
			getSurveyCountry: false,
			getSPSchemaCorporate: false,
			runningTXT: false
		};
		self.twilioValues = [];
		self.twilioValuesChange = '0';
		self.objectRSC = '';
		self.ckEditors = {};
	},

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

		// Correo de usuario administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.userMail = user.email;

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

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

		// Opciones de header
		let jsonsubopt = {
			save: 'btn-send',
			expandcollapse: 'expCollAll',
			runningTXT: 'btn-deleteTXT',
			service: 'btn-service'
		};

		let nav = `
			<div class="row mx-0">
				${createSubOptionExpandCollapse(jsonsubopt.expandcollapse)}
				${createSubOptionRunningTXT(jsonsubopt.runningTXT)}
				${createSubOptionService(jsonsubopt.service)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>
		`;

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

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

		// Botones secundarios
		$('#expCollAll').addClass('secondary-button');
		$('#expCollAll svg').addClass('icon-color');
		$('#btn-deleteTXT').addClass('secondary-button');
		$('#btn-service').addClass('secondary-button');

		// Añadir textos explicativos
		$('#logoPrimarioTooltip').attr('title', pf.const.language.RSC2506);
		$('#logoSecundarioTooltip').attr('title', pf.const.language.RSC1709);
		$('#faviconTooltip').attr('title', pf.const.language.RSC1710);
		$('#logoEmailTooltip').attr('title', pf.const.language.RSC1711);
		$('#logoWalletTooltip').attr('title', pf.const.language.RSC1712);
		$('#logoWellcomeTooltip').attr('title', pf.const.language.RSC1713);
		$('#logoIconTooltip').attr('title', pf.const.language.RSC1714);
		$('#logoLoginTooltip').attr('title', pf.const.language.RSC1715);

		$('#runingTXT').hide();
		$('#btn-deleteTXT').hide();

		self.renderConfig();

		// Abrir tabla usuarios notificaciones
		let users = new TableUsers(0, 'configuration');
		$('#btn-users').click(function() {
			users.setEvents('tableModal');
		});

		// Abrir tabla usuarios misiones
		let usersMissions = new TableUsers(0, 'configurationMissions');
		$('#btn-users-missi').click(function() {
			usersMissions.setEvents('tableModal');
		});

		addLoader();
		self.getPolitics();

		$('#btn-send').click(function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC78;
			let alertText = pf.const.language.RSC105;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.sendForm();
			}, function() {});
		});

		$('#btn-service').click(function() {
			let token = sessionStorage['STCMBackEnd:token'];
			reqName = 'service';

			let form = new FormData();
			form.append('action', reqName);
			form.append('token', token);

			let reqData = {
				url: stcm.const.serverAPI,
				method: 'POST',
				timeout: stcm.const.AJAX_TIMEOUT,
				processData: false,
				mimeType: 'multipart/form-data',
				contentType: false,
				data: form
			};

			addLoader();
			pf.ajax.request(reqName, reqData);
			$(document).off(reqName);
			$(document).on(reqName, function(event, response) {
				removeLoader();
				// Aviso de servicio activado
				let noticeTitle = pf.const.language.RSC20;
				let noticeContent = pf.const.language.RSC530;
				pf.utils.showInfoDialog(noticeTitle, noticeContent);
			});
		});

		//Añadir colores
		$('#add-color').click(function() {
			self.addColor();
		});

		self.loadLanguage();

		// Imágenes de plantilla
		self.idTenant = sessionStorage['STCMBackEnd:idTenant'];
		let raiz = stcm.const.downloads + 'tenants/' + self.idTenant + '/';
		$('#faviconIMG').attr('src', raiz + 'favicon.ico?stamp=' + new Date().getTime());

		// Si no hay imagenes de plantilla en un tenant se cargan las del tenant 0
		$('#plantillaIMG').attr('src', raiz + 'plantilla.PNG?stamp=' + new Date().getTime());
		$('#plantillaIMG').one('error', function() {
			$('#plantillaIMG').attr('src', stcm.const.downloads + 'tenants/0/plantilla.PNG?stamp=' + new Date().getTime());
		});
		$('#plantillaPortadaIMG').attr('src', raiz + 'plantilla_portada.PNG?stamp=' + new Date().getTime());
		$('#plantillaPortadaIMG').one('error', function() {
			$('#plantillaPortadaIMG').attr('src', stcm.const.downloads + 'tenants/0/plantilla_portada.PNG?stamp=' + new Date().getTime());
		});
		$('#logoIMG').attr('src', raiz + 'logo_rep.PNG?stamp=' + new Date().getTime());
		$('#logoIMG').one('error', function() {
			$('#logoIMG').attr('src', stcm.const.downloads + 'tenants/0/logo_rep.PNG?stamp=' + new Date().getTime());
		});
		// Comprobación rango de valores y decimales
		$('#numWordsWordcloudPhrases').focusout('values', function() {
			let inputValue = $('#numWordsWordcloudPhrases').val();
			if(inputValue < 2) {
				inputValue = 2;
			}
			if(inputValue > 50) {
				inputValue = 50;
			}
			$('#numWordsWordcloudPhrases').val(parseInt(inputValue));
		});

		self.getSurveyCountry();
		self.applyEvents();
		self.getAlgoritmosPerfilacionData();

		// Comprobación de existencia del archivo running.txt
		self.runningTXT();

		// RSC de eslogan
		let parameters = {
			rsc: '2618'
		};
		ajaxComunCallWithCallback('getRSC', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(ajaxReturn.result[i].app == '0' && ajaxReturn.result[i].system == '1') {
						self.objectRSC = ajaxReturn.result[i];
						break;
					}
				}

				// Render RSC
				let RSCInputs = '';
				let n = 0;
				for(let key in self.objectRSC) {
					if(key == 'app' || key == 'country' || key == 'idCPG' || key == 'idRSC' || key == 'idTenant' || key == 'system') {
						continue;
					}

					RSCInputs += `
						<div class="form-group">
							<label for="${key}">${key}</label>
							<input id="${key}" type="text" class="ckEditor" name="editor${n}" value="${self.objectRSC[key]}">
						</div>
					`;

					n++;
				}

				$('#RSCForm').html(RSCInputs);

				$('.ckEditor').each(function() {
					let id = $(this).attr('id');
					let value = $(this).val();
					ClassicEditor.create(document.querySelector('#' + id), {
						toolbar: ['bold', 'italic', 'underline']
					})
					.then(editor => {
						self.ckEditors[id] = editor;
						editor.setData(value);
					})
					.catch(error => {
						console.log('CKEditor Error');
					});
				});

				// Editar entrada RSC
				$('#saveRsc').on('click', function() {
					let parameters = {
						rsc: self.objectRSC.idRSC,
						system: self.objectRSC.system,
						country: self.objectRSC.country,
						app: self.objectRSC.app
					};

					for(let key in self.objectRSC) {
						if(key == 'app' || key == 'country' || key == 'idCPG' || key == 'idRSC' || key == 'idTenant' || key == 'system') {
							continue;
						}

						if(key in self.ckEditors) {
							RSCKeyParameters = key.toLowerCase();
							parameters[RSCKeyParameters] = self.ckEditors[key].getData().replace('<p>', '').replace('</p>', '');
						} else {
							RSCKeyParameters = key.toLowerCase();
							parameters[RSCKeyParameters] = $('#' + self.languagesList[i]).val().trim();
						}
					}

					ajaxComunCallWithCallback('updateRSC', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							let successTitle = pf.const.language.RSC466;
							let successContent = pf.const.language.RSC464;
							pf.utils.showInfoDialog(successTitle, successContent);

							let lenguage = sessionStorage['STCMBackEnd:lenguage'].toLowerCase();
							$('#slogan').val(parameters[lenguage].replace('&amp;', "&"));
							$('#slogan').attr('title', parameters[lenguage].replace('&amp;', "&"));
						}
					});
				});
			}
		});
	},

	clickUser(user) {
		let self = NotificacionesNuevaController;
		if(self.typeUsers == 'aNotif') {
			$('#UsuarioANotificar').val(user.id);
			$('#DescUsuarioANotificar').text(user.email);
		} else {
			$('#UsuarioQueNotifica').val(user.id);
			$('#DescUsuarioQueNotifica').text(user.email);
		}
	},

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

		// TITLES
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('#showBreakdown').attr('title', pf.const.language.RSC2628);

		// RSC de eslogan
		let slogan = pf.const.language.RSC2618.replace('&amp;amp;', "&");
		$('#slogan').val(slogan);
		$('#slogan').attr('title', slogan);
	},

	getPolitics() {
		let self = ConfiguracionController;

		ajaxComunCallWithCallbackOne('getPoliciesByID', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let res = JSON.parse(ajaxReturn.resData.response);
				if(res.status == 'OK') {
					self.politics = atob(res.result);
					let toquit = `<!DOCTYPE html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content=""><meta name="author" content=""></head><body>`;
					self.politics = self.politics.replace(toquit, '');
					self.politics = self.politics.replace('<p></p>', '');
					tinymce.remove();
					$('#tinytext').val(decodeURIComponent(escape(self.politics)));
					tinymce.init(tiny);
				} else {
					$('#btn-politics').attr('disabled', true);
				}

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

	savePolitics() {
		tinyMCE.triggerSave();
		let file = `<!DOCTYPE html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta name="description" content=""><meta name="author" content=""></head><body>`;
		file += $('#tinytext').val();
		file += '</body></html>';

		let parameters = {
			file: file
		};
		ajaxComunCallWithCallback('setPolicies', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let title = pf.const.language.RSC358;
				let content = pf.const.language.RSC106;
				pf.utils.showInfoDialog(title, content);
			}
		});
	},

	// Seleccionar usuario de la lista para notificaciones
	selectUser(user) {
		let id = user.id;
		let userName = user.nameUser;
		$('#SYSNotifUserName').val(userName);
		$('#SYSNotifUser').text(id);
	},

	// Seleccionar usuario de la lista para misiones
	selectUserMissions(user) {
		let id = user.email;
		let userName = user.nameUser;
		$('#SYSMisionsUserName').val(userName);
		$('#SYSMisionsUser').text(id);
	},

	renderConfig() {
		let self = ConfiguracionController;

		ajaxComunCallWithCallback('getCMBPConfig', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.config = ajaxReturn.result[0];
				self.maxSize = self.config.upload_max_filesize_bytes;

				// Actualización de valores de configuración en session storage
				sessionStorage.setItem('STCMBackEnd:config', btoa(JSON.stringify(self.config)));

				if(self.config) {
					//obtenemos la sysconfig para recoger el valor de market
					ajaxComunCallWithCallback('getSystemConfig', {}, function(ajaxReturn) {
						if(ajaxReturn) {
							self.functionalities = ajaxReturn.result;

							self.renderConfigInfoAndSysUser();
							self.renderConfigEmailInfo();
							self.renderConfigOptions();
							self.renderConfigURL();
							self.renderConfigAnalytics();
							self.lookAndFeel();
							self.renderEmailPrevisualization();
							self.renderConfigAPIs();
							self.renderSmsValidation();

							$('#FormatoFechaServer').val(self.config.FormatoFechaServer);
							$('#FormatoHoraServer').val(self.config.FormatoHoraServer);

							self.setEventsConfig();

							// Pintar texto de label
							changeLabelsColor();

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

	renderConfigInfoAndSysUser() {
		let self = this;

		// INFORMACIÓN
		// If tenant == 0, display it, if not, don't
		let infSection = `
			<div class="row p-2 glass-effect">
				<div class="col-12 p-0">
					<!-- Header -->
					<div class="d-flex justify-content-between p-0 c-pointer">
						<div class="d-flex align-items-center">
							<span class="section-title mx-3">${pf.const.language.RSC1314}</span>
						</div>

						<!-- Botón Collapse -->
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#tableCollapseInformacion" data-arrow="left">
							${stcmbackend.svg.chevronRight}
						</button>
					</div>

					<!-- Body -->
					<div id="tableCollapseInformacion" class="m-0 px-3 pt-3 pb-2 collapseConf collapse section-body">
						<!-- Número de la versión -->
						<div class="form-group">
							<label for="numVersión">${pf.const.language.RSC2508}</label>
							<input id="numVersión" type="text" class="form-control" value="${'v.' + stcmVersionCtrl.const.version + ' (' + stcmVersionCtrl.const.compilacion + ')'}" disabled>
						</div>

						<!-- Tamaño máximo de archivo configurado -->
						<div class="form-group">
							<label for="maxFileSize">${pf.const.language.RSC1353}</label>
							<input id="maxFileSize" type="text" class="form-control" name="maxFileSize" disabled>
						</div>

						<!-- Dominio -->
						<div class="form-group">
							<label for="domain">${pf.const.language.RSC1361}</label>
							<input id="domain" type="text" class="form-control" name="domain">
						</div>
					</div>
				</div>
			</div>
		`;

		self.config.tenant[0].idTenant == 0 ? $('#informaciónSection').html(infSection) : $('#informaciónSection').html('');
		// Tamaño máximo de archivo configurado
		$('#maxFileSize').val(self.config.upload_max_filesize);
		// Dominio
		$('#domain').val(self.config.xmpp_domain);

		// Notificaciones
		$('#SYSNotifUser').text(self.config.SYSNotifUser);
		$('#SYSNotifUserName').val(self.config.SYSNotifUserName);

		// Misiones
		$('#SYSMisionsUser').text(self.config.SYSMisionsUser);
		$('#SYSMisionsUserName').val(self.config.SYSMisionsUserName);
	},

	renderConfigEmailInfo() {
		let self = this;

		$('#SMTPServer').val(self.config.SMTPServer);

		if(self.config.SMTPSSL == '1') {
			$('#SMTPSSL').prop('checked', true);
		} else {
			$('#SMTPSSL').prop('checked', false);
		}

		$('#SMTPUser').val(self.config.SMTPUser);
		$('#SMTPUserPassword').val(self.config.SMTPUserPassword);
		$('#SMTPNombreMail').val(self.config.SMTPNombreMail);
		$('#SMTPPort').val(self.config.SMTPPort);
	},

	renderConfigOptions() {
		let self = this;

		// OPCIONES
		// Límite de tiempo para eliminar mensaje
		let timeToDelete = self.formatTime(self.config.minutesToDelete);
		$('#messTimeLimit').val(timeToDelete);

		// Límite de tiempo para editar mensaje
		let minutesToEdit = self.formatTime(self.config.minutesToEdit);
		$('#minutesToEdit').val(minutesToEdit);

		// Tiempo a incrementar por intento fallido
		let timeToMBT = self.formatTime(self.config.minutesBlockTry);
		$('#minutesBlockTry').val(timeToMBT);

		// Número de intentos fallidos antes de bloqueo
		$('#numErrorLogin').val(self.config.numErrorLogin);
		$('#numErrorLogin').off().on('blur', function() {
			if($('#numErrorLogin').val() < 1) {
				$('#numErrorLogin').val(1);
			}
		});

		// Tiempo de reset intentos fallidos
		let timeToMREL = self.formatTime(self.config.minutesResetErrorLogin);
		$('#minutesResetErrorLogin').val(timeToMREL);

		// Rol por defecto para usuarios registrados desde la App
		$('#defaultRoleApp').val(self.config.defaultRoleUser);

		// Tiempo Tracking
		let secondsTracking = self.config.secondsTracking;
		let secondsTT = secondsTracking % 60;
		if(secondsTT < 10) {
			secondsTT = '0' + secondsTT;
		}
		let minutesTT = ((secondsTracking - secondsTT) % 3600) / 60;
		if(minutesTT < 10) {
			minutesTT = '0' + minutesTT;
		}
		let hoursTT = Math.floor(secondsTracking / 3600);
		if(hoursTT < 10) {
			hoursTT = '0' + hoursTT;
		}
		let timeTracking = hoursTT + ':' + minutesTT + ':' + secondsTT;
		$('#trackingTime').val(timeTracking);

		//Nº registros log
		$('#LOGRowsLoad').val(self.config.LOGRowsLoad);

		// Tipo de perfilación
		if(self.config.TipoPerfilacion == 1) {
			$('#profilingType1').prop('checked', true);

			$('#perfABI').hide();
			$('#profilingAlgorithmLabel').hide();
			$('#profilingAlgorithmSel').hide();

			// Ocultar encuesta y preguntas de perfilación
			$('#perfSurveys').hide();

			// ID encuesta perfilación
			$('#surveyProfiling').val('');
			// Pregunta género
			$('#genderProfiling').val('');
			// Pregunta estado
			$('#stateProfiling').val('');
			// Pregunta edad
			$('#ageProfiling').val('');
		} else if(self.config.TipoPerfilacion == 2) {
			$('#profilingType2').prop('checked', true);
			$('#perfABI').hide();
			$('#perfSurveys').show();
			$('#profilingAlgorithmLabel').hide();
			$('#profilingAlgorithmSel').hide();

			// ID encuesta perfilación
			$('#surveyProfiling').val(self.config.SurveyPerfilacionDefault);
			// Pregunta género
			$('#genderProfiling').val(self.config.QuestionGenero);
			// Pregunta estado
			$('#stateProfiling').val(self.config.QuestionEstado);
			// Pregunta edad
			$('#ageProfiling').val(self.config.QuestionEdad);
		} else if(self.config.TipoPerfilacion == 3) {
			// Algoritmo de Perfilación por Defecto
			$('#inputProfilingAlgorithm').val(self.config.sp_perfilacion_default);
			$('#profilingType3').prop('checked', true);
			$('#perfABI').show();
			$('#perfSurveys').hide();
			$('#profilingAlgorithmLabel').show();
			$('#profilingAlgorithmSel').show();
		}
	},

	renderConfigURL() {
		let self = this;

		//URL section
		let urlSection = `
			<div class="row p-2 glass-effect">
				<div class="col-12 p-0">
					<!-- Header -->
					<div class="d-flex justify-content-between p-0 c-pointer">
						<div class="d-flex align-items-center">
							<span class="section-title mx-3">${pf.const.language.RSC355}</span>
						</div>

						<!-- Botón Collapse -->
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#tableCollapseUrl" data-arrow="left">
							${stcmbackend.svg.chevronRight}
						</button>
					</div>

					<!-- Body -->
					<div id="tableCollapseUrl" class="m-0 px-3 pt-3 pb-2 collapseConf collapse section-body">
						<div class="form-group">
							<label for="URLEncuestas">${pf.const.language.RSC73}</label>
							<input id="URLEncuestas" type="text" class="form-control" name="URLEncuestas">
						</div>

						<div class="form-group">
							<label for="URLQnA">${pf.const.language.RSC74}</label>
							<input id="URLQnA" type="text" class="form-control" name="URLQnA">
						</div>

						<div class="form-group">
							<label for="URLWordCloud">${pf.const.language.RSC75}</label>
							<input id="URLWordCloud" type="text" class="form-control" name="URLWordCloud">
						</div>

						<div class="form-group">
							<label for="URLPoliticas">${pf.const.language.RSC83}</label>
							<div class="input-group new-input-others-style">
								<input id="URLPoliticas" type="text" class="form-control" name="URLPoliticas" aria-describedby="btn-users">
								<div class="input-group-append">
									<button id="btn-politics" type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#politicModal">
										${stcmbackend.svg.pencilWithoutColor}
									</button>
								</div>
							</div>
						</div>

						<div class="form-group">
							<label for="URLVideoCalls">${pf.const.language.RSC84}</label>
							<input id="URLVideoCalls" type="text" class="form-control" name="URLVideoCalls">
						</div>

						<div class="form-group d-none">
							<label for="URLMarket">${pf.const.language.RSC985}</label>
							<input id="URLMarket" type="text" class="form-control" name="URLMarket">
						</div>

						<div class="form-group">
							<label for="URLAndroid">${pf.const.language.RSC1882}</label>
							<input id="URLAndroid" type="text" class="form-control" name="URLAndroid">
						</div>

						<div class="form-group">
							<label for="URLiOS">${pf.const.language.RSC1883}</label>
							<input id="URLiOS" type="text" class="form-control" name="URLiOS">
						</div>
					</div>
				</div>
			</div>
		`;

		// Only append to html if tenant == 0;
		self.config.tenant[0].idTenant == 0 ? $('#urlSection').html(urlSection) : $('#urlSection').html('');

		$('#URLEncuestas').val(self.config.URLEncuestas);
		$('#URLQnA').val(self.config.URLQnA);

		$('#URLPoliticas').val(self.config.URLPoliticas);
		$('#URLVideoCalls').val(self.config.URLVideoCalls);

		$('#URLWordCloud').val(self.config.URLWordCloud);

		$('#URLMarket').val(self.config.URLMarket);
		$('#URLAndroid').val(self.config.URLAndroid);
		$('#URLiOS').val(self.config.URLiOS);
	},

	renderConfigAnalytics() {
		let self = this;

		// Caracter de corte
		$('#splitCharacter').val(self.config.splitCharacter);

		//market 
		var market = self.functionalities.find(obj => {return obj.name === 'market'});
		if(market)
			if(market.enabled === '1' && $('#URLMarket').length > 0) {
				$('#URLMarket').parent().removeClass('d-none');
			}
		if(!self.config.RGBInicio) {
			$('#RGBInicio').val('#0000FF');
		} else {
			$('#RGBInicio').val(rgb2hex('rgb(' + self.config.RGBInicio + ')'));
		}
		if(!self.config.RGBFin) {
			$('#RGBFin').val('#FF0000');
		} else {
			$('#RGBFin').val(rgb2hex('rgb(' + self.config.RGBFin + ')'));
		}

		self.colorPriOld = 'ffffff';
		$('#colorPri').val('#' + self.colorPriOld);
		self.colorSecOld = 'ffffff';
		$('#colorSec').val('#' + self.colorSecOld);

		$('#numPregPerfEnMostreo').val(self.config.numPregPerfEnMostreo);
		$('#numWordsWordcloudPhrases').val(self.config.numWordSentenceWordCloud);

		//Rellenamos colores
		self.colorsFixed = [];
		for(let i = 0; i < self.config.colores.length; i++) {
			self.colorsFixed.push(rgb2hex('rgb(' + self.config.colores[i].color + ')'));
		}
		$('#fontSize').val(self.config.SizeFontAnalytics);
		$('#font-picker').val(self.config.FontAnalytics);

		// Tipo de colores seleccionados
		if(self.config.UsarColorDegradado == 1) {
			$('#range').attr('checked', true);
			$('#fixeds').attr('checked', false);

			$('#rango').css('display', 'block');
			$('#fijos').css('display', 'none');
		} else {
			$('#range').attr('checked', false);
			$('#fixeds').attr('checked', true);

			$('#rango').css('display', 'none');
			$('#fijos').css('display', 'block');
			self.renderColors();
		}

		$(function() {
			$('#font-picker').fontselect();
		});
	},

	renderEmailPrevisualization() {
		let self = this;

		// Mail section / Mail preconsejeros
		if(self.config.mailingImagePosition == '0') {
			// Icon to the left
			$('#iconWrapper').removeClass('justify-content-end');
			$('#iconWrapperPre').removeClass('justify-content-end');
			$('#iconWrapper').removeClass('justify-content-center');
			$('#iconWrapperPre').removeClass('justify-content-center');
			$('#leftIcon').prop('checked', true);
		} else if(self.config.mailingImagePosition == '2') {
			// Icon center
			$('#iconWrapper').removeClass('justify-content-end');
			$('#iconWrapperPre').removeClass('justify-content-end');
			$('#iconWrapper').addClass('justify-content-center');
			$('#iconWrapperPre').addClass('justify-content-center');
			$('#centerIcon').prop('checked', true);
		} else {
			// Icon to the right
			$('#iconWrapper').removeClass('justify-content-center');
			$('#iconWrapperPre').removeClass('justify-content-center');
			$('#iconWrapper').addClass('justify-content-end');
			$('#iconWrapperPre').addClass('justify-content-end');
			$('#rightIcon').prop('checked', true);
		}

		if(self.config.URLLogoEmail) {
			$('#iconMail').attr('src', self.config.URLLogoEmail);
			$('#iconMailPre').attr('src', self.config.URLLogoEmail);
		}

		if(self.config.mailingImageVisible == '0') {
			$('#iconPositionInputs').addClass('d-none');
			$('#iconMail').addClass('d-none');
			$('#iconMailPre').addClass('d-none');
			$('#showIcon').prop('checked', false);
		} else {
			$('#iconPositionInputs').removeClass('d-none');
			$('#iconMail').removeClass('d-none');
			$('#iconMailPre').removeClass('d-none');
			$('#showIcon').prop('checked', true);
		}

		// Enlace email preconsejeros
		$('#linkPre').text(stcm.const.multimedia.replace('img/', ''));
		$('#linkPre').on('click', function(e) {
			e.preventDefault();
		});

		// Imágenes de stores
		$('#iosMailPre').attr('src', stcm.const.multimedia + '/ios.png');
		if(self.config.URLiOS == '') {
			$('#iosMailPreCont').hide();
		}
		$('#androidMailPre').attr('src', stcm.const.multimedia + '/android.png');
		if(self.config.URLAndroid == '') {
			$('#androidMailPreCont').hide();
		}
	},

	renderConfigAPIs() {
		let self = this;

		// Cognitive Services (Azure API)
		$('#keyTranscription').val(self.config.azureCognitiveLenguajeKEY);
		$('#regionTranscriptionOptions').val(self.config.azureCognitiveLenguajeRegion);
		$('#keyImage').val(self.config.azureCognitiveVisualKEY);
		$('#hostImage').val(self.config.azureCognitiveVisualHost);
		$('#keyText').val(self.config.azureCognitiveTextKEY);
		$('#hostText').val(self.config.azureCognitiveTextHost);
		$('#keyTranslator').val(self.config.azureCognitiveTranslatorKEY);
		$('#hostTranslator').val(self.config.azureCognitiveTranslatorHost);
		$('#regionTranslatorOptions').val(self.config.azureCognitiveTranslatorRegion);

		// Google Maps API
		$('#googleMapsAPIKey').val(self.config.googleMapsAPIKey);

		if(self.config.googleMapsAPIKeyConsumoLimit < 0) {
			$('#googleMapsAPIConsumo').text(pf.const.language.RSC2157);
		} else {
			$('#googleMapsAPIConsumo').text(pf.const.language.RSC2158 + ' ' + self.config.googleMapsAPIKeyConsumo + ' ' + pf.const.language.RSC2159 + ' ' + self.config.googleMapsAPIKeyConsumoLimit);
		}
	},

	setEventsConfig() {
		// Collapse
		// Para abarcar todo el título
		$('.section-title').parent().parent().off().on('click', function() {
			$(this).find('.arrow').trigger('click');
		});

		$('.arrow').on('click', function(event) {
			// Evitar la propagación
			event.stopPropagation();

			let arrow = $(this).data('arrow');
			let direction = '';
			if(arrow == 'left') {
				direction = stcmbackend.svg.chevronDown;
				$(this).data('arrow', 'down');
			} else {
				direction = stcmbackend.svg.chevronRight;
				$(this).data('arrow', 'left');
			}
			$(this).html(direction);
			$(this).parent().parent().find('.collapseConf').collapse('toggle');
		});

		// Collapse all
		$('#expCollAll').off().on('click', function() {
			let arrow = $(this).data('arrow');
			let direction = '';
			if(arrow == 'left') {
				direction = `<span class="mr-2">${pf.const.language.RSC989}</span>${stcmbackend.svg.chevronDown}`;
				let directionAll = stcmbackend.svg.chevronDown;
				$(this).data('arrow', 'down');
				$('.collapseConf').data('arrow', 'down');
				$('.collapseConf').collapse('show');
				$('.arrow').html(directionAll);
				$('.arrow').data('arrow', 'down');
				$('#expCollAll').attr('title', pf.const.language.RSC989);
			} else {
				direction = `<span class="mr-2">${pf.const.language.RSC988}</span>${stcmbackend.svg.chevronRight}`;
				let directionAll = stcmbackend.svg.chevronRight;
				$(this).data('arrow', 'left');
				$('.collapseConf').data('arrow', 'left');
				$('.collapseConf').collapse('hide');
				$('.arrow').html(directionAll);
				$('.arrow').data('arrow', 'left');
				$('#expCollAll').attr('title', pf.const.language.RSC988);
			}
			$(this).html(direction);
			$('#expCollAll svg').addClass('icon-color');
		});

		// Si todos los collapse están a la izquierda o a abajo, cambio del collapse general
		$('.arrow').on('click', function() {
			let direction = '';
			if($('.arrow').length == $('.arrow[data-arrow="left"]').length) {
				direction = `<span class="mr-2">${pf.const.language.RSC988}</span>${stcmbackend.svg.chevronRight}`;
				$('#expCollAll').html(direction);
				$('#expCollAll').data('arrow', 'left');
				$('#expCollAll').attr('title', pf.const.language.RSC988);
				$('#expCollAll svg').addClass('icon-color');
			} else if($('.arrow').length == $('.arrow[data-arrow="down"]').length) {
				direction = `<span class="mr-2">${pf.const.language.RSC989}</span>${stcmbackend.svg.chevronDown}`;
				$('#expCollAll').html(direction);
				$('#expCollAll').data('arrow', 'down');
				$('#expCollAll').attr('title', pf.const.language.RSC989);
				$('#expCollAll svg').addClass('icon-color');
			}
		});
	},

	formatTime(minutes) {
		let hours = Math.floor(minutes / 60);
		if(hours < 10) {
			hours = '0' + hours;
		}
		let restMinutes = minutes % 60;
		if(restMinutes < 10) {
			restMinutes = '0' + restMinutes;
		}

		return hours + ':' + restMinutes;
	},

	lookAndFeel() {
		let self = this;

		self.tenantParams = {
			idTenant: self.config.tenant[0].idTenant,
			colorPrimario: self.config.tenant[0].colorPrimario,
			colorSecundario: self.config.tenant[0].colorSecundario,
			colorMenu1: self.config.tenant[0].colorMenu1,
			colorFuenteMenu1: self.config.tenant[0].colorFuenteMenu1,
			colorMenu2: self.config.tenant[0].colorMenu2,
			colorFuenteMenu2: self.config.tenant[0].colorFuenteMenu2,
			colorMenu3: self.config.tenant[0].colorMenu3,
			colorFuenteMenu3: self.config.tenant[0].colorFuenteMenu3,
			favicon: self.config.tenant[0].favicon,
			logoPrimario: self.config.tenant[0].logoPrimario,
			logoSecundario: self.config.tenant[0].logoSecundario,
			logoEmail: '',
			logoWalletApp: self.config.tenant[0].logoWalletApp,
			logoWelcomeApp: self.config.tenant[0].logoWelcomeApp
		};

		// Imágenes de look and feel
		let raiz = stcm.const.downloads + 'tenants/' + self.tenantParams.idTenant + '/';
		$('#faviconIMG').attr('src', raiz + 'favicon.ico?stamp=' + new Date().getTime());
		$('#logoPrimIMG').attr('src', raiz + 'logo.png?stamp=' + new Date().getTime());
		$('#logoSecIMG').attr('src', raiz + 'logo_home.png?stamp=' + new Date().getTime());
		$('#logoEmailIMG').attr('src', raiz + 'logo_email.png?stamp=' + new Date().getTime());
		$('#logoWalletIMG').attr('src', raiz + 'wallet_card.png?stamp=' + new Date().getTime());
		$('#logoWellcomeIMG').attr('src', raiz + 'logo_welcome.png?stamp=' + new Date().getTime());

		if(self.idTenant != 0) {
			$('#iconLogin').hide();
		} else {
			$('#logoIconIMG').attr('src', raiz + 'logo_icon.png?stamp=' + new Date().getTime());
			$('#logoLoginIMG').attr('src', raiz + 'logo_login.png?stamp=' + new Date().getTime());
		}

		// Colores
		$('#colorPrincipal').val(self.tenantParams.colorPrimario);
		$('#colorPrincipalDiv').css('background-color', self.tenantParams.colorPrimario);
		$('#colorSecundario').val(self.tenantParams.colorSecundario);
		$('#colorSecundarioDiv').css('background-color', self.tenantParams.colorSecundario);
		$('#menuColor').val(self.tenantParams.colorMenu1);
		$('#menuColorDiv').css('background-color', self.tenantParams.colorMenu1);
		$('#menuFontColor').val(self.tenantParams.colorFuenteMenu1);
		$('#menuFontColorDiv').css('background-color', self.tenantParams.colorFuenteMenu1);
		$('#submenu2Color').val(self.tenantParams.colorMenu2);
		$('#submenu2ColorDiv').css('background-color', self.tenantParams.colorMenu2);
		$('#submenu2FontColor').val(self.tenantParams.colorFuenteMenu2);
		$('#submenu2FontColorDiv').css('background-color', self.tenantParams.colorFuenteMenu2);
		$('#submenu3Color').val(self.tenantParams.colorMenu3);
		$('#submenu3ColorDiv').css('background-color', self.tenantParams.colorMenu3);
		$('#submenu3FontColor').val(self.tenantParams.colorFuenteMenu3);
		$('#submenu3FontColorDiv').css('background-color', self.tenantParams.colorFuenteMenu3);

		self.lookAndFeelEvents();
	},

	lookAndFeelEvents() {
		let self = this;

		// Apariencia y comportamiento de los inputs tipo 'color'
		inputTypeColorEvents();

		// Logo principal
		$('#logoPrimIMGdiv').on('click', function() {
			$('#logoPrimario').trigger('click');
		});
		$('#logoPrimario').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			$('#logoPrimIMG').attr('src', info.src);
			self.logoPrimario = info.file;
		});

		// Logo secundario
		$('#logoSecIMGdiv').on('click', function() {
			$('#logoSecundario').trigger('click');
		});
		$('#logoSecundario').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logoSecundario = info.file;
			$('#logoSecIMG').attr('src', info.src);
		});

		// Favicon
		$('#faviconIMGdiv').on('click', function() {
			$('#faviconInput').trigger('click');
		});
		$('#faviconInput').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.favicon = info.file;
			$('#faviconIMG').attr('src', info.src);
		});

		// Logo e-mail
		$('#logoEmailIMGdiv').on('click', function() {
			$('#logoEmail').trigger('click');
		});
		$('#logoEmail').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logoEmail = info.file;
			$('#logoEmailIMG').attr('src', info.src);
		});

		// Logo wallet
		$('#logoWalletIMGdiv').on('click', function() {
			$('#logoWallet').trigger('click');
		});
		$('#logoWallet').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logoWallet = info.file;
			$('#logoWalletIMG').attr('src', info.src);
		});

		// Logo bienvenida
		$('#logoWellcomeIMGdiv').on('click', function() {
			$('#logoWellcome').trigger('click');
		});
		$('#logoWellcome').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logoWellcome = info.file;
			$('#logoWellcomeIMG').attr('src', info.src);
		});

		// Logo icon
		$('#logoIconIMGdiv').on('click', function() {
			$('#logoIcon').trigger('click');
		});
		$('#logoIcon').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logoIcon = info.file;
			$('#logoIconIMG').attr('src', info.src);
		});

		// Logo login
		$('#logoLoginIMGdiv').on('click', function() {
			$('#logoLogin').trigger('click');
		});
		$('#logoLogin').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logoLogin = info.file;
			$('#logoLoginIMG').attr('src', info.src);
		});
	},

	sendForm() {
		let self = ConfiguracionController;

		// Información
		let xmpp_domain = self.config.xmpp_domain;
		if($('#domain').length > 0) {
			xmpp_domain = $('#domain').val();
		}

		// Look and feel
		let tenantChanges = false;
		let newColorPrimario = $('#colorPrincipal').val();
		let newColorSecundario = $('#colorSecundario').val();
		let colorMenu1 = $('#menuColor').val();
		let colorFuenteMenu1 = $('#menuFontColor').val();
		let colorMenu2 = $('#submenu2Color').val();
		let colorFuenteMenu2 = $('#submenu2FontColor').val();
		let colorMenu3 = $('#submenu3Color').val();
		let colorFuenteMenu3 = $('#submenu3FontColor').val();

		// Comprobación de cambios
		if(
			self.tenantParams.colorPrimario != newColorPrimario ||
			self.tenantParams.colorSecundario != newColorSecundario ||
			self.tenantParams.colorMenu1 != colorMenu1 ||
			self.tenantParams.colorFuenteMenu1 != colorFuenteMenu1 ||
			self.tenantParams.colorMenu2 != colorMenu2 ||
			self.tenantParams.colorFuenteMenu2 != colorFuenteMenu2 ||
			self.tenantParams.colorMenu3 != colorMenu3 ||
			self.tenantParams.colorFuenteMenu3 != colorFuenteMenu3 ||
			self.favicon != null ||
			self.logoPrimario != null ||
			self.logoSecundario != null ||
			self.logoEmail != null ||
			self.logoWallet != null ||
			self.logoWellcome != null ||
			self.logoIcon != null ||
			self.logoLogin != null
		) {
			tenantChanges = true;
		}

		let tenantURL = stcm.const.downloads + 'tenants/' + self.tenantParams.idTenant + '/';

		// Herramientas
		self.colorPri = self.colorPriOld;
		if($('#colorPri').length > 0 && self.idTenant == 0) {
			self.colorPri = $('#colorPri').val().replace('#', '');
		}

		self.colorSec = self.colorSecOld;
		if($('#colorSec').length > 0 && self.idTenant == 0) {
			self.colorSec = $('#colorSec').val().replace('#', '');
		}

		let SMTPSSL = 0;
		if($('#SMTPSSL').prop('checked')) {
			SMTPSSL = '1';
		}

		let urlEncuestasVal = self.config.URLEncuestas;
		if($('#URLEncuestas').length > 0) {
			urlEncuestasVal = $('#URLEncuestas').val().replace(/\\/g, '/');
		}

		let URLQnA = self.config.URLQnA;
		if($('#URLQnA').length > 0) {
			URLQnA = $('#URLQnA').val().replace(/\\/g, '/');
		}

		let URLWordCloud = self.config.URLWordCloud;
		if($('#URLWordCloud').length > 0) {
			URLWordCloud = $('#URLWordCloud').val().replace(/\\/g, '/');
		}

		let URLPoliticas = self.config.URLPoliticas;
		if($('#URLPoliticas').length > 0) {
			URLPoliticas = $('#URLPoliticas').val().replace(/\\/g, '/');
		}

		let URLMarket = self.config.URLMarket;
		if($('#URLMarket').length > 0) {
			URLMarket = $('#URLMarket').val().replace(/\\/g, '/');
		}

		let URLAndroid = self.config.URLAndroid;
		if($('#URLAndroid').length > 0) {
			URLAndroid = $('#URLAndroid').val().replace(/\\/g, '/');
		}

		let URLiOS = self.config.URLiOS;
		if($('#URLiOS').length > 0) {
			URLiOS = $('#URLiOS').val().replace(/\\/g, '/');
		}

		let URLVideoCalls = self.config.URLVideoCalls;
		if($('#URLVideoCalls').length > 0) {
			URLVideoCalls = $('#URLVideoCalls').val().replace(/\\/g, '/');
		}

		// Estilo analytics
		let colores = '[';
		for(let i = 0; i < self.colorsFixed.length; i++) {
			position = i + 1;
			colores += '"' + position + ':' + HEX2RGB(self.colorsFixed[i]) + '"';
			if(position < self.colorsFixed.length) {
				colores += ',';
			}
		}
		colores += ']';

		// Tiempo Tracking
		let trackingTime = $('#trackingTime').val();
		let trackingTimeArray = trackingTime.split(':');
		if(trackingTimeArray[2] === undefined) {
			trackingTimeArray[2] = 0;
		}
		let secondsTT = (parseInt(trackingTimeArray[0]) * 3600) + (parseInt(trackingTimeArray[1]) * 60) + parseInt(trackingTimeArray[2]);

		// Límite de tiempo para eliminar mensaje
		let hourMinutes = $('#messTimeLimit').val();
		let HMArray = hourMinutes.split(':');
		let minutes = (HMArray[0] * 60) + parseInt(HMArray[1]);

		// Límite de tiempo para editar mensaje
		let hourMinutesEdit = $('#minutesToEdit').val();
		let HMArrayEdit = hourMinutesEdit.split(':');
		let minutesEdit = (HMArrayEdit[0] * 60) + parseInt(HMArrayEdit[1]);

		// Tiempo a incrementar por intento fallido
		let hourMinutesMBT = $('#minutesBlockTry').val();
		let HMArrayMBT = hourMinutesMBT.split(':');
		let minutesMBT = (HMArrayMBT[0] * 60) + parseInt(HMArrayMBT[1]);

		// Tiempo de reset intentos fallidos
		let hourMinutesMREL = $('#minutesResetErrorLogin').val();
		let HMArrayMREL = hourMinutesMREL.split(':');
		let minutesMREL = (HMArrayMREL[0] * 60) + parseInt(HMArrayMREL[1]);

		// Tipo de perfilación
		let TipoPerfilacion = 0;
		if($('#profilingType1').prop('checked')) {
			TipoPerfilacion = 1;
		} else if($('#profilingType2').prop('checked')) {
			TipoPerfilacion = 2;
		} else if($('#profilingType3').prop('checked')) {
			TipoPerfilacion = 3;
		}

		// Perfilación ABI
		let countries = '';
		if(TipoPerfilacion == 3) {
			// Comprobación de campos de encuesta de perfilación por ABI
			let cSize = self.country.length;
			for(let i = 0; i < cSize; i++) {
				if(self.country[i].survey != '') {
					if(self.country[i].QuestionEdad == '' || self.country[i].QuestionEstado == '' || self.country[i].QuestionGenero == '' || self.country[i].QuestionNSE == '') {
						let warningTitle = pf.const.language.RSC578;
						let warningContent = pf.const.language.RSC994;
						pf.utils.showInfoDialog(warningTitle, warningContent);
						return;
					}
				}
			}
			countries = JSON.stringify(self.country);
		}

		let iconPos = 0;
		if($('#rightIcon').prop('checked')) {
			iconPos = 1;
		} else if($('#centerIcon').prop('checked')) {
			iconPos = 2;
		}

		let parameters = {
			userMail: self.userMail,
			idTenant: self.idTenant,
			SMTPServer: $('#SMTPServer').val(),
			SMTPUser: $('#SMTPUser').val(),
			SMTPUserPassword: $('#SMTPUserPassword').val(),
			xmpp_domain: xmpp_domain,
			plantilla: self.plantilla,
			plantilla_portada: self.plantilla_portada,
			logo: self.logo,
			tenantChanges: tenantChanges,
			tenantColorPrimario: newColorPrimario,
			tenantColorSecundario: newColorSecundario,
			colorMenu1: colorMenu1,
			colorFuenteMenu1: colorFuenteMenu1,
			colorMenu2: colorMenu2,
			colorFuenteMenu2: colorFuenteMenu2,
			colorMenu3: colorMenu3,
			colorFuenteMenu3: colorFuenteMenu3,
			favicon: self.favicon,
			logoPrimario: self.logoPrimario,
			logoSecundario: self.logoSecundario,
			logoEmail: self.logoEmail,
			logoWalletApp: self.logoWallet,
			logoWelcomeApp: self.logoWellcome,
			logoIcon: self.logoIcon,
			logoLogin: self.logoLogin,
			tenantURL: tenantURL,
			colorprincipal: self.colorPri,
			colorPriOld: self.colorPriOld,
			colorsecundario: self.colorSec,
			colorSecOld: self.colorSecOld,
			SMTPSSL: SMTPSSL,
			SMTPNombreMail: $('#SMTPNombreMail').val(),
			SMTPPort: $('#SMTPPort').val(),
			LOGRowsLoad: $('#LOGRowsLoad').val(),
			SYSNotifUser: $('#SYSNotifUser').text().trim(),
			SYSNotifUserName: $('#SYSNotifUserName').val(),
			SYSMisionsUser: $('#SYSMisionsUser').text().trim(),
			SYSMisionsUserName: $('#SYSMisionsUserName').val(),
			FormatoFechaServer: 103,
			FormatoHoraServer: 24,
			URLEncuestas: urlEncuestasVal,
			URLQnA: URLQnA,
			URLWordCloud: URLWordCloud,
			URLWordCloudSurvey: '',
			URLPoliticas: URLPoliticas,
			URLMarket: URLMarket,
			URLAndroid: URLAndroid,
			URLiOS: URLiOS,
			URLVideoCalls: URLVideoCalls,
			RGBInicio: HEX2RGB($('#RGBInicio').val()),
			RGBFin: HEX2RGB($('#RGBFin').val()),
			numPreguntasPerfilacionEnAnalyticMostreo: $('#numPregPerfEnMostreo').val(),
			numWordSentenceWordCloud: $('#numWordsWordcloudPhrases').val(),
			FontAnalytics: $('#font-picker').val(),
			SizeFontAnalytics: $('#fontSize').val(),
			splitCharacter: $('#splitCharacter').val().trim(),
			UsarColorDegradado: $('input:radio[name=inlineRadioOptions]:checked').val(),
			colores: colores,
			secondsTracking: secondsTT,
			minutesToDelete: minutes,
			minutesToEdit: minutesEdit,
			minutesBlockTry: minutesMBT,
			numErrorLogin: $('#numErrorLogin').val(),
			minutesResetErrorLogin: minutesMREL,
			defaultRoleUser: $('#defaultRoleApp').val(),
			countries: countries,
			TipoPerfilacion: TipoPerfilacion,
			sp_perfilacion_default: $('#inputProfilingAlgorithm').val(),
			SurveyPerfilacionDefault: $('#surveyProfiling').val(),
			QuestionGenero: $('#genderProfiling').val(),
			QuestionEstado: $('#stateProfiling').val(),
			QuestionEdad: $('#ageProfiling').val(),
			mailingImageVisible: ($('#showIcon').prop('checked') ? '1': '0'),
			mailingImagePosition: iconPos,
			azureCognitiveLenguajeKEY: $('#keyTranscription').val(),
			azureCognitiveLenguajeRegion: $('#regionTranscriptionOptions').val(),
			azureCognitiveVisualKEY: $('#keyImage').val(),
			azureCognitiveVisualHost: $('#hostImage').val(),
			azureCognitiveTextKEY: $('#keyText').val(),
			azureCognitiveTextHost: $('#hostText').val(),
			azureCognitiveTranslatorKEY: $('#keyTranslator').val(),
			azureCognitiveTranslatorHost: $('#hostTranslator').val(),
			azureCognitiveTranslatorRegion: $('#regionTranslatorOptions').val(),
			googleMapsAPIKey: $('#googleMapsAPIKey').val(),
			twilioSSID: $('#twilioSSID').val(),
			twilioToken: $('#twilioToken').val(),
			twilioValues: JSON.stringify(self.twilioValues),
			twilioValuesChange: self.twilioValuesChange
		};
		ajaxComunCallWithCallback('setCMBPConfig', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC78;
				let errorContent = pf.const.language.RSC106;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				loadHTML('inc/configuracion/configuracion.html', 'wrapper', ConfiguracionController);
			}
		});
	},

	inputColors() {
		let self = this;

		let type = $('input:radio[name=inlineRadioOptions]:checked').val();
		if(type == '1') {
			$('#rango').css('display', 'block');
			$('#fijos').css('display', 'none');
		} else {
			$('#rango').css('display', 'none');
			$('#fijos').css('display', 'block');
		}
		self.renderColors();
	},

	applyEvents() {
		let self = ConfiguracionController;

		$('body').ready(function() {
			// Selector opciones colores
			$('input:radio[name=inlineRadioOptions]').click(function() {
				self.inputColors();
			});

			$('#btn-send-politics').click(function() {
				self.savePolitics();
			});

			$('#preview').click(function() {
				let type = $('input:radio[name=inlineRadioOptions]:checked').val();
				let colors = '';
				if(type == '1') {
					let i = $('#RGBInicio').val();
					let f = $('#RGBFin').val();
					colors = generateColors(f, i, 10);
				} else {
					let totalColors = self.colorsFixed.length;
					colors = [];
					let arraylColors = colors.length;
					while(arraylColors < 10) {
						for(let i = 0; i < totalColors; i++) {
							colors.push(self.colorsFixed[i])
							arraylColors = colors.length;
							if(arraylColors == 10) {
								break;
							}
						}
					}
				}

				let fontSize = $('#fontSize').val();
				let fontFamily = $('#font-picker').val();
				Chart.defaults.global.defaultFontSize = fontSize;
				Chart.defaults.global.defaultFontFamily = fontFamily;

				if(self.myChart) {
					self.myChart.destroy();
				}

				let ctx = $('#graph');
				self.myChart = new Chart(ctx, {
					type: 'bar',
					data: {
						labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
						datasets: [{
							data: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
							backgroundColor: colors
						}]
					},
					options: {
						// Radio de ángulos
						cornerRadius: 6,
						layout: {
							padding: {
								top: 30
							}
						},
						responsive: true,
						maintainAspectRatio: true,
						scales: {
							yAxes: [{
								display: false,
								ticks: {
									beginAtZero: true
								}
							}],
							xAxes: [{
								barPercentage: 0.5,
								ticks: {
									display: true,
									autoSkip: false
								}
							}]
						},
						legend: {
							display: false
						},
						tooltips: {
							enabled: false
						},
						plugins: {
							datalabels: {
								color: 'black',
								font: {
									weight: 'bold'
								},
								anchor: 'end',
								align: 'end',
								formatter(value, context) {
									return value;
								}
							}
						}
					}
				});
			});
		});

		// Encuesta de perfilación
		$('#searchSurvey').on('click', function() {
			if(self.surveysProfiling === '') {
				self.requestSurveysProfiling();
			} else {
				$('#surveyTable').modal('show', true);
			}
		});

		// Pregunta género
		$('#searchGender').on('click', function() {
			if(self.genderProfiling == '') {
				self.requestQuestionsProfiling('gender', false);
			} else {
				$('#genderTable').modal('show', true);
			}
		});

		// Pregunta estado
		$('#searchState').on('click', function() {
			if(self.stateProfiling == '') {
				self.requestQuestionsProfiling('state', false);
			} else {
				$('#stateTable').modal('show', true);
			}
		});

		// Pregunta nse
		$('#searchNse').on('click', function() {
			if(self.nseProfiling == '') {
				self.requestQuestionsProfiling('nse', false);
			} else {
				$('#nseTable').modal('show', true);
			}
		});

		// Pregunta edad
		$('#searchAge').on('click', function() {
			if(self.ageProfiling == '') {
				self.requestQuestionsProfiling('age', false);
			} else {
				$('#ageTable').modal('show', true);
			}
		});

		$('#plantillaIMGdiv').on('click', function() {
			$('#plantilla').trigger('click');
		});
		$('#plantilla').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.plantilla = info.file;
			$('#plantillaIMG').attr('src', info.src);
		});

		$('#plantillaPortadaIMGdiv').on('click', function() {
			$('#plantilla_portada').trigger('click');
		});
		$('#plantilla_portada').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.plantilla_portada = info.file;
			$('#plantillaPortadaIMG').attr('src', info.src);
		});

		$('#logoIMGdiv').on('click', function() {
			$('#logo').trigger('click');
		});
		$('#logo').change(function(evt) {
			let info = pf.utils.getFileSrc(evt);
			self.logo = info.file;
			$('#logoIMG').attr('src', info.src);
		});

		$('#profilingType1').on('change', function() {
			if($('#profilingType1').prop('checked')) {
				$('#perfABI').hide();
				$('#profilingAlgorithmLabel').hide();
				$('#profilingAlgorithmSel').hide();
				$('#inputProfilingAlgorithm').val('');

				// Ocultar encuesta y preguntas de perfilación
				$('#perfSurveys').hide();

				// ID encuesta perfilación
				$('#surveyProfiling').val('');
				// Pregunta género
				$('#genderProfiling').val('');
				// Pregunta estado
				$('#stateProfiling').val('');
				// Pregunta edad
				$('#ageProfiling').val('');
			}
		});
		$('#profilingType2').on('change', function() {
			if($('#profilingType2').prop('checked')) {
				$('#perfABI').hide();
				$('#perfSurveys').show();
				$('#profilingAlgorithmLabel').hide();
				$('#profilingAlgorithmSel').hide();
				$('#inputProfilingAlgorithm').val('');
			}
		});
		$('#profilingType3').on('change', function() {
			if($('#profilingType3').prop('checked')) {
				$('#perfABI').show();
				$('#perfSurveys').hide();
				$('#profilingAlgorithmLabel').show();
				$('#profilingAlgorithmSel').show();
			}
		});

		// Rol por defecto para usuarios registrados desde la App
		$('#btn-defaultRoleApp').click(function() {
			tableRol.setEvents('confGeneral');
		});

		$('#rightIcon').off().click(()=>{
			$('#iconWrapper').removeClass('justify-content-center');
			$('#iconWrapperPre').removeClass('justify-content-center');
			$('#iconWrapper').addClass('justify-content-end');
			$('#iconWrapperPre').addClass('justify-content-end');
		});

		$('#centerIcon').off().click(()=>{
			$('#iconWrapper').removeClass('justify-content-end');
			$('#iconWrapperPre').removeClass('justify-content-end');
			$('#iconWrapper').addClass('justify-content-center');
			$('#iconWrapperPre').addClass('justify-content-center');
		});

		$('#leftIcon').off().click(()=>{
			$('#iconWrapper').removeClass('justify-content-end');
			$('#iconWrapperPre').removeClass('justify-content-end');
			$('#iconWrapper').removeClass('justify-content-center');
			$('#iconWrapperPre').removeClass('justify-content-center');
		});

		$('#showIcon').change(function() {
			// this will contain a reference to the checkbox
			if(this.checked) {
				// the checkbox is now checked
				$('#iconMail').removeClass('d-none');
				$('#iconMailPre').removeClass('d-none');
				$('#iconPositionInputs').removeClass('d-none');
			} else {
				$('#iconMail').addClass('d-none');
				$('#iconMailPre').addClass('d-none');
				$('#iconPositionInputs').addClass('d-none');
				// the checkbox is now no longer checked
			}
		});

		$('#colorCode').change(function() {
			$('#codeMockup').css('color', this.value + ' !important');
		});

		// Mostrar desglose de uso de Google API
		$('#showBreakdown').off().on('click', function() {
			self.getDetallePeticionesAPI_Google();
		});
	},

	renderColors() {
		let self = ConfiguracionController;

		let n = self.colorsFixed.length;
		let content = '';
		for(let i = 0; i < n; i++) {
			content += '<div class="form-inline mt-2">';
			content += `
				<input type="color" class="form-control color-pick wi-cal-100per-n150" data-position="${i}" value="${self.colorsFixed[i]}">
				<button id="up-color_${i}" type="button" class="btn btn-nav ml-2 li-he-5" data-action="up" data-position="${i}">
					${stcmbackend.svg.caretUpFillWithoutColor}
				</button>
			`;
			content += `
				<button id="down-color_${i}" type="button" class="btn btn-nav ml-2 li-he-5" data-action="down" data-position="${i}">
					${stcmbackend.svg.caretDownFillWithoutColor}
				</button>
			`;
			content += `
				<button id="remove-color_${i}" type="button" class="btn btn-nav ml-2 li-he-5" data-action="remove" data-position="${i}">
					${stcmbackend.svg.trash}
				</button>
			`;
			content += `
				</div>
			`;
		};
		$('#formColors').html(content);

		$('#up-color_0').css('dissabled', 'true');
		$('#up-color_0').css('visibility', 'hidden');
		$('#down-color_' + (n - 1)).css('dissabled', 'true');
		$('#down-color_' + (n - 1)).css('visibility', 'hidden');

		$('[data-action]').click(function() {
			let position = $(this).data('position');
			if($(this).data('action') == 'up') {
				self.orderUp(position);
			} else if($(this).data('action') == 'down') {
				self.orderDown(position);
			} else if($(this).data('action') == 'remove') {
				self.removeColor(position);
			}
		});

		$('.color-pick').change(function() {
			let i = $(this).data('position');
			let color = $(this).val();
			self.colorsFixed[i] = color;
		});
	},

	orderUp(x) {
		let self = ConfiguracionController;

		self.colorsFixed.splice(x - 1, 0, self.colorsFixed[x]);
		self.colorsFixed.splice(x + 1, 1);
		self.renderColors();
	},

	orderDown(x) {
		let self = ConfiguracionController;

		self.colorsFixed.splice(x + 2, 0, self.colorsFixed[x]);
		self.colorsFixed.splice(x, 1);
		self.renderColors();
	},

	removeColor(x) {
		let self = ConfiguracionController;

		self.colorsFixed.splice(x, 1);
		self.renderColors();
	},

	addColor() {
		let self = ConfiguracionController;

		//Obtener color
		let color = $('#newColor').val();
		self.colorsFixed.push(color);

		self.renderColors();
	},

	requestSurveysProfiling() {
		let self = this;

		ajaxComunCallWithCallback('getAllSurveysPerfilacion', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				removeLoader();
				self.surveysProfiling = ajaxReturn.result;
				for(let i = 0; i < self.surveysProfiling.length; i++) {
					let survey = {
						sid: self.surveysProfiling[i].sid,
						surveyls_title: self.surveysProfiling[i].surveyls_title
					}
					self.surveys.push(survey);
				}
				self.renderSurveysProfiling();
				self.printSurveys();
			}
		});
	},

	renderSurveysProfiling() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
					<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
					<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
					<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
					<th scope="col" title="${pf.const.language.RSC118}">${pf.const.language.RSC118}</th>
				</tr>
			</thead>

			<thead class="filters">
				<tr>
					<td>id</td>
					<td>name</td>
					<td>dateCreation</td>
					<td>enabled</td>
					<td>startDate</td>
					<td>endDate</td>
					<td>remuneration</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.surveysProfiling.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="sid-${self.surveysProfiling[i].sid}" class="c-pointer">
					<td class="text-truncate" title="${self.surveysProfiling[i].sid}">${self.surveysProfiling[i].sid}</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].surveyls_title}">${self.surveysProfiling[i].surveyls_title}</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].datecreated}">${self.surveysProfiling[i].datecreated}</td>
					<td class="text-center">
						<span class="d-none">${(self.surveysProfiling[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveysProfiling[i].active == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].startdate}">${self.surveysProfiling[i].startdate}</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].expires}">${self.surveysProfiling[i].expires}</td>
					<td class="text-center" title="${self.surveysProfiling[i].remuneracion}">${self.surveysProfiling[i].remuneracion}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filters');

		$('#tableSurvey tbody').off().on('click', 'tr', function() {
			let id = $(this).prop('id').replace('sid-', '');
			$('#surveyProfiling').val(id);
			self.genderProfiling = '';
			$('#genderProfiling').val('');
			self.stateProfiling = '';
			$('#stateProfiling').val('');
			self.ageProfiling = '';
			$('#ageProfiling').val('');

			$('#tableSurvey tbody tr').css('outline-width', 'initial');
			$('#tableSurvey tbody tr').css('outline-style', 'none');
			$('#tableSurvey tbody tr').css('outline-color', '#000');
			$('#tableSurvey 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');
			$('#surveyClose').trigger('click');
		});
	},

	requestQuestionsProfiling(type, abi) {
		let self = this;

		let survey = $('#surveyProfiling').val();
		if(abi) {
			survey = self.country[self.iCountry].survey;
		}

		let parameters = {
			survey: survey
		};
		ajaxComunCallWithCallback('getQuestionsSurvey', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(abi) {
					switch(type) {
						case 'gender':
							self.genderProfilingABI = ajaxReturn.result;
							break;
						case 'state':
							self.stateProfilingABI = ajaxReturn.result;
							break;
						case 'age':
							self.ageProfilingABI = ajaxReturn.result;
							break;
						case 'nse':
							self.nseProfilingABI = ajaxReturn.result;
					}
				} else {
					switch(type) {
						case 'gender':
							self.genderProfiling = ajaxReturn.result;
							break;
						case 'state':
							self.stateProfiling = ajaxReturn.result;
							break;
						case 'age':
							self.ageProfiling = ajaxReturn.result;
							break;
					}
				}
				self.renderQuests(type, abi);
			}
		});
	},

	renderQuests(type, abi) {
		let self = this;

		let idTable = '';
		let filter = '';
		let data = [];
		let idInput = '';
		let closeTable = '';

		switch(type) {
			case 'nse':
				if(abi) {
					if(self.nseFlagABI) {
						$('#tableNseABI').dataTable().fnDestroy();
					} else {
						self.nseFlagABI = true;
					}
					idTable = '#tableNseABI';
					filter = 'filtersNseABI';
					data = self.nseProfilingABI;
					idInput = '#nseProfilingABI';
					closeTable = '#nseCloseABI';
				} else {
					if(self.nseFlag) {
						$('#tableNse').dataTable().fnDestroy();
					} else {
						self.nseFlag = true;
					}
					idTable = '#tableNse';
					filter = 'filtersNse';
					data = self.nseProfiling;
					idInput = '#nseProfiling';
					closeTable = '#nseClose';
				}
				break;
			case 'gender':
				if(abi) {
					if(self.genderFlagABI) {
						$('#tableGenderABI').dataTable().fnDestroy();
					} else {
						self.genderFlagABI = true;
					}
					idTable = '#tableGenderABI';
					filter = 'filtersGenderABI';
					data = self.genderProfilingABI;
					idInput = '#genderProfilingABI';
					closeTable = '#genderCloseABI';
				} else {
					if(self.genderFlag) {
						$('#tableGender').dataTable().fnDestroy();
					} else {
						self.genderFlag = true;
					}
					idTable = '#tableGender';
					filter = 'filtersGender';
					data = self.genderProfiling;
					idInput = '#genderProfiling';
					closeTable = '#genderClose';
				}
				break;
			case 'state':
				if(abi) {
					if(self.stateFlagABI) {
						$('#tableStateABI').dataTable().fnDestroy();
					} else {
						self.stateFlagABI = true;
					}
					idTable = '#tableStateABI';
					filter = 'filtersStateABI';
					data = self.stateProfilingABI;
					idInput = '#stateProfilingABI';
					closeTable = '#stateCloseABI';
				} else {
					if(self.stateFlag) {
						$('#tableState').dataTable().fnDestroy();
					} else {
						self.stateFlag = true;
					}
					idTable = '#tableState';
					filter = 'filtersState';
					data = self.stateProfiling;
					idInput = '#stateProfiling';
					closeTable = '#stateClose';
				}
				break;
			case 'age':
				if(abi) {
					if(self.ageFlagABI) {
						$('#tableAgeABI').dataTable().fnDestroy();
					} else {
						self.ageFlagABI = true;
					}
					idTable = '#tableAgeABI';
					filter = 'filtersAgeABI';
					data = self.ageProfilingABI;
					idInput = '#ageProfilingABI';
					closeTable = '#ageCloseABI';
				} else {
					if(self.ageFlag) {
						$('#tableAge').dataTable().fnDestroy();
					} else {
						self.ageFlag = true;
					}
					idTable = '#tableAge';
					filter = 'filtersAge';
					data = self.ageProfiling;
					idInput = '#ageProfiling';
					closeTable = '#ageClose';
				}
				break;
		}

		let table = `
			<thead>
				<tr>
					<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="${filter}">
				<tr>
					<td>columnName</td>
					<td>section</td>
					<td>question</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = data.length;
		let checked = '';
		let qnse;

		if(self.iCountry) {
			qnse = self.country[self.iCountry].QuestionNSE;
		}

		let nses =[]
		if(qnse != undefined && qnse != null && typeof(qnse) != null) {
			nses = self.country[self.iCountry].QuestionNSE.split(';');
		}

		for(let i = 0; i < size; i++) {
			checked = '';
			if(nses.indexOf(data[i].columnName) > -1) {
				checked = 'checked';
			}

			table += `
				<tr class="c-pointer">
					<td class="columnName" data-id="${data[i].columnName}">
						${(type === 'nse' ? `<input type="checkbox" class="selection" ${checked}>` : '')}
						${data[i].columnName}
					</td>
					<td>${data[i].group_name}</td>
					<td class="question">${data[i].question}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$(idTable).html(table);

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

		switch(type) {
			case 'gender':
				let tableGender = $(idTable).DataTable({
					language: pf.const.language_table,
					scrollY: 300,
					scroller: false,
					paging: true,
					pageLength: 25,
					columnDefs: [
						{width: '120px', targets: 0}
					],
					autoWidth: false,
					aaSorting: []
				});

				// Apply the search
				applyTheSearch(tableGender, filter);
				break;
			case 'state':
				let tableState = $(idTable).DataTable({
					language: pf.const.language_table,
					scrollY: 300,
					scroller: false,
					paging: true,
					pageLength: 25,
					columnDefs: [
						{width: '120px', targets: 0}
					],
					autoWidth: false,
					aaSorting: []
				});

				// Apply the search
				applyTheSearch(tableState, filter);
				break;
			case 'age':
				let tableAge = $(idTable).DataTable({
					language: pf.const.language_table,
					scrollY: 300,
					scroller: false,
					paging: true,
					pageLength: 25,
					columnDefs: [
						{width: '120px', targets: 0}
					],
					autoWidth: false,
					aaSorting: []
				});

				// Apply the search
				applyTheSearch(tableAge, filter);
				break;
			case 'nse':
				let tableNse = $(idTable).DataTable({
					language: pf.const.language_table,
					scrollY: 300,
					scroller: false,
					paging: true,
					pageLength: 25,
					columnDefs: [
						{width: '140px', targets: 0}
					],
					autoWidth: false,
					aaSorting: []
				});

				// Apply the search
				applyTheSearch(tableNse, filter);
				break;
		}

		// Ocultar botones de tabla
		let tableID = idTable.replace('#', '');
		hideTableButtons(tableID);

		$(idTable + ' tbody').on('click', 'tr', function() {
			let columnName = $(this).find('.columnName').text();
			if(abi) {
				switch(type) {
					case 'gender':
						self.country[self.iCountry].QuestionGenero = columnName.trim();
						$(closeTable).trigger('click');
						self.printCountries();
						break;
					case 'state':
						self.country[self.iCountry].QuestionEstado = columnName.trim();
						$(closeTable).trigger('click');
						self.printCountries();
						break;
					case 'age':
						self.country[self.iCountry].QuestionEdad = columnName.trim();
						$(closeTable).trigger('click');
						self.printCountries();
						break;
					case 'nse':
						let checkedComp = $(this).find('.selection').prop('checked');
						if(checkedComp) {
							$(this).find('.selection').prop('checked', false);
						} else {
							$(this).find('.selection').prop('checked', true);
						}

						$('.selection').off().on('click', function() {
							let checkedComp = $(this).prop('checked');
							if(checkedComp) {
								$(this).prop('checked', false);
							} else {
								$(this).prop('checked', true);
							}
						});
						break;
				}
			} else {
				if(columnName && columnName != null) {
					columnName = columnName.trim();
				}
				$(idInput).val(columnName);

				$(idTable + ' tbody tr').css('outline-width', 'initial');
				$(idTable + ' tbody tr').css('outline-style', 'none');
				$(idTable + ' tbody tr').css('outline-color', '#000');
				$(idTable + ' 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');
				$(closeTable).trigger('click');
			}
		});

		//seleccion multiples preguntas
		if(type === 'nse') {
			$('#selectNse').off().on('click', function() {
				let questions = '';
				$(idTable + ' tbody tr').each(function() {
					let cheked = $(this).find('.selection');
					if(cheked.prop('checked')) {
						let columnName = $(this).find('.columnName').text();
						if(questions !== '') {
							questions = questions.concat(';');
						}
						questions = questions.concat(columnName.trim());
					}
				});

				self.country[self.iCountry].QuestionNSE = questions;
				self.printCountries();

				$(closeTable).trigger('click');
			});
		}
	},

	getSurveyCountry() {
		let self = this;

		ajaxComunCallWithCallback('getSurveyCountry', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				removeLoader();
				self.country = ajaxReturn.enabled;
				let countries = ajaxReturn.result;
				for(let i = 0; i < countries.length; i++) {
					for(let j = 0; j < self.country.length; j++) {
						if(countries[i].country == self.country[j].descripcion) {
							self.country[j].survey = countries[i].survey;
							self.country[j].QuestionEstado = countries[i].QuestionEstado;
							self.country[j].QuestionEdad = countries[i].QuestionEdad;
							self.country[j].QuestionGenero = countries[i].QuestionGenero;
							self.country[j].QuestionNSE = countries[i].QuestionNSE || '';
						}
					}
				}

				self.printCountries();

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

	printCountries() {
		let self = this;

		let table = `
			<table id="tableCountries" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
						<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
						<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
						<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
						<th scope="col" title="${pf.const.language.RSC598}">${pf.const.language.RSC598}</th>
					</tr>
				</thead>

				<thead class="filtersCountry">
					<tr>
						<td>pais</td>
						<td>perfilacion</td>
						<td>estado</td>
						<td>edad</td>
						<td>genero</td>
						<td>nse</td>
					</tr>
				</thead>

				<tbody>
		`;

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

			table += `
				<tr data-id="${i}">
					<td class="text-truncate title="${self.country[i].descripcion}">${(self.country[i].descripcion != '' ? self.country[i].descripcion : '-')}</td>
					<td class="px-1 justify-content-center">
						<span class="d-none">${self.country[i].survey}</span>
						<div class="input-group new-input-style justify-content-center">
							<input type="text" class="form-control-sm inputGrid inputValue" title="${self.country[i].survey}" placeholder="${pf.const.language.RSC110}" aria-label="Valores" value="${self.country[i].survey}" disabled>
							<div class="input-group-append d-block">
								<button type="button" class="selectCountry btn btn-outline-secondary searchValues py-0 px-1" data-toggle="modal" data-target="#valuesTable" data-id="${i}">
									${stcmbackend.svg.threeDotsSmall}
								</button>
							</div>
						</div>
					</td>
					<td class="px-1 justify-content-center">
						<span class="d-none">${(self.country[i].QuestionEstado == undefined ? '' : self.country[i].QuestionEstado)}</span>
						<div class="input-group new-input-style justify-content-center">
							<input type="text" class="form-control-sm inputGrid inputValue" title="${(self.country[i].QuestionEstado == undefined ? '' : self.country[i].QuestionEstado)}" placeholder="${pf.const.language.RSC564}" aria-label="Valores" value="${(self.country[i].QuestionEstado == undefined ? '' : self.country[i].QuestionEstado)}" disabled>
							<div class="input-group-append d-block">
								<button type="button" class="selectEstado btn btn-outline-secondary searchValues py-0 px-1" data-toggle="modal" data-target="#stateTableABI" data-id="${i}" ${(!self.country[i].survey ? 'disabled' : '')}>
									${stcmbackend.svg.threeDotsSmall}
								</button>
							</div>
						</div>
					</td>
					<td class="px-1 justify-content-center">
						<span class="d-none">${(self.country[i].QuestionEdad == undefined ? '' : self.country[i].QuestionEdad)}</span>
						<div class="input-group new-input-style justify-content-center">
							<input type="text" class="form-control-sm inputGrid inputValue" title="${(self.country[i].QuestionEdad == undefined ? '' : self.country[i].QuestionEdad)}" placeholder="${pf.const.language.RSC565}" aria-label="Valores" value="${(self.country[i].QuestionEdad == undefined ? '' : self.country[i].QuestionEdad)}" disabled>
							<div class="input-group-append d-block">
								<button type="button" class="selectEdad btn btn-outline-secondary searchValues py-0 px-1" data-toggle="modal" data-target="#ageTableABI" data-id="${i}" ${(!self.country[i].survey ? 'disabled' : '')}>
									${stcmbackend.svg.threeDotsSmall}
								</button>
							</div>
						</div>
					</td>
					<td class="px-1 justify-content-center">
						<span class="d-none">${(self.country[i].QuestionGenero == undefined ? '' : self.country[i].QuestionGenero)}</span>
						<div class="input-group new-input-style justify-content-center">
							<input type="text" class="form-control-sm inputGrid inputValue" title="${(self.country[i].QuestionGenero == undefined ? '' : self.country[i].QuestionGenero)}" placeholder="${pf.const.language.RSC151}" aria-label="Valores" value="${(self.country[i].QuestionGenero == undefined ? '' : self.country[i].QuestionGenero)}" disabled>
							<div class="input-group-append d-block">
								<button type="button" class="selectGenero btn btn-outline-secondary searchValues py-0 px-1" data-toggle="modal" data-target="#genderTableABI" data-id="${i}" ${(!self.country[i].survey ? 'disabled' : '')}>
									${stcmbackend.svg.threeDotsSmall}
								</button>
							</div>
						</div>
					</td>
					<td class="px-1 justify-content-center">
						<span class="d-none">${(self.country[i].QuestionNSE == undefined ? '' : self.country[i].QuestionNSE)}</span>
						<div class="input-group new-input-style justify-content-center">
							<input type="text" class="form-control-sm inputGrid inputValue" title="${(self.country[i].QuestionNSE == undefined ? '' : self.country[i].QuestionNSE)}" placeholder="${pf.const.language.RSC598}" aria-label="Valores" value="${(self.country[i].QuestionNSE == undefined ? '' : self.country[i].QuestionNSE)}" disabled>
							<div class="input-group-append d-block">
								<button class="selectNse btn btn-outline-secondary searchValues py-0 px-1" type="button" data-toggle="modal" data-target="#nseTableABI" data-id="${i}" ${(!self.country[i].survey ? 'disabled' : '')}>
									${stcmbackend.svg.threeDotsSmall}
								</button>
							</div>
						</div>
					</td>
				</tr>
			`;
		}

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

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

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

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

		let tableCountries = $('#tableCountries').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			columnDefs: [
				{width: '140px', targets: 1},
				{width: '140px', targets: 2},
				{width: '140px', targets: 3},
				{width: '140px', targets: 4},
				{width: '140px', targets: 5}
			],
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC578,
				className: 'btn btn-nav',
				title: pf.const.language.RSC578,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		$('.dataTables_filter').hide();

		$('#btn-actions').html(tableCountries.buttons().container());

		// Dar estilo al boton de excel
		$('.buttons-excel').removeClass('btn-secondary');
		$('.buttons-excel').attr('title', pf.const.language.RSC47);

		$('.buttons-excel').html(
			stcmbackend.svg.download +
			`<span class="d-none d-xl-inline">${pf.const.language.RSC47}</span>`
		);

		// Apply the search
		applyTheSearch(tableCountries, 'filtersCountry');

		// Eventos
		self.applyEventsTable();
		$('#tableCountries').on('draw.dt', function() {
			self.applyEventsTable();
		});
	},

	applyEventsTable() {
		let self = this;

		$('.selectCountry').click(function() {
			self.iCountry = $(this).data('id');
			if(self.surveysProfiling === '') {
				self.requestSurveysProfiling();
			} else {
				$('#valuesTable').modal('show', true);
			}
		});

		$('.selectEstado').off().on('click', function() {
			self.iCountry = $(this).data('id');
			self.requestQuestionsProfiling('state', true);
		});

		$('.selectEdad').off().on('click', function() {
			self.iCountry = $(this).data('id');
			self.requestQuestionsProfiling('age', true);
		});

		$('.selectGenero').off().on('click', function() {
			self.iCountry = $(this).data('id');
			self.requestQuestionsProfiling('gender', true);
		});

		$('.selectNse').off().on('click', function() {
			self.iCountry = $(this).data('id');
			self.requestQuestionsProfiling('nse', true);
		});
	},

	printSurveys() {
		let self = this;

		let table = `
			<table id="tableValues" class="table tRegs table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
						<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.surveys.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="selectSurvey c-pointer" data-id="${i}">
					<td class="text-truncate title="${self.surveys[i].sid}">${(self.surveys[i].sid != '' ? self.surveys[i].sid : '-')}</td>
					<td class="text-truncate title="${self.surveys[i].surveyls_title}">${(self.surveys[i].surveyls_title != '' ? self.surveys[i].surveyls_title : '-')}</td>
				</tr>
			`;
		}

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

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

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

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

		// Eventos
		self.applyEventsTableSurvey();

		$('#resultTableSurvey').on('draw.dt', function() {
			self.applyEventsTableSurvey();
		});
	},

	applyEventsTableSurvey() {
		let self = this;

		$('.selectSurvey').click(function() {
			let id = $(this).data('id');
			self.country[self.iCountry].survey = self.surveys[id].sid;
			self.country[self.iCountry].QuestionGenero = '';
			self.country[self.iCountry].QuestionEstado = '';
			self.country[self.iCountry].QuestionEdad = '';
			self.country[self.iCountry].QuestionNSE = '';
			self.printCountries();
			$('#closeValues').trigger('click');
		});
	},

	runningTXT() {
		let self = this;

		ajaxComunCallWithCallbackOne('runningTXT', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);

				if(resp.file == 1) {
					$('#runingTXT').show();
					$('#btn-deleteTXT').show();
					$('#runingTXT').text(pf.const.language.RSC966 + ' ');
					let timeZone = sessionStorage['STCMBackEnd:timeZone'];
					let dateTXT = moment(resp.date);
					let date = new Date();

					// Fecha y hora adaptada al timeZone del servidor
					let todayTimeZone = moment.tz(date, timeZone).format('YYYY-MM-DD HH:mm:ss');
					let today = moment(todayTimeZone);

					let years = today.diff(dateTXT, 'years');
					if(years > 0) {
						$('#runingTXT').append(years + ' ' + pf.const.language.RSC967 + ', ');
						dateTXT = moment(dateTXT).add(years, 'y');
					}

					let months = today.diff(dateTXT, 'months');
					if(months > 0) {
						$('#runingTXT').append(months + ' ' + pf.const.language.RSC968 + ', ');
						dateTXT = moment(dateTXT).add(months, 'M');
					}

					let days = today.diff(dateTXT, 'd');
					if(days > 0) {
						$('#runingTXT').append(days + ' ' + pf.const.language.RSC426.toLowerCase() + ', ');
						dateTXT = moment(dateTXT).add(days, 'd');
					}

					let hours = today.diff(dateTXT, 'hours');
					if(hours > 0) {
						$('#runingTXT').append(hours + ' ' + pf.const.language.RSC427.toLowerCase() + ', ');
						dateTXT = moment(dateTXT).add(hours, 'h');
					}

					let minutes = today.diff(dateTXT, 'minutes');
					if(minutes > 0) {
						$('#runingTXT').append(minutes + ' ' + pf.const.language.RSC428.toLowerCase() + '.');
					} else {
						$('#runingTXT').append('0 ' + pf.const.language.RSC428.toLowerCase() + '.');
					}

					// Borrar archivo running.txt
					$('#btn-deleteTXT').off().on('click', function() {
						let objInfo = {
							accept: {
								text: pf.const.language.RSC95
							},
							cancel: {
								text: pf.const.language.RSC57
							}
						};

						let alertTitle = pf.const.language.RSC969;
						let alertText = pf.const.language.RSC970;
						pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
							self.deleteRunningTXT();
						}, function() {});
					});
				} else {
					$('#runingTXT').hide();
					$('#btn-deleteTXT').hide();
				}

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

	deleteRunningTXT() {
		ajaxComunCallWithCallbackOne('deleteRunningTXT', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				if(resp.status == 'OK') {
					$('#runingTXT').hide();
					$('#btn-deleteTXT').hide();
				}
			}
		});
	},

	modalAlgoritmosPerfilacion() {
		let self = this;

		let table = `
			<table id="tableAlgoritmoPerfilacion" class="table table-hover tr-pointer tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1934}">${pf.const.language.RSC1934}</th>
					</tr>
				</thead>

				<thead class="filtersPA">
					<tr>
						<td>profilingAlgorithm</td>
					</tr>
				</thead>

				<tbody>
		`;

		size = self.profilingAlgorithms.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="${i}" class="user_selected edit-group" data-id="${i}">
					<td class="text-truncate" title="${self.profilingAlgorithms[i].ROUTINE_NAME}">${(self.profilingAlgorithms[i].ROUTINE_NAME != '' ? self.profilingAlgorithms[i].ROUTINE_NAME : '-')}</td>
				</tr>
			`;
		}

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

		$('#modalProfilingAlgorithm-body').html(table);

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

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

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

		// Como se genera al cargar la página y el modal está oculto, se utiliza el botón de mostrarlo con un intervalo para la animación de la aparición del modal para ajustar las columnas de la tabla
		$('#btn_ProfilingAlgorithm').on('click', function() {
			setTimeout(function() {
				dataTable.columns.adjust();
			}, 200);
		});

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

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

		// Detectar click
		$('#modalProfilingAlgorithm-body tbody').off().on('click', 'tr', function() {
			let profAlgortihm = $(this).find('.text-truncate').text();
			$('#inputProfilingAlgorithm').val(profAlgortihm);
			$('#inputProfilingAlgorithm').attr('title', profAlgortihm);
			$('#closeProfilingAlgorithm').trigger('click');
		});
	},

	getAlgoritmosPerfilacionData() {
		let self = this;

		ajaxComunCallWithCallback('getSPSchemaCorporate', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.profilingAlgorithms = ajaxReturn.result;
				self.modalAlgoritmosPerfilacion();

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

	renderSmsValidation() {
		let self = this;

		self.twilioValues = self.config.twilio;
		$('#twilioSSID').val(self.config.twilioSSID);
		$('#twilioToken').val(self.config.twilioToken);

		// Tabla de países para Twilio
		let table = `
			<table id="tableSmsValidation" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC1228}">${pf.const.language.RSC1228}</th>
					</tr>
				</thead>

				<thead class="filtersSmsValidation">
					<tr>
						<td>code</td>
						<td>country</td>
						<td>phone</td>
					</tr>
				</thead>

				<tbody>
		`;

		size = self.twilioValues.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${self.twilioValues[i].isocode}">${self.twilioValues[i].isocode}</td>
					<td class="text-truncate" title="${self.twilioValues[i].descripcion}">${self.twilioValues[i].descripcion}</td>
					<td class="text-truncate" title="${self.twilioValues[i].telefono}">
						<span class="d-none">${self.twilioValues[i].telefono}</span>
						<input type="text" class="form-control smsValidationInput" value="${self.twilioValues[i].telefono}" title="${self.twilioValues[i].telefono}" data-index="${i}">
					</td>
				</tr>
			`;
		}

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

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

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

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

		let dataTable = $('#tableSmsValidation').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false
		});

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

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

		self.smsValidationEvents();

		$('#resultTableSmsValidation').on('draw.dt', function() {
			self.smsValidationEvents();
		});
	},

	smsValidationEvents() {
		let self = this;

		$('.smsValidationInput').off().on('blur', function() {
			let index = $(this).data('index');
			let value = $(this).val().trim()

			self.twilioValues[index].telefono = value;
			$(this).attr('title', value);
			$(this).parent().find('span').text(value);
			self.twilioValuesChange = '1';
		});
	},

	getDetallePeticionesAPI_Google() {
		let self = this;

		ajaxComunCallWithCallback('getDetallePeticionesAPI_Google', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let data = ajaxReturn.result;

				self.renderDetallePeticionesAPI_Google(data);
			}
		});
	},

	renderDetallePeticionesAPI_Google(data) {
		let table = `
			<table id="tableShowBreakdownGoogle" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC2630}">${pf.const.language.RSC2630}</th>
						<th scope="col" title="${pf.const.language.RSC1315}">${pf.const.language.RSC1315}</th>
					</tr>
				</thead>

				<thead class="filtersShowBreakdownGoogle">
					<tr>
						<td>userCaller</td>
						<td>origen</td>
						<td>stampServer</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = data.length;
		for(let i = 0; i < size; i++) {
			let stampServer = data[i].stampServer.split(".")[0];

			table += `
				<tr>
					<td class="text-truncate" title="${data[i].userCaller}">${data[i].userCaller}</td>
					<td class="text-truncate" title="${data[i].origen}">${data[i].origen}</td>
					<td class="text-truncate" title="${stampServer}">${stampServer}</td>
				</tr>
			`;
		}

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

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

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

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

		let tableBreakdown = $('#tableShowBreakdownGoogle').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '100px', targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2629,
				className: 'd-none',
				title: pf.const.language.RSC2629,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

		// Apply the search
		applyTheSearch(tableBreakdown, 'filtersShowBreakdownGoogle');

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

	clickEvents(data) {
		$('#defaultRoleApp').val(data.role);
	}
};

function HEX2RGB(hex) {
	'use strict';
	if(hex.charAt(0) === '#') {
		hex = hex.substr(1);
	}
	if((hex.length < 2) || (hex.length > 6)) {
		return false;
	}
	var values = hex.split(''),
		r,
		g,
		b;

	if(hex.length === 2) {
		r = parseInt(values[0].toString() + values[1].toString(), 16);
		g = r;
		b = r;
	} else if(hex.length === 3) {
		r = parseInt(values[0].toString() + values[0].toString(), 16);
		g = parseInt(values[1].toString() + values[1].toString(), 16);
		b = parseInt(values[2].toString() + values[2].toString(), 16);
	} else if(hex.length === 6) {
		r = parseInt(values[0].toString() + values[1].toString(), 16);
		g = parseInt(values[2].toString() + values[3].toString(), 16);
		b = parseInt(values[4].toString() + values[5].toString(), 16);
	} else {
		return false;
	}
	return r + ', ' + g + ', ' + b;
}