ips.templates.set("eventLoading",`
	<li class='ipsData__item ipsData__item--loading'>
		<div class="ipsData__image" aria-hidden="true"></div>
		<div class="ipsData__content">
			<div class="ipsData__main">
				<div class="ipsData__title"></div>
				<div class="ipsData__desc"></div>
			</div>
		</div>
	</li>
`);ips.templates.set("nearMe",`
	<i-data>
		<ul class='ipsData ipsData--grid ipsData--events-list ipsEventList ipsEventList--nearMe'>
			<li class="ipsData__item ipsEventsNearMe__map"><div class='cEvents__skeleton cEvents__skeleton--map' id='map'></div></li>
			{{{events}}}
		</ul>
	</i-data>
`);;
var PER_PAGE=16;;(function($){"use strict";ips.controller.register('calendar.front.overview.eventList',{initialize:function(){this.on('click','[data-action="loadMore"]',this.loadMore);this.on('click','[data-action="changeMonth"]',this.changeMonth);this.setup();},setup:function(){this._eventList=this.scope.find('[data-role="eventList"]');this._loadMore=this.scope.find('[data-action="loadMore"]');this._monthNav=this.scope.find('[data-role="monthNav"]');},loadMore:function(e){e.preventDefault();var placeholders=this.getPlaceholders();this._eventList.append(placeholders);this._loadMore.prop('disabled',true);var self=this;var current=this.getCurrentDate();var total=this.scope.find('[data-eventID]').length;var url=ips.getSetting('baseURL')+'?app=calendar&module=calendar&controller=view&view=overview&get=byMonth&m='+current.month+'&y='+current.year+'&offset='+total;ips.getAjax()(url).done(function(response){self._eventList.append(response.html);self.removePlaceholders();self.checkMoreButton(response.count);self._loadMore.prop('disabled',false);$(document).trigger('contentChange',[self.scope]);});},changeMonth:function(e){e.preventDefault();var placeholders=this.getPlaceholders(4);this._eventList.html(placeholders);this._loadMore.prop('disabled',true);this._monthNav.find('[data-action="changeMonth"]').removeClass('cEvents__monthNav__monthItem--active');$(e.currentTarget).addClass('cEvents__monthNav__monthItem--active');var self=this;var current=this.getCurrentDate();var url=ips.getSetting('baseURL')+'?app=calendar&module=calendar&controller=view&view=overview&get=byMonth&m='+current.month+'&y='+current.year+'&offset=0';ips.getAjax()(url).done(function(response){self._eventList.html(response.html);self.checkMoreButton(response.count);self._loadMore.prop('disabled',false);$(document).trigger('contentChange',[self.scope]);});},getPlaceholders:function(count){var events=[];if(count===undefined){count=4;}
for(var i=0;i<count;i++){events.push(ips.templates.render('eventLoading'));}
return events.join('');},removePlaceholders:function(){this.scope.find('.ipsData__item--loading').remove();},checkMoreButton:function(count){if(Number.isFinite(count)&&count<PER_PAGE){this.scope.find('[data-action="loadMore"]').prop('hidden',true);this.scope.find('[data-role="noMoreResults"]').prop('hidden',false);}else{this.scope.find('[data-action="loadMore"]').prop('hidden',false);this.scope.find('[data-role="noMoreResults"]').prop('hidden',true);}},getCurrentDate:function(){var current=this.scope.find('[data-role="monthNav"] .cEvents__monthNav__monthItem--active');return{month:current.attr('data-month'),year:current.attr('data-year')};}});}(jQuery));;
;(function($){"use strict";ips.controller.register('calendar.front.overview.nearMe',{useGoogleMaps:false,events:{},useGeolocation:false,initialize:function(){this.setup();this.on('change','input#useCurrentLocation',this.useCurrentLocation);},setup(){if(ips.utils.geolocation.getGeolocationIsAllowed()){this.scope.find('input[type="checkbox"]').prop('checked',true);this.useGeolocation=true;}
if('nearmeUseGoogle'in this.scope.data()){let apiKey=this.scope.data()['googlemapsApiKey'];if(!apiKey){}
this.useGoogleMaps=true;ips.ui.map.afterGoogleMapsLoaded(()=>this.setupGoogleMaps())}
else{$('head').append(`<link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css'>
                        <link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.css' rel='stylesheet' />
                        <link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.Default.css' rel='stylesheet' />
                        <link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/plugins/leaflet-fullscreen/v1.0.1/leaflet.fullscreen.css' />`);window.ips.loader.get(['https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js']).then(()=>ips.loader.get(['https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/leaflet.markercluster.js','https://api.mapbox.com/mapbox.js/plugins/leaflet-fullscreen/v1.0.1/Leaflet.fullscreen.min.js'])).then(()=>{if(this.useGeolocation){this.getEventsByLocation();}else{this.fetchEvents();}
this._mapReady=true;});}},googleMap:undefined,setupGoogleMaps:function(){if(this.useGeolocation){this.getEventsByLocation();}else{this.fetchEvents();}
window.ipsGoogleMapsCallback=undefined;this._mapReady=true;},useCurrentLocation:function(){if(this.useGoogleMaps){this.googleMap=false;}
if(this.scope.find('#useCurrentLocation').is(':checked')){this.getEventsByLocation();}else{ips.utils.geolocation.setGeolocationIsAllowed(ips.utils.geolocation.permissions.DENIED);this.fetchEvents();}},getEventsByLocation:function(){this.showPlaceholders();ips.utils.geolocation.getCurrentPosition().then(coords=>{var lat=coords.latitude;var long=coords.longitude;this.scope.find('[data-role="nearMeLink"]').attr('href',ips.getSetting('baseURL')+'?app=calendar&do=search&form_submitted=1&lat='+lat+'&lon='+long).attr('data-lat',lat).attr('data-long',long);this.fetchEvents(lat,long);}).catch(()=>{ips.ui.alert.show({type:'alert',message:ips.getString('event_your_current_location_sorry'),icon:'warn'});this.scope.find('#useCurrentLocation').closest('li').remove();this.fetchEvents();});},fetchEvents:function(lat,long){var self=this;this.showPlaceholders();ips.getAjax()(ips.getSetting('baseURL')+'?app=calendar&module=calendar&controller=view&view=overview&get=nearMe'+(lat&&long?'&lat='+lat+'&lon='+long:'')).done(function(response){self.scope.find('[data-role="locationEvents"]').html(response.content);self.setUpMap(response.lat,response.long);$(document).trigger('contentChange',[self.scope]);});},setUpMap:function(lat,long){var self=this;var mapDiv=this.scope.find('#map');if(!mapDiv.length){Debug.log("No map container");return;}
if(this.useGoogleMaps){lat=Number(lat);long=Number(long);if(!this.googleMap){const mapContainer=mapDiv.get(0);mapContainer.style.width='100%';mapContainer.style.height='400px';this.googleMap=new window.google.maps.Map(mapContainer,{zoom:4,center:{lat,lng:long}});}else{this.googleMap.setCenter({lat,lng:long});}
self.scope.find('[data-role="nearMeLink"]').attr('href',ips.getSetting('baseURL')+'?app=calendar&do=search&form_submitted=1&lat='+lat+'&lon='+long).attr('data-lat',lat).attr('data-long',long);if(this.googleMap){let markers;try{let _markers=JSON.parse(mapDiv.attr('data-markers'));let markers=[];for(let marker of Object.values(_markers)){markers.push({...marker,lat:Number(marker.lat),long:Number(marker.long)});}
for(let marker of Object.values(markers)){let mapMarker=new window.google.maps.Marker({position:{lat:marker.lat,lng:marker.long},map:this.googleMap,title:marker.title});}
if(Object.values(markers).length){const cb=(()=>{let bounds=this.googleMap.getBounds();if(!bounds){return window.setTimeout(cb,200);}
let firstMarker=null;let markerVisible=false;let markerBounds={latMax:null,latMin:null,lngMax:null,lngMin:null};for(let marker of Object.values(markers)){markerBounds.latMax=markerBounds.latMax===null?marker.lat:Math.max(markerBounds.latMax,marker.lat);markerBounds.latMin=markerBounds.latMin===null?marker.lat:Math.min(markerBounds.latMin,marker.lat);markerBounds.lngMax=markerBounds.lngMax===null?marker.long:Math.max(markerBounds.lngMax,marker.long);markerBounds.lngMin=markerBounds.lngMin===null?marker.long:Math.min(markerBounds.lngMin,marker.long);firstMarker=firstMarker||marker;if(bounds.contains({lat:marker.lat,lng:marker.long})){markerVisible=true;}}
if(!markerVisible&&firstMarker){let evtMidpoint={lat:((markerBounds.latMax+markerBounds.latMin)/2),lng:((markerBounds.lngMax+markerBounds.lngMin)/2)};let minDistance=null;let mostMiddleMarker=null;if(Object.values(markers).length>1){for(let marker of Object.values(markers)){let distance=this.getDistance(evtMidpoint.lat,marker.lat,evtMidpoint.lng,marker.long);if(minDistance===null||distance<minDistance){minDistance=distance;mostMiddleMarker={lat:marker.lat,lng:marker.long};}}}else{mostMiddleMarker={lat:firstMarker.lat,lng:firstMarker.long};}
this.googleMap.panTo(mostMiddleMarker);}}).bind(this);window.setTimeout(cb,0);}}catch(e){}}}else{L.mapbox.accessToken=ips.getSetting('mapApiKey');this._map=L.mapbox.map(mapDiv.get(0)).addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));this._map.zoomControl=false;this._map.minZoom=2;this._map.dragging=false;this._map.zoomControl=false;var markersGroup=new L.featureGroup([]);var markers=JSON.parse(mapDiv.attr('data-markers'));for(var id in markers){var marker=L.marker([Number(markers[id].lat),Number(markers[id].long)],{title:markers[id].title,draggable:false,eventId:parseInt(id)});markersGroup.addLayer(marker);marker.on('mouseover',this._markerMouseOver.bind(this));marker.on('mouseout',this._markerMouseOut.bind(this));}
markersGroup.addTo(this._map);this._map.fitBounds(markersGroup.getBounds(),{maxZoom:5});}},getDistance:function(lat1,lat2,lng1,lng2){lng1=lng1*Math.PI/180;lng2=lng2*Math.PI/180;lat1=lat1*Math.PI/180;lat2=lat2*Math.PI/180;let dlng=lng2-lng1;let dlat=lat2-lat1;let a=Math.pow(Math.sin(dlat/2),2)
+Math.cos(lat1)*Math.cos(lat2)*Math.pow(Math.sin(dlng/2),2);let c=Math.asin(Math.sqrt(a));return c;},_markerMouseOver:function(e){var eventId=e.target.options.eventId;this.scope.find('[data-eventid]').stop(false,true);this.scope.find('[data-eventid]:not([data-eventid="'+eventId+'"])').animate({opacity:0.4},'fast');},_markerMouseOut:function(e){this.scope.find('[data-eventid]').stop(false,true);this.scope.find('[data-eventid]').animate({opacity:1},'fast');},showPlaceholders:function(count){var events=[];for(var i=0;i<6;i++){events.push(ips.templates.render('eventLoading'));}
this.scope.find('[data-role="locationEvents"]').removeClass('ipsJS_hide').html(ips.templates.render('nearMe',{events:events.join('')}));}});}(jQuery));;
;(function($){"use strict";ips.controller.register('calendar.front.overview.search',{initialize(){this.on('click','[data-action="useMyLocation"]',this.useMyLocation);this.on('click','[data-action="cancelLocation"]',this.cancelLocation);this.on('submit',this.doSearch);this.on(document,'click','[data-action="backToOverview"]',this.backToOverview);this.on(document,'click','[data-action="loadMoreSearch"]',this.loadMore);this.on(document,'menuItemSelected','#elSortMenu',this.changeSort);this.on(document,'click','[data-action="moreNearMe"]',this.moreNearMe);this.on(document,'click','[data-action="moreExhibitions"]',this.moreExhibitions);this.on(window,'historychange:calendarSearch',this.stateChange);this.setup();},setup(){this._gotCoords=false;this._offset=0;this._limit=20;this._currentSort=$('body').find('#elSortMenu_menu [aria-selected="true"]').attr('data-ipsMenuValue');this._baseURL=this.scope.attr('action');this._initialURL=window.location.href;this._cancelledLookup=false;this._searchBox=this.scope.find('input[name="location"]');this._previousValue=this._searchBox.val();this._originalPlaceholder=this.scope.attr('data-placeholder');this._locationLink=this.scope.find('[data-action="useMyLocation"]');this._cancelLocationLink=this.scope.find('[data-action="cancelLocation"]');this._page=this.scope.closest('[data-role="eventsPage"]');this._resultsContainer=$('body').find('[data-role="searchResults"]');this._noResults=$('body').find('[data-role="noSearchResults"]');this._loadMore=$('body').find('[data-action="loadMoreSearch"]');this._noMore=$('body').find('[data-role="noMoreSearchResults"]');this._map=null;this._mapContainer=$('body').find('[data-role="searchResultsMap"]');this._markers={};this.getInitialLocation();if(ips.getSetting('mapProvider')==='google'){this.setupGoogle();}else if(ips.getSetting('mapProvider')==='mapbox'){this.setupMapbox();}else{this._mapContainer.hide();}},setupGoogle(){this._mapReady=true;Debug.log(this._resultsContainer.find('[data-eventid]'));Debug.log(this._mapContainer.attr('data-markers'));if(this._resultsContainer.find('[data-eventid]').length&&this._mapContainer.attr('data-markers')){Debug.log('here');try{var markers=JSON.parse(this._mapContainer.attr('data-markers'));Debug.log(markers);this._updateGoogleMap(markers);}catch(err){Debug.log("Invalid marker JSON");Debug.log(err);}}},setupMapbox(){$('head').append`
<link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css'>
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.css' rel='stylesheet' />
<link href='https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/MarkerCluster.Default.css' rel='stylesheet' />
<link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/plugins/leaflet-fullscreen/v1.0.1/leaflet.fullscreen.css' />`;ips.loader.get(['https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js']).then(()=>{ips.loader.get(['https://api.mapbox.com/mapbox.js/plugins/leaflet-markercluster/v1.0.0/leaflet.markercluster.js','https://api.mapbox.com/mapbox.js/plugins/leaflet-fullscreen/v1.0.1/Leaflet.fullscreen.min.js']).then(()=>{this._mapReady=true;if(this._resultsContainer.find('[data-eventid]').length&&this._mapContainer.attr('data-markers')){try{const markers=JSON.parse(this._mapContainer.attr('data-markers'));this._updateMapboxMap(markers);}catch(err){Debug.log("Invalid marker JSON");Debug.log(err);}}});});},getInitialLocation(){if(ips.utils.geolocation.getGeolocationIsAllowed()){ips.utils.geolocation.getCurrentPosition().then(coords=>{this.setCoords(coords.latitude,coords.longitude);})
this.setSearchToLocation();this._locationLink.prop('hidden',true);this._cancelLocationLink.prop('hidden',false);}},setCoords(lat,long){this.scope.prepend("<input type='hidden' name='lat' value='"+lat+"'>");this.scope.prepend("<input type='hidden' name='lon' value='"+long+"'>");this._gotCoords=true;},clearCoords(){this.scope.find('input[name="lat"]').remove();this.scope.find('input[name="lon"]').remove();this._gotCoords=false;},moreNearMe(e){e.preventDefault();var lat=$(e.currentTarget).attr('data-lat');var long=$(e.currentTarget).attr('data-long');var self=this;this.setSearchToLocation();this.scope.find('[name="date[start]"]').val('');this.scope.find('[name="date[end]"]').val('');this.scope.find('[name="show"]').val('regular');$("html, body").animate({scrollTop:"300px"},function(){self.doSearch();});},moreExhibitions(e){e.preventDefault();this.cancelLocation();this.scope.find('[name="date[start]"]').val('');this.scope.find('[name="date[end]"]').val('');this.scope.find('[name="show"]').val('exhibitions');$("html, body").animate({scrollTop:"300px"},()=>{this.doSearch();});},doSearch(e){e?.preventDefault()
const url=this._getUrlFromData();ips.utils.history.replaceState({controller:'calendar.front.overview.search',url},'calendarSearch',url);},getPlaceholders(count){let events='';count=typeof count==='number'?10:count;for(let i=0;i<count;i++){events+=ips.templates.render('eventLoading');}
return events;},stateChange(){if(!('calendarSearch'in ips.utils.history.getState())&&this._initialURL!==window.location.href){return;}
const state=ips.utils.history.getState('calendarSearch')
if(this._initialURL===state?.url){this.hideResults();}else if(this._initialURL===window.location.href&&state?.url===undefined){this._loadResults(this._getUrlFromData(this._initialData));}else{this._loadResults(state?.url);}},changeSort(e,data=e.detail){e.preventDefault();this._currentSort=data.selectedItemID;const title=$(data.menuElem).find('[data-ipsMenuValue="'+this._currentSort+'"]').text();$('body').find('[data-role="searchOrder"]').text(title);this.doSearch();},_getUrlFromData(){const formData=this.scope.serializeArray();const params=[];formData.forEach(function(item){if((item.value||'').trim()!==''){params.push(item.name+"="+encodeURIComponent(item.value));}});params.push("sortBy="+this._currentSort);if(this._baseURL.match(/\?/)){if(!this._baseURL.endsWith('?')){this._baseURL+='&';}}else{this._baseURL+='?';}
return this._baseURL+params.join('&');},async _loadResults(url){if(this._page.length){this._page.find('[data-role="eventsOverview"]').hide();this._page.find('[data-role="searchResultsWrapper"]').show();}
this._resultsContainer.removeClass('ipsHide').html(this.getPlaceholders(6));if(ips.getSetting('mapProvider')!=='none'){this._mapContainer.addClass('cEvents__searchMap--loading').show();}
this._currentUrl=url;const response=await ips.fetch(url);if(response.count){this._resultsContainer.html(response.content);this._noResults.addClass('ipsHide');this._updateMap({...this._markers,...response.markers});if(response.totalCount>(response.count+this._offset)){this._loadMore.show();this._noMore.hide();}else{this._loadMore.hide();this._noMore.hide();}}else{this._resultsContainer.html('').addClass('ipsHide');this._noResults.removeClass('ipsHide');this._loadMore.hide();this._noMore.hide();this._mapContainer.hide();}
if(response.virtual||!response.markerCount){this._mapContainer.hide();}
$(document).trigger('contentChange',[this._resultsContainer]);},_updateMap(markers){if(ips.getSetting('mapProvider')==='google'){this._updateGoogleMap(markers);}else if(ips.getSetting('mapProvider')==='mapbox'){this._updateMapboxMap(markers);}else{this._mapContainer.hide();}},_updateGoogleMap(markers){if(!this._map){this._map=new window.google.maps.Map(document.querySelector('[data-role="searchResultsMap"]'));this._mapMarkers=[];}
this._mapContainer.removeClass('cEvents__searchMap--loading');if(this._mapMarkers.length){for(let marker of Object.values(this._mapMarkers)){marker.setMap(null);}
this._mapMarkers=[];}
const bounds=new google.maps.LatLngBounds();for(let marker of Object.values(markers)){let mapMarker=new window.google.maps.Marker({position:{lat:marker.lat,lng:marker.long},map:this._map,title:marker.title});this._mapMarkers.push(mapMarker);const coords=new google.maps.LatLng(marker.lat,marker.long);if(!(bounds.contains(coords))){bounds.extend(coords);}}
if(this._mapMarkers.length===1){this._map.setZoom(15);this._map.setCenter(bounds.getCenter());}else{this._map.fitBounds(bounds);}
this._mapContainer.show();},_updateMapboxMap(markers){if(!this._map){L.mapbox.accessToken=ips.getSetting('mapApiKey');this._map=L.mapbox.map(this._mapContainer.get(0)).addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));this._map.zoomControl=false;this._map.minZoom=2;this._map.dragging=false;this._map.zoomControl=false;this._markersGroup=new L.featureGroup([]);this._markersGroup.addTo(this._map);}
this._mapContainer.removeClass('cEvents__searchMap--loading');this._markersGroup.clearLayers();for(let id in markers){const marker=L.marker([markers[id].lat,markers[id].long],{title:markers[id].title,draggable:false,eventId:parseInt(id)});this._markersGroup.addLayer(marker);marker.on('click',this._markerClick.bind(this));}
this._mapContainer.show();this._map.fitBounds(this._markersGroup.getBounds(),{maxZoom:5});},_markerClick(e){const targetEvent=e.target.options.eventId;const eventBlock=this._resultsContainer.find('[data-eventId="'+targetEvent+'"]');const topPos=eventBlock.offset().top;$('html, body').animate({scrollTop:topPos},function(){eventBlock.css({transform:'scale(1.1)'});setTimeout(function(){eventBlock.css({transform:'scale(1)'});},2000);});},async loadMore(e){e.preventDefault();const placeholders=this.getPlaceholders(2);this._resultsContainer.append(placeholders);this._loadMore.prop('disabled',true);const currentCount=this._resultsContainer.find('[data-eventid]').length;const response=await ips.fetch(this._currentUrl+"&offset="+currentCount+"&limit="+this._limit);this._resultsContainer.find('.ipsData__item--loading').remove();this._resultsContainer.append(response.content);this._updateMap(response.markers);this._loadMore.prop('disabled',false);if(this._resultsContainer.find('[data-eventid]').length>=response.totalCount){this._loadMore.hide();this._noMore.show();}else{this._loadMore.show();this._noMore.hide();}
$(document).trigger('contentChange',[this._resultsContainer]);},cancelLocation(e){e?.preventDefault()
ips.utils.geolocation.setGeolocationIsAllowed(ips.utils.geolocation.permissions.DENIED);this._cancelledLookup=true;this._searchBox.val(this._previousValue).attr('placeholder',this._originalPlaceholder).prop('disabled',false).removeClass('ipsField_loading');this._locationLink.prop('hidden',false);this._cancelLocationLink.prop('hidden',true);this.scope.find('[name="searchNearLocation"]').remove();},useMyLocation(e){e.preventDefault();this._cancelledLookup=false;this._searchBox.val('').attr('placeholder',ips.getString('event_finding_location')).prop('disabled',true).addClass('ipsField_loading');this._locationLink.prop('hidden',true);this._cancelLocationLink.prop('hidden',false);const afterCoords=()=>{if(this._cancelledLookup){this._cancelledLookup=false;return;}
this.setSearchToLocation();this._cancelledLookup=false;};if(this._gotCoords){afterCoords()}else{ips.utils.geolocation.getCurrentPosition().then(coords=>{this.setCoords(coords.latitude,coords.longitude);this.setSearchToLocation();});}},setSearchToLocation(){this._searchBox.val('').attr('placeholder',ips.getString('event_your_current_location')).prop('disabled',true).removeClass('ipsField_loading');this.scope.prepend("<input type='hidden' name='searchNearLocation' value='1'>");},backToOverview(e){if(!this._page.length){return;}
e.preventDefault();ips.utils.history.replaceState({controller:'calendar.front.overview.search',url:this._initialURL},'calendarSearch',this._initialURL);},hideResults(){this._page.find('[data-role="eventsOverview"]').show();this._page.find('[data-role="searchResultsWrapper"]').hide();}});}(jQuery));;