var width992QueryHighContrast=window.matchMedia("(max-width: 992px)"),highContrastCorrutineDelay=2E3,highContrastCorrutineActualTries=0,highContrastCorrutineMaxTries=3;function initHighContrast(){width992QueryHighContrast.addListener(highContrastMobileHandler);var a=getCookie(params.HIGH_CONTRAST_COOKIE_NAME);null!=a?a=a.includes("true")?!0:!1:initHighContrastCorrutine();a&&!window.matchMedia("(max-width: 992px)").matches&&$("body").addClass("alto-contraste")}
function initHighContrastCorrutine(){highContrastCorrutineActualTries++;highContrastCorrutineActualTries<highContrastCorrutineMaxTries&&setTimeout(function(){initHighContrast()},highContrastCorrutineDelay)}function setHighContrast(){$("body").toggleClass("alto-contraste");setHighContrastCookie(params.HIGH_CONTRAST_COOKIE_NAME,10)}
function setHighContrastCookie(a,d){var b=new Date;b.setTime(b.getTime()+864E5*d);var b="expires\x3d"+b.toUTCString(),c=getCookie(a).includes("true")?!0:!1;document.cookie=a+"\x3d"+!c+";"+b+";path\x3d/"}function getCookie(a){a+="\x3d";for(var d=decodeURIComponent(document.cookie).split(";"),b=0;b<d.length;b++){for(var c=d[b];" "==c.charAt(0);)c=c.substring(1);if(0==c.indexOf(a))return c.substring(a.length,c.length)}return""}
function highContrastMobileHandler(){getCookie(params.HIGH_CONTRAST_COOKIE_NAME).includes("true")&&(window.matchMedia("(max-width: 992px)").matches?$("body").removeClass("alto-contraste"):$("body").addClass("alto-contraste"))};
var width992Query=window.matchMedia("(max-width: 992px)");function initSecondaryMenu(){width992Query.addListener(cleanMenu);$("#language_modal_responsive").prependTo("#wrapper");setTimeout(function(){$(".secondary-menu").removeAttr("style")},2E3)}function cleanMenu(){$("#header .black-div").addClass("display-none");$("#header #menu-container").removeClass("menu-grey")}function showModalLanguage(){$("#language_modal_responsive").modal()}
function changeLanguageForm(a){$("#languageTypeHidden").val(a)}function submitLanguageForm(a){a.preventDefault();a="#a_language_"+$("#languageTypeHidden").val();jQuery(a)[0].click()}function roundDecimals(a,b){if(0==b)return Math.round(a);var c=Math.pow(10,b);return Math.round(a*c)/c}
$(document).ready(function(){if(params.busplusUser){if(params.cashPoints&&document.getElementById("secondarymenu-cashPoints")){var a=roundDecimals(params.cashPoints,2);document.getElementById("secondarymenu-cashPoints").innerHTML="("+a+"\u20ac)"}params.cardCurrentBalance&&document.getElementById("secondarymenu-busplusUserInfoBalance")&&(a=roundDecimals(params.cardCurrentBalance,2),document.getElementById("secondarymenu-busplusUserInfoBalance").innerHTML=a+"\u20ac")}});
var idFirstLevel = "1";
var idSecondLevel = "2";
var idThirdLevel = "3";
var idFourthLevel = "4";

$(document).ready(function () {
	if (typeof params["fullMainMenu"] != "undefined") {
		initMenu(params["fullMainMenu"]);
	}
	moveSubheader();
	window.matchMedia("(max-width: 992px)").addListener(moveSubheader);
});

/**
 * Cambia de posicion el subheader en funcion de la resolucion de la pantalla
 */
function moveSubheader(){
	var placeOfSubheaderForDesktop = document.getElementById("header");
	var placeOfSubheaderForTabletsMoviles = document.getElementById("mainmenu");


	if( window.matchMedia("(min-width: 992px)").matches ){
		if( placeOfSubheaderForDesktop ){

		    let placeOfLogin = document.getElementById("linkMenu");
			let dom_subheader = placeOfSubheaderForTabletsMoviles.getElementsByClassName("sub-header")[0];

			if( dom_subheader ){
				placeOfSubheaderForDesktop.insertAdjacentElement("afterbegin",dom_subheader);
				document.getElementsByClassName("header_home_linkbusplus_desktop")[0].insertAdjacentElement("afterbegin", placeOfLogin);
			}


		}
	}
	if( window.matchMedia("(max-width: 991px)").matches ){
		if( placeOfSubheaderForTabletsMoviles ){
		    let placeOfLogin = document.getElementById("linkMenu");
			let dom_subheader = placeOfSubheaderForDesktop.getElementsByClassName("sub-header")[0];

			if( dom_subheader ){
				placeOfSubheaderForTabletsMoviles.insertAdjacentElement("beforeend",dom_subheader);
				document.getElementsByClassName("header_home_linkbusplus_mobile")[0].insertAdjacentElement("afterbegin", placeOfLogin)
			}
		}
	}
};

//Funcionamiento complejo, forma una matriz de cuatro por cuatro
function initMenu (listaItems) {
	for (var i = 0; i < listaItems.length; i++) {
		// Creamos el primer nivel de la lista
		createTextList("listaMenuWeb2020MainMenuPortlet", [i], listaItems[i], 0);

		// Creamos la estructura base dentro de cada primer item de --- la lista
		createMenuList(listaItems[i], i);

		if (typeof listaItems[i].children != "undefined") {	// Si tiene hijos

			for (var y = 0; y < listaItems[i].children.length; y++) {

				// Creamos el segundo nivel de la lista
				var secondLevelItem = listaItems[i].children[y];
				var secondLevelSelector = concatString(["col", secondLevelItem.column, i, "ul"]);
				createTextList(secondLevelSelector, [i,y], secondLevelItem, 3);

				if (typeof secondLevelItem.children != "undefined") {	// Si tiene hijos

					// Creamos el tercer nivel de la lista y de llegar a este nivel se le añadira una clase especial al segundo nivel
					var thirdLevelSelector = "menu"+i+""+y;

					$("#" + thirdLevelSelector).append(
						"<ul id='menu"+i+""+y+"ul' class='novisible_992'></ul>");
					var ulThirdLevelSelector =  "menu"+i+""+y+"ul";

					for (var x = 0; x < secondLevelItem.children.length; x++) {
						var thirdLevelItem = secondLevelItem.children[x];
						createTextList(ulThirdLevelSelector, [i,y,x], thirdLevelItem, 4);

						if (typeof thirdLevelItem.children != "undefined") {	// Si tiene hijos
							// Creamos el cuarto nivel de la lista y de llegar a este nivel se le añadira una clase especial al segundo nivel
							var fourthLevelSelector = "menu"+i+""+y+""+x;
							$("#" + concatString([fourthLevelSelector, "h"])).addClass("has-childs");

							$("#" + fourthLevelSelector).append(
								"<ul id='menu"+i+""+y+""+x+"ul' class='foutrhlevel'></ul>");
							var ulFourthLevelSelector = "menu"+i+""+y+""+x+"ul";

							for (var z = 0; z < thirdLevelItem.children.length; z++) {
								var fourthLevelItem = thirdLevelItem.children[z];
								createTextList(ulFourthLevelSelector, [i,y,x,z], fourthLevelItem, 5);
							}
						}


					}
				}


			}
		}


	}
}

/**
 * Crea un texto dentro de la lista
 * selector: el selector por el que se buscara en el DOM
 * arrayLevel: indica el nivel de profundidad, en el menu, del elemento que se va a crear
 * item: el elemento de menu
 * hElement: el numero del h con el que se creara este componente
 */
function createTextList (selector, arrayLevel, item, hElement) {

	var textStructure = "";
	var baseId = "menu"+arrayLevel.join("").toString();
	//var nextChildLevel = concatString(baseId,"ul");
	var iteration = arrayLevel[arrayLevel.length-1]
	var depth = arrayLevel.length;
	var classElement = "menu"+iteration;

	if(item.colorblue)
	{
		classElement= classElement +" isblue";
	}

	// Se construye el <li>
	if (item.children && item.children.length > 0) {
		textStructure += '<li'
		textStructure += ' id="' + baseId + '"';
		textStructure += ' onmouseleave="hideMenuList_desktop(['+arrayLevel+'])";';
		textStructure += ' onmouseover="showMenuList_desktop(['+arrayLevel+'])";';
		textStructure += ' onclick="toggleMenuList_tablets(['+arrayLevel+'],event)";';
		if (depth ==1 ) {
			textStructure += ' class="icn-angle-down -mobile ' + item.classid + '"';
		} else if(depth ==2 ){
			textStructure += ' class="icon icn-plus ' + item.classid + '"';
		}



		textStructure += '>'
		// Si se quiere encapsular el texto en un <h?>
		if (hElement > 0) {
			textStructure += '<h' + hElement + ' id="' + concatString([baseId, "h"]) + '"><a href="' + item.url + '" class="' + classElement + ' has-childs" ';
			textStructure += 'onclick="event.stopPropagation()"><span>' + item.title + '</span></a></li>';
		} else {
			textStructure += '<a href="' + item.url + '" class="' + classElement + ' has-childs" ';
			textStructure += 'onclick="event.stopPropagation()"><span>' + item.title + '</span></a></li>';
		}
	} else {
		textStructure += '<li ';
		textStructure += 'id="' + baseId +'"';
		if (depth = 1) {
			//En caso de que no tenga hijos, y estemos en el primer nivel, mostramos tambien los
			//estilos del hover
			textStructure += 'class="' + item.classid + '"';
			textStructure += ' onmouseover="showHoverOnly(\'' + baseId + '\')"';
			textStructure += ' onmouseleave="hideHoverOnly(\'' + baseId + '\')"';
		} else {
			textStructure += 'class="' + item.classid + '"';
		}
		textStructure += ' ">';
		// Si se quiere encapsular el texto en un <h?>
		if (hElement > 0) {
			textStructure += '<h' + hElement + ' id="' + concatString([baseId, "h"]) + '"><a href="' + item.url + '" class="' + classElement+'"><span>' + item.title + '</span></a></h' + hElement + '></li>';
		} else {
			textStructure += '<a href="' + item.url + '" class="' + classElement + '"';

			if(item.url.includes("http") || item.url.includes("www.")){
				textStructure += ' target="_blank" ;'
			}

			textStructure += '><span>' + item.title + '</span></a></li>';
		}
	}

	$("#" + selector).append(textStructure);
}


/**
 * Crea la estructura basica del menu
 */
function createMenuList (rootElemnt, iteration) {

	var listBaseStructure =
	'<div id="' + concatString(["contenedorDatosItemWeb2020MainMenuPortlet", iteration]) + '" class="display-none contenedor-submenus">' +
			'<div class="container">' +
				'<div class="main-menu-title">' +
					'<h2 id="' + concatString(['itemSeleccionadoWeb2020MainMenuPortlet', iteration]) + '">' + rootElemnt.title + '</h2>' +
				'</div>' +
				'<ul id="' + concatString(['contenedorColumnasWeb2020MainMenuPortlet', iteration]) + '" class="contenedor-columnas">' +
					'<li id="' + concatString(['col-1', iteration]) + '" class="col-1"><ul id="' + concatString(['col-1', iteration, 'ul']) + '"></ul></li>' +
					'<li id="' + concatString(['col-2', iteration]) + '" class="col-2"><ul id="' + concatString(['col-2', iteration, 'ul']) + '"></ul></li>' +
					'<li id="' + concatString(['col-3', iteration]) + '" class="col-3"><ul id="' + concatString(['col-3', iteration, 'ul']) + '"></ul></li>' +
				'</ul>' +
			'</div>' +
	'</div>';
	var baseId = "menu"+iteration;
	$("#" + baseId).append(listBaseStructure);
}



/**
 * Para Elementos de primer nivel, sin hijos, solo añade la clase hover
 *
 * @returns
 */
function showHoverOnly(baseId) {
	$("#" + baseId +" > a").addClass("hover");
}

/**
 * Para Elementos de primer nivel, sin hijos, solo quita la clase hover
 *
 * @param arrayLevel
 * @returns
 */
function hideHoverOnly(baseId) {
	$("#" + baseId +" > a").removeClass("hover");
}

/**
 * Acciones que solo tienen lugar en resoluciones desktop
 * para mostrar la opcion del menu principal indicada por el parametro "arrayLevel"
 * @param arrayLevel
 */
function showMenuList_desktop(arrayLevel) {
	if( window.matchMedia("(max-width: 991px)").matches ){
		return;
	}
	$("#content-web2020").addClass("not-scroll");
	$(".black-div").removeClass("display-none");
	showMenuList(arrayLevel);
}


/**
 * Acciones que solo tienen lugar en resoluciones desktop
 * para ocultar la opcion del menu principal indicada por el parametro "arrayLevel"
 * @param arrayLevel
 */
function hideMenuList_desktop(arrayLevel) {
	if( window.matchMedia("(max-width: 991px)").matches ){
		return;
	}
	$("#content-web2020").removeClass("not-scroll");
	$(".black-div").addClass("display-none");
	hideMenuList(arrayLevel);
}

/**
 * Muestra los distintos elementos del menu
 * Pone la capa negra que cubrirá el contenido de la página
 * Pone los estilos del hover para los elementos principales del menú
 * Deshabilita el scroll en el contenido
 */
function showMenuList(arrayLevel) {
	var depth = arrayLevel.length;
	if( depth == idFirstLevel ){
		var iteration = arrayLevel[arrayLevel.length-1];
		$("#contenedorDatosItemWeb2020MainMenuPortlet-" + iteration).siblings ("a").addClass("hover");
		$("#contenedorDatosItemWeb2020MainMenuPortlet-" + iteration).removeClass("display-none");
		$("#menu"+arrayLevel.join("")).addClass("open-menu");
	}
}


/**
 * Oculta los distintos elementos del menu
 * Quita la capa negra
 * Quita estilos hover
 * Habilita el scroll
 */
function hideMenuList (arrayLevel) {
	var depth = arrayLevel.length;
	if (depth == idFirstLevel) {
		var iteration = arrayLevel[arrayLevel.length-1];
		$("#contenedorDatosItemWeb2020MainMenuPortlet-" + iteration).siblings ("a").removeClass("hover");
		$("#contenedorDatosItemWeb2020MainMenuPortlet-" + iteration).addClass("display-none");
		$("#menu"+arrayLevel.join("")).removeClass("open-menu");
	}  if (depth < idThirdLevel) {
		var elementId = "menu"+arrayLevel.join("").toString();
		$("#" + elementId).removeClass("open-menu");
		$("#" + elementId).find('li.open-menu').removeClass("icn-minus").addClass("icn-plus");
		$("#" + elementId).find('li.open-menu').removeClass("open-menu");
		if ( $("#" + elementId).hasClass("icn-angle-up") ) {
			$("#" + elementId).removeClass("icn-angle-up").addClass("icn-angle-down");
		}
		if ( $("#" + elementId).hasClass("icn-minus") ) {
			$("#" + elementId).removeClass("icn-minus").addClass("icn-plus");
		}

		$("#" + elementId).find('ul:not(.foutrhlevel)[id^="menu"]').addClass("novisible_992");
	}

}


/**
 * Solo en pantallas de moviles/tablets, en funcion del estado del elemento del menu, realiza lo siguiente:
 * Muestra/oculta los distintos elementos del menu
 * Pone/quita la capa negra
 * Pone/quita estilos hover
 * Des/Habilita el scroll
 */
function toggleMenuList_tablets( arrayLevel,e ) {
	if( window.matchMedia("(min-width: 992px)").matches ){
		return;
	}
	var depth = arrayLevel.length;
	if (depth == idFirstLevel ){
		var iteration = arrayLevel[arrayLevel.length-1]
		$("#contenedorDatosItemWeb2020MainMenuPortlet-" + iteration).toggleClass("display-none");
		$("#contenedorDatosItemWeb2020MainMenuPortlet-" + iteration).siblings ("a").addClass("hover");

	}
	if (depth < idThirdLevel){
		var elementId = "menu"+arrayLevel.join("").toString();
		currentElement = $('#'+elementId);
		currentElement.toggleClass("open-menu");
		childElement = $('#'+elementId).find('ul').first()
		childElement.toggleClass("novisible_992");
		if ( currentElement.hasClass("icn-angle-down") )
			currentElement.removeClass("icn-angle-down").addClass("icn-angle-up");
		else
			if ( currentElement.hasClass("icn-angle-up") )
				currentElement.removeClass("icn-angle-up").addClass("icn-angle-down");
			else
				if ( currentElement.hasClass("icn-plus") )
					currentElement.removeClass("icn-plus").addClass("icn-minus");
				else
					if ( currentElement.hasClass("icn-minus") )
						currentElement.removeClass("icn-minus").addClass("icn-plus");
	}
	toggleSiblingMenus( arrayLevel );
	e.stopPropagation();
}

/**
 * Muestra/oculta los menus que sean distintos al que se recibe como parametro
 */
function toggleSiblingMenus( arrayLevel ) {
	var iteration = arrayLevel[arrayLevel.length-1]
	for (var i=0; i<=iteration-1; i++) {
		var arrayLevelSibling = arrayLevel.slice(0);
		arrayLevelSibling.pop();
		arrayLevelSibling.push(i)
		hideMenuList(arrayLevelSibling);
	}
	for (var i=iteration+1; i<params["fullMainMenu"].length; i++) {
		var arrayLevelSibling = arrayLevel.slice(0);
		arrayLevelSibling.pop();
		arrayLevelSibling.push(i)
		hideMenuList(arrayLevelSibling);
	}
}

/**
 * Esta funcion nos ayudara a que los selectores coincidan sin ensuciar demasiado el codigo
 */
function concatString (valores) {
	var finalString = "";
	for (var i = 0; i < valores.length; i++) {
		finalString += valores[i];
		if (i+1 != valores.length) {
			finalString += '-';
		}
	}

	return finalString;
}




$(document).ready(function(){
	$('.journey-row').addClass('show-twice');

	let items = $(".journey-row");
	let numToShow = 2;
	let button = $("#showMoreJourneys");
	let numToShowIncrement = numToShow;

	items.slice(0, numToShow).addClass('show');

	button.on('click', function() {
		let showing = items.filter('.show').length;
		numToShowIncrement += 2;
		items.slice(showing, numToShowIncrement).addClass('show');
		items.slice(showing, numToShowIncrement).removeClass('hidden');
		if (items.filter('.show').length === items.length) {
		  button.hide();
		}
	});
});

