ips.templates.set('core.streams.teaser',`
	<li data-action='insertNewItems' class='ipsStream__loadMore' style='display: none'>
		<button>{{{words}}}</button>
	</li>
`);ips.templates.set('core.streams.unreadBar',`
	<li data-role='unreadBar' class='ipsStreamItem_bar'><hr class='ipsHr'></li>
`);ips.templates.set('core.streams.noMore',`
	<div class='ipsEmptyMessage i-padding_0' data-role="loadMoreContainer">
		{{#lang}}noMoreActivity{{/lang}}
	</div>
`);ips.templates.set('core.streams.loadMore',`
	<a href='#' class='ipsButton ipsButton--inherit' data-action='loadMore'>{{#lang}}loadNewActivity{{/lang}}</a>
`);;
;(function($){"use strict";ips.controller.register('core.front.streams.form',{loaded:{},formSnapshot:false,reloaded:false,_loadedContainer:{},_loadedClubs:false,_formData:{},initialize:function(){this.on('streamStateUpdate.streamForm',this.streamStateUpdate);this.on('itemClicked.sideMenu','[data-filterType="type"]',this.selectedType);this.on('menuItemSelected','#elStreamReadStatus, #elStreamShowMe',this.checkFormUpdate);this.on('tokenAdded tokenDeleted',this.tokensChanged);this.on('menuItemSelected','#elStreamSortEdit',this.changeSort);this.on('click','[data-action="saveStream"], [data-action="newStream"]',this.submitForm);this.on('click','[data-role="streamContainer"]',this.openStreamContainer);this.on('click','[data-role="streamClubs"]',this.openStreamClubs);this.on('click','[data-action="dismissSave"]',this.dismissSave);this.on('keydown','input',this.inputKeydown);if(this.scope.attr('data-formType')=='createStream'){this.on('itemClicked.sideMenu','[data-filterType="date"]',this.selectedDate);this.on('itemClicked.sideMenu','[data-filterType="ownership"]',this.selectedOwnership);}else{this.on('menuItemSelected','#elStreamFollowStatus',this.selectedFollowStatus);this.on('menuItemSelected','#elStreamTimePeriod',this.selectedDate);this.on('menuItemSelected','#elStreamOwnership',this.selectedOwnership);}
this.on('change','#elSelect_stream_club_filter',this.clubSelectionChanged);this.on('change','#stream_club_filter_unlimited',this.clubSelectionChanged);this.on('menuItemSelected','#elStreamSortEdit, #elStreamFollowStatus',this.selectedMenuItem);this.on('menuItemSelected','#elStreamTimePeriod, #elStreamOwnership, #elStreamShowMe',this.selectedMenuItem);this.on('menuItemSelected','#elStreamReadStatus',this.selectedReadStatus);this.on('menuClosed',this.menuClosed);this.setup();},setup:function(){this._serializeConfig={'stream_date_range[start]':this._serializeDate,'stream_date_range[end]':this._serializeDate};if(this.scope.attr('data-formType')!='createStream'){this._formData=ips.getSetting('stream_config');this._changeReadStatus(this._formData['stream_read']);this._updateFilterOverview();this.takeFormSnapshot();}
this.trigger('initialFormData.stream',{data:this._formData});},inputKeydown:function(e){if(e.which==13){e.preventDefault();}},streamStateUpdate:function(e,data){this._formData=data.filterData;this._updateFieldValues();if(data.hideSaveBar!==undefined&&data.hideSaveBar){this.scope.find('[data-role="saveButtonContainer"]').slideUp();}else{this.scope.find('[data-role="saveButtonContainer"]').slideDown();}},_updateFilterOverview:function(){if(this.scope.attr('data-formType')=='createStream'){return;}
var self=this;var values=this._formData;var _overview=function(type){return self.scope.find('[data-filter="'+type+'"] [data-role="filterOverview"]');};for(const val of['stream_include_comments','stream_read','stream_sort','stream_solved']){var lang='streamFilter_'+val+'_'+values[val];_overview(val).html(ips.getString(lang));};if(values['stream_tags']!==undefined&&values['stream_tags'].trim()!==''){var tags=values['stream_tags'].split(/\r?\n/).filter(Boolean);if(tags.length<=2){var tagLang=ips.getString('streamFilter_stream_tags_tags',{'tags':ips.utils.escapeHTML(tags.join(','))});}else{var tagLang=ips.pluralize(ips.getString('streamFilter_stream_tags_count'),tags.length);}
_overview('stream_include_comments').append('; '+tagLang);}else{_overview('stream_include_comments').append('; '+ips.getString('streamFilter_stream_tags_noTags'));}
if(values['stream_ownership']=='custom'&&(values['stream_custom_members']===undefined||values['stream_custom_members']==null||values['stream_custom_members']=='')){values['stream_ownership']='all'}
if(values['stream_ownership']!=='custom'){var ownershipLang='streamFilter_stream_ownership_'+values['stream_ownership'];_overview('stream_ownership').html(ips.getString(ownershipLang));}else if(values['stream_custom_members']!==undefined&&values['stream_custom_members']!=null){var names=((typeof values['stream_custom_members']==="object"&&values['stream_custom_members']!==null)?values['stream_custom_members']:values['stream_custom_members'].split(/\r?\n/)).filter(Boolean);var ownershipLang=ips.pluralize(ips.getString('streamFilter_stream_ownership_custom'),names.length);_overview('stream_ownership').text(ownershipLang);}
if(values['stream_follow']=='all'){_overview('stream_follow').html(ips.getString('streamFilter_stream_follow_all'));}else{var value=Object.keys(values['stream_followed_types']);var follows=[];for(var i=0;i<value.length;i++){follows.push(ips.getString('streamFilter_stream_follow_'+value[i]));}
_overview('stream_follow').html(follows.join(', '));}
if(values['stream_date_type']=='relative'&&(values['stream_date_relative_days']===undefined||values['stream_date_relative_days']==null||values['stream_date_relative_days']=='')){values['stream_date_type']='all';}else if(values['stream_date_type']=='custom'&&((values['stream_date_range']['start']===undefined||values['stream_date_range']['start']==null||values['stream_date_range']['start']=='')||(values['stream_date_range']['end']===undefined||values['stream_date_range']['end']==null||values['stream_date_range']['end']==''))){values['stream_date_type']='all';}
if(values['stream_date_type']=='all'||values['stream_date_type']=='last_visit'){_overview('stream_date_type').html(ips.getString('streamFilter_stream_date_type_'+values['stream_date_type']));}else if(values['stream_date_type']=='relative'){if(values['stream_date_relative_days']['unit']=='w'){var dateLang=ips.pluralize(ips.getString('streamFilter_stream_date_type_relative_weeks'),(values['stream_date_relative_days']['val']?values['stream_date_relative_days']['val']:values['stream_date_relative_days']));}
else{var dateLang=ips.pluralize(ips.getString('streamFilter_stream_date_type_relative'),(values['stream_date_relative_days']['val']?values['stream_date_relative_days']['val']:values['stream_date_relative_days']));}
_overview('stream_date_type').text(dateLang);}else{if(values['__stream_owner']!==undefined||(isNaN(values['stream_date_range']['start'])&&values['stream_date_range']['start'].match('-'))){var start=ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(isNaN(values['stream_date_range']['start'])&&values['stream_date_range']['start'].match('-')?values['stream_date_range']['start']:values['stream_date_range']['start']*1000)));var end=ips.utils.time.localeDateString(ips.utils.time.removeTimezone(new Date(isNaN(values['stream_date_range']['end'])&&values['stream_date_range']['end'].match('-')?values['stream_date_range']['end']:values['stream_date_range']['end']*1000)));}else{var start=ips.utils.time.localeDateString(new Date(values['stream_date_range']['start']*1000));var end=ips.utils.time.localeDateString(new Date(values['stream_date_range']['end']*1000));}
if(values['stream_date_range']['start']!==undefined&&values['stream_date_range']['end']!==undefined){var dateLang=ips.getString('streamFilter_stream_date_type_range',{start:start,end:end});}else if(values['stream_date_range']['start']!==undefined){var dateLang=ips.getString('streamFilter_stream_date_type_start',{start:start});}else if(values['stream_date_range']['start']!==undefined){var dateLang=ips.getString('streamFilter_stream_date_type_end',{end:end});}
_overview('stream_date_type').text(dateLang);}
if(!values['stream_classes']||values['stream_classes_type']==0){if(values['stream_club_select']=='none'){_overview('stream_classes').html(ips.getString('streamFilter_stream_classes_no_clubs'));}else if(values['stream_club_select']=='all'){_overview('stream_classes').html(ips.getString('streamFilter_stream_classes_all'));}else if(values['stream_club_filter']){_overview('stream_classes').text(ips.getString('loading'));this._loadClubs(function(){var elem=this.scope.find('#elSelect_stream_club_filter');var clubIds=values['stream_club_filter'].split(',');var clubNames=[];for(var i=0;i<clubIds.length;i++){var option=elem.find('option[value="'+clubIds[i]+'"]');if(option.length){clubNames.push(option.text().trim());}}
_overview('stream_classes').text(clubNames.join(', '));}.bind(this));}}else{var classKeys=Object.keys(values['stream_classes']);var classes=[];for(var i=0;i<classKeys.length;i++){var elem=this.scope.find('[data-class="'+classKeys[i].replace(/\\/g,'\\\\')+'"] > span');if(elem.length){classes.push(elem.text().trim());}}
_overview('stream_classes').text(classes.join(', '));}},_updateFieldValues:function(){var self=this;var data=this._formData;if(data['stream_read']=='unread'){data['stream_include_comments']=0;}
for(const key of['stream_include_comments','stream_read','stream_sort','stream_follow','stream_ownership','stream_date_type']){self.scope.find('[name="'+key+'"]').prop('checked',false).filter('[value="'+data[key]+'"]').prop('checked',true).trigger('change');};var followSelector=Object.keys(data['stream_followed_types']||{}).map(key=>'[name="stream_followed_types['+key+']"]');this.scope.find('[name^="stream_followed_types"]').prop('checked',false);if(followSelector.length){this.scope.find('[name^="stream_followed_types"]').filter(followSelector.join(',')).prop('checked',true).trigger('change');}
if(this.scope.find('#elInput_stream_custom_members').length){var ownerAC=ips.ui.autocomplete.getObj(this.scope.find('#elInput_stream_custom_members'));ownerAC.removeAll();if(data['stream_ownership']=='custom'){var names=data['stream_custom_members'].split(/\r?\n/).filter(Boolean);for(var i=0;i<names.length;i++){ownerAC.addToken(names[i]);}}}
if(data['stream_tags']!==undefined){var tags=data['stream_tags'].split(/\r?\n/).filter(Boolean);var tagAC=ips.ui.autocomplete.getObj(this.scope.find('#elInput_stream_tags'));tagAC.removeAll();if(tags.length){for(var i=0;i<tags.length;i++){tagAC.addToken(tags[i]);}}}
this.scope.find('[name="stream_date_relative_days"], [name="stream_date_range[start]"], [name="stream_date_range[end]"]').val('');if(data['stream_date_type']=='relative'){this.scope.find('[name="stream_date_relative_days"]').val(data['stream_date_relative_days']);}else if(data['stream_date_type']=='custom'){if(data['stream_date_range']['start']){var startDateObj=new Date(data['stream_date_range']['start']);this.scope.find('[name="stream_date_range[start]"]').get(0).valueAsDate=startDateObj;}
if(data['stream_date_range']['end']){var endDateObj=new Date(data['stream_date_range']['end']);this.scope.find('[name="stream_date_range[end]"]').get(0).valueAsDate=endDateObj;}}
var classChecks=$('#elStreamContentTypes_menu').find('[type="checkbox"][name^="stream_classes"]');var classSelector=[];classChecks.prop('checked',false).trigger('change').closest('.ipsSideMenu_item').removeClass('ipsSideMenu_itemActive');if(data['stream_classes_type']==0){this.scope.find('[name="stream_classes_type"]').first().closest('.ipsSideMenu_item').addClass('ipsSideMenu_itemActive');}else{var classKeys=Object.keys(data['stream_classes']);for(const val of classKeys){self.scope.find('[data-class="'+val.replace(/\\/g,'\\\\')+'"] input[type="checkbox"]').prop('checked',true).trigger('change').closest('.ipsSideMenu_item').addClass('ipsSideMenu_itemActive');};}
this._updateFilterOverview();},openStreamContainer:function(e,data){e.preventDefault();var self=this;var link=$(e.currentTarget);var className=link.attr('data-class');var contentKey=link.attr('data-contentKey');var nodeContainer=link.next('.cStreamForm_nodes');if(!this._loadedContainer[className]){nodeContainer.slideDown();var containers=[];if(typeof ips.getSetting('stream_config')==='object'&&ips.getSetting('stream_config')!==null&&Object.keys(ips.getSetting('stream_config')['containers']).length!==0){var keys=Object.keys(ips.getSetting('stream_config')['containers']);var values=Object.values(ips.getSetting('stream_config')['containers']);for(var i=0;i<keys.length;i++){containers.push('stream_containers['+keys[i]+']='+values[i]);}}
ips.getAjax()(this.scope.find('form').attr('action').replace('do=create',''),{type:'post',data:'do=getContainerNodeElement&className='+className+'&key='+contentKey+'&'+containers.join('&')}).done(function(returnedData){nodeContainer.html(returnedData.node);self._loadedContainer[className]=true;$(document).trigger('contentChange',[nodeContainer.parent()]);});}else{nodeContainer.slideToggle();}},openStreamClubs:function(e){e.preventDefault();var clubContainer=$('#elStreamClubs');if(!this._loadedClubs){clubContainer.slideDown();this._loadClubs(null);}else{clubContainer.slideToggle();}},_loadClubs:function(callback){if(!this._loadedClubs){var clubContainer=$('#elStreamClubs');var extra=null;if((typeof ips.getSetting('stream_config')==="object"&&ips.getSetting('stream_config')!==null)){extra='&stream_club_select='+ips.getSetting('stream_config')['stream_club_select']+'&stream_club_filter='+ips.getSetting('stream_config')['stream_club_filter'];}
var self=this;ips.getAjax()(this.scope.find('form').attr('action').replace('do=create',''),{type:'post',data:'do=getClubElement&'+extra}).done(function(returnedData){clubContainer.html(returnedData.field);self._loadedClubs=true;$(document).trigger('contentChange',[clubContainer.parent()]);if(callback){callback();}});}else if(callback){callback();}},menuClosed:function(e,data=e.detail){if(data.elemID=='elStreamContentTypes'||($('#'+data.elemID+'_menu').length&&data.elemID!='elSaveStream')){setTimeout(function(self){self.checkFormUpdate();self.reloaded=true;},500,this);}},checkFormUpdate:function(){if(this.hasFormChanged()){this.updateResults();this.scope.find('#elSaveStream').removeClass('i-opacity_4');this.takeFormSnapshot();}},hasFormChanged:function(){const currentForm=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);return JSON.stringify(this.formSnapshot)!==JSON.stringify(currentForm);},takeFormSnapshot:function(){this.formSnapshot=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);},tokensChanged:function(){this.reloaded=false;},changeSort:function(){this.checkFormUpdate();},selectedMenuItem:function(e,data=e.detail){if(data.originalEvent){data.originalEvent.preventDefault();}},selectedReadStatus:function(e,data=e.detail){if(data.originalEvent){}
this._changeReadStatus(data.selectedItemID);},_changeReadStatus:function(type){if(type=='unread'){this._formData['stream_include_comments']=0;this.scope.find('#stream_ownership_0').trigger('click');this.scope.find('#stream_ownership_1').prop('disabled',true);}else{this.scope.find('#stream_ownership_1').prop('disabled',false);}},dismissSave:function(e){this.scope.find('[data-role="saveButtonContainer"]').slideUp();},submitForm:function(e){var button=$(e.currentTarget);var form=button.closest('form');if(this.scope.attr('data-formType')=='createStream'){return;}
if(button.attr('data-action')=='newStream'){form.prepend($('<input />').attr('type','hidden').attr('name','do').attr('value','create'));}else{this._formData=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);this.trigger('formSubmitted.stream',{data:this._formData,action:(button.attr('data-action')=='newStream')?'createForm':'saveForm'});}},updateResults:function(){this._formData=ips.utils.form.serializeAsObject(this.scope.find('form'),this._serializeConfig);this._updateFilterOverview();this.trigger('formSubmitted.stream',{data:this._formData,action:'updateForm'});},selectedDate:function(e,data=e.detail){this.reloaded=false;if(data.selectedItemID=='custom'){this.scope.find('[data-role="dateRelativeForm"]').slideUp();this.scope.find('[data-role="dateForm"]').slideDown();}else if(data.selectedItemID=='relative'){this.scope.find('[data-role="dateForm"]').slideUp();this.scope.find('[data-role="dateRelativeForm"]').slideDown();this.scope.find('[name="stream_date_relative_days"]').trigger('focus');}else{if(data.selectedItemID!==undefined){this.scope.find('[data-role="dateForm"]').slideUp();this.scope.find('[data-role="dateRelativeForm"]').slideUp();this.checkFormUpdate();}}},selectedFollowStatus:function(e,data=e.detail){var selectedItems=data.selectedItems;if(!selectedItems||Object.keys(selectedItems).length===0){this.scope.find('[name="stream_follow"]').val('all');}else{this.scope.find('[name="stream_follow"]').val('followed');}
this.checkFormUpdate();},selectedOwnership:function(e,data=e.detail){if(data.selectedItemID=='custom'){this.scope.find('[data-role="ownershipMemberForm"]').slideDown();}else{if(data.selectedItemID!==undefined){this.scope.find('[data-role="ownershipMemberForm"]').slideUp();this.checkFormUpdate();}}},clubSelectionChanged:function(){if(this.scope.find('[name="stream_club_filter_dummy_unlimited"]').is(':checked')){this.scope.find('[name="stream_club_select"]').val('all');}else{this.scope.find('[name="stream_club_select"]').val('select');this.scope.find('[name="stream_club_filter"]').val($('#elSelect_stream_club_filter').val());}},selectedType:function(e,data=e.detail){var self=this;var typeMenu=this.scope.find('[data-filterType="type"]');var all=typeMenu.find('[data-ipsMenuValue="__all"]');var allButAll=typeMenu.find('[data-ipsMenuValue]:not( [data-ipsMenuValue="__all"] )');var allButAllChecks=allButAll.find('> input[type="checkbox"]');this.reloaded=false;if(data.selectedItemID=='__all'){allButAll.removeClass('ipsSideMenu_itemActive').find('> input[type="checkbox"]').prop('checked',false);all.addClass('ipsSideMenu_itemActive');this.scope.find('input[type="radio"][name="stream_classes_type"][value="0"]').prop('checked',true);this.scope.find('[data-contentType]').closest('.cStreamForm_nodes').slideUp();}else{if(allButAllChecks.filter(':checked').length){all.removeClass('ipsSideMenu_itemActive')
this.scope.find('input[type="radio"][name="stream_classes_type"][value="1"]').prop('checked',true);allButAllChecks.filter(':checked').each(function(){var type=$(this).closest('[data-ipsMenuValue]').attr('data-ipsMenuValue');if(self.scope.find('[data-contentType="'+type+'"]').length){self.scope.find('[data-contentType="'+type+'"]').slideDown();}});allButAllChecks.filter(':not( :checked )').each(function(){var type=$(this).closest('[data-ipsMenuValue]').attr('data-ipsMenuValue');if(self.scope.find('[data-contentType="'+type+'"]').length){self.scope.find('[data-contentType="'+type+'"]').slideUp();}})}else{all.addClass('ipsSideMenu_itemActive').find('> input[type="checkbox"]').prop('checked',true);this.scope.find('[data-contentType]').slideUp();}}},_serializeDate:function(name,value){return value;}});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.front.streams.main',{_streamLoadingOverlay:null,_tooltip:null,_tooltipTimer:null,_baseURL:'',_streamID:0,_currentView:'',_shortInterval:15,_longInterval:45,_killUpdate:45,_timer:null,_killTimer:null,_activityUpdate:null,_loadMore:null,_timestamp:0,_autoUpdate:false,_windowFocus:false,initialize(){this.on('formSubmitted.stream',this.formSubmitted);this.on('initialFormData.stream',this.initialFormData);this.on('loadMoreResults.stream',this.loadMoreResults);this.on('latestTimestamp.stream',this.latestTimestamp);this.on('click','[data-action="switchView"]',this.switchView);this.on('menuOpened','#elStreamShare',this.menuOpened);this.on('click','[data-action="toggleStreamDefault"]',this.toggleDefault);this.on('click','[data-action="removeStream"]',this.removeStream);this.on('click','[data-action="loadMore"]',this.loadMoreResults);this.on('resultsUpdated.stream',this.resultsUpdated);this.on(document,'markAllRead',this.markAllRead);this.on(document,ips.utils.events.getVisibilityEvent(),this.windowVisibilityChange);this.on(window,'historychange:streams',this.stateChange);this.setup();},setup(){this._streamID=this.scope.attr('data-streamID');this._baseURL=ips.getSetting('stream_config')['url'];if(this._baseURL.match(/\?/)){this._baseURL+='&';}else{this._baseURL+='?';}
if(this._baseURL.slice(-1)==='&'){this._baseURL=this._baseURL.slice(0,-1)}
this._timestamp=parseInt(this.scope.find('[data-timestamp]').first().attr('data-timestamp'));this._currentView=this.scope.find('[data-action="switchView"].ipsDataFilters__button--active').attr('data-view');if(this.scope.find('[data-role="streamResults"]').attr('data-autoPoll')!==undefined){this._autoUpdate=true;this.windowVisibilityChange();}
if(!document.getElementById('elStreamFilterForm')){document.querySelector("[aria-controls='elStreamFilterForm']").hidden=true;}},stateChange(){const state={data:ips.utils.history.getState('streams')||{},url:window.location.href,title:document.title}
if((!state.data.controller||state.data.controller!=='core.front.streams.main')&&this._initialURL!==state.url){return;}
if(state.data.action==='saveForm'||state.data.action==='updateForm'){this.triggerOn('core.front.streams.form','streamStateUpdate.streamForm',{filterData:state.data.filterData,hideSaveBar:(Object.keys(this._getUrlDiff(state.data.filterData)).length===0||state.data.action==='saveForm')});ips.utils.analytics.trackPageView(state.url);if(state.data.filterData.stream_sort!==undefined){this._togglePolling(!(state.data.filterData.stream_sort==='oldest'));}
const data=Object.assign({view:this._currentView},state.data.filterData);switch(state.data.action){case'updateForm':data.updateOnly=1
break;case'saveForm':data.form='save'
break;}
this._loadResults(data).done((response)=>{this.triggerOn('core.front.streams.results','updateResults.stream',{append:false,response});if(state.data.action==='saveForm'){ips.setSetting('stream_config',JSON.parse(response.config));ips.utils.history.replaceState({controller:'core.front.streams.main',url:ips.getSetting('stream_config')['url'],skipUpdate:true},'core.front.streams.main',ips.getSetting('stream_config').url);}})}else if(state.data.action==='loadMore'){const data=Object.assign({before:state.data.before,view:this._currentView},state.data.filters);const before=this.scope.find('[data-role="activityItem"]').last().attr('data-timestamp');this._loadResults(data).done((response)=>{const content=$('<div>'+response.results+'</div>');const latest=parseInt(content.find('[data-role="activityItem"]').last().attr('data-timestamp'))-1;ips.utils.history.replaceState({controller:'core.front.streams.main',latest:latest},'core.front.streams.main',this._buildRequestURL({before:before,latest:isNaN(latest)?0:latest}));this.triggerOn('core.front.streams.results','updateResults.stream',{append:true,response:response,url:this._buildRequestURL({before:before,latest:isNaN(latest)?0:latest})});});}else if(state.data.action==='viewToggle'){this._setViewType(state.data.view);this._loadResults({view:state.data.view,...state.data.filters}).done(response=>this.triggerOn('core.front.streams.results','updateResults.stream',{response}));}else{Debug.log('skip update');}},loadMoreResults(e,data){e.preventDefault();var timestamp=this.scope.find('[data-role="activityItem"]').last().attr('data-timestamp');var url=this._buildRequestURL({before:timestamp});this.scope.find('[data-role="loadMoreContainer"] [data-action="loadMore"]').addClass('ipsButton--disabled').text(ips.getString('loading'));ips.utils.history.pushState({controller:'core.front.streams.main',before:timestamp,filters:this._getUrlDiff(this._formData),action:'loadMore'},'streams',url);},_setViewType(type){this._currentView=type;this.scope.find('[data-action="switchView"]').removeClass('ipsButton--active').filter('[data-view="'+type+'"]').addClass('ipsButton--active');ips.utils.cookie.set('stream_view_'+this._streamID,type,true);},switchView(e){e.preventDefault();const view=$(e.currentTarget).attr('data-view');ips.utils.history.pushState({controller:'core.front.streams.main',view,filters:this._getUrlDiff(this._formData),action:'viewToggle'},'streams',this._buildRequestURL({view}));},formSubmitted(e,data){this._formData=this._getFormData(data.data);const url=this._buildRequestURL();ips.utils.history.pushState({controller:'core.front.streams.main',url:url,filterData:this._formData,action:data.action},'streams',url);},initialFormData(e,data){this._formData=this._getFormData(data.data);},latestTimestamp(e,data){this._timestamp=data.timestamp;},windowVisibilityChange(){var hiddenProp=ips.utils.events.getVisibilityProp();if(hiddenProp!==undefined){if(document[hiddenProp]){this._windowFocus=false;this._startTimer(this._longInterval);this._killTimer=setTimeout(this._stopPolling.bind(this),this._killUpdate*60*1000);Debug.log("Set the kill timer");}else{this._windowFocus=true;this._startTimer(this._shortInterval);this._updateTitle(0);clearTimeout(this._killTimer);Debug.log("Cleared the kill timer");}}else{this._startTimer(this._longInterval);}},_loadResults(data,resetConfig,silent){var self=this;var promise=$.Deferred();if(!silent){this._setStreamLoading(true);}
ips.getAjax()(ips.getSetting('stream_config')['url'],{type:'post',data:data||{}}).done(function(response){if(!silent){self._setStreamLoading(false);self._updateStreamUI(response);}
promise.resolve(response);}).fail(function(response){if(!silent){ips.ui.alert.show({type:'alert',message:ips.getString('errorLoadingStream'),icon:'warn'});}
promise.reject();});return promise;},resultsUpdated:function(e,data){if(this.scope.find('[data-role="activityItem"]').length===0){this.scope.find('[data-role="loadMoreContainer"]').hide();this.scope.find('[data-role="streamContent"]').removeClass('ipsStream_withTimeline');}
else{this.scope.find('[data-role="streamContent"]').addClass('ipsStream_withTimeline');this.scope.find('[data-role="loadMoreContainer"]').show();}},_updateStreamUI(response){Debug.log("Updating stream UI...");this.scope.find('[data-role="streamBlurb"]').text(response.blurb.replace(/&#039;/g,"'"));this.scope.find('[data-role="streamTitle"]').html(response.title);if(response.count===0){this.scope.find('[data-role="loadMoreContainer"]').show().html(ips.templates.render('core.streams.noMore'));}else{this.scope.find('[data-role="loadMoreContainer"]').show().html(ips.templates.render('core.streams.loadMore'));}
if(response.id){var menuItem=$('body').find('[data-streamid="'+response.id+'"] .ipsNavBar__text');menuItem.html(response.title);}},_getFormData(data){var returnValues={};for(const[key,val]of Object.entries(data)){if(key.startsWith('stream_')){returnValues[key]=val;}};try{if(returnValues['stream_classes']&&returnValues['stream_classes']['__EMPTY']!==undefined){delete returnValues['stream_classes']['__EMPTY'];}}catch(err){}
return returnValues;},_getUrlDiff(data){var returnedValues={};var defaultValues=ips.getSetting('stream_config');if(defaultValues['changed']!==undefined){for(const[key,val]of Object.entries(defaultValues['changed'])){returnedValues[(key==='containers')?'stream_containers':key]=defaultValues[key];};}
if(!data||Object.keys(data).length===0){return returnedValues;}
for(const val of['stream_sort','stream_include_comments','stream_read','stream_default_view','stream_club_select','stream_club_filter']){if(defaultValues[val]!==data[val]&&data[val]!==undefined){returnedValues[val]=data[val];}};if(data['stream_ownership']==='custom'){var newNames=(typeof data['stream_custom_members']==="object"&&data['stream_custom_members']!==null)?data['stream_custom_members']:data['stream_custom_members'].split(/\r?\n/);var oldNames=defaultValues['stream_custom_members'];if(!Array.isArray(oldNames)){oldNames=[];}
var nameIntersection=newNames.filter(name=>oldNames.includes(name));if(!newNames.length){returnedValues['stream_ownership']='all';}
else if(newNames.length!==oldNames.length||nameIntersection.length!==newNames.length){returnedValues['stream_ownership']='custom';returnedValues['stream_custom_members']=data['stream_custom_members'];}}else if(defaultValues['stream_ownership']!==data['stream_ownership']){returnedValues['stream_ownership']=data['stream_ownership'];}
if(!(defaultValues['stream_follow']==='all'&&data['stream_follow']==='all')){if(data['stream_follow']==='followed'){var newFollowTypes=Object.keys(data['stream_followed_types']);var oldFollowTypes=Object.keys(defaultValues['stream_followed_types']);var followIntersection=newFollowTypes.filter(name=>oldFollowTypes.includes(name));if(newFollowTypes.length!==oldFollowTypes.length||followIntersection.length!==newFollowTypes.length){returnedValues['stream_follow']='followed';returnedValues['stream_followed_types']=data['stream_followed_types'];}}else{returnedValues['stream_follow']=data['stream_follow'];}}
if(data['stream_tags']!==undefined&&data['stream_tags'].trim().length!==0){var newTags=(data['stream_tags']||'').split(/\r?\n/).filter(Boolean);var oldTags=(defaultValues['stream_tags']||'').split(/\r?\n/).filter(Boolean);var tagIntersection=newTags.filter(name=>oldTags.includes(name));if(newTags.length!==oldTags.length||tagIntersection.length!==newTags.length){returnedValues['stream_tags']=newTags.map(str=>str.trim()).join(',');}}else if(defaultValues['stream_tags']){returnedValues['stream_tags']='';}
if(data['stream_date_type']==='custom'){var startTest=data['stream_date_range']['start'];if(startTest.toString().match(/^[0-9]{9,10}$/)){var start=data['stream_date_range']['start'];var end=data['stream_date_range']['end'];}
else
{var start=new Date(data['stream_date_range']['start']).getTime()/1000;var end=new Date(data['stream_date_range']['end']).getTime()/1000;}
if(data['stream_date_range']['start']&&(defaultValues['stream_date_range']===undefined||start!==defaultValues['stream_date_range']['start'])){returnedValues['stream_date_type']='custom';returnedValues['stream_date_start']=start;}
if(data['stream_date_range']['end']&&(defaultValues['stream_date_range']===undefined||end!==defaultValues['stream_date_range']['end'])){returnedValues['stream_date_type']='custom';returnedValues['stream_date_end']=end;}}else if(data['stream_date_type']==='relative'){if(defaultValues['stream_date_relative_days']!==data['stream_date_relative_days']){returnedValues['stream_date_type']='relative';returnedValues['stream_date_relative_days']=data['stream_date_relative_days'];}}else if(defaultValues['stream_date_type']!==data['stream_date_type']){returnedValues['stream_date_type']=data['stream_date_type'];}
if(data['stream_classes_type']===0&&defaultValues['stream_classes_type']===1){returnedValues['stream_classes']={};}else{var newClasses=Object.keys(data['stream_classes']||{}).filter(key=>key!=='__EMPTY');var classIntersection=newClasses.filter(name=>defaultValues['stream_classes'][name]);if(classIntersection.length!==newClasses.length){returnedValues['stream_classes']={...data['stream_classes']};delete returnedValues['stream_classes']['__EMPTY'];}}
var containers={};if(typeof data['stream_classes']==='object'&&data['stream_classes']!==null){Object.keys(data['stream_classes']).filter(key=>key!=='__EMPTY').forEach(val=>{var contentType=$('div[data-role="streamContainer"][data-className="'+val.replace(/\\/g,'\\\\')+'"]').attr('data-contentKey');if(contentType!==undefined&&$('input[name="stream_containers_'+contentType+'"]').length){containers[val]=$('input[name="stream_containers_'+contentType+'"]').val();}});}
if(Object.keys(containers).length!==0){if(defaultValues['containers']!==undefined&&JSON.stringify(containers)!==JSON.stringify(defaultValues['containers'])){returnedValues['stream_containers']=containers;}}
return returnedValues;},_buildRequestURL(extraParams){var urlDiff=this._getUrlDiff(this._formData);var params=[];for(const[key,val]of Object.entries(urlDiff)){if(typeof val==='object'&&val!==null){const keys=Object.keys(val);const values=Object.values(val);if(keys.length===0){params.push(key+'=');}else{for(var i=0;i<keys.length;i++){var paramValue=((values[i]!==undefined)?values[i]:1);params.push(key+'['+encodeURIComponent(keys[i])+']='+paramValue);}}}else{params.push(key+'='+encodeURIComponent(val));}};if(typeof extraParams==='object'&&extraParams!==null){for(const[key,val]of Object.entries(extraParams)){params.push(key+'='+encodeURIComponent(val));};}
return this._baseURL+'&'+params.join('&');},menuOpened(e,data=e.detail){$(data.menu).find('input[type="text"]').trigger('focus').get(0).select();},removeStream(e){e.preventDefault();ips.ui.alert.show({type:'confirm',message:ips.getString('confirmRemoveStream'),callbacks:{ok(){window.location=$(e.currentTarget).attr('href')+'&wasConfirmed=1';},}});},toggleDefault(e){e.preventDefault();var self=this;var link=$(e.currentTarget);var value=link.attr('data-change');var url=link.attr('href');ips.getAjax()(url).done(function(response){if(value==1){self.scope.find('[data-role="toggleDefaultTrue"]').prop('hidden',true);self.scope.find('[data-role="toggleDefaultFalse"]').prop('hidden',false);}else{self.scope.find('[data-role="toggleDefaultTrue"]').prop('hidden',false);self.scope.find('[data-role="toggleDefaultFalse"]').prop('hidden',true);}
if(!response.title){$('a[data-action="defaultStream"]').hide();}else{$('a[data-action="defaultStream"]').attr('href',response.url).attr('aria-label',response.title).show().find('[data-role="defaultStreamName"]').html(response.title);}
if(value==1){if(!ips.utils.responsive.enabled||!ips.utils.responsive.currentIs('phone')&&$('a[data-action="defaultStream"]').is(':visible')){self._showStreamTooltip(response.tooltip);}else{ips.utils.anim.go('pulseOnce',$('a[data-action="defaultStream"]'));}}});},_showStreamTooltip(title){if(!this._tooltip){var tooltipHTML=ips.templates.render('core.tooltip',{id:'elDefaultStreamTooltip_'+this.controllerID});ips.getContainer().append(tooltipHTML);this._tooltip=$('#elDefaultStreamTooltip_'+this.controllerID);}else{this._tooltip[0].hidePopover();}
if(this._tooltipTimer){clearTimeout(this._tooltipTimer);}
this._tooltip.text(ips.getString('streamDefaultTooltip',{title:title}));var streamLink=$('a[data-action="defaultStream"]:visible');var self=this;var positionInfo={trigger:streamLink.first(),target:this._tooltip,center:true,above:true};var tooltipPosition=ips.utils.position.positionElem(positionInfo);$(this._tooltip).css({left:tooltipPosition.left+'px',top:tooltipPosition.top+'px'});if(tooltipPosition.location.vertical==='top'){this._tooltip.addClass('ipsTooltip_top');}else{this._tooltip.addClass('ipsTooltip_bottom');}
this._tooltip[0].showPopover();setTimeout(function(){if(self._tooltip&&self._tooltip.is(':visible')){self._tooltip[0].hidePopover();}},3000);},_setStreamLoading(loading){var stream=this.scope.find('[data-role="streamContent"]');if(!loading){this._streamLoadingOverlay.hide();stream.css({opacity:"1"});return;}else{if(!this._streamLoadingOverlay){this._streamLoadingOverlay=$('<div/>').addClass('ipsLoading');ips.getContainer().append(this._streamLoadingOverlay);}
var dims=ips.utils.position.getElemDims(stream);var position=ips.utils.position.getElemPosition(stream);this._streamLoadingOverlay.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()});stream.css({opacity:"0.5"});}},_startTimer(interval){if(!this._autoUpdate){return;}
if(!interval){interval=this._shortInterval;}
if(this._timer){clearInterval(this._timer);}
this._timer=setInterval(this._autoFetchNew.bind(this),interval*1000);},_togglePolling(status){if(!this._autoUpdate){clearInterval(this._timer);return;}
if(status){this._startTimer();this.scope.find('[data-role="updateMessage"]').show();}else{if(this._timer){clearInterval(this._timer);this.scope.find('[data-role="updateMessage"]').hide();}}},_autoFetchNew(){if(!Number.isFinite(this._timestamp)){Debug.log("Timestamp not a number");clearInterval(this._timer);return;}
this._loadResults({after:this._timestamp},false,true).done(response=>{const count=parseInt(response.count);if(response.error&&response.error==='auto_polling_disabled'){this.scope.find('[data-role="updateMessage"]').remove();clearInterval(this._timer);return;}
if(Number.isNaN(count)||count===0){return;}
this.triggerOn('core.front.streams.results','resultsTeaser.stream',{response:response});});},_stopPolling(){clearInterval(this._timer);this._autoUpdate=false;this.scope.find('[data-role="updateMessage"]').html(ips.getString('autoUpdateStopped'));Debug.log("Stopped polling due to user inactivity");},_updateTitle(count){},markAllRead(){this.scope.find('[data-ips-unread]').removeAttr('data-ips-unread');}});}(jQuery));;
;(function($){"use strict";ips.controller.register('core.front.streams.results',{_streamID:0,_newUpdates:$('<div/>'),_waitingCount:0,_config:{},initialize:function(){this.on('updateResults.stream',this.updateResults);this.on('resultsTeaser.stream',this.resultsTeaser);this.on('click','[data-action="insertNewItems"]',this.insertNewItems);this.on('click','a[data-linkType]',this.clickResult);this.setup();},setup:function(){if(this.scope.attr('data-streamID')){this._streamID=this.scope.attr('data-streamID');}
this._config=ips.getSetting('stream_config');},updateResults:function(e,data){if(data.append){this._appendNewResults(data);}else{this._replaceWithNewResults(data);}},_replaceWithNewResults:function(data){this._config=JSON.parse(data.response.config);if(data.response.results.indexOf('core.front.streams.results')!==-1){var content=$('<div>'+data.response.results+'</div>');var root=content.find('[data-controller="core.front.streams.results"]');this.cleanContents();this.scope.html(root.html()).attr('data-streamReadType',root.attr('data-streamReadType')).attr('data-streamURL',root.attr('data-streamURL')).attr('data-streamID',root.attr('data-streamID'));}else{ips.controller.cleanContentsOf(this.scope.find('[data-role="streamContent"]'));this.scope.find('[data-role="streamContent"]').html(data.response.results);}
this.trigger('resultsUpdated.stream',{response:data.response});$(document).trigger('contentChange',[this.scope]);},_appendNewResults:function(data){var content=$('<div>'+data.response.results+'</div>');var latestBubble=this.scope.find('[data-timeType]').last().attr('data-timeType');content.find('[data-timeType="'+latestBubble+'"]').remove();content.find('[data-role="activityItem"]').attr('data-new',true).css({opacity:"0"});if(data.url!==undefined){content.find('.js-ipsEntry__content form[action="'+this._config['url']+'"]').attr('action',data.url);}
var existingItems=this.scope.find('[data-role="activityItem"]');var count=existingItems.length;existingItems.last().after(content);this.scope.find('[data-role="activityItem"]').slice(count).each(function(){$(document).trigger('contentChange',[$(this)]);});this._animateNewItems();},clickResult:function(e,data){var item=$(e.target).closest('[data-indexID]');var star=item.find('a[data-linkType="star"]');this.scope.find('.ipsStreamItem_active').removeClass('ipsStreamItem_active');item.addClass('ipsStreamItem_active').removeAttr('data-ips-unread');if(star.attr('data-iPostedIn')){star.addClass('ipsIndicator--read').unwrap();}else{star.prop('hidden',true);}},insertNewItems:function(e){e.preventDefault();var insertBefore=null;if(this.scope.find('[data-timeType="past_hour"]').length){insertBefore=this.scope.find('[data-timeType="past_hour"]').siblings('[data-role="activityItem"]').first();this._newUpdates.find('[data-timeType]').remove();}else{insertBefore=this.scope.find('[data-timeType], [data-role="activityItem"]').first();}
this.scope.find('[data-role="unreadBar"]').remove();this._newUpdates.append(ips.templates.render('core.streams.unreadBar'));this._newUpdates.find('[data-role="activityItem"]').attr('data-new',true).css({opacity:"0"});insertBefore.before(this._newUpdates.html());$(document).trigger('contentChange',[this.scope]);this.scope.find('[data-action="insertNewItems"]').remove();this._animateNewItems();this._newUpdates=$('<div/>');this._waitingCount=0;},_animateNewItems:function(){var newItems=this.scope.find('[data-new]');var delay=200;newItems.each(function(index){var d=(index*delay);$(this).delay((d>1200)?1200:d).animate({opacity:"1"}).removeAttr('data-new');});},resultsTeaser:function(e,data){var self=this;var response=data.response;var count=parseInt(response.count);var tmp=$('<div>'+response.results+'</div>');self.trigger('latestTimestamp.stream',{timestamp:parseInt(tmp.find('[data-timestamp]').first().attr('data-timestamp'))});self._waitingCount+=count;if(tmp.find('[data-timeType]').length){var type=tmp.find('[data-timeType]').attr('data-timeType');self._newUpdates.find('[data-timeType="'+type+'"]').remove();}
self._newUpdates.prepend(tmp.contents());var teaser=ips.templates.render('core.streams.teaser',{count:self._waitingCount,words:ips.pluralize(ips.getString('newActivityItems'),[self._waitingCount,self._waitingCount])});if(self.scope.find('[data-action="insertNewItems"]').length){self.scope.find('[data-action="insertNewItems"]').replaceWith(teaser);self.scope.find('[data-action="insertNewItems"]').show();}else{self.scope.find('[data-role="activityItem"]').first().before(teaser);self.scope.find('[data-action="insertNewItems"]').slideDown();}}});}(jQuery));;