let addons = {};
let init = {
	diccionario: null,
	lang: 'ESP',
	version: '1.0.8',
	idTenant: null,
	sectionTitle: '',
	refreshTime: false,

	events() {
		let self = init;

		// Ocultar enlace y sección de gestión de comunidad
		$('#commManagLink').hide();
		$('#communityManagement').hide();

		//Volver a la pagina de inicio despues de x tiempo
		setTimeout(function() {
			sessionStorage.removeItem('STCMBackEnd:token');
			pf.ajax.setWindowLocationIndex();
		}, 1000 * 3600 * 12);

		self.getLanguage();
		self.getUserAPICountries();
		self.getCMBPConfig();

		// Reloj - Zona horaria
		let timeZone = sessionStorage['STCMBackEnd:timeZone'];

		setInterval(function() {
			let date = new Date();
			let renderTimeNow = moment.tz(date, timeZone).format('HH:mm:ss');
			$('#clock').text(renderTimeNow);
		}, 1000);

		// Valor de versión para desplegable de profile
		$('#versionAPP').text('v.' + stcmVersionCtrl.const.version);

		// Fecha de control registrada
		regDateArray = stcmVersionCtrl.const.versionDate.split('.');
		let regDate = new Date('20' + regDateArray[0], regDateArray[1], regDateArray[2]);

		// Fecha de control actual
		newDateArray = sessionStorage['STCMBackEnd:versionCtrl'].split('.');
		let newDate = new Date('20' + newDateArray[0], newDateArray[1], newDateArray[2]);

		// Control de versión para notificación de novedades en el blog
		if(newDate.getTime() > regDate.getTime()) {
			$('#blog_social_news').show();
		}
	},

	getAddons() {
		ajaxComunCallWithCallbackOne('getAllAddOns', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				const resp = ajaxReturn.resData.response;
				const result = JSON.parse(resp);
				for(const i in result.response) {
					const resp = result.response[i];
					if(resp.addon_enabled == 1) {
						$('body').append(`<script type="text/javascript" src="${resp.addon_path}"></script>`);
						const func = resp.addon_function;
						let addonName = resp.addon_var;
						addons[addonName][func]();
					}
				}
			}
		});
	},

	getLanguage() {
		let self = init;

		let lenguage = sessionStorage['STCMBackEnd:lenguage'];

		let parameters = {
			lenguage: lenguage,
			system: '1'
		};
		ajaxComunCallWithCallbackOne('getAllRSCByLenguage', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = ajaxReturn.resData.response;
				response = JSON.parse(resp);
				if(response.status == 'OK') {
					let resp = response.result;

					// Comprobación de array
					if(!Array.isArray(resp)) {
						resp = [];
					}

					self.diccionario = '{';
					$.each(resp, function(ind, elem,) {
						self.diccionario += '"RSC' + elem.idRSC + '":"' + elem[lenguage] + '"';

						if(ind != (resp.length - 1)) {
							self.diccionario += ', ';
						}
					});

					self.diccionario += '}';
					pf.const.language = JSON.parse(self.diccionario);
					if(lenguage == 'ENG') {
						pf.const.language_table = '';
					} else {
						pf.const.language_table = {
							sProcessing: pf.const.language.RSC1050,
							sLengthMenu: pf.const.language.RSC1051,
							sZeroRecords: pf.const.language.RSC1052,
							sEmptyTable: pf.const.language.RSC1053,
							sInfo: pf.const.language.RSC1054,
							sInfoEmpty: pf.const.language.RSC1055,
							sInfoFiltered: pf.const.language.RSC1056,
							sInfoPostFix: '',
							sSearch: pf.const.language.RSC1057,
							sUrl: '',
							sInfoThousands: '.',
							sLoadingRecords: pf.const.language.RSC1058,
							oPaginate: {
								sFirst: pf.const.language.RSC1059,
								sLast: pf.const.language.RSC1060,
								sNext: pf.const.language.RSC663,
								sPrevious: pf.const.language.RSC1061
							},
							oAria: {
								sSortAscending: pf.const.language.RSC1062,
								sSortDescending: pf.const.language.RSC1063
							},
							buttons: {
								copy: pf.const.language.RSC445,
								colvis: pf.const.language.RSC1064
							}
						}
					}

					for(let i = 1; i <= 2000; i++) {
						let rsc = 'RSC' + i;
						if(!pf.const.language[rsc]) {
							pf.const.language[rsc] = rsc;
						}
					}
					init.getNavbar();

					// País e Idioma por defecto
					let defaultCountry = sessionStorage['STCMBackEnd:defaultCountry'];
					let defaultLenguage = sessionStorage['STCMBackEnd:defaultLenguage'];
					if(defaultCountry == '' || defaultLenguage == '') {
						let warningTitle = pf.const.language.RSC1616;
						let warningContent = '';
						if(defaultCountry == '' && defaultLenguage == '') {
							warningContent = pf.const.language.RSC1617;
						} else if(defaultCountry == '') {
							warningContent = pf.const.language.RSC1618;
						} else {
							warningContent = pf.const.language.RSC1619;
						}

						pf.utils.showInfoDialog(warningTitle, warningContent);
					}
				} else {
					if(response.result == 'Not authorized') {
						pf.ajax.setWindowLocationIndex();
					}
					pf.const.language = {};
					init.getNavbar();
				}
			}
		});
	},

	setClientColor(object) {
		let colorPrimario = object.colorPrimario;
		let colorSecundario = object.colorSecundario;
		let colorMenu1 = object.colorMenu1;
		let colorFuenteMenu1 = object.colorFuenteMenu1;
		let colorMenu2 = object.colorMenu2;
		let colorFuenteMenu2 = object.colorFuenteMenu2;
		let colorMenu3 = object.colorMenu3;
		let colorFuenteMenu3 = object.colorFuenteMenu3;
		document.documentElement.style.setProperty('--maincolor', colorPrimario);
		let colorPrimarioRGB = hex2rgb(colorPrimario);
		document.documentElement.style.setProperty('--maincolorRGB', colorPrimarioRGB);
		document.documentElement.style.setProperty('--maincolorlighter', init.getTintedColor(colorPrimario, 170));
		document.documentElement.style.setProperty('--maincolorlighter2', init.getTintedColorDetailed(colorPrimario, 7, 46, 44));
		document.documentElement.style.setProperty('--secondcolor', colorSecundario);
		document.documentElement.style.setProperty('--menulevel1', colorMenu1);
		document.documentElement.style.setProperty('--menulevel1color', colorFuenteMenu1);
		document.documentElement.style.setProperty('--menulevel2', colorMenu2);
		document.documentElement.style.setProperty('--menulevel2color', colorFuenteMenu2);
		document.documentElement.style.setProperty('--menulevel3', colorMenu3);
		document.documentElement.style.setProperty('--menulevel3color', colorFuenteMenu3);

		/* Convert a hex string to an RGB triplet */
		function convertToRGB(hex) {
			let color = [];

			color[0] = parseInt((trim(hex)).substring(0, 2), 16);
			color[1] = parseInt((trim(hex)).substring(2, 4), 16);
			color[2] = parseInt((trim(hex)).substring(4, 6), 16);

			return color;
		}
	},

	getTintedColor(color, v) {
		if(color.length > 6) {
			color = color.substring(1,color.length);
		}
		var rgb = parseInt(color, 16);
		var r = Math.abs(((rgb >> 16) & 0xFF) + v);
		if(r > 255) {
			r = r - (r - 255);
		}
		var g = Math.abs(((rgb >> 8) & 0xFF) + v);
		if(g > 255) {
			g = g - (g - 255);
		}
		var b = Math.abs((rgb & 0xFF) + v);
		if(b > 255) {
			b = b - (b - 255);
		}
		r = Number(r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r).toString(16);
		if(r.length == 1) {
			r = '0' + r;
		}
		g = Number(g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g).toString(16);
		if(g.length == 1) {
			g = '0' + g;
		}
		b = Number(b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b).toString(16);
		if(b.length == 1) {
			b = '0' + b;
		}
		return '#' + r + g + b;
	},

	getTintedColorDetailed(color, red, green, blue) {
		if(color.length > 6) {
			color = color.substring(1, color.length);
		}

		let rgb = parseInt(color, 16);

		let r = Math.abs(((rgb >> 16) & 0xFF) + red);
		if(r > 255) {
			r = r - (r - 255);
		}
		let g = Math.abs(((rgb >> 8) & 0xFF) + green);
		if(g > 255) {
			g = g - (g - 255);
		}
		let b = Math.abs((rgb & 0xFF) + blue);
		if(b > 255) {
			b = b - (b - 255);
		}

		r = Number(r < 0 || isNaN(r)) ? 0 : ((r > 255) ? 255 : r).toString(16);
		if(r.length == 1) {
			r = '0' + r;
		}
		g = Number(g < 0 || isNaN(g)) ? 0 : ((g > 255) ? 255 : g).toString(16);
		if(g.length == 1) {
			g = '0' + g;
		}
		b = Number(b < 0 || isNaN(b)) ? 0 : ((b > 255) ? 255 : b).toString(16);
		if(b.length == 1) {
			b = '0' + b;
		}

		return '#' + r + g + b;
	},

	getUser() {
		let self = this;

		let token = sessionStorage['STCMBackEnd:token'];
		let user = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let email = user.email;
		let reqName = 'getUserAPI';

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

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

		pf.ajax.request(reqName, reqData);
		$(document).off(reqName);
		$(document).on(reqName, async function(event, response) {
			if(response.status == 'OK') {
				let resp = response.resData.response;
				response = JSON.parse(resp);
				if(response.status == 'OK') {
					let resp = response.result;
					$('#adminName').text(resp[0].name);
					sessionStorage['STCMBackEnd:user'] = JSON.stringify(resp[0]);
					sessionStorage['STCMBackEnd:user_avatar'] = JSON.stringify(resp.avatar);
					let idTenant = resp[0].idTenant;
					self.idTenant = idTenant;

					// funcionalidades_app
					if(self.idTenant != 0) {
						// Ocultar sección
						$('[href="#!funcionalidades_app"]').hide();
						$('[href="#!funcionalidades_app"]').attr('href', '');
					}

					// Comprobacion si es CPG
					const idCPG = resp[0].idCPG;
					if(idCPG == 0 || idCPG == undefined) {
						let raiz = stcm.const.downloads + 'tenants/' + idTenant + '/';

						// Favicon
						$('#favicon').attr('href', raiz + 'favicon.ico?stamp=' + new Date().getTime());

						// Imagen de navegador
						$('.logoCabecera').attr('src', raiz + 'logo.png?stamp=' + new Date().getTime());
						let adminData = resp[0];
						let adminName = adminData.name + ' ' + (adminData.apellido1 || '') + ' ' + (adminData.apellido2 || '');
						$('#admin-name-nav').text(adminName);
						$('#admin-nav').text(pf.const.language.RSC163);

						// Imagen de avatar
						let email = resp[0].email;
						let attachedImg = stcm.const.downloads + 'tenants/0/avatar.jpg';
						if(resp.avatar) {
							attachedImg = stcm.const.downloads + 'avatar/' + email + '/avatar.jpg';
						}

						//cargar colores
						if(resp.tenantInfo && resp.tenantInfo[0].colorPrimario) {
							self.setClientColor(resp.tenantInfo[0]);
						}

						$('#img-avatar').attr('src', attachedImg);
					} else {
						// Obtener informacion del cpg
						let parameters = {
							idCPG: idCPG
						};
						ajaxComunCallWithCallback('getCPGById', parameters, function(ajaxReturn) {
							if(ajaxReturn) {
								const cpg = ajaxReturn.result[0];

								let raiz = stcm.const.downloads + 'tenants/' + idTenant + '/cpg/' + idCPG + '/';

								// Favicon
								$('#favicon').attr('href', raiz + 'favicon.ico?stamp=' + new Date().getTime());

								// Imagen de navegador
								$('.logoCabecera').attr('src', cpg.logoPrimario + '?stamp=' + new Date().getTime());
								let adminData = resp[0];
								let adminName = adminData.name + ' ' + adminData.apellido1 + ' ' + adminData.apellido2;
								$('#admin-name-nav').text(adminName);
								$('#admin-nav').text(pf.const.language.RSC163);

								// Imagen de avatar
								let email = resp[0].email;
								let attachedImg = stcm.const.downloads + 'tenants/0/avatar.jpg';
								if(resp.avatar) {
									attachedImg = stcm.const.downloads + 'avatar/' + email + '/avatar.jpg';
								}

								//cargar colores
								if(resp.tenantInfo && resp.tenantInfo[0].colorPrimario) {
									self.setClientColor(cpg);
								}

								$('#img-avatar').attr('src', attachedImg);
							}
						});
					}
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = response.result;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					pf.ajax.setWindowLocationIndex();
				}
			} else {
				let errorTitle = pf.const.language.RSC61;
				let errorContent = response.result;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				pf.ajax.setWindowLocationIndex();
			}
		});
	},

	getUserAPICountries() {
		let user = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let email = user.email;

		let parameters = {
			email: email
		};
		ajaxComunCallWithCallback('getUserAPICountries', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = ajaxReturn.result;

				let countries = [];
				let countriesDesc = '';
				let size = resp.length;
				for(let i = 0; i < size; i++) {
					countries.push(resp[i].country);
					countriesDesc += resp[i].descripcion + ',';
				}
				countriesDesc = countriesDesc.substring(0, countriesDesc.length - 1);

				sessionStorage.setItem('STCMBackEnd:userCountries', btoa(JSON.stringify(countries)));
				sessionStorage.setItem('STCMBackEnd:userCountriesDesc', btoa(countriesDesc));

				// Cargar datos del modal de país
				ajaxComunCallWithCallback('getPaisesEnabled', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						pf.countryOptions = ajaxReturn.result;
					}
				}, false);
			}
		});
	},

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

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

	getNavbar() {
		let self = this;

		// Render del nav
		$('#stcm-navbar').load('inc/menu/menu.html');

		// Buscamos las secciones que seran visibles
		ajaxComunCallWithCallbackOne('getSystemConfig', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.getUser();

				let resp = ajaxReturn.resData.response;
				response = JSON.parse(resp);

				// Secciones permitidas por usuario para el Navegador
				let sectionsHTML = sessionStorage['STCMBackEnd:sectionsHTML'];
				let sectionsHTMLMini = sessionStorage['STCMBackEnd:sectionsHTMLMini'];

				$('#menuSections').html(sectionsHTML);
				$('#menuSectionsMini').html(sectionsHTMLMini);

				// Títulos del navegador mini
				$('#menuSectionsMini a').each(function() {
					let title = $(this).attr('title');
					$(this).attr('title', pf.const.language[title]);
				});

				$('.app-content').css('width', 'calc(100% - 270px)');
				$('.app-content').css('margin-left', '270px');

				// Control para anular la creación de misión paso a paso si no se tienen permisos
				if(sessionStorage['STCMBackEnd:newMission'] == 0) {
					$('#stepByStepOpen').remove();
					$('#stepByStepClosed').remove();
					$('#stcm-navbar').addClass('stcm-navbar-wo-stepByStep');
					$('#stcm-navbar-mini').addClass('stcm-navbar-wo-stepByStep');
				}

				// Comprobar si el administrador tiene usuario de app
				if(sessionStorage['STCMBackEnd:adminAppUser'] !== '') {
					$('#commManagLink').show();

					// Crear sección de Gestión de comunidad
					loadHTML('inc/gestion_comunidad/gestion_comunidad.html', 'communityManagement', CommunityManagement);

					$('#commManagLink').off().on('click', function(e) {
						e.preventDefault();

						// Cambiar icono
						let svgIcon = '';
						if($('#commManagLink').data('state') === 'off') {
							// Guardar título anterior
							self.sectionTitle = $('#title-section').html();

							// Añadir titulo
							$('#title-section').html(pf.const.language.RSC2241);

							$('#commManagLink').data('state', 'on');
							svgIcon = `
								<svg class="bi bi-chat-left-text-fill ml-1 mb-1" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
									<path d="M0 2a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4.414a1 1 0 0 0-.707.293L.854 15.146A.5.5 0 0 1 0 14.793V2zm3.5 1a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1h-9zm0 2.5a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1h-9zm0 2.5a.5.5 0 0 0 0 1h5a.5.5 0 0 0 0-1h-5z"/>
								</svg>
							`;

							// Mostrar sección de Gestión de comunidad
							$('#communityManagement').show();
							$('#subOptionsContainer').hide();
							$('#wrapper').hide();
							$('.main').css('height', 'auto');
						} else {
							// Recuperar título anterior
							$('#title-section').html(self.sectionTitle);

							$('#commManagLink').data('state', 'off');
							svgIcon = `
								<svg class="bi bi-chat-left-text ml-1 mb-1" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
									<path d="M14 1a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H4.414A2 2 0 0 0 3 11.586l-2 2V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12.793a.5.5 0 0 0 .854.353l2.853-2.853A1 1 0 0 1 4.414 12H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/>
									<path d="M3 3.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 6a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 6zm0 2.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>
								</svg>
							`;

							// Ocultar sección de Gestión de comunidad
							$('#communityManagement').hide();
							$('#subOptionsContainer').show();
							$('#wrapper').show();
							$('.main').css('height', '100vh');
						}

						$('#commManagLink').html(svgIcon);
					});

					$('#client-img, #saasAPIoAUTH, #blog_social_link, #profileLink, .link-section').on('click', function() {
						// Ocultar Gestión de comunidad
						$('#communityManagement').hide();
						$('#saasAPIoAUTH').show();
						$('#subOptionsContainer').show();

						$('#wrapper').show();
						$('.main').css('height', '100vh');

						$('#commManagLink').data('state', 'off');
						let svgIcon = `
							<svg class="bi bi-chat-left-text ml-1 mb-1" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
								<path d="M14 1a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H4.414A2 2 0 0 0 3 11.586l-2 2V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12.793a.5.5 0 0 0 .854.353l2.853-2.853A1 1 0 0 1 4.414 12H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/>
								<path d="M3 3.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 6a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 6zm0 2.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>
							</svg>
						`;
						$('#commManagLink').html(svgIcon);
					});

					$('#client-img, #saasAPIoAUTH, #blog_social_link, #profileLink, .link-section').on('click', function() {
						$('#communityManagement').hide();
						$('#blog_social_link').show();
						$('#subOptionsContainer').show();
						$('#wrapper').show();
						$('.main').css('height', '100vh');

						$('#saasAPIoAUTH').data('state', 'off');
						let svgIcon = `
							<svg class="bi bi-file-earmark-code" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
								<path d="M14 4.5V14a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V2a2 2 0 0 1 2-2h5.5L14 4.5zm-3 0A1.5 1.5 0 0 1 9.5 3V1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V4.5h-2z"/>
								<path d="M8.646 6.646a.5.5 0 0 1 .708 0l2 2a.5.5 0 0 1 0 .708l-2 2a.5.5 0 0 1-.708-.708L10.293 9 8.646 7.354a.5.5 0 0 1 0-.708zm-1.292 0a.5.5 0 0 0-.708 0l-2 2a.5.5 0 0 0 0 .708l2 2a.5.5 0 0 0 .708-.708L5.707 9l1.647-1.646a.5.5 0 0 0 0-.708z"/>
							</svg>
						`;
						$('#saasAPIoAUTH').html(svgIcon);
					});
				}

				// Imagen para los navegadores
				let plusStepByStep = stcm.const.downloads + 'svg_new/white_cross.svg';
				$('.newPlusSvg').attr('src', plusStepByStep);

				// Abrir navegador
				$('#open-nav-bottom').off().on('click', function() {
					$('#open-nav-bottom').addClass('d-none');
					$('#stcm-navbar-mini').addClass('d-none');
					$('#stcm-navbar-mini-shadow').addClass('d-none');
					$('#stepByStepClosed').addClass('d-none');
					$('#close-nav-bottom').removeClass('d-none');
					$('#stcm-navbar').removeClass('d-none');
					$('#stcm-navbar-shadow').removeClass('d-none');
					$('#stepByStepOpen').removeClass('d-none');
					$('.app-content').css('width', 'calc(100% - 270px)');
					$('.app-content').css('margin-left', '270px');
					$('#stickyFooterContainer').css('width', 'calc(100% - 270px)');
					$('#stickyFooterContainer').css('margin-left', '270px');
					$('#nav-options-container').addClass('nav-options-open');
					$('#nav-options-container').removeClass('nav-options-close');
				});

				// Cerrar navegador
				$('#close-nav-bottom').off().on('click', function() {
					$('#open-nav-bottom').removeClass('d-none');
					$('#stcm-navbar-mini').removeClass('d-none');
					$('#stcm-navbar-mini-shadow').removeClass('d-none');
					$('#stepByStepClosed').removeClass('d-none');
					$('#close-nav-bottom').addClass('d-none');
					$('#stcm-navbar').addClass('d-none');
					$('#stcm-navbar-shadow').addClass('d-none');
					$('#stepByStepOpen').addClass('d-none');
					$('.app-content').css('width', 'calc(100% - 80px)');
					$('.app-content').css('margin-left', '80px');
					$('#stickyFooterContainer').css('width', 'calc(100% - 80px)');
					$('#stickyFooterContainer').css('margin-left', '80px');
					$('#nav-options-container').addClass('nav-options-close');
					$('#nav-options-container').removeClass('nav-options-open');
				});

				// Control de cambio de elementos superiores para cierre de elementos secundarios abiertos
				$('.navFirstElement').off('click').on('click', function() {
					$('.navSecondElement').each(function() {
						if($(this).attr('aria-expanded') == 'true') {
							$(this).click();
						}
					});
				});

				// PROVISIONAL
				// Se ocultan el enlace a 'Welcome Tour' para los entornos que no sean locales o de social
				let url = window.location.href;
				if(!url.includes('localhost') && !url.includes('sociallabs')) {
					$('[href="#!welcome_tour"]').hide();
				}

				if(response.status == 'OK') {
					let resp = response.result;

					let market = resp.filter(obj => {
						return obj.name === 'market';
					});

					if(market[0] != undefined) {
						sessionStorage.setItem('STCMBackEnd:config_market', market[0].enabled);
					} else {
						sessionStorage.setItem('STCMBackEnd:config_market', '0');
					}

					// Gestión de GDPR
					let size = response.result.length;
					for(let i = 0; i < size; i++) {
						if(response.result[i].name === 'workingwithgdpr') {
							sessionStorage.setItem('STCMBackEnd:GDPR', response.result[i].enabled);
						} else if(response.result[i].name === 'workingwithconsumer') {
							sessionStorage.setItem('STCMBackEnd:Consumer', response.result[i].enabled);
						} else if(response.result[i].name === 'multicpg') {
							// Gestión de uso de CPG
							sessionStorage.setItem('STCMBackEnd:multicpg', response.result[i].enabled);
						}
					}

					// Idioma menu
					pf.rsc.translateByTag('html');

					// Nav
					// Initialize the plugin
					$('#stcm-navbar').perfectScrollbar();
					$('#stcm-navbar-mini').perfectScrollbar();
					$('li').click(function() {
						// actualizar scrollbar
						setTimeout(function() {
							$('#stcm-navbar').perfectScrollbar('update');
							$('#stcm-navbar-mini').perfectScrollbar('update');
						}, 500);
					});

					// Cerrar menu en pantallas pequeña cuando se selecciona una sección
					$('.link-section').on('click', function() {
						if(screen.width < 768) {
							$('#hidden-menu').trigger('click');
						}
					});

					// Cambio de ángulo con el dropdown de acciones de usuario
					let profileContainer = document.getElementById('profileContainer');
					const observer = new MutationObserver(function(mutations) {
						mutations.forEach(function(mutation) {
							let angle = `
								<svg class="bi bi-chevron-down" width="12" height="12" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
									<path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 01.708 0L8 10.293l5.646-5.647a.5.5 0 01.708.708l-6 6a.5.5 0 01-.708 0l-6-6a.5.5 0 010-.708z" clip-rule="evenodd"/>
								</svg>
							`;
							if(mutation.target.className.includes('show')) {
								angle = `
									<svg class="bi bi-chevron-up" width="12" height="12" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
										<path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/>
									</svg>
								`;
							}

							$('#svgContainer').html(angle);
						});
					});
					observer.observe(profileContainer, {attributes: true});

					// Página de perfil de administrador
					$('#profile').click(function() {
						window.location.href = '#!perfil';
					});

					// Cerrar sesión
					$('#logout').click(function(e) {
						e.preventDefault();
						let objInfo = {
							accept: {
								text: pf.const.language.RSC141
							},
							cancel: {
								text: pf.const.language.RSC57
							}
						};

						let alertTitle = pf.const.language.RSC139;
						let alertText = pf.const.language.RSC140;
						pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
							addLoader();
							//add function to logout
							setTimeout(function() {
								removeLoader();
								sessionStorage.clear();
								pf.ajax.setWindowLocationIndex();
							}, 300);
						}, function() {});
					});

					$('#show-generating-reports').off().on('click', () => {
						$('#dowloadCard').slideToggle(150, () => {});
					});

					// Imagenes para Proyecto nuevo y Proyecto existente del paso a paso
					let srcImgNew = stcm.const.downloads + 'svg_new/rocket.svg';
					$('#newStepByStepIMG').attr('src', srcImgNew);
					let srcImgEdit = stcm.const.downloads + 'svg_new/document.svg';
					$('#editStepByStepIMG').attr('src', srcImgEdit);

					// Iniciar paso a paso
					$('.stepByStepStart').off().on('click', function() {
						$('#modalStepByStep').modal('toggle');
					});

					// Paso a paso con proyecto nuevo
					$('#newStepByStepProject').off().on('click', function() {
						$('#modalStepByStep').modal('toggle');
						window.location.href = '#!step_by_step_project_new';
					});

					// Paso a paso con proyecto existente
					$('#editStepByStepProject').off().on('click', function() {
						$('#modalStepByStep').modal('toggle');
						$('#modalContainer').modal('toggle');

						// Modal de proyectos
						TableProyectos.setEvents('proyectStepByStep');
					});

					// Quitar loader
					routerStart();
					setTimeout(function() {
						$('.loaderinitspinner').remove();
					}, 1000);
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = response.result;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					pf.ajax.setWindowLocationIndex();
				}
			}
		});
	},

	proyectStepByStep(data) {
		sessionStorage.setItem('idProjectSBS', data.id);
		sessionStorage.setItem('nameProjectSBS', data.NombreProyecto);
		sessionStorage.setItem('countryProjectSBS', data.country);

		window.location.href = '#!step_by_step_mission_new';
	},

	getCPGById(idCPG) {
		return new Promise((resolve, reject) => {
			let parameters = {
				idCPG: idCPG
			};
			ajaxComunCallWithCallbackOne('getCPGById', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let resp = JSON.parse(ajaxReturn.resData.response);
					if(resp.status === 'OK') {
						resolve(resp.result[0]);
					} else {
						resolve(false);
					}
				}
			});
		});
	}
};

$('body').ready(function() {
	// En el caso de entrada solo a la app para gestión de la comunidad
	if(sessionStorage['STCMBackEnd:onlyAppZone'] === '1') {
		// Crear sección de Gestión de comunidad
		loadHTML('inc/gestion_comunidad/gestion_comunidad.html', 'communityManagement', CommunityManagement);

		// Mostrar sección de Gestión de comunidad
		$('#communityManagement').show();
		$('#subOptionsContainer').hide();
		$('header').hide();
		$('.navigation-menu').hide();
		$('.app-content').css('margin-left', '0');
		$('.app-content').css('width', '100%');
	} else {
		$('body').append('<section id="wrapInitLoader" class="animated loaderinitspinner"><div id="initLoader" class="color-loader"></i></section>');
		init.events();
	}
});