;(function($){"use strict";ips.controller.register('core.front.search.filters',{initialize:function(){this.on('click','[data-action="showFilters"]',this.showFilters);this.on('click','[data-action="searchByTags"]',this.toggleSearchFields);this.on('click','[data-action="searchByAuthors"]',this.toggleSearchFields);this.on('click','[data-action="cancelFilters"]',this.cancelFilters);this.on('ips:refreshTogglesDone',this.toggleFilterByCounts);this.on('itemClicked.sideMenu','[data-filterType="dateCreated"]',this.filterDate);this.on('itemClicked.sideMenu','[data-filterType="dateUpdated"]',this.filterDate);this.on('itemClicked.sideMenu','[data-filterType="joinedDate"]',this.filterDate);this.on('change','[name^="search_min_"]',this.changeValue);this.on('tokenDeleted tokenAdded',this.tokenChanged);this.on('resultsLoading.search',this.resultsLoading);this.on('resultsDone.search',this.resultsDone);this.on('cancelResults.search',this.cancelResults);this.on('submit',this.submitForm);this.on('tabShown',this.tabShown);this.on('nodeInitialValues',this.setup);if(!this.scope.find('[data-role="hints"] ul li').length){this.scope.find('[data-role="hints"]').hide();}
this.setup();},setup:function(){var data=this.scope.find('form').serializeArray();this.trigger('initialData.search',{data:data});this.toggleFilterByCounts();},toggleFilterByCounts:function(){const searchTitleEl=document.getElementById('elSearch_filter_by_number');if(!searchTitleEl){return;}
const searchByNumberOptions=document.querySelector("#elSearch_filter_by_number + ul");if(!searchByNumberOptions||!searchByNumberOptions.querySelector(':scope > :not([hidden])')){searchTitleEl.hidden=true;}else{searchTitleEl.hidden=!this.elem.querySelector('input[name="type"]:checked').value;}},cancelResults:function(){this.showFilters();this.scope.find('[data-role="hints"]').remove();this.scope.find('#elMainSearchInput').val('').trigger('focus');this.scope.find('[data-action="cancelFilters"], [data-action="searchAgain"]').hide();},changeValue:function(e){var field=$(e.currentTarget);var name=field.attr('name');var bubble=this.scope.find('[data-role="'+name+'_link"] [data-role="fieldCount"]');if(field.val()==0){bubble.text('0').addClass('ipsHide');}else{bubble.text(field.val()).removeClass('ipsHide');}},tokenChanged:function(e,data){var tags=this.scope.find('#elInput_tags_wrapper li.cToken');var term=this.scope.find('input[name="q"]');var andOr=this.scope.find('[data-role="searchTermsOrTags"]');if(tags.length&&term.val()&&!andOr.is(':visible')){andOr.slideDown();}else if((!tags.length||!term.val())&&andOr.is(':visible')){andOr.slideUp();}},tabShown:function(e,data){if(data.tabID=='ipsTabs_search_searchMembers'){this.scope.find('input[name="type"][value="core_members"]').prop('checked',true).trigger('change').end().find('[data-action="updateResults"]').text(ips.getString('searchMembers'));}else{this.scope.find('[data-role="searchApp"] .ipsSideMenu_itemActive input[type="radio"]').prop('checked',true).trigger('change').end().find('[data-action="updateResults"]').text(ips.getString("searchContent"));}},cancelFilters:function(e){var self=this;this.scope.find('[data-role="searchFilters"]').slideUp('fast',function(){self.scope.find('[data-action="showFilters"]').slideDown();});},showFilters:function(e){if(e){e.preventDefault();}
this.scope.find('[data-action="showFilters"]').hide();this.scope.find('[data-role="searchFilters"]').slideDown();$(document).trigger('contentChange',[this.scope]);},resultsDone:function(e,data){var searchButton=this.scope.find('[data-action="updateResults"]');searchButton.prop('disabled',false).text(searchButton.attr('data-originalText'));this.scope.find('[data-role="searchFilters"]').hide();this.scope.find('[data-action="showFilters"]').removeClass('ipsHide').show();this.scope.find('[data-action="searchAgain"]').removeClass('ipsHide ipsButton--disabled').show();if(data.hints!==undefined){this.scope.find('[data-role="hints"]').html(data.hints).show();}
if(!this.scope.find('[data-role="hints"] ul li').length){this.scope.find('[data-role="hints"]').hide();}
$(document).trigger('contentChange',[this.scope]);},resultsLoading:function(e,data){var searchButton=this.scope.find('[data-action="updateResults"]');this.scope.find('[data-action="searchAgain"]').addClass('ipsButton--disabled');searchButton.prop('disabled',true).attr('data-originalText',searchButton.text()).text(ips.getString("searchFetchingResults"));},toggleSearchFields:function(e){e.preventDefault();var link=$(e.currentTarget);var opens=link.attr('data-opens').split(',');var i;for(i=0;i<opens.length;i++){this.scope.find('[data-role="'+opens[i]+'"]').slideDown(function(){if(!link.closest('ul').find('li').length){link.closest('ul').remove();}
$(this).find('input[type="text"]').trigger('focus');});}
link.closest('li').hide();},filterDate:function(e,data){var elem=$(e.currentTarget);if(data.selectedItemID=='custom'){elem.find('[data-role="dateForm"]').slideDown();}else{elem.find('[data-role="dateForm"]').slideUp();}},submitForm:function(e){e.preventDefault();this.scope.find('#elMainSearchInput').trigger('blur');var self=this;var app=this.scope.find('[data-role="searchApp"] .ipsSideMenu_itemActive');var appKey=app.attr('data-ipsMenuValue');var appTitle=app.find('[data-role="searchAppTitle"]').text();var isMemberSearch=$('#ipsTabs_search_searchMembers').attr('aria-selected')=='true';var searchTerm=this.scope.find('#elMainSearchInput').val().trim();var tagExists=(this.scope.find('#elInput_tags').length&&this.scope.find('#ipsTabs_search_searchContent').attr('aria-selected')==='true');if(tagExists){var tagField=ips.ui.autocomplete.getObj(this.scope.find('#elInput_tags'));var tokens=tagField.getTokens();}
if(!isMemberSearch){if((!searchTerm&&!tagExists)||(!searchTerm&&tagExists&&tokens.length===0)){ips.ui.alert.show({type:'alert',message:(!searchTerm&&!tagExists)?ips.getString('searchRequiresTerm'):ips.getString('searchRequiresTermTags'),icon:'info',callbacks:{ok:function(){setTimeout(function(){self.scope.find('#elMainSearchInput').trigger('focus');},300);}}});return;}}
const el=document.createElement('div');const data=this.scope.find('form').serializeArray();const tagsObject=data.find(item=>item.name==='tags');if(tagsObject){el.innerHTML=tagsObject.value;tagsObject.value=el.textContent;}
this.trigger('formSubmitted.search',{data,appKey:appKey,tabType:this.scope.closest('data-tabType').attr('data-tabType'),appTitle:appTitle});}});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.front.search.main',{_content:null,_formData:{},_loadingDiv:null,_initialURL:'',_initialData:{},initialize(){this.on('initialData.search',this.initialData);this.on('formSubmitted.search',this.submittedSearch);this.on('paginationClicked paginationJump',this.paginationClicked);this.on(window,'historychange:search',this.stateChange);this.setup();},setup(){this._content=this.scope.find('#elSearch_main');this._baseURL=this.scope.attr('data-baseURL');if(this._baseURL.match(/\?/)){this._baseURL+='&';}else{this._baseURL+='?';}
if(this._baseURL.slice(-1)==='&'){this._baseURL=this._baseURL.slice(0,-1)}
this._initialURL=window.location.href;},initialData(e,data){this._formData=this._getFormData(data.data);this._initialData={...this._formData};},stateChange(){const state={data:ips.utils.history.getState('search'),url:window.location.href};if(this._initialURL===state.url&&!Object.keys(state.data).length){this._cancelSearch();}else if(this._initialURL===state.url&&state.data.url===undefined){this._loadResults(this._getUrlFromData(this._initialData));}else{this._loadResults(state.data.url);}},submittedSearch(e,data){this._formData=this._getFormData(data.data);const url=this._getUrlFromData(this._formData);try{if(IpsDataLayerContext&&!window.IpsDataLayerContext){let unique='';let self=this;Object.keys(this._formData).sort().forEach(function(index){let value=self._formData[index];if(value.join){value=value.join();}
if(value.toString){value=value.toString();}
if(value&&(typeof value==='string')){unique+=value;}});$('body').trigger('ipsDataLayer',{_key:'search',_properties:{query:this._formData.q||null},_uniquekeys:{'key':unique}});}}catch(e){}
ips.utils.history.pushState({controller:'core.front.search.main',url:url,filterData:this._formData},'search',url);document.title=this._getBrowserTitle();},_cancelSearch(){var results=this.scope.find('[data-role="filterContent"]');var blurb=this.scope.find('[data-role="searchBlurb"]');ips.controller.cleanContentsOf(results);this.triggerOn('core.front.search.filters','cancelResults.search');results.html('');blurb.html('').hide();},_getUrlFromData(data){var params=[];for(const val of['q','type','page','quick']){if(data[val]!==undefined&&data[val]!==''){params.push(val+'='+encodeURIComponent(data[val]));}};if(data['type']==='core_members'){if(data['joinedDate']!==undefined){if(data['joinedDate']!=='custom'){params.push('joinedDate='+data['joinedDate']);}else{if(data['joinedDateCustom[start]']!==undefined){params.push('start_after='+encodeURIComponent(new Date(data['joinedDateCustom[start]']).getTime()/1000));}
if(data['joinedDateCustom[end]']!==undefined){params.push('start_before='+encodeURIComponent(new Date(data['joinedDateCustom[end]']).getTime()/1000));}}}
if(data['group']!==undefined){if(!Array.isArray(data['group'])){data['group']=[data['group']];}
for(var i=0;i<data['group'].length;i++){params.push('group['+data['group'][i]+']=1');}}
for(const[key,val]of Object.entries(data)){if(!key.startsWith('core_pfield')||val===0||val===''){continue;}
params.push(key+'='+val);};}else{for(const val of['item','author','search_min_replies','search_min_views','search_min_comments','search_min_reviews']){if(data[val]!==undefined&&data[val]!==''&&parseInt(data[val])!==0){if(val==='author'){params.push(val+'='+encodeURIComponent(data[val]));continue;}
params.push(val+'='+data[val]);}};if(data['tags']!==undefined){params.push('tags='+encodeURIComponent(data['tags'].replace(/\n/g,',')));}
if(data[data['type']+'_node']!==undefined){params.push('nodes='+data[data['type']+'_node']);}
else if(data['nodes']!==undefined){params.push('nodes='+data['nodes'].replace(/\n/g,','));}
if(data['club[]']!==undefined){if(Array.isArray(data['club[]'])){params.push('club='+data['club[]'].filter(function(v){return v!=='__EMPTY';}));}else if(data['club[]'].replace('__EMPTY','')){params.push('club='+data['club[]'].replace('__EMPTY',''));}}
if(data['eitherTermsOrTags']!==undefined){if(data['q']!==undefined&&data['q'].trim()!==''&&data['tags']!==undefined&&data['tags'].trim()!==''){params.push('eitherTermsOrTags='+data['eitherTermsOrTags']);}}
if(data['search_and_or']!==undefined&&(data['search_and_or']==='or'||data['search_and_or']==='and')){params.push('search_and_or='+data['search_and_or']);}
if(data['search_in']!==undefined&&data['search_in']==='titles'){params.push('search_in='+data['search_in']);}
var datesSet={startDate:false,updatedDate:false};for(const val of[['startDate','start_after'],['updatedDate','updated_after']]){if(data[val[0]]!==undefined){if(data[val[0]]!=='any'&&data[val[0]]!=='custom'){params.push(val[1]+'='+data[val[0]]);datesSet[val[0]]=true;}else if(data[val[0]]==='any'){datesSet[val[0]]=true;}}};for(const val of[['startDateCustom[start]','start_after'],['startDateCustom[end]','start_before'],['updatedDateCustom[start]','updated_after'],['updatedDateCustom[end]','updated_before']]){var thisType=(val[0].indexOf('startDate')!==-1)?'startDate':'updatedDate';if(data[val[0]]!==undefined&&!datesSet[thisType]){if((val[0]==='startDateCustom[start]'||val[0]==='startDateCustom[end]')&&data['startDate']!==undefined&&data['startDate']==='any'){}else if((val[0]==='updatedDateCustom[start]'||val[0]==='updatedDateCustom[end]')&&data['updatedDate']!==undefined&&data['updatedDate']==='any'){}else{params.push(val[1]+'='+encodeURIComponent(ips.utils.time.getDateFromInput($('[name="'+val[0]+'"]')).getTime()/1000));}}};}
if(data['sortby']!==undefined){params.push('sortby='+data['sortby']);}
if(data['sortdirection']!==undefined){params.push('sortdirection='+data['sortdirection']);}
return this._baseURL+'&'+params.join('&');},async _loadResults(url){this.triggerOn('core.front.search.filters','resultsLoading.search');this._setContentLoading(true);try{const response=await ips.fetch(url)
if(typeof response!=='object'){window.location=url;}
if(response.css){this._addCSS(response.css);}
this.triggerOn('core.front.search.filters','resultsDone.search',{contents:response.filters,hints:response.hints});this._content.html(response.content);$(document).trigger('contentChange',[this._content]);this.scope.find('[data-role="searchBlurb"]').show().html(response.title);this.scope.find('[data-action="cancelFilters"]').show();const newItems=this.scope.find('[data-role="resultsArea"] [data-role="activityItem"]').css({opacity:"0"});const delay=100;newItems.slideDown(function(){newItems.each(function(index){var d=(index*delay);$(this).delay((d>1200)?1200:d).animate({opacity:"1"});});});}catch(e){window.location=url;}
this._setContentLoading(false);},paginationClicked(e,data){if(data.originalEvent){data.originalEvent.preventDefault();}
this._formData['page']=data.pageNo;const url=this._getUrlFromData(this._formData);ips.utils.history.pushState({controller:'core.front.search.main',url},'search',url);const elemPosition=ips.utils.position.getElemPosition(this.scope);$('html, body').animate({scrollTop:elemPosition.absPos.top+'px'});},_getFormData(data){if(typeof data!=='object'||data===null){return;}
var returnData={};var skipData=['page','csrfKey'];for(var i=0;i<data.length;i++){if((skipData).indexOf(data[i].name)===-1&&data[i].value!==''){if(returnData[data[i].name]!==undefined&&!Array.isArray(returnData[data[i].name])){var tmp=returnData[data[i].name];returnData[data[i].name]=[];returnData[data[i].name].push(tmp);}
if(returnData[data[i].name]!==undefined){returnData[data[i].name].push(data[i].value);}else{returnData[data[i].name]=data[i].value;}
if(data[i].name!=='club[]'){if($('#'+data[i].name+'-unlimitedCheck').length){if(!$('#'+data[i].name+'-unlimitedCheck:checked').length){returnData[data[i].name]=$('input[type=number][name='+data[i].name+']').val();}
else
{delete(returnData[data[i].name]);}}}}}
if(data['type']!==undefined&&data['type']!=='core_members'){if(data['sortby']!==undefined){delete(data['sortby']);}
if(data['sortdirection']!==undefined){delete(data['sortdirection']);}}
return returnData;},_getBrowserTitle(){var title=ips.getString('searchTitle');var currentType=this.scope.find('input[type="radio"][name="type"]:checked');var q=this._formData['q'];if(q===undefined){q='';}
if(q!==''&&!currentType.length){title=ips.getString('searchTitleTerm',{term:q});}else if(q!==''&&currentType.length){title=ips.getString('searchTitleTermType',{term:q,type:currentType.next('[data-role="searchAppTitle"]').text()});}else if(q===''&&this._currentType!==''){title=ips.getString('searchTitleType',{type:currentType.next('[data-role="searchAppTitle"]').text()});}
return title;},_addCSS(css){var head=$('head');if(css&&css.length){for(var i=0;i<css.length;i++){head.append($('<link/>').attr('href',css[i]).attr('type','text/css').attr('rel','stylesheet'));}}},_setContentLoading(state){var results=this.scope.find('[data-role="resultsContents"]');if(!results.length){if(this._loadingDiv){this._loadingDiv.hide();}
return;}
var dims=ips.utils.position.getElemDims(results);var position=ips.utils.position.getElemPosition(results);if(!this._loadingDiv){this._loadingDiv=$('<div/>').append($('<div/>').css({height:Math.min(200,results.outerHeight())+'px'}).addClass('ipsLoading'));ips.getContainer().append(this._loadingDiv);}
this._loadingDiv.show().css({left:position.viewportOffset.left+'px',top:position.viewportOffset.top+$(document).scrollTop()+'px',width:dims.width+'px',height:dims.height+'px',position:'absolute',zIndex:ips.ui.zIndex()})
if(state){results.animate({opacity:"0.6"}).css({height:results.height()+'px'});}else{results.css({height:'auto',opacity:"1"});this._loadingDiv.hide();}}});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.front.search.results',{_resultLength:300,_terms:[],_minTermLength:3,initialize:function(){this.setup();this.on(document,'contentChange',this.contentChange);},setup(){const self=this;try{this._terms=JSON.parse(this.scope.attr('data-term'));if(!Array.isArray(this._terms)){throw new TypeError(`The 'data-term' attribute is expected to be a JSON-encoded array of strings.`);}
this._terms=this._terms.map(term=>term.trim()).filter(term=>term.length>=this._minTermLength);}catch(err){Debug.log("Error parsing search terms");return;}
this._regex=this.compileRegex(this._terms);if(window.CSS&&CSS.highlights){if(!(window.RegExp.escape instanceof Function)){window.RegExp.escape=str=>str.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');}
this._lowercaseTerms=this._terms.map(t=>t.toLowerCase());this.highlight=CSS.highlights.get('search-results');if(!this.highlight){this.highlight=new Highlight();CSS.highlights.set('search-results',this.highlight);}
this.highlight.clear();}
this.scope.find('[data-role="activityItem"]').each(function(){self._processResult($(this));});},contentChange:function(){var self=this;this.scope.find('[data-role="activityItem"]').each(function(){self._processResult($(this));});},_processResult:function(result){if(result.attr('data-processed')){return;}
var findWords=result.find('[data-findTerm]');if(findWords.length){this._findWords(findWords);}
if(window.CSS&&CSS.highlights){result[0].querySelectorAll('[data-searchable]').forEach(el=>{this._highlight(el);});}
result.attr('data-processed',true);},_findWords:function(result){var text=result.text().trim();var firstMatch=text.length;var startPoint=0;var foundMatches=false;for(var i=0;i<this._terms.length;i++){var indexOf=text.search(new RegExp(ips.utils.escapeRegexp(this._terms[i]),'i'));if(indexOf!==-1){foundMatches=true;if(indexOf<firstMatch){firstMatch=indexOf;}}}
var punctuationMarks=['.',',','?','!'];var searchBack=(firstMatch-(this._resultLength/2)<0)?0:firstMatch-(this._resultLength/2);if(!foundMatches){startPoint=0;}else{for(var j=firstMatch;j>searchBack;j--){if(punctuationMarks.indexOf(text[j])!==-1){startPoint=j+1;break;}}}
var finalSnippet=text.substring(startPoint,startPoint+300).trim();if(startPoint>0&&foundMatches){finalSnippet='...'+finalSnippet;}
if(startPoint+this._resultLength<text.length||(!foundMatches&&text.length>this._resultLength)){finalSnippet=finalSnippet+'...';}
result.text(finalSnippet);},compileRegex:function(terms){return new RegExp(`\\b(${terms.map(t => RegExp.escape(t.trim())).join('|')})\\w*`,'ig');},findRangesInNode:function(root){const ranges=[];const regex=this._regex;const walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT);let node;while((node=walker.nextNode())){const parent=node.parentElement;if(parent&&parent.offsetParent===null){continue;}
regex.lastIndex=0;let match;while((match=regex.exec(node.nodeValue))!==null){const range=new Range();range.setStart(node,match.index);range.setEnd(node,match.index+match[0].length);ranges.push(range);}}
return ranges;},_highlight(root){this.findRangesInNode(root).forEach(range=>{this.highlight.add(range);});}});}(jQuery));;