ips.templates.set('lego.clubs.loadingRows'," <li class='ipsDataItem ipsDataItem_loading legoClubRow_loading'>  <div>   <span></span>   <span></span>  </div> </li>");ips.templates.set('lego.clubs.noLocationMatch'," <li class='ipsType_light'>No locations found</li>");ips.templates.set('lego.clubs.noTitleMatch'," <li class='ipsType_light'>No communities or events found</li>");ips.templates.set('lego.clubs.searchError'," <li class='ipsType_light'>Sorry, there was an error searching</li>");ips.templates.set('lego.clubs.locationRow'," <li data-role='locationMatch' data-corner1='{{corner1}}' data-corner2='{{corner2}}' class='legoMapbox_locationResult'>{{placeName}}</li>");ips.templates.set('lego.clubs.titleRow'," <li data-role='titleMatch' data-lat='{{lat}}' data-long='{{long}}' data-url='{{url}}' class='{{typeClass}}'>{{placeName}}</li>");ips.templates.set('lego.clubs.noLocationRows'," <p class='ipsType_normal ipsType_light ipsType_large ipsType_center ipsSpacer_both ipsSpacer_double'>  {{#lang}}noLocationRows{{/lang}} </p>");ips.templates.set('lego.clubs.noOnlineRows'," <p class='ipsType_normal ipsType_light ipsType_large ipsType_center ipsSpacer_both ipsSpacer_double'>  {{#lang}}noOnlineRows{{/lang}} </p>");ips.templates.set('lego.clubs.showMore'," <div data-role='loadMoreResults' data-page='{{page}}' data-type='{{type}}'>  <a href='#' class='ipsPad ipsType_center ipsType_normal legoClubsLoadMore'>See more results...</a> </div>");ips.templates.set('lego.clubs.clubHeader'," <div class='ipsClearfix'>  <div class='ipsType_normal'>   <a href='#' data-role='backToResults' data-type='{{type}}'><i class='fa fa-angle-left'></i> Back to results</a>  </div> </div> <hr class='ipsHr'> <div class='ipsPad ipsAreaBackground'>  <div class='ipsPad ipsAreaBackground_reset'>");ips.templates.set('lego.clubs.clubFooter',"  </div> </div>");;
;(function($,_,undefined){"use strict";ips.controller.register('lego.front.clubs.clubDirectory',{_mapReady:false,_map:null,_timer:null,_keypressTimeout:null,_lastQuery:'',_ajax:null,_titleAjax:null,_perPage:20,_ignoreMapMovement:false,_currentLanguage:null,_dialog:null,_initialURL:null,initialize:function(){this.on('click','#legoGeolocate',this.geoLocate);this.on('submit','#search_lugs',this.submitSearch);this.on('focus','#search_lugs',this.focusSearch);this.on('blur','#search_lugs',this.blurSearch);this.on('click','[data-role="locationMatch"]',this.clickLocationMatch);this.on('click','[data-role="titleMatch"]',this.clickTitleMatch);this.on('click','[data-role="clearSearch"]',this.showAllClubs);this.on('click','[data-role="loadMoreResults"]',this.loadMoreResults);this.on('click','[data-role="showAllClubs"]',this.showAllClubs);this.on('change','#select_language',this.selectLanguage);this.on('tabShown','#tabs_clubDirectory',this.tabShown);this.on('click','[data-role="viewResult"]',this.viewResult);this.on(window,'resize',this.positionResultsPopup)
this.on(document,'hideDialog',this.hideDialog);this.on(window,'statechange',this.stateChange);this.setup();},setup:function(){var self=this;this._initialURL=window.location.href;$('head').append("<link rel='stylesheet' type='text/css' media='all' href='https://api.mapbox.com/mapbox.js/v3.1.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.1.1/mapbox.js']).then(function(){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(function(){self._setUpMap();self._setUpMapEvents();self._mapReady=true;});});if(!navigator.geolocation){this.scope.find('#legoGeolocate').hide();}},stateChange:function(e){var state=History.getState();if(this._dialog){try{this._dialog.hide();}catch(err){}}
if(_.isUndefined(state.data.controller)||state.data.controller!='locator'){return;}
Debug.log(state.data);switch(state.data.do){case'openResult':this._openResult(state.data.lat,state.data.long,state.data.url,state.data.target||null);break;}},hideDialog:function(e,data){if(this._dialog&&data.dialogID==this._dialog.dialogID){History.replaceState({controller:'locator'},document.title,this._initialURL);}},viewResult:function(e){e.preventDefault();var lat=null;var long=null;var url=$(e.currentTarget).attr('href')+"?preview=1";var result=$(e.currentTarget).closest('[data-role="resultRow"]');if(!_.isUndefined(result.attr('data-lat'))){var lat=parseFloat(result.attr('data-lat'));var long=parseFloat(result.attr('data-long'));}
History.pushState({controller:'locator',do:'openResult',lat:lat,long:long,url:url,target:$(e.currentTarget).identify().attr('id')},document.title,url);},_openResult:function(lat,long,url,showFrom){var self=this;if(self._dialog){try{self._dialog.hide();}catch(err){}}
this._viewAjax=ips.getAjax()(url,{}).done(function(response){self._dialog=ips.ui.dialog.create({url:url,size:'medium',showFrom:(showFrom)?$('#'+showFrom):false,close:true,destructOnClose:true});self._dialog.show();var dialogElem=$('#'+self._dialog.dialogID);dialogElem.addClass('legoDialog');}).fail(function(){window.location=url;});},tabShown:function(e,data){if(data.tabID=='clubDirectory_tab_physical'&&this._map){try{this._map.invalidateSize();}catch(err){}}},focusSearch:function(e){if(!this._mapReady){Debug.log('map not ready');return;}
clearTimeout(this._keypressTimeout);this._keypressTimeout=setInterval(_.bind(this._doSearch,this),300);if($.trim(this.scope.find('#search_map').val())!==''){this._openResultsList();}else{this.scope.find('[data-role="clearSearch"]').animate({opacity:0});}},blurSearch:function(e){clearTimeout(this._keypressTimeout);},submitSearch:function(e){e.preventDefault();},clearSearch:function(e){if(e){e.preventDefault();}},selectLanguage:function(e){var language=$(e.currentTarget).val();this._currentLanguage=language;this._loadOnlineCommunities();},_loadOnlineCommunities:function(){var self=this;if(this._ajax&&_.isFunction(this._ajax.abort)){this._ajax.abort();}
this._setResultsLoading(1,'online');this._ajax=ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=clubs&controller=directory',{data:{language:self._currentLanguage}}).done(function(response){self.scope.find('[data-role="onlineRecordsFound"]').show().text(ips.pluralize(ips.getString('legoCountOnline'),response.count));if(parseInt(response.count)<1){self.scope.find('[data-role="onlineResultsContainer"]').html(ips.templates.render('lego.clubs.noOnlineRows'));return;}
var html=[];for(var i=0;i<response.results.length;i++){html.push(response.results[i].html);}
self.scope.find('[data-role="onlineResultsContainer"]').html(html.join(''));});},_doSearch:function(){var self=this;var query=$.trim(this.scope.find('#search_map').val());if(this._lastQuery==query||query==''){return;}
this.positionResultsPopup();this.scope.find('[data-role="clearSearch"]').animate({opacity:1});this._lastQuery=query;var geocoder=L.mapbox.geocoder('mapbox.places',{types:'country,region,postcode,district,place,locality,neighborhood,address'});geocoder.query(query,_.bind(this._showLocations,this));if(this._titleAjax&&_.isFunction(this._titleAjax.abort)){this._titleAjax.abort();}
this.scope.find('[data-role="titleResults"]').html("<li><span class='ipsType_light'>Searching...</span></li>");this._titleAjax=ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=clubs&controller=directory&do=fetchByTitle',{data:{title:encodeURIComponent(query)}}).done(function(response){var results=[];if(!response.length){self.scope.find('[data-role="titleResults"]').html(ips.templates.render('lego.clubs.noTitleMatch'));return;}
for(var i=0;i<response.length;i++){results.push(ips.templates.render('lego.clubs.titleRow',{placeName:response[i].title,lat:response[i].lat,long:response[i].long,url:response[i].url,typeClass:(response[i].type=='club')?'legoMapbox_titleResult':'legoMapbox_eventResult'}));}
self.scope.find('[data-role="titleResults"]').html(results.join(''));}).fail(function(){self.scope.find('[data-role="titleResults"]').html(ips.templates.render('lego.clubs.searchError'));});},positionResultsPopup:function(){var searchBox=this.scope.find('#search_lugs');var pos=ips.utils.position.getElemPosition(searchBox);var dims=ips.utils.position.getElemDims(searchBox);var results=this.scope.find('[data-role="searchResults"]');results.css({top:pos.offsetPos.top+dims.outerHeight+'px',left:pos.offsetPos.left+'px',width:dims.outerWidth+'px'});},_showLocations:function(err,data){var results=this.scope.find('[data-role="locationResults"]');var searchBox=this.scope.find('#search_lugs');var pos=ips.utils.position.getElemPosition(searchBox);var dims=ips.utils.position.getElemDims(searchBox);results.css({top:pos.offsetPos.top+dims.outerHeight+'px',left:pos.offsetPos.left+'px',width:dims.outerWidth+'px'});if(err||!data.results.features.length){results.html(ips.templates.render('lego.clubs.noLocationMatch'));}else{if(data.lbounds){}else if(data.latlng){}
if(data.results.features.length){var resultsList=[];for(var i=0;i<data.results.features.length;i++){if(resultsList.length==3){break;}
if((data.results.features[i].place_type&&data.results.features[i].place_type.indexOf('poi')!==-1)||(_.isUndefined(data.results.features[i].bbox))){continue;}
resultsList.push(ips.templates.render('lego.clubs.locationRow',{placeName:(data.results.features[i].matching_place_name||data.results.features[i].place_name),corner1:data.results.features[i].bbox[0]+','+data.results.features[i].bbox[1],corner2:data.results.features[i].bbox[2]+','+data.results.features[i].bbox[3]}));}
if(!resultsList.length){results.html(ips.templates.render('lego.clubs.noLocationMatch'));}else{results.html(resultsList.join(''));}}}
this._openResultsList(true);},clickLocationMatch:function(e){var corner1=$(e.currentTarget).attr('data-corner1').split(',');var corner2=$(e.currentTarget).attr('data-corner2').split(',');var bound1=L.latLng(parseFloat(corner1[1]),parseFloat(corner1[0]));var bound2=L.latLng(parseFloat(corner2[1]),parseFloat(corner2[0]));this._map.fitBounds(L.latLngBounds(bound1,bound2));var name=$(e.currentTarget).text();this.scope.find('#search_map').val(name).blur();this._closeResultsList();},clickTitleMatch:function(e){var lat=parseFloat($(e.currentTarget).attr('data-lat'));var long=parseFloat($(e.currentTarget).attr('data-long'));var url=$(e.currentTarget).attr('data-url');var name=$(e.currentTarget).text();this.scope.find('#search_map').val(name).blur();this._closeResultsList();History.pushState({controller:'locator',do:'openResult',lat:lat,long:long,url:url},document.title,url);},_openResultsList:function(immediate){this.scope.find('[data-role="searchResults"]').show();},_closeResultsList:function(){this.scope.find('[data-role="searchResults"]').hide();},geoLocate:function(e){if(e){e.preventDefault();}
if(!this._mapReady){return;}
this._map.locate();this.scope.find('#legoGeolocate').find('[data-role="button"]').hide().end().find('[data-role="loading"]').show();this._closeResultsList();},locationFound:function(e){this._map.fitBounds(e.bounds,{maxZoom:8});this.scope.find('#legoGeolocate').find('[data-role="loading"]').hide().end().find('[data-role="button"]').show();},locationError:function(e){this.scope.find('#legoGeolocate').html(this._geolocateText);ips.ui.alert.show({type:'alert',message:ips.getString('geolocationError'),icon:'warn'});},zoomStart:function(e){if(!this._ignoreMapMovement){this._closeResultsList();}},zoomEnd:function(e){if(!this._ignoreMapMovement){this._startSearchTimer();}},dragStart:function(e){if(!this._ignoreMapMovement){this._closeResultsList();}},dragEnd:function(e){if(!this._ignoreMapMovement){this._startSearchTimer();}},_startSearchTimer:function(){clearTimeout(this._timer);this._timer=setTimeout(_.bind(this._findResultsByBoundingBox,this),750);},showAllClubs:function(e){if(e){e.preventDefault();}
this._ignoreMapMovement=true;this._map.setView([45,0],2);this._ignoreMapMovement=false;if(this.scope.find('[data-role="searchResults"]:visible').length){this._closeResultsList();}
this.scope.find('#search_map').val('');this.scope.find('[data-role="clearSearch"]').animate({opacity:0});this._getResults(1,{});this.scope.find('[data-role="showAllClubs"]').hide();},_findResultsByBoundingBox:function(page){var self=this;var bounds=this._map.getBounds();var center=this._map.getCenter();if(_.isUndefined(page)){page=1;}
var data={minLon:bounds._southWest.lng,maxLon:bounds._northEast.lng,minLat:bounds._southWest.lat,maxLat:bounds._northEast.lat,centerLat:center.lat,centerLon:center.lng};this._getResults(page,data);this.scope.find('[data-role="showAllClubs"]').fadeIn();},_getResults:function(page,data){var self=this;var fetchEvents=this.scope.find('#show_events').prop('checked');var fetchGroups=this.scope.find('#show_groups').prop('checked');if(this._ajax&&_.isFunction(this._ajax.abort)){this._ajax.abort();}
this._setResultsLoading(page);this._ajax=ips.getAjax()(ips.getSetting('baseURL')+'index.php?app=core&module=clubs&controller=directory&page='+page+((fetchEvents)?'&fetchEvents=1':'')+((fetchGroups)?'&fetchGroups=1':''),{data:data}).done(function(response){var countString='legoCountBoth';countString='legoCountGroups';self.scope.find('[data-role="directoryNavigator"]').hide();self.scope.find('[data-role="recordsFound"]').show().text(ips.pluralize(ips.getString(countString),response.count));if(parseInt(response.count)<1){self.scope.find('[data-role="resultsContainer"]').html(ips.templates.render('lego.clubs.noLocationRows'));return;}
var html=[];for(var i=0;i<response.results.length;i++){html.push(response.results[i].html);}
if(response.count>(page*self._perPage)){html.push(ips.templates.render('lego.clubs.showMore',{page:page+1,type:'location'}));}
if(page==1){self.scope.find('[data-role="resultsContainer"]').html(html.join(''));}else{self.scope.find('[data-role="resultsContainer"]').find('.legoClubRow_loading').remove().end().append(html.join(''));}});},loadMoreResults:function(e){e.preventDefault();var page=$(e.currentTarget).attr('data-page');var type=$(e.currentTarget).attr('data-type');if(type=='online'){this._loadOnlineCommunities();}else{this._findResultsByBoundingBox(page);}},_setResultsLoading:function(page,type){var newRows=[];var typeRole=(type=='online')?'onlineResultsContainer':'resultsContainer';var noToBuild=this.scope.find('[data-role="'+typeRole+'"] [data-role="resultRow"]').length;if(!noToBuild){noToBuild=2;}
for(var i=0;i<noToBuild;i++){newRows.push(ips.templates.render('lego.clubs.loadingRows'));}
if(page==1){this.scope.find('[data-role="'+typeRole+'"]').html(newRows.join(''));}else{this.scope.find('[data-role="'+typeRole+'"] [data-role="loadMoreResults"]').replaceWith(newRows.join(''));}},_setUpMapEvents:function(){this._map.on('locationfound',_.bind(this.locationFound,this));this._map.on('locationerror',_.bind(this.locationError,this));this._map.on('zoomstart',_.bind(this.zoomStart,this));this._map.on('zoomend',_.bind(this.zoomEnd,this));this._map.on('dragstart',_.bind(this.dragStart,this));this._map.on('dragend',_.bind(this.dragEnd,this));},_setUpMap:function(){var mapDiv=this.scope.find('#legoMap');L.mapbox.accessToken=ips.getSetting('mapApiKey');this._map=L.mapbox.map(mapDiv.get(0),'mapbox.streets',{zoomControl:false,minZoom:2}).setView([36,0],2);L.control.zoom({position:'bottomright'}).addTo(this._map);this._map.addControl(new L.Control.Fullscreen({position:'bottomleft'}));var cluster=new L.MarkerClusterGroup();this._map.addLayer(cluster);var clubIcon=L.icon({iconUrl:ips.getSetting('clubIcon'),iconSize:[41,23],iconAnchor:[20,23],popupAnchor:[0,-30]});var markers=$.parseJSON(mapDiv.attr('data-markers'));for(var id in markers){var marker=L.marker([markers[id].lat,markers[id].long],{icon:clubIcon,typeID:id,title:markers[id].title,draggable:false})
cluster.addLayer(marker);if(mapDiv.attr('data-contentUrl')){marker.bindPopup(ips.getString('loading'));marker.on('click',_.bind(this._loadMapPopup,this));}}},_loadMapPopup:function(e){var mapDiv=this.scope.find('#legoMap');var popup=e.target.getPopup();var id=e.target.options.typeID;var pieces=id.split('-');var type=pieces[0];var realID=pieces[1];ips.getAjax()(mapDiv.attr('data-contentUrl')+realID,{data:{type:type}}).done(function(response){popup.setContent(response);popup.update();});}});}(jQuery,_));;