PageSourceSearch

https://www.aragon.es/o/aragon-theme/js/main.js?browserId=chrome&m…=js&languageId=es_ES&t=1790166456000

js aragon.es collected 2026-09-24 08:28:01 UTC 45,843 bytes, 1,453 lines download raw bytes

1/*1790166454000*/
2/**
3 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
4 *
5 * This library is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Lesser General Public License as published by the Free
7 * Software Foundation; either version 2.1 of the License, or (at your option)
8 * any later version.
9 *
10 * This library is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
13 * details.
14 */
15
16/*
17 * This function gets loaded when all the HTML, not including the portlets, is
18 * loaded.
19 */
20AUI().ready(
21	function() {
22		moveDivYui3();
23		registerVisitedPage();
24		assignBackURL();
25		renderOpenDataVisor();
26		createUserTypeFieldGoogleAnalytics();
27	}	
28);
29
30/*
31 * This function gets loaded after each and every portlet on the page.
32 *
33 * portletId: the current portlet's id
34 * node: the Alloy Node object of the current portlet
35 */
36Liferay.Portlet.ready(function (_portletId, _node) {});
37
38/*
39 * This function gets loaded when everything, including the portlets, is on
40 * the page.
41 */
42Liferay.on('allPortletsReady', function () {
43	var scrollValueForSedeSearcherResults = document.getElementById("scrollValueForSedeSearcherResults");
44	const hash = window.location.hash; // Obtenemos el hash de la URL
45
46	if (hash && document.getElementById(hash.substring(1))) {
47        const element = document.getElementById(hash.substring(1));
48        scrollHastaAncla( hash.substring(1) , 500, 150);
49
50	}else if(scrollValueForSedeSearcherResults != undefined && scrollValueForSedeSearcherResults != null){
51		if(scrollValueForSedeSearcherResults.value > 0) {
52			window.scroll(0, scrollValueForSedeSearcherResults.value);
53		}
54	}else{
55		$('html,body').animate({scrollTop:0},0);
56	}
57});
58
59/**
60 * Realiza un scroll suave al id que le mandemos como primer parámetro,
61 *   El segundo hace referencia al tiempo que tarda en realizar dicha transición, la velocidad con la que lo realiza.
62 *   El tercer parámetro hace referencia a la cantidad de px que deja como margen con el top de la pantalla.
63 */
64function scrollHastaAncla(a, e, t) {
65  var o, n;
66  switch ((null === e && (e = 200), a)) {
67    case "TOP":
68      o = 0;
69      break;
70    case "BOTTOM":
71      o = $("body").height();
72      break;
73    default:
74      (n = void 0 === t ? 0 : t), (o = $("#" + a).offset().top - n);
75  }
76  $("html, body").animate({ scrollTop: o }, e);
77}
78
79/**
80 * Escuchador que oculta el supermenu y pone el foco en el boton del minimenu
81 */
82function triggerAndFocusOnCloseMenuButton() {
83	$('#megamenu-mini-button-is-open').trigger('click'); // Ejecutar el click
84	$('#megamenu-mini-button-is-open').focus(); // Mantener el foco
85}
86
87/**
88 * Creates tipo_usuario field for GA event in all pages, depending on IP
89 */
90function createUserTypeFieldGoogleAnalytics(){
91	$.getJSON( "https://api.ipify.org?format=json" )
92	.done(function(data) {
93		let jsonValueFromReq = typeof data !== "string" ? JSON.stringify(data) : data;
94		try {
95			jsonValueFromReq = JSON.parse(jsonValueFromReq);
96			if(jsonValueFromReq != null && jsonValueFromReq != undefined ){
97				if(jsonValueFromReq.ip != null && jsonValueFromReq.ip != undefined && jsonValueFromReq.ip != 'unknown'){
98					window.dataLayer = window.dataLayer || [];
99					if(data.ip.startsWith('188.244.80.')){
100						dataLayer.push({
101							'event':'ut',
102							'tipo_usuario': 'interno'
103						});
104					}else{
105						dataLayer.push({
106							'event':'ut',
107							'tipo_usuario': 'externo'
108						});
109					}
110				}
111			}
112		} catch (e) {
113			console.log("Error api.ipify ip format " + e);
114		}
115	})
116	.fail(function(){
117		console.log("Error on request to api.apify.org");
118	});
119}
120
121/**
122 * Assigns an url to the back buttons
123 */
124function assignBackURL() {
125	if (document.referrer && document.referrer !== "") {
126		$('.back_button_container').each(
127			function() {
128				$(this).find("a").attr("href", document.referrer);
129				$(this).removeClass("oculto");
130			}
131		);
132	}
133}
134
135/**
136 * Change position item because it given error accessibility
137 */
138function moveDivYui3(){
139	var divYui3 = $('#yui3-css-stamp');
140	if (divYui3 != null){
141		$("body").append(divYui3);
142	}
143}
144
145/**
146 * User accepted all cookies
147 */
148function cookiesAccepted(){
149	var allCookiesAccepted = "GOOGLE_ANALYTICS-1[COOKIE-SEPARATOR]LAST_VISITED_PAGES-1[COOKIE-SEPARATOR]MARKETING-1";
150	setCookie("COOKIES_ACCEPTED", allCookiesAccepted, 30);
151	$(".banner-aceptacion-cookies").remove();
152	location.reload();
153}
154
155/**
156 * Gets video miniature from url
157 */
158function getVideoThumbnail(url, imgElementId) {
159	var videoType = "";
160	var videoID = "";
161	var match ="";
162	if (url.indexOf('youtu') > -1) {
163		match = url.match(/^.*(youtu\.be\/|vi?\/|u\/\w\/|embed\/|\?vi?=|\&vi?=)([^#\&\?]*).*/);
164		if(RegExp.$2 != null && RegExp.$2 != undefined){
165			videoID = RegExp.$2;
166		}
167		videoType = 'youtube';
168	} else if (url.indexOf('vimeo') > -1) {
169		match = url.match(/https?:\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)/);
170		if(RegExp.$3 != null && RegExp.$3 != undefined){
171			videoID = RegExp.$3;
172		}
173		videoType = 'vimeo';
174	}
175	if (videoType == 'youtube') {
176		$("#" + imgElementId).attr("src", 'https://img.youtube.com/vi/' + videoID + '/hqdefault.jpg');
177	} else if (videoType == 'vimeo') {
178		var xhr = new XMLHttpRequest();
179		xhr.open("GET", "https://vimeo.com/api/v2/video/" + videoID + ".json", true);
180		xhr.onload = function (e) {
181			if (xhr.readyState === 4) {
182				if (xhr.status === 200) {
183					var data = xhr.responseText;
184					var parsedData = JSON.parse(data);
185					var thumbSRClarge = parsedData[0].thumbnail_large;
186					var thumbSplit = thumbSRClarge.split(/\d{3}(?=.jpg)/);
187					$("#" + imgElementId).attr("src", thumbSplit[0] + '1280x720' + thumbSplit[1]);
188				} else {
189					console.error(xhr.statusText);
190				}
191			}
192		};
193		xhr.send();
194	}
195}
196
197/**
198 * Set cookie value
199 */
200function setCookie(cname, cvalue, exdays) {
201	var d = new Date();
202	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
203	var expires = "expires=" + d.toGMTString();
204	document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
205}
206
207/**
208 * Get cookie value
209 */
210function getCookie(cname) {
211	var name = cname + "=";
212	//var decodedCookie = decodeURIComponent(document.cookie);
213	var codedCookie = document.cookie;
214	var ca = codedCookie.split(';');
215	for(var i = 0; i < ca.length; i++) {
216		var c = ca[i];
217		while (c.charAt(0) == ' ') {
218			c = c.substring(1);
219		}
220		if (c.indexOf(name) == 0) {
221			return c.substring(name.length, c.length);
222		}
223	}
224	return "";
225}
226
227/**
228 * Updates the LAST_VISITED_PAGES cookie with the current page information
229 */
230function registerVisitedPage() {
231	//Check if user has accepted the cookies
232	const LAST_VISITED_PAGES = "LAST_VISITED_PAGES";
233	var cookiesAcceptedCookieName = getCookie("COOKIES_ACCEPTED");
234	if (cookiesAcceptedCookieName.indexOf("LAST_VISITED_PAGES-1") != -1 || cookiesAcceptedCookieName == ""){
235		//Gets current page title
236		var currentPageTitle = document.title;
237		var url = document.location.href;
238		if (currentPageTitle.lastIndexOf('.') != -1) {
239			currentPageTitle = currentPageTitle.substring(0, currentPageTitle.lastIndexOf('.'));
240		}
241		if(url.indexOf('?') != -1){
242			var indexUrl = url.indexOf('?');
243			url = url.substring(0, indexUrl );
244		}
245		//Saves the current page title in the cookie if is not "Inicio" or "Estado"
246		if (currentPageTitle != "Inicio" && currentPageTitle != "Estado") {
247			//Gets last visited pages cookie
248			var lastVisitedPagesCookie = getCookie(LAST_VISITED_PAGES);
249			//Declares the register separator between title and value
250			var titleValueSeparator = "[COOKIE_SEPARATOR]";
251			//Updates the cookie value
252			if (lastVisitedPagesCookie != "") {
253				//Gets the last visited pages value separated by '|'
254				var lastVisitedPagesList = lastVisitedPagesCookie.split('|');
255				//Deletes the current page from list if exists
256				for (var i = 0; i < lastVisitedPagesList.length; i++) {
257					var lastVisitedPageEntry = lastVisitedPagesList[i].trim();
258					var lastVisitedPageEntryTitleValueSeparatorIndex = lastVisitedPageEntry.indexOf(titleValueSeparator);
259					var lastVisitedPageEntryTitle = lastVisitedPageEntry.substring(0, lastVisitedPageEntryTitleValueSeparatorIndex);
260					var lastVisitedPageEntryURL = lastVisitedPageEntry.substring(lastVisitedPageEntryTitleValueSeparatorIndex + titleValueSeparator.length, lastVisitedPageEntry.length);
261					if (lastVisitedPageEntryTitle == encodeURIComponent(currentPageTitle)) {
262						lastVisitedPagesList.splice(i, 1);
263					} else if (lastVisitedPageEntryURL == document.location) {
264						lastVisitedPagesList.splice(i, 1);
265					}
266				}
267				//Adds the current page in the first position of the cookie value
268				lastVisitedPagesCookie = encodeURIComponent(currentPageTitle) + titleValueSeparator + url;
269				//Adds the previous pages to the cookie value (4 max)
270				if (lastVisitedPagesList != null && lastVisitedPagesList.length > 0) {
271					var visitedPagesCount = 0;
272					for (var j = 0; j < lastVisitedPagesList.length && visitedPagesCount < 4; j++) {
273						if (lastVisitedPagesList[j].trim().indexOf(titleValueSeparator) != -1) {
274							lastVisitedPagesCookie = lastVisitedPagesCookie + "|" + lastVisitedPagesList[j].trim();
275							visitedPagesCount++;
276						}
277					}
278				}
279			} else {
280				lastVisitedPagesCookie = encodeURIComponent(currentPageTitle) + titleValueSeparator + url;
281			}
282			//Saves the cookie in the browser
283			setCookie(LAST_VISITED_PAGES, lastVisitedPagesCookie, 30);
284		}
285	} else {
286		document.cookie = "LAST_VISITED_PAGES" + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
287	}
288}
289
290/**
291 * Prevents the standard onsubmit function
292 */
293$("#portal_searcher_form").submit(function(event) {
294	event.preventDefault();
295});
296
297/**
298 * Assigns onsubmit to the theme search form
299 */
300function onClickSearchOrFilterPortal(searchType, searcherURL, inputSearchType){
301    //Default search url
302	if(searchType != null && searchType!= ""){
303		var url = searcherURL + "?type=" + searchType ;
304	}else{
305		var url = searcherURL;
306	}
307    //Gets the original searched text
308    var searchedText = "";
309    //var searchedText = document.getElementById("searchTextHeader");
310    if(inputSearchType == "searcherHome"){
311        searchedText = $("#searchTextHome")[0].value;
312    }else if(inputSearchType == "searcherHeader"){
313    	searchedText =  $("#searchTextHeader")[0].value;
314    }else{
315    	searchedText = $("#searchTextSede")[0].value;
316    }
317    //Limits the searched text to 400
318    if (searchedText != null && searchedText != "") {
319        searchedText = searchedText.length > 400 ? searchedText.substring(0, 400) : searchedText;
320        searchedText = searchedText.replace(/\//g, ""); //"0x2f"
321        searchedText = searchedText.replace(/\\/g, ""); //"0x5c"
322        searchedText = searchedText.replace(/\./g, ""); //"0x2e"
323        searchedText = searchedText.replace(/[!'()*]/g, "");
324        searchedText = encodeURIComponent(searchedText);
325
326        if(searchType != null && searchType!= ""){
327        	 var continueURL =  "&";
328        }else{
329             var continueURL = "?";
330        }
331        url = url + continueURL + "q=" + searchedText;
332
333    }
334    window.location.href = url;
335}
336
337/**
338 * Assigns onsubmit to the theme search form in Opendata
339 */
340function onClickSearchOpendata(){
341	window.location.href = "/datos/catalogo?texto=" + $("#searchTextHeaderOpendata")[0].value;
342}
343
344/**
345 * Removes all accents from the given string
346 * @param text String to remove accents
347 * @returns The formatted String
348 */
349function cleanString(text) {
350	var accents = "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç";
351	var original = "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc";
352	for (var i = 0; i < accents.length; i++) {
353		text = text.replace(new RegExp(accents.charAt(i), 'g'), original.charAt(i));
354	}
355	return text;
356}
357
358// ESTOS SON JS PARA EL DISENO
359var mainApp = (function(){
360	/***********	Funciones privadas	****************/
361	/************************* CONTROL MENÚ PRINCIPAL ************************************/
362	// despliegue menú principal
363	var desplegarMenu = function(){
364		// Desplegar menú y	bloquear navegación en resto de página
365		$('.navbar-toggler').on('click', function(){
366			if(!$(this).find('.navbar-menu-icon').hasClass('active')){
367				$(this).attr('aria-label','Cerrar menú');
368			}
369			else{
370				$(this).attr('aria-label','Abrir menú');
371			}
372			$(this).find('.navbar-menu-icon').toggleClass('active');
373
374			if(window.innerWidth < 768){
375				$('html,body').addClass('noScroll');
376			}
377		});
378
379		$('.nav-link').click(function(){
380			$('.language__list').hide();
381		})
382	}
383
384	//Despliegue menú de cabecera segundo nivel
385	var desplegarMenuSec = function(){
386		//desplegar menu secundario onmouseover
387		if(window.innerWidth > 768){
388			$('.nav-item.dropdown').hover(
389					function(){
390						$('.nav-item.dropdown .dropdown-menu').removeClass('show');
391						$('.nav-item.dropdown').find('.nav-link').attr('aria-expanded',false);
392						$(this).children().focus();
393						$(this).addClass('show');
394						$(this).find('.nav-link').attr('aria-expanded',true);
395						$(this).find('.dropdown-menu').addClass('show');
396				$(this).keydown(function(e) {
397				if(e.which === 27) {
398					$(this).find('.nav-link').focus();
399				}
400				});
401			},
402			function(){
403				$(this).removeClass('show');
404				$(this).find('.nav-link').attr('aria-expanded',false);
405				$(this).find('.dropdown-menu').removeClass('show');
406			}
407			);
408			$('.breadcrumb .link').focus(
409			function(){
410				$('.navbar-collapse').removeClass('show');
411				$('.navbar-toggler').addClass('collapsed');
412				$('.navbar-toggler').attr('aria-label','Abrir menú');
413				//desbloqear navegación
414				$('html,body').removeClass('noScroll');
415				$('html, body').animate({ scrollTop: 0 }, 'slow');
416			}
417			)
418		}
419	}
420
421	// Cerrar menú responsive
422	var cerrarMenu = function(){
423		$('.close').click(function(){
424			$(this).parent().removeClass('show');
425			$('.navbar-toggler').addClass('collapsed');
426			$('.navbar-toggler').attr('aria-label','Abrir menú');
427			//desbloqear navegación
428			$('html,body').removeClass('noScroll');
429			$(this).parent().parent().find('.nav-link').attr('aria-expanded','false');
430		});
431		$('.close').keydown(function(e) {
432			if(e.which == 13) {
433			$(this).parent().removeClass('show');
434			$('.navbar-toggler').addClass('collapsed');
435			$('.navbar-toggler').attr('aria-label','Abrir menú');
436			$('html,body').removeClass('noScroll');
437			$(this).parent().parent().find('.nav-link').attr('aria-expanded','false');
438			}
439		});
440		$('.close').focusout(function(){
441			$('.language__select').focus();
442		});
443	}
444
445
446	/************************* FIN CONTROL MENÚ PRINCIPAL ************************************/
447
448	/* CONTROL de los enlaces de salto a contenido */
449	var saltoContenidoTeclado = function(){
450	if($('.js-salto-contenido')){
451        var contentToTop = $('#content').offset();
452        contentToTop = contentToTop.top - 100;
453
454		$('.js-salto-contenido').click(function(){
455		$('html, body').animate({ scrollTop: contentToTop }, 'slow');
456		});
457		var footerToTop = $('#footer').offset();
458		footerToTop = footerToTop.top - 100;
459		$('.js-salto-nav').click(function(){
460		$('html, body').animate({ scrollTop: footerToTop }, 'slow');
461		});
462		$('.js-salto-contenido,.js-salto-nav').keydown(function(e) {
463		if(e.which == 27) {
464			$('.logo-dga').focus();
465		}
466		});
467	}
468	}
469
470	// Modificar tabindex en elementos de LifeRay
471	var updateTabIndex = function(){
472	if(window.innerWidth < 768){
473		$('.portlet-bgwhite-title h2 a').attr('tabindex',0);
474		$('.dga-view .footer__links__list > li .title').attr('tabindex',0);
475	}
476	else{
477		$('.portlet-bgwhite-title h2 a').attr('tabindex',-1);
478		$('.dga-view .footer__links__list > li .title').attr('tabindex',-1);
479	}
480	}
481	
482
483
484	// Mostrar/Ocultar selector de idioma
485//Mostrar/Ocultar selector de idioma
486	var selectorIdioma = function () {
487
488		function showMenu() {
489			$('.language__list').show();
490			$('.language').addClass('active');
491			$('.language__select').attr('aria-expanded', true);
492		}
493
494		function hideMenu() {
495			$('.language__list').hide();
496			$('.language').removeClass('active');
497			$('.language__select').attr('aria-expanded', false);
498		}
499
500		$('.language').hover(
501			function () {
502				if ($(window).width() > 768) {
503					$('.language__select').focus();
504					showMenu();
505				}
506			},
507			function () {
508				if ($(window).width() > 768) {
509					hideMenu();
510				}
511			}
512		);
513
514		$('.language').click(
515			function () {
516				if (!$('.language').hasClass('active')) {
517					showMenu();
518				} else {
519					hideMenu();
520				}
521			}
522		);
523
524		$('.language').keydown(function (e) {
525			if (e.which == 13) {
526				if (!$('.language').hasClass('active')) {
527					showMenu();
528				} else {
529					hideMenu();
530				}
531			}
532			if (e.which === 27) {
533				hideMenu();
534			}
535		});
536
537		$('.language__list li:last-child').focusout(function () {
538			hideMenu();
539		});
540	}
541
542	// Código para mostrar correctamente imágenes con atributo objetc-fit en ie11 
543	var IExplorer = function(contenedor){
544		$(contenedor).each(function() {
545		var $container = $(this),
546		imgUrl = $container.find("img").prop("src");
547		if (imgUrl) {
548			$container.css("backgroundImage", 'url(' + imgUrl + ')').addClass("custom-object-fit");
549			$container.find('img').addClass('featured-image');
550		}
551		});
552		//Oculto SVG bandera europa para que dse muestre png de la bandera en IE11, donde no funciona el SVG
553		$('.european-flag-head .image,.european-flag img').css('opacity','0');
554	}	
555
556	// Deshabilitar el colapso en módulos en los que el contenido aparece
557	// plegado y tiene un CTA para ser desplegado
558	var disableCollapse = function(ruta,width){
559	$(ruta).click(function(e){
560		if ($(window).width() >= width) { 
561		// Should prevent the collapsible and default anchor linking 
562		// behavior for screen sizes equal or larger than 768px.
563		e.preventDefault();
564		e.stopPropagation();
565		}	
566	});
567	}
568
569	// Ocultar el menú mobile
570	var ocultarMenuAuto = function(){
571	var $win = $(window);
572	var $box = $(".navbar-collapse,.navbar-toggler");
573
574	$win.on("click.Bst", function(event){		
575		if ($box.has(event.target).length == 0 && !$box.is(event.target)){
576			$('.close').parent().removeClass('show');
577			$('.navbar-toggler').addClass('collapsed');
578			$('.navbar-toggler').attr('aria-label','Abrir menú');
579			$('html,body').removeClass('noScroll');
580			$('.close').parent().parent().find('.nav-link').attr('aria-expanded','false');
581			}
582		});
583	
584		$('.navbar-toggler').keydown(function(e) {
585			if(e.which === 27) {
586			$('.close').parent().removeClass('show');
587			$('.navbar-toggler').addClass('collapsed');
588			$('.navbar-toggler').attr('aria-label','Abrir menú');
589			$('html,body').removeClass('noScroll');
590			$('.close').parent().parent().find('.nav-link').attr('aria-expanded','false');
591			}
592		});
593		$('div.navbar.container').children().not('#toogle-button-collapsable').on('click', function(){
594			if($('#searchContainer').hasClass("show")){
595				$('#searchContainer').removeClass('show')
596				$('#toogle-button-collapsable').attr('aria-expanded','false');
597				$('#toogle-button-collapsable').addClass('collapsed');
598			}
599		});
600		$('#toogle-button-collapsable').on('click', function(){
601			if($('.navbar-menu__collapsable.collapse').hasClass('show')){
602				$('.navbar-menu__collapsable.collapse.show').prev().attr('aria-expanded','false');
603				$('.navbar-menu__collapsable.collapse.show').prev().addClass('collapsed');
604				$('.navbar-menu__collapsable.collapse.show').removeClass('show');
605			}
606			var buttonText = $('#toogle-button-collapsable').text().replace(/[\n\t]/g, '');
607			if(buttonText === 'Abrir buscador'){
608				$('#search-button-alt').text('Cerrar buscador');
609			} else {
610				$('#search-button-alt').text('Abrir buscador');
611			}
612		})
613
614	}
615	
616	
617	// Foco al abandona vía teclado la galeria de fotos
618	var cerrarGalTeclado = function(){
619	$('.ekko-lightbox .modal-header .close').on('click',function(e) {
620		if(e.which === 13) {
621		$('.dga-view .gallery-module .swiper-container .swiper-button-next').focus();
622		}
623	});
624	}
625
626	//limitar caracteres en un texto
627	var limitarCaracteres = function (texto,numero){
628	$(texto).each(function () {
629		len=$(this).text().length;
630		str= $(this).text().substr(0,numero);
631		lastIndexOf = str.lastIndexOf(" "); 
632		if(len > numero) {
633			$(this).text(str.substr(0, lastIndexOf) + '…');
634		}
635	});
636	}
637
638	// Funcionamiento botones de Zoom
639	var increaseFontSize = function(){
640
641	function changeFont(fontSize) {
642		return function() {
643			$('html').css('font-size', fontSize + '%');
644			sessionStorage.setItem('fSize', fontSize);
645		}
646	}
647
648	var normalFont = changeFont(62.5),
649		littleFont = changeFont(48.625),
650		largeFont	= changeFont(125);
651		
652	// gestion click	botones al decrecer fuente
653	$('.zoom__neg').on('click', function(){
654		$('body').removeClass('zoom-in');
655		$('.zoom__pos a').attr('aria-disabled','false');
656		if($('.zoom__pos').hasClass('active')){
657			normalFont();
658			$('.zoom > li').removeClass('active');
659			$(this).find('a').attr('aria-disabled','false');
660			$('.dga-view header .navbar-collapse .language').addClass('d-sm-none').addClass('d-md-none').addClass('d-lg-none').removeClass('show');
661		}
662		else{
663			littleFont();
664			$(this).addClass('active');
665			$('body').addClass('zoom-out');
666			$(this).find('a').attr('aria-disabled','true');
667		}
668		stickyBar();
669	});
670	// gestion teclado	botones al decrecer fuente
671	$('.zoom__neg').keydown(function(e) {
672		$('body').removeClass('zoom-in');
673		$('.zoom__pos a').attr('aria-disabled','false');
674		if(e.which == 13) {
675			if($('.zoom__pos').hasClass('active')){
676			normalFont();
677			$('.zoom > li').removeClass('active');
678			$(this).find('a').attr('aria-disabled','false');
679			$('.dga-view header .navbar-collapse .language').addClass('d-sm-none').addClass('d-md-none').addClass('d-lg-none').removeClass('show');
680			}
681			else{
682			littleFont();
683			$(this).addClass('active');
684			$('body').addClass('zoom-out');
685			$(this).find('a').attr('aria-disabled','true');
686			}
687		}
688		stickyBar();
689	});
690	// gestion click	botones al aumentar fuente
691	$('.zoom__pos').on('click', function(){
692		$('body').removeClass('zoom-out');
693		$('.zoom__neg a').attr('aria-disabled','false');
694		if($('.zoom__neg').hasClass('active')){
695			normalFont();
696			$('.zoom > li').removeClass('active');
697			$(this).find('a').attr('aria-disabled','false');
698		}
699		else{
700			largeFont();
701			$(this).addClass('active');
702			$('body').addClass('zoom-in');
703			$('.dga-view header .navbar-collapse .language').removeClass('d-sm-none').removeClass('d-md-none').removeClass('d-lg-none').addClass('show');
704			$(this).find('a').attr('aria-disabled','true');
705		}
706		stickyBar();
707	});
708	// gestion teclado	botones al aumentar fuente
709	$('.zoom__pos').keydown(function(e) {
710		$('body').removeClass('zoom-out');
711		$('.zoom__neg a').attr('aria-disabled','false');
712		if(e.which == 13) {
713			if($('.zoom__neg').hasClass('active')){
714				normalFont();
715				$('.zoom > li').removeClass('active');
716				$(this).find('a').attr('aria-disabled','false');
717			}
718			else{
719			largeFont();
720			$(this).addClass('active');
721			$('body').addClass('zoom-in');
722			$('.dga-view header .navbar-collapse .language').removeClass('d-sm-none').removeClass('d-md-none').removeClass('d-lg-none').addClass('show');
723			$(this).find('a').attr('aria-disabled','true');
724			}
725		}
726		stickyBar();
727	});
728
729	
730	}
731
732	// Inicialización del Slider de contenido final
733	var swiperSlider = function(){
734	/* 1 of 2 : SWIPER */
735	var mySwiper = new Swiper(".swiper-container", {
736		loop: false,
737		slidesPerView: 3,
738		spaceBetween: 45,
739		centeredSlides: false,
740		a11y: {
741		prevSlideMessage: 'Mostrar elementos anteriores',
742		nextSlideMessage: 'Mostrar elementos siguientes'
743		},
744		breakpoints: {
745		// when window width is <= 480px
746		767: {
747			slidesPerView: 1
748		},
749		// when window width is <= 640px
750		1200: {
751			slidesPerView: 2
752		}
753		},
754		navigation: {
755		nextEl: '.swiper-button-next',
756		prevEl: '.swiper-button-prev',
757		},
758		on: {
759		init: function() {
760			if($(window).width() < 767){
761			if($('.my-gallery .swiper-slide').length < 2){
762				$('.swiper-button-prev').hide();
763				$('.swiper-button-next').hide();
764			}
765			}
766			else if($(window).width() < 1200){
767			if($('.my-gallery .swiper-slide').length < 3){
768				$('.swiper-button-prev').hide();
769				$('.swiper-button-next').hide();
770			}
771			}
772			else if($(window).width() >= 1200){
773			if($('.my-gallery .swiper-slide').length == 3){
774				$('.swiper-button-prev').hide();
775				$('.swiper-button-next').hide();
776			}
777			}
778		},
779		resize: function () {
780			if($(window).width() < 767){
781			if($('.my-gallery .swiper-slide').length < 2){
782				$('.swiper-button-prev').hide();
783				$('.swiper-button-next').hide();
784			}
785			}
786			else if($(window).width() < 1200){
787			if($('.my-gallery .swiper-slide').length < 3){
788				$('.swiper-button-prev').hide();
789				$('.swiper-button-next').hide();
790			}
791			}
792			else if($(window).width() >= 1200){
793			if($('.my-gallery .swiper-slide').length == 3){
794				$('.swiper-button-prev').hide();
795				$('.swiper-button-next').hide();
796			}
797			}
798		}
799		}
800		
801
802	});
803
804	$(document).on("click", '[data-toggle="lightbox"]', function(event) {
805		event.preventDefault();
806		$(this).ekkoLightbox({
807		title:'Galería de imágenes',
808		rightArrow:'<a href="#" role="button" aria-label="Mostrar la siguiente imagen"><span>❯</span></a>',
809		leftArrow:'<a href="#" role="button" aria-label="Mostrar la imagen anterior"><span>❮</span></a>',
810		strings:{
811			close: 'Cerrar'
812		}
813		});
814	});
815
816	}
817
818	// Enlaces ancla en página de contenido final
819	var anchorCustom = function(){
820	var count = $(".detail-news-module__anchor .listado__item").length;
821	var multipoTres = count % 3;
822	var multipoDos = count % 2;
823	if($(window).width() >= 992){
824		if(multipoTres == 0){
825		$(".detail-news-module__anchor .listado__item:nth-last-child(3) .link,.detail-news-module__anchor .listado__item:nth-last-child(2) .link,.detail-news-module__anchor .listado__item:nth-last-child(1) .link").addClass('no-border');
826		}
827		else if(multipoDos == 0){
828		$(".detail-news-module__anchor .listado__item:nth-last-child(2) .link,.detail-news-module__anchor .listado__item:nth-last-child(1) .link").addClass('no-border');
829		}
830		else{
831		$(".detail-news-module__anchor .listado__item:nth-last-child(1) .link").addClass('no-border');
832		}
833	}
834	else if($(window).width() >= 768 && $(window).width() < 992){
835		if(multipoDos == 0){
836		$(".detail-news-module__anchor .listado__item:nth-last-child(2) .link,.detail-news-module__anchor .listado__item:nth-last-child(1) .link").addClass('no-border');
837		}
838		else{
839		$(".detail-news-module__anchor .listado__item:nth-last-child(1) .link").addClass('no-border');
840		}
841	}
842	else{
843		$(".detail-news-module__anchor .listado__item .link").removeClass("no-border");
844		$(".detail-news-module__anchor .listado__item:nth-last-child(1) .link").addClass('no-border');
845	}
846
847	$(".detail-news-module__anchor .listado__item .link").click(function() {
848		var link = $(this).attr('href');
849		var position = $(link).offset();
850		var headerHeight;
851		if($('.control-menu-container').length > 0){
852			headerHeight =  position.top - 30 - ( $('#banner').height() + $('.control-menu-container').height());
853		}else{
854			headerHeight = position.top - 30 - $('#banner').height();
855		}
856        positionContent = headerHeight;
857		$('html,body').animate({ 
858		scrollTop: positionContent }
859		, 1000);
860	});
861	}
862
863	// Sticky Bar
864	var stickyBar = function(){
865	// ACTIVACIÓN DE LA STICKY BAR
866		var firstScroll = $('.old-version').height();
867		firstScroll = firstScroll + 10;
868		firstScroll = firstScroll;
869		var lastScrollTop = 0;
870		$(window).scroll(function (event) {
871		if ($(window).width() >= 768){
872			$('.header').removeClass('sticky');
873			$('.header').css('top','0');
874			$('.dga-view').css('padding-top','0');
875		}
876		else
877		{
878			var scrollPosition = $(window).scrollTop(); // get posición scroll
879			if($('body').hasClass('zoom-in') == false){
880			if(scrollPosition >= firstScroll){
881				$('.header').addClass('sticky');
882				$('.header').css('top','-' + firstScroll + 'px');
883				$('.dga-view').css('padding-top', $('.header').height());
884			}
885			else{
886				$('.header').removeClass('sticky');
887				$('.header').css('top','0');
888				$('.dga-view').css('padding-top','0');
889			}
890			}
891			else{
892				$('.header').removeClass('sticky');
893				$('.header').css('top','0');
894				$('.dga-view').css('padding-top','0');
895			}
896			// posición del buscador al activarse Sticky bar
897			//if( $(window).width() < 1200){
898			$('.interior .dga-view .navbar .search-module').removeClass('is-not-visible').addClass('is-visible');
899			$('.header').addClass('gray-border');
900			if (scrollPosition > lastScrollTop && scrollPosition > firstScroll){
901				// downscroll code
902					$('.interior .dga-view .navbar .search-module').removeClass('is-visible').addClass('is-not-visible');
903					$('.header').removeClass('gray-border');
904				} else {
905					// upscroll code
906					$('.interior .dga-view .navbar .search-module').removeClass('is-not-visible').addClass('is-visible');
907					$('.header').addClass('gray-border');
908			}
909			lastScrollTop = scrollPosition;
910		}
911		});
912	}
913
914	// Apertura/Cierre Filtro buscador
915	var abrirCerrarFiltrado = function(){
916		$('.js-abrir-filtro-buscador').on('click keypress', function(event){
917			event.preventDefault();
918			$('.filtrado-buscador').removeClass('d-none');
919			$('html,body').addClass('noScroll-busq');
920			$('.js-abrir-filtro-buscador').attr("aria-expanded", "true");
921			const  focusableElements =
922			    'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';
923			const modal = document.querySelector('#buscadorAvanzado'); 
924	
925			const firstFocusableElement = modal.querySelectorAll(focusableElements)[0]; 
926			const focusableContent = modal.querySelectorAll(focusableElements);
927			const lastFocusableElement = focusableContent[focusableContent.length - 1];
928			document.addEventListener('keydown', function(e) {
929			  let isTabPressed = e.key === 'Tab' || e.keyCode === 9;
930			  if (!isTabPressed) {
931			    return;
932			  }
933			  if (e.shiftKey) { 
934			    if (document.activeElement === firstFocusableElement) {
935			      lastFocusableElement.focus();
936			      e.preventDefault();
937			    }
938			  } else { 
939			    if (document.activeElement === lastFocusableElement) { 
940			      firstFocusableElement.focus();
941			      e.preventDefault();
942			    }
943			  }
944			});
945			if(event.keyCode==13){
946				$('.js-filtrado-close-btn').focus();
947			}
948
949		});
950		$('.js-filtrado-close-btn').on('click', function(){
951			$('.filtrado-buscador').addClass('d-none');
952			$('html,body').removeClass('noScroll-busq');
953			$('.js-abrir-filtro-buscador').attr("aria-expanded", "false");
954			$('.js-abrir-filtro-buscador').focus();
955		});
956	
957	}
958	
959	//Cambiar la etiqueta aria-label al ejecutarse un evento
960	var changeAriaLabel = function (){
961	$('.js-arrow-open').on('click',function(){
962		var ariaLabel = $(this).attr('aria-label');
963		var labelClosed = $(this).attr('data-label-closed');
964		var labelOpened = $(this).attr('data-label-opened');
965		if(ariaLabel == labelClosed){
966			$(this).attr('aria-label',labelOpened);
967		}
968		else{
969			$(this).attr('aria-label',labelClosed);
970		}
971
972	});
973	}
974	
975	/**
976	 * Toggle para listados de enlaces del footer
977	 */
978	var slideToggleFooter = function () {
979		$('.footer__links').find('[data-control-collapse]').on('click', function () {
980			if ($(window).width() <= 767) {
981				var et = $(this).data('control-collapse');
982				var ec = $('[data-content-collapse="' + et + '"]');
983				$(this).toggleClass('active');
984				$(ec).toggleClass('active');
985				$(ec).slideToggle();
986				$(this).attr("aria-expanded") === "true" ?
987				$(this).attr("aria-expanded", "false") :
988				$(this).attr("aria-expanded", "true");
989			}
990		});
991	}
992
993	/**
994	 * Toggle para listados de enlaces de enlinea
995	 */
996	var slideToggleCustom = function () {
997		$('.en-linea').not('.preguntas-frecuentes-list').find('[data-control-collapse]').on('click', function () {
998			var et = $(this).data('control-collapse');
999			var ec = $('[data-content-collapse="' + et + '"]');
1000			if ($(this).attr("aria-expanded") === "false") {
1001				$(ec).slideDown(500, function () {
1002					$(et).addClass('active');
1003					$(ec).addClass('active');
1004				});
1005				$(this).attr("aria-expanded", "true");
1006			} else {
1007				$(ec).slideUp(500, function () {
1008					$(et).removeClass('active');
1009					$(ec).removeClass('active');
1010				});
1011				$(this).attr("aria-expanded", "false");
1012			}
1013		});
1014	}
1015	
1016	/**
1017	 * Toggle para listados de preguntas frecuentes
1018	 */
1019	var slideTogglePreguntasFrecuentes = function () {
1020		$('.preguntas-frecuentes-list').find('[data-control-collapse]').on('click', function () {
1021			var et = $(this).data('control-collapse');
1022			var ec = $('[data-content-collapse="' + et + '"]');
1023			if ($(this).attr("aria-expanded") === "false") {
1024				$('.preguntas-frecuentes-list').find('[aria-expanded=true]').each(function() {
1025					var et = $(this).data('control-collapse');
1026					var ec = $('[data-content-collapse="' + et + '"]');
1027					$(ec).slideUp(500, function () {
1028						$(et).removeClass('show');
1029						$(ec).removeClass('show');
1030					});
1031					$(this).attr("aria-expanded", "false");
1032				});
1033				$(ec).slideDown(500, function () {
1034					$(et).addClass('show');
1035					$(ec).addClass('show');
1036				});
1037				$(this).attr("aria-expanded", "true");
1038			} else {
1039				$(ec).slideUp(500, function () {
1040					$(et).removeClass('show');
1041					$(ec).removeClass('show');
1042				});
1043				$(this).attr("aria-expanded", "false");
1044			}
1045		});
1046	}
1047
1048	/**
1049	 * Eliminacion de atributo style de los collapse
1050	 */
1051	var slideToggleFooterClean = function () {
1052		var dataNum = $('[data-content-collapse]').length;
1053		for (var i= 0; i < dataNum; i++) {
1054			$('[data-content-collapse]')[i].removeAttribute("style");
1055		}
1056	} 
1057	
1058	return{
1059	saltoContenidoTeclado : function(){
1060		saltoContenidoTeclado();
1061	},
1062	updateTabIndex : function(){
1063		updateTabIndex();
1064	},
1065	changeAriaLabel : function(){
1066		changeAriaLabel();
1067	},
1068	desplegarMenu : function(){
1069		desplegarMenu();
1070	},
1071	desplegarMenuSec : function(){
1072		desplegarMenuSec();
1073	},
1074	cerrarMenu : function(){
1075		cerrarMenu();
1076	},
1077	selectorIdioma : function(){
1078		selectorIdioma();
1079	},
1080	IExplorer : function(){
1081		IExplorer('.img-title-container .image');
1082		IExplorer('.swiper-slide a');
1083	},
1084	disableCollapse : function(){
1085		disableCollapse('.modules-two-columns a[data-toggle="collapse"]',580);
1086		disableCollapse('.resultados .info-resultados [data-toggle="collapse"]',768);
1087		disableCollapse('.dga-view .footer__links__list > li .title[data-toggle="collapse"]',768);
1088	},
1089	ocultarMenuAuto : function(){
1090		ocultarMenuAuto();
1091	},
1092	cerrarGalTeclado : function(){
1093		cerrarGalTeclado();
1094	},
1095	limitarCaracteres : function(){
1096		limitarCaracteres($('.detail-news-module__anchor .listado__item .link','50'));
1097	},
1098	increaseFontSize : function(){
1099		increaseFontSize();
1100	},
1101	swiperSlider : function(){
1102		swiperSlider();
1103	},
1104	anchorCustom : function(){
1105		anchorCustom();
1106	},
1107	stickyBar : function(){
1108		stickyBar();
1109	},
1110	abrirCerrarFiltrado : function(){
1111		abrirCerrarFiltrado();
1112	},
1113	slideToggleFooter : function(){
1114		slideToggleFooter();
1115		},	
1116	slideToggleCustom : function(){
1117		slideToggleCustom();
1118	},
1119	slideTogglePreguntasFrecuentes : function(){
1120		slideTogglePreguntasFrecuentes();
1121	},
1122	slideToggleFooterClean: function(){
1123		slideToggleFooterClean();
1124	}
1125	}
1126})();
1127
1128$(document).ready(function() {
1129	// On load
1130	
1131
1132	mainApp.saltoContenidoTeclado();
1133	mainApp.updateTabIndex();
1134	mainApp.desplegarMenuSec();
1135	mainApp.cerrarMenu();
1136	mainApp.selectorIdioma();
1137	mainApp.disableCollapse();
1138	mainApp.ocultarMenuAuto();
1139	mainApp.cerrarGalTeclado();
1140	mainApp.limitarCaracteres();
1141	mainApp.increaseFontSize();
1142	mainApp.desplegarMenu();
1143	mainApp.anchorCustom();
1144	mainApp.abrirCerrarFiltrado();
1145	mainApp.changeAriaLabel();
1146	mainApp.stickyBar();
1147	mainApp.slideToggleFooter();
1148	mainApp.slideToggleCustom();
1149	mainApp.slideTogglePreguntasFrecuentes();
1150	mainApp.slideToggleFooterClean();
1151	// Evitamos inicializar la función cuando el slider no esté implementado en la página cargada
1152	if($('.swiper-wrapper').hasClass('my-gallery') == true){
1153		mainApp.swiperSlider();
1154	}
1155
1156	var userAgent, ieReg, ie;
1157	userAgent = window.navigator.userAgent;
1158	ieReg = /msie|Trident.*rv[ :]*11\./gi;
1159	ie = ieReg.test(userAgent);
1160	/* Imágenes object-fit en ie11 */
1161	if(ie) {
1162		mainApp.IExplorer();
1163	}
1164	
1165	// Cambio en la anchura dispositivo
1166	$(window).resize(function() {
1167		mainApp.updateTabIndex();
1168		mainApp.desplegarMenuSec();
1169		mainApp.anchorCustom();
1170		mainApp.stickyBar();
1171		mainApp.slideToggleFooterClean();
1172		if($(window).width() > 767){
1173		$('html,body').removeClass('noScroll-busq');
1174		}
1175	});
1176});
1177
1178
1179function extractExtension(href){
1180	var extension= href.split("/");
1181	var finalExt = extension[extension.length - 2].match("\.(.+)");
1182	return "." + finalExt[finalExt.length - 1] + "/";
1183}
1184
1185function renderOpenDataVisor(){
1186	
1187	$(".opendata-visor").each(function(index){	
1188		
1189		var tableHTML = '';
1190		var visor = $(this);	
1191		var paragraph = visor.text();
1192		var randomNumber = Math.floor((Math.random() * 5000) + 1);
1193		
1194		visor.text('');
1195		visor.addClass('loading-animation');
1196				
1197		
1198	    $.getJSON(visor.attr('data-opendata-url'), function(data, status){
1199	    	console.log(status);
1200	    	console.log(paragraph);
1201	    	
1202	    	if(status == 'success'){
1203	    		if(data.length > 0){
1204					
1205					tableHTML += '<p id="custom-table-'+randomNumber+'">';
1206					tableHTML += paragraph;
1207					tableHTML += '</p>';
1208					
1209					tableHTML += '<table aria-describedby="custom-table-'+randomNumber+'" border="1">';
1210					tableHTML += '<thead>';
1211					tableHTML += '<tr>';
1212
1213					$.each(data[0], function (clave, valor) {
1214						tableHTML += '<th>'+clave+'</th>';
1215					});
1216					
1217					tableHTML += '</tr>';
1218					tableHTML += '</thead>';
1219					tableHTML += '<tbody>';
1220					
1221					$.each(data, function (index) {
1222						tableHTML += '<tr>';
1223						
1224						$.each(data[index], function (clave, valor) {
1225							tableHTML += '<td>'+valor+'</td>';
1226						});
1227						
1228						tableHTML += '</tr>';
1229					});
1230					
1231					tableHTML += '</tbody>';
1232					tableHTML += '</table>';
1233					
1234					visor.removeClass('loading-animation');
1235					
1236					visor.append(tableHTML);
1237				}
1238	    	}else if(status == 'error'){
1239	    		console.log('Error javascript');
1240	    	}
1241		});	  
1242	});	
1243}
1244
1245// Comportamiento del scroll en ficha de servicio
1246window.scrollTo({
1247  top: 0,
1248  left: 0,
1249  behavior: "instant",
1250});
1251
1252// Función para obtener elementos por data-component
1253function getComponents(name) {
1254	return document.querySelectorAll(`[data-component="${name}"]`);
1255}
1256
1257// Obtener todos los enlaces y mensajes
1258const copyLinks = getComponents('c-copy-link');
1259const copyMessages = getComponents('c-copy-message');
1260
1261// Función para mostrar mensaje en todos los elementos de mensaje
1262function showMessage(message, isError = false) {
1263	copyMessages.forEach(msg => {
1264		msg.textContent = message;
1265		msg.classList.remove('text-success-dark', 'text-alert-base');
1266		msg.classList.add(isError ? 'text-alert-base' : 'text-success-dark');
1267	});
1268
1269	copyLinks.forEach(link => {
1270		link.classList.add('d-none');
1271	});
1272}
1273
1274// Función para resetear el estado
1275function resetState() {
1276	copyMessages.forEach(msg => {
1277		msg.textContent = '';
1278		msg.classList.remove('text-success-dark', 'text-alert-base');
1279	});
1280
1281	copyLinks.forEach(link => {
1282		link.classList.remove('d-none');
1283	});
1284}
1285
1286// Función principal para copiar URL
1287function copyURL(e) {
1288	e.preventDefault();
1289	const currentURL = window.location.href;
1290
1291	navigator.clipboard.writeText(currentURL)
1292		.then(() => {
1293			showMessage('URL copiada al portapapeles');
1294		})
1295		.catch((err) => {
1296			showMessage('Error al copiar la URL', true);
1297		})
1298		.finally(() => {
1299			setTimeout(resetState, 3000);
1300		});
1301}
1302
1303// Agregar event listener a todos los enlaces
1304copyLinks.forEach(link => {
1305	link.addEventListener('click', copyURL);
1306});
1307
1308// Cierra el menu sticky y hace scroll instantáneo arriba
1309scrollTopInstant = function() {
1310  const btnToggle = document.getElementById('toggle-2-icons');
1311  if (btnToggle.getAttribute('aria-expanded') == 'true') {
1312	btnToggle.click();
1313  }
1314  window.scroll({ top: 0, behavior: 'instant' });
1315}
1316
1317// Tabs con botón atrás
1318$(document).ready(function() {
1319	// Función para activar un tab basado en el hash de la URL (sin ejecutarla al cargar)
1320	function activateTabFromHash() {
1321	    var hash = window.location.hash;
1322        if (hash) {
1323            $('[data-toggle="tab"][href="' + hash + '"]').tab('show');
1324        }
1325	}
1326
1327    function handleInitialState() {
1328        if($('.tab-pane').length){
1329           var hashOld = window.location.hash;
1330
1331            if (hashOld) {
1332              //evita scroll con reinit o share
1333
1334                if ("scrollRestoration" in history) {
1335                  history.scrollRestoration = "manual";
1336                }
1337                var hash = hashOld.replace('#', '');
1338
1339                // Desactiva todos elementos
1340                $('[data-toggle="tab"]').removeClass('active');
1341                $('.tab-pane').removeClass('active');
1342
1343                // Añade la clase 'active' a los elementos coincidentes
1344                $('.tab-pane[id="' + hash + '"]').addClass('active');
1345                $('[data-toggle="tab"][aria-controls="' + hash + '"]').addClass('active');
1346
1347            }
1348        }
1349    }
1350
1351    // Manejar el estado inicial al cargar la página
1352    handleInitialState();
1353
1354    // Manejar cambios de tab
1355    $('[data-toggle="tab"]').on('click', function(e) {
1356    	e.preventDefault();
1357
1358        var currentTab = $(this).attr('href');
1359
1360        // Actualizar la URL con el nuevo hash
1361        if (history.pushState) {
1362        	history.pushState(null, null, currentTab);
1363        } else {
1364        	location.hash = currentTab;
1365        }
1366
1367
1368        if($('.tab-pane').length){
1369            var hrefActive = $(this).attr('href').replace('#', '');
1370
1371            // Quita la clase 'active' de los demás elementos
1372            $('[data-toggle="tab"]').removeClass('active');
1373            $('.tab-pane').removeClass('active');
1374
1375            // Añade la clase 'active' a los elementos coincidentes
1376            $('.tab-pane[id="' + hrefActive + '"]').addClass('active');
1377            $('[data-toggle="tab"][aria-controls="' + hrefActive + '"]').addClass('active');
1378
1379            // Scroll to a specific element without using the hash
1380            if ($(this).data("content") === "mandatory") {
1381                let target = $('[data-title="mandatory"]');
1382                if (target.length) {
1383                    $("html, body").animate(
1384                        { scrollTop: target.offset().top },
1385                        300 // Duración del scroll en milisegundos
1386                    );
1387                }
1388            }
1389        }
1390
1391        //$(this).tab('show');
1392    });
1393
1394
1395    // Manejar el botón de retroceso del navegador
1396    $(window).on('popstate', function() {
1397    	activateTabFromHash();
1398    });
1399});
1400
1401//Pagina de Temas, fragmento de Servicios y Tramites
1402document.addEventListener('DOMContentLoaded', function () {
1403
1404  // Evito scroll y hash al cargar si ya hay un hash en la URL
1405  if (location.hash && $('#myTabTramites').length > 0) {
1406
1407    const scrollHash = location.hash;
1408    // Quito el hash de la URL sin hacer scroll
1409    history.replaceState(null, '', location.pathname + location.search);
1410
1411    // Activar la pestaña correspondiente manualmente
1412    const tabLink = document.querySelector('#myTabTramites a[href="' + scrollHash + '"]');
1413    if (tabLink) {
1414      $(tabLink).tab('show');
1415    }
1416  }
1417
1418  // Intercepto clics en tabs para evitar que el hash cambie
1419  document.querySelectorAll('#myTabTramites a[data-toggle="tab"]').forEach(link => {
1420        link.addEventListener('click', function (e) {
1421
1422          e.preventDefault();
1423          e.stopImmediatePropagation();
1424
1425          const target = this.getAttribute('href');
1426          const idTag = this.getAttribute('id');
1427
1428          $('#myTabContent .tab-pane').removeClass('active');
1429          $('#myTabContent .tab-pane[aria-labelledby="' + idTag +'"]').addClass('active')
1430
1431          $(this).tab('show');
1432
1433
1434          // Evito modificar el hash
1435          history.replaceState(null, '', location.pathname + location.search);
1436        });
1437
1438        // Manejo tecla Enter
1439        link.addEventListener('keydown', function (e) {
1440          if (e.key === 'Enter' || e.keyCode === 13) {
1441            e.preventDefault();
1442            this.click(); // Llama evento click
1443          }
1444        });
1445
1446        // Elimino href para evitar comportamiento por defecto
1447        link.removeAttribute('href');
1448
1449        // Aseguro que sea navegable con teclado
1450        //link.setAttribute('tabindex', '0');
1451        //link.setAttribute('role', 'tab');
1452  });
1453});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.