1document.addEventListener('DOMContentLoaded',function(){const filterbars=Array.prototype.slice.call(document.querySelectorAll('[data-sm-filterbar]'));filterbars.forEach(filterbar=>{if(filterbar.dataset.smFilterbar!=='23509SmSn1p3T64')return;new SM_Filterbar(filterbar,{designMode:!0,}).init()})});document.addEventListener('DOMContentLoaded',e=>{const filterdropdowns=Array.prototype.slice.call(document.querySelectorAll('[data-sm-filterbar-dropdown]'));filterdropdowns.forEach(dropdown=>{if(dropdown.dataset.smFilterbarDropdown!=='23509SmSn1p3T66')return;const smFilterbarDropdown=new SM_Filterbar_Dropdown(dropdown).init()})});document.addEventListener('DOMContentLoaded',e=>{const filterdropdowns=Array.prototype.slice.call(document.querySelectorAll('[data-sm-filterbar-dropdown]'));filterdropdowns.forEach(dropdown=>{if(dropdown.dataset.smFilterbarDropdown!=='23509SmSn1p3T68')return;const smFilterbarDropdown=new SM_Filterbar_Dropdown(dropdown).init()})});document.addEventListener('DOMContentLoaded',function(){const renders=Array.prototype.slice.call(document.querySelectorAll('[data-sm-filter]'));renders.forEach(render=>{if(render.dataset.smFilter!=='23509SmSn1p3T53')return;const smFilter=new SM_Filter(render,{designMode:!0,loadmore:'auto',});smFilter.on("change",e=>{const event=new Event('filterbarchanged');window.dispatchEvent(event)});smFilter.init()})});class SM_Filterbar{constructor(el,options={}){this._defaults={submit:"auto",logic:"AND",URLHandling:!1,showNameInUrlParams:!1,};this._statics={submit:"[data-form-submit]",};this._options=options?this._deepMerge(this._defaults,options):this._defaults;this._events={};this.options=options;this.filterbar=el;this.renderID=this.filterbar.dataset.render} 2_deepMerge(arr){const argl=arguments.length;let retObj;if(Object.prototype.toString.call(arr)==="[object Array]"){retObj=[];for(let p in arr){retObj.push(arr[p])}}else{retObj={};for(let p in arr){retObj[p]=arr[p]}} 3for(let i=1;i<argl;i++){for(let p in arguments[i]){if(retObj[p]&&typeof retObj[p]==="object"){retObj[p]=this._deepMerge(retObj[p],arguments[i][p])}else{retObj[p]=arguments[i][p]}}} 4return retObj} 5_warnMsg(type){switch(type){case "el":{console.warn("SiteManager Filterbar: No filterbar found.");return} 6case "render":{console.warn("SiteManager Filterbar: No render found.");return} 7case "generic":{console.warn("SiteManager Filterbar: An error has occured.");return}}} 8_validateDropdown(input){input.setCustomValidity("");if(!input.required)return!0;const selectedOptions=input.selectedOptions;for(let i=0;i<selectedOptions.length;i++){if(selectedOptions[i].disabled&&selectedOptions[i].hidden) 9return!1} 10return!0} 11_getExternalFilter(property){return new Promise((res,rej)=>{this._getRender().then((renderFilter)=>{renderFilter.loadFilter(property).then(res).catch(rej)}).catch((err)=>{rej(err)})})} 12_formatFilters(arr,parent=!1){arr.forEach((cat,i,arr)=>(cat.sub_categories=arr.filter((el)=>cat.id===el.prev_category)));return parent&&parent!=0&&parent!==""?arr.find((main)=>main.id==parent):arr[0]} 13_formatExternalFilters(arr,parent=!1){const filter=arr.find((filter)=>filter.id===parent||filter.label===parent)||arr[0];if(!filter)return null;filter.sub_categories=filter.values.map((value)=>{return{id:value.data,name:value.value,filterId:filter.repeater||filter.id,field:filter.field||null,type:filter?.repeater?"repeater":filter.type,total:value.total??0,}});return filter} 14_createExternalFilterstring(selectedOptions,logic){const values=[];const subvalues={};[...selectedOptions].forEach((option)=>{if(option.value==="")return;const{filterId,filterType,subFilterId}=option.dataset;if(!filterId||!filterType)return;if(!subvalues.hasOwnProperty(filterId)){subvalues[filterId]=[]} 15let filterCondition="equals";if(["multi_select","repeater"].includes(filterType)){filterCondition="contains"} 16const data={[filterType]:{[filterCondition]:option.value,},property:filterId,};if(filterType==="repeater"&&subFilterId) 17data[filterType].field=subFilterId;subvalues[filterId].push(data)});for(const[filterId,filters]of Object.entries(subvalues)){if(filters.length===1){values.push(filters[0])}else if(filters.length>1){values.push({[logic.toLowerCase()]:filters,})}} 18return values} 19_detectsubmitType(){const submitType=this.filterbar.querySelector(this._statics.submit);if(submitType)return"submit";return"change"} 20_getRender(){return new Promise((resolve,reject)=>{if(this.render.SM_Filter)resolve(this.render.SM_Filter);this.render.addEventListener("init",()=>{resolve(this.render.SM_Filter)});setTimeout(()=>{if(!this.render.SM_Filter)resolve(null);},500)})} 21_initRender(){return new Promise((resolve,reject)=>{const scriptTag=document.createElement("script");scriptTag.type="text/javascript";scriptTag.src="//s1.sitemn.gr/users/lib/SM_Filterbar/SM_Filter.js";scriptTag.addEventListener("load",()=>{const smFilter=new SM_Filter(this.render,this.options);smFilter.init();resolve(smFilter)});scriptTag.addEventListener("error",()=>{console.log("error");resolve(null)});document.head.append(scriptTag)})} 22initEvents(){this.filterbar.addEventListener("submit",(e)=>{e.preventDefault();if(this.submitType!=="submit")return;const dropdowns=this.filterbar.querySelectorAll("select");
22[...dropdowns].forEach((dropdown)=>{if(!this._validateDropdown(dropdown)){dropdown.setCustomValidity("Please select a value.")}});const validity=this.filterbar.checkValidity();if(validity){this.SM_Filter._createFilterstring(this._options.logic)}});this.SM_Filter.on("change.before",(type)=>{this.options.URLHandling&&this.setParameters();if(this._events["change.before"]){this.emit("change.before",type)}});this.SM_Filter.on("change",(type,data)=>{if(this._events.change){this.emit("change",type,data)}});this.SM_Filter.on("rerender",(...data)=>{if(this._events.rerender){this.emit("rerender",...data)}});this.SM_Filter.on("total",(data)=>{if(this._events.total){this.emit("total",data)}});this.SM_Filter.on("reset",()=>{if(this._events.reset){this.emit("reset")}});this.SM_Filter.on("reset.before",()=>{if(this._events["reset.before"]){this.emit("reset.before")}})} 23on(name,listener){if(!this._events[name]){this._events[name]=[]} 24this._events[name].push(listener)} 25removeListener(name,listenerToRemove){if(!this._events[name]){throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`)} 26const filterListeners=(listener)=>listener!==listenerToRemove;this._events[name]=this._events[name].filter(filterListeners)} 27emit(name,...data){if(!this._events[name]){console.info(`Event "${name}" has no listeners.`);return} 28const fireCallbacks=(callback)=>{callback.call(this,...data)};this._events[name].forEach(fireCallbacks)} 29async init(){if(!this.filterbar){this._warnMsg("el");return} 30this.render=document.querySelector(`[data-filter="${this.filterbar.dataset.render}"]`);if(!this.render){this._warnMsg("render");return} 31this.SM_Filter=await this._getRender();if(!this.SM_Filter){this.SM_Filter=await this._initRender()} 32if(!this.SM_Filter){this._warnMsg("render");return} 33this.initialParams=this.SM_Filter.initialParams;this.showNameInUrlParams=this.options.showNameInUrlParams??!1;this.filterbar.SM_Filterbar=this;const dataOptions=["logic","errorMessageText"];dataOptions.forEach((option)=>(this._options[option]=this.filterbar.dataset[option]||this._options[option]));this.submitType=this._options.submit!=="auto"?this._options.submit:this._detectsubmitType();this.type=this.getType();this.initEvents();if(this._events.init){this.emit("init")} 34const initEvent=new Event("init");this.filterbar.dispatchEvent(initEvent)} 35getCategories(){return this.SM_Filter.categories} 36getType(){return this.SM_Filter.type} 37setParameters(alias,params){if(alias&¶ms)this.SM_Filter.setParameters(alias,params);} 38updateParameters(){this.SM_Filter.updateParameters()} 39getFilters(){return{filters:JSON.parse(JSON.stringify(this.SM_Filter._filters)),fields:JSON.parse(JSON.stringify(this.SM_Filter._fieldFilters)),search:JSON.parse(JSON.stringify(this.SM_Filter._searchFilter)),orders:JSON.parse(JSON.stringify(this.SM_Filter._orderFilters)),connected:JSON.parse(JSON.stringify(this.SM_Filter._connectedFilters)),}} 40getPropertyBounds(property){return this.SM_Filter.getPropertyBounds(property)} 41getActiveFilters(){return this.SM_Filter.getActiveFilters()} 42setSubmitType(type){if(!["auto","change","submit"].includes(type))return;this.submitType=type} 43setFilter(id,filterstring,submit="auto",activeFilters=[]){this.SM_Filter.setFilter(id,filterstring,(submit==="auto"&&this.submitType==="change")||submit===!0,activeFilters)} 44clearInitialFilters(){this.SM_Filter.clearInitialFilters()} 45clearInitialFieldFilters(){this.SM_Filter.clearInitialFieldFilters()} 46setLimit(limit,submit=!1){this.SM_Filter.setLimit(limit,submit)} 47setFieldFilter(id,filterstring,submit="auto",replaceOnEmpty=!0){this.SM_Filter.setFieldFilter(id,filterstring,(submit==="auto"&&this.submitType==="change")||submit===!0,replaceOnEmpty)} 48setSearchFilter(value,properties,submit="auto"){this.SM_Filter.setSearchFilter(value,properties,(submit==="auto"&&this.submitType==="change")||submit===!0)} 49setOrderFilter(id,filterstring,submit="auto"){this.SM_Filter.setOrderFilter(id,filterstring,(submit==="auto"&&this.submitType==="change")||submit===!0)} 50setConnectedFilter(filterobject,submit="auto"){this.SM_Filter.setConnectedFilter(filterobject,(submit==="auto"&&this.submitType==="change")||submit===!0)} 51reset(){this.SM_Filter.reset()} 52submit(id=null){this.SM_Filter._createFilterstring(this._options.logic,id)}};class SM_Filterbar_Dropdown{constructor(dropdown,options={}){this.dropdown=dropdown;this._defaults={active:[],generateFilter:!0,logic:"AND",allowRerender:!0,isLoadmoreFilter:!1,showTotal:!1,showNameInUrlParams:!1,sort:"",renderLabel:function(category,input){let name=category.name;if(input.dataset.prefix){name=input.dataset.prefix+name} 53if(input.dataset.suffix){name+=input.dataset.suffix}
54if(this.type==="external"&&this._options.showTotal){name+=` (${category.total})`} 55return name},};this._selectedValues=new Set();this._events={};this._statics={filterbar:"[data-sm-filterbar]",};this._options=options?Object.assign(this._defaults,options):this._defaults} 56_warnMsg(type){switch(type){case "el":{console.warn("SiteManager Filter - Dropdown: No dropdown found.");return} 57case "filterbar":{console.warn("SiteManager Filter - Dropdown: No filterbar found.");return} 58case "generic":{console.warn("SiteManager Filter - Dropdown: An error has occured.");return}}} 59_sortData(data,sort){return data.sort((a,b)=>{if(a.id<b.id){return sort==="asc"?-1:1} 60if(a.id>b.id){return sort==="asc"?1:-1} 61return 0})} 62_createOption(category,isActive=!1){const option=document.createElement("option");const{id,name,filterId,type}=category;option.value=id;option.dataset.title=name;if(this._options.renderLabel&&{}.toString.call(this._options.renderLabel)==="[object Function]"){option.innerHTML=this._options.renderLabel.call(this,category,option)}else{option.textContent=name} 63if(isActive){option.setAttribute("selected",!0)} 64if(filterId&&type){option.dataset.filterId=filterId;option.dataset.filterType=type} 65return option} 66_setURLParams(selectedOptions=[]){let newParams=new URLSearchParams();[...selectedOptions].forEach((option)=>{const value=this.showNameInUrlParams?option.dataset.title:option.value;newParams.append(this.identifier,value)});this.SM_Filterbar.setParameters(this.identifier,newParams)} 67_resetState(){const options=[...this.dropdown.querySelectorAll(`option`)];let hasActive=!1;[...options].forEach((option)=>{const cat=this.formattedCategories.sub_categories.find((sub)=>sub.id==option.value);if(!cat)return;if(cat.active){option.selected=!0;hasActive=!0}else{option.selected=!1}});if(!hasActive){const placeholder=this.dropdown.querySelector("option[disabled][selected][hidden], option[data-placeholder='true']");if(placeholder){placeholder.selected=!0}} 68if(this.select?.slim&&this.select?.slim?.config){const config=this.select.slim.config;this.select.slim.destroy();new SlimSelect({select:this.select,...config,})} 69if(hasActive){this._createFilterstring(!0)}else if(this.SM_Filterbar.options.URLHandling){this._setURLParams()}} 70_reset(){this.SM_Filterbar.setFilter(this.identifier,"","auto")} 71_createFilterstring(init=!1,isRerender=!1){const{logic}=this._options;const selectedOptions=this.select.selectedOptions;let filterstring="";this._selectedValues.clear();for(let i=0;i<selectedOptions.length;i++){this._selectedValues.add(selectedOptions[i].value)} 72this.SM_Filterbar.options.URLHandling&&this._setURLParams(selectedOptions);switch(this.type){case "external":filterstring=this.SM_Filterbar._createExternalFilterstring(selectedOptions,logic);break;case "dynamic":default:filterstring=[...selectedOptions].map((option)=>option.value).reduce((acc,value)=>acc+`cat_${value} ${logic} `,"").slice(0,-4);break} 73const activeOptions=[...selectedOptions].filter((option)=>option.value!==this.option.value);if(isRerender){this.SM_Filterbar.setFilter(this.identifier,filterstring,!1,activeOptions)}else{this.SM_Filterbar.setFilter(this.identifier,filterstring,init?!0:"auto",activeOptions)}} 74_getFilterbar(){return new Promise((resolve,reject)=>{if(this.filterbar.SM_Filterbar)resolve(this.filterbar.SM_Filterbar);this.filterbar.addEventListener("init",()=>{resolve(this.filterbar.SM_Filterbar)});setTimeout(()=>{if(!this.filterbar.SM_Filterbar)resolve(null);},5000)})} 75initEvents(){this.select.addEventListener("change",(e)=>{this._createFilterstring()});this.SM_Filterbar.on("reset",()=>{this._resetState()})} 76initDropdown(isRerender=!1){let{active,inactive}=this.dropdown.dataset;const{sort}=this._options;this.parent=this.option.value;switch(this.type){case "external":this.formattedCategories=this.SM_Filterbar._formatExternalFilters(this.categories,this.parent);break;case "dynamic":default:this.formattedCategories=this.SM_Filterbar._formatFilters(this.categories,this.parent);break} 77if(isRerender&&(this.formattedCategories||this._selectedValues.size===0)){this.select.innerHTML=""} 78if(!this.formattedCategories)return;if(isRerender){this.option.selected=!1;this.select.append(this.option)} 79if(this.parent==0||this.parent==""){this.option.value=this.formattedCategories.id;this.parent=this.formattedCategories.id} 80active=active?active.split(","):[];inactive=inactive?inactive.split(","):[];let hasActive=!1;const params=!isRerender?this.SM_Filterbar.initialParams.getAll(this.identifier):[];const hasParams=params&¶ms.length>0;if(sort&&sort!=="") 81this.formattedCategories.sub_categories=this._sortData(this.formattedCategories.sub_categories,sort);
81this.formattedCategories.sub_categories.forEach((sub)=>{const stringId=sub.id.toString();const urlParamName=this.showNameInUrlParams?sub.name:stringId;if(inactive.includes(stringId))return;let isActive=hasParams?params.includes(stringId)||params.includes(urlParamName):active.includes(stringId);if(isActive){this._selectedValues.add(stringId)}else if(this._selectedValues.has(stringId)){isActive=!0} 82const option=this._createOption(sub,isActive);this.select.append(option);sub.active=isActive;if(isActive){hasActive=!0}});if(hasActive){this._createFilterstring(!0,isRerender)}} 83getSelectedValues(){return Array.from(this._selectedValues)} 84async init(){this.select=this.dropdown.querySelector("[data-filter]");if(!this.select){this._warnMsg("el");return} 85this.filterbar=this.select.closest(this._statics.filterbar);if(!this.filterbar){this._warnMsg("filterbar");return} 86this.SM_Filterbar=await this._getFilterbar();if(!this.SM_Filterbar){this._warnMsg("filterbar");return} 87this.showNameInUrlParams=this.SM_Filterbar.showNameInUrlParams??this._options.showNameInUrlParams??!1;this.option=this.select.querySelector("option");const dataOptions=["logic","alias","isLoadmoreFilter","sort"];dataOptions.forEach((option)=>(this._options[option]=this.dropdown.dataset[option]||this._options[option]));this.categories=this.SM_Filterbar.getCategories();this.formattedCategories={};this.type=this.SM_Filterbar.getType();this.property=this.option.value;this.identifier=this._options.alias&&this._options.alias!==""?this._options.alias:this.dropdown.id;this.select.multiple&&(this.identifier=this.identifier+"[]");if(this._options.generateFilter){if(this.type==="external"&&this._options.isLoadmoreFilter){this.SM_Filterbar._getExternalFilter(this.property).then((filter)=>{this.categories=filter.data?[filter.data]:[];this.initDropdown();this.initEvents();const loader=this.dropdown.querySelector("[data-sm-loader]");if(loader&&loader.hasOwnProperty("SM_Loader")){loader.SM_Loader.stop()} 88const initEvent=new Event("init");this.select.dispatchEvent(initEvent);if(this._events.init){this.emit("init")}}).catch((err)=>{console.log(err)})}else{this.initDropdown();this.initEvents();const initEvent=new Event("init");this.select.dispatchEvent(initEvent);if(this._events.init){this.emit("init")}} 89this.SM_Filterbar.on("rerender",(data)=>{if(this._options.allowRerender&&this._options.generateFilter){if(this.type==="external"&&this._options.isLoadmoreFilter){const loader=this.dropdown.querySelector("[data-sm-loader]");if(loader&&loader.hasOwnProperty("SM_Loader")){loader.SM_Loader.play()} 90this.SM_Filterbar._getExternalFilter(this.property).then((filter)=>{this.categories=filter.data?[filter.data]:[];this.initDropdown(!0);if(loader&&loader.hasOwnProperty("SM_Loader")){loader.SM_Loader.stop()} 91this.emit("rerender",this.categories)}).catch((err)=>{console.log(err)})}else{this.categories=data;this.initDropdown(!0);this.emit("rerender",this.categories)}}})}else{this.initEvents();const initEvent=new Event("init");this.select.dispatchEvent(initEvent);if(this._events.init){this.emit("init")}}} 92on(name,listener){if(!this._events[name]){this._events[name]=[]} 93this._events[name].push(listener)} 94removeListener(name,listenerToRemove){if(!this._events[name]){throw new Error(`Can't remove a listener. Event "${name}" doesn't exits.`)} 95const filterListeners=(listener)=>listener!==listenerToRemove;this._events[name]=this._events[name].filter(filterListeners)} 96reset(){this._reset()} 97emit(name,...data){if(!this._events[name]){console.info(`Event "${name}" has no listeners.`);return} 98const fireCallbacks=(callback)=>{callback(...data)};this._events[name].forEach(fireCallbacks)}};class SM_Filter{constructor(el,options={}){this._defaults={loadmore:"auto",designMode:!1,rendersettings:"rendersettings",filters:"selectedfilters",categories:"categories",errorMessageText:"",submitRerender:!1,defaultExternalLimit:30,forceInit:!1,logic:"AND"};this._statics={structurePrefix:"s-structure-layout-",loadmoreWrapper:"load-more",loadmoreButtonCls:"s-btn",loadmoreText:"",hidden:"s-hidden",paginationCls:"db-pagination",scrollViewPrefix:"scrollView",errorMessageCls:"s-error",};this._options=options?this._deepMerge(this._defaults,options):this._defaults;this._events={};this.initialParams=new URLSearchParams(location.search);this.render=el;
98this.renderID=this.render.dataset.filter} 99_deepMerge(arr){const argl=arguments.length;let retObj;if(Object.prototype.toString.call(arr)==="[object Array]"){retObj=[];for(let p in arr){retObj.push(arr[p])}}else{retObj={};for(let p in arr){retObj[p]=arr[p]}} 100for(let i=1;i<argl;i++){for(let p in arguments[i]){if(retObj[p]&&typeof retObj[p]==="object"){retObj[p]=this._deepMerge(retObj[p],arguments[i][p])}else{retObj[p]=arguments[i][p]}}} 101return retObj} 102_isArray(variable){return Array.isArray(variable)} 103_detectEnvironment(){const url=new URL(window.location.href);const page=url.searchParams.get("page");const layID=url.searchParams.get("layID");const isCMS=page!==null&&page==="vcmspage.php";const isDesign=url.pathname.includes("preview.php")&&layID!==null;const isLocal=isCMS||isDesign;const isPreview=isLocal?!1:url.hostname.includes("sitemn.gr");const projectPath=typeof cleanURL_path!=="undefined"?cleanURL_path:url.searchParams.get("SM_User")?`/users/${url.searchParams.get("SM_User")}`:url.pathname.split("/").filter((path,i)=>i<=2).join("/");return{local:isLocal,env:isCMS?"cms":isDesign?"design":isPreview?"preview":"live",baseUrl:`${url.hostname}${projectPath}`,}} 104_warnMsg(type){switch(type){case "el":{console.warn("SiteManager Filter: No render overview found.");return} 105case "object":{console.warn("SiteManager Filter: Error parsing render. Add the data attributes.");return} 106case "generic":{console.warn("SiteManager Filter: An error has occured.");return}}} 107_objectToUrl(obj){if(!obj)return obj;switch(this.type){case "external":return JSON.stringify(obj);case "dynamic":default:return Object.keys(obj).map((key)=>`${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`).join("&")}} 108_fetchData(url,data,type="POST"){return new Promise((resolve,reject)=>{const xhr=new XMLHttpRequest();xhr.open(type,url,!0);this.type==="external"?xhr.setRequestHeader("Content-Type","application/json"):xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.onload=()=>{if(xhr.status===200){resolve(xhr.responseText)}else{reject({status:xhr.status,statusText:xhr.statusText,responseText:xhr.responseText,})}};xhr.onerror=function(){reject(Error("There was a network error."))};xhr.send(data)})} 109_buildErrorWindow(){const template=`<div class="s-error__window" style="position: absolute; left: 0; top: 0; width: 100%; height: 100%; z-index: 99999; background: #f55442; opacity: .9; padding: 3em; color: #fff; overflow: auto;"> 110 <header style="margin-bottom: 3em;"> 111 <h3 style="font-family: Arial, Helvetica, sans-serif, sans-serif; color: #fff; font-size: 2em; text-align: center; margin-bottom: .3em;">Some errors have been detected in your dynamic list.</h3> 112 <h4 style="font-family: Arial, Helvetica, sans-serif, sans-serif; color: #fff; font-size: 1.5em; text-align: center;">Please fix these errors before publishing your project!</h4> 113 </header> 114 <ul class="s-body__section" style="padding: 0; margin: 0; list-style-type: disc;"></ul> 115 </div>`;this.render.insertAdjacentHTML("afterbegin",template);this.render.style.minHeight="400px";this.errorWindow=this.render.querySelector(".s-error__window")} 116_setError(error){if(!this.errorWindow)this._buildErrorWindow();const body=this.errorWindow.querySelector(".s-body__section");const errorItem=`<li style="font-family: Arial, Helvetica, sans-serif, sans-serif;"> 117 ${error} 118 </li>`;body.insertAdjacentHTML("beforeend",errorItem)} 119_createErrorMessage(){const{hidden,errorMessageCls}=this._statics;let{errorMessageText}=this._options;if(errorMessageText==="")errorMessageText=this.filterbar?.dataset?.errorMessageText||"";this.error=document.createElement("div");this.error.textContent=errorMessageText;this.error.classList.add(errorMessageCls,hidden);this.renderContainer.append(this.error)} 120_setErrorMessage(){const{hidden}=this._statics;if(this.error){this.error.classList.remove(hidden);return}} 121_hideErrorMessage(){const{hidden}=this._statics;if(!this.error)return;
121this.error.classList.add(hidden)} 122_setURLParams(){const newParams=new URLSearchParams(window.location.search);const filters=this.getFilters();for(const[alias,params]of Object.entries(this.params)){newParams.delete(alias);for(const[key,value]of params.entries()){newParams.append(key,value)}} 123window.history.replaceState("","","?"+newParams.toString())} 124_clearRender(isTemplate=!1){const entries=isTemplate?[...this.renderContainer.content.children]:[...this.renderContainer.children];entries.forEach((entry)=>{if(entry===this.loadmore||entry===this.error)return;entry.remove()})} 125_detectErrors(){const{paginationCls}=this._statics;const hasPagination=this.render.querySelector(`.${paginationCls}`);if(hasPagination){this._setError("<b>Pagination Error:</b> As of now, pagination is not supported with dynamic filters.")} 126if(!this.loadmoreCheck){const rendersettings=JSON.parse(this.rendersettingsStart);switch(this.type){case "external":rendersettings.options.limit=1;break;case "dynamic":default:rendersettings.list_nr=1;break} 127this._fetchData(this.loadmoreUrl,this._objectToUrl(rendersettings)).then((response)=>{if(response==="no results"){this._setError("<b>Open Data Error:</b> Open data is not enabled. Please enable this option in the configuration of the collection.");return}}).catch((err)=>console.error(err))}} 128_detectLoadmore(){const{scrollViewPrefix}=this._statics;const loadmore=this.render.querySelector(`.${this._statics.loadmoreWrapper}`);if(loadmore){const nestedScript=loadmore.querySelector("script");if(nestedScript)nestedScript.remove();const id=loadmore.lastElementChild.id;this._statics.loadmoreText=loadmore.innerText;loadmore.remove();const script=this.render.querySelector("script");if(script)script.remove();if(id.startsWith(scrollViewPrefix)){this.onScroll=!0} 129return!0} 130return!1} 131_getPropertyBounds(property){return[]} 132_createDynamicFilterstring(logic){if(Object.keys(this._filters).length>0){const filterstring="("+Object.values(this._filters).join(`) ${logic} (`)+")";this.rendersettings.list_cat=`(${this.rendersettings.list_cat}) AND (${filterstring})`} 133if(Object.keys(this._fieldFilters).length>0){const fieldFilterstring="("+Object.values(this._fieldFilters).join(`) ${logic} (`)+")";this.rendersettings.list_filters+=`(${fieldFilterstring}) AND `} 134if(Object.keys(this._orderFilters).length>0){this.rendersettings.order_filters=Object.values(this._orderFilters).join(", ")} 135if(Object.keys(this._connectedFilters).length>0){this.rendersettings.connected=JSON.stringify(this._connectedFilters)} 136if(this._limit||this._limit===0){this.rendersettings.list_nr=this._limit} 137if(this._searchFilter?.value!==""&&this._searchFilter?.properties?.length>0){const searchFilterstring="("+this._searchFilter.properties.map(property=>'LOWER('+property+') LIKE `%'+this._searchFilter.value.toLowerCase()+'%`').join(" OR ")+")";this.rendersettings.list_filters+=`(${searchFilterstring}) AND `}} 138_createExternalFilterstring(logic){if(Object.keys(this._filters).length>0||Object.keys(this._fieldFilters).length>0){if(!this.rendersettings.options.hasOwnProperty("filter")||(!this.rendersettings.options.filter.hasOwnProperty("and")&&!this.rendersettings.options.filter.hasOwnProperty("or"))){this.rendersettings.options.filter={}} 139if(!this.rendersettings.options.filter.hasOwnProperty(logic)){const filters=JSON.parse(JSON.stringify(this.rendersettings.options.filter));this.rendersettings.options.filter[logic]=[];if(logic==="and"&&this.rendersettings.options.filter?.or){this.rendersettings.options.filter.and.push(filters);delete this.rendersettings.options.filter.or}} 140if(Object.keys(this._filters).length>0){if(logic==="or"&&this.rendersettings.options.filter?.and?.length===0){delete this.rendersettings.options.filter.and} 141if(logic==="or"&&this.rendersettings.options.filter?.and?.length>0){this.rendersettings.options.filter.and.push({or:Object.values(this._filters).flat(),});delete this.rendersettings.options.filter.or}else{this.rendersettings.options.filter[logic].push(...Object.values(this._filters).flat())}} 142if(Object.keys(this._fieldFilters).length>0){this.rendersettings.options.filter[logic].push(...Object.values(this._fieldFilters))}} 143if(Object.keys(this._orderFilters).length>0){if(!this.rendersettings.options.sorts) 144this.rendersettings.options.sorts=[];this.rendersettings.options.sorts.push(...Object.values(this._orderFilters))} 145if(this._searchFilter?.value!=="") 146this.rendersettings.options.search=this._searchFilter;if(this._limit||this._limit===0){this.rendersettings.options.limit=this._limit}} 147_createFilterstring(logic="AND",id=null,replaceOnEmpty=!0){this.rendersettings=JSON.parse(this.rendersettingsStart);
147if(this._events["change.before"]){this.emit("change.before","replace","filter")} 148switch(this.type){case "external":this._createExternalFilterstring(logic.toLowerCase());break;case "dynamic":default:this._createDynamicFilterstring(logic);break} 149this.loadEntries("replace","filter",id,replaceOnEmpty)} 150_getEndpoint(){switch(this.type){case "external":return this._environment.local?"https://s1.sitemn.gr/cmsfiles/ec_loadmore.php":`//${this._environment.baseUrl}swfiles/lib/external_content/loadmore.php`;case "dynamic":default:return this._environment.local?"https://s1.sitemn.gr/cmsfiles/loadmore.php":`//${this._environment.baseUrl}swfiles/lib/loadmore.php`}} 151_parseFetchResponse(response){switch(this.type){case "external":if(!response.success){throw new Error(response.message)} 152return{html:response.data?.reduce((acc,val)=>acc+val,"")||"",empty:!response.has_more,total:response.total,};case "dynamic":default:return response}} 153checkLoadmore(){this.rendersettings=JSON.parse(this.rendersettingsStart);let rendersettings={};let showAll=!1;switch(this.type){case "external":this._createExternalFilterstring(this.logic.toLowerCase());rendersettings=JSON.parse(JSON.stringify(this.rendersettings));showAll=rendersettings.options.limit===0;rendersettings.options.offset=rendersettings.options.limit;rendersettings.options.limit=1;break;case "dynamic":default:this._createDynamicFilterstring(this.logic);rendersettings=JSON.parse(JSON.stringify(this.rendersettings));showAll=parseInt(rendersettings.list_nr)===0;rendersettings.pageno=parseInt(rendersettings.list_nr)+1;rendersettings.list_nr=1;break} 154if(showAll&&this.loadmore){this.loadmore.classList.add(this._statics.hidden)} 155this._fetchData(this.loadmoreUrl,this._objectToUrl(rendersettings)).then((response)=>{if(response==="no results"){this._setError("<b>Open Data Error:</b> Open data is not enabled. Please enable this option in the configuration of the collection.");return} 156const data=this._parseFetchResponse(JSON.parse(response));const html=data.html;if(html!==""){if(this.loadmore) 157this.loadmore.classList.remove(this._statics.hidden);if(this.onScroll)this.initScroll();}else if(this.loadmore){this.loadmore.classList.add(this._statics.hidden)} 158if(this._events.total){this._total=data.total;this.emit("total",data.total)}}).catch((err)=>console.error(err))} 159initLoadmore(){const{loadmoreWrapper,loadmoreButtonCls,loadmoreText}=this._statics;this.loadmore=document.createElement("div");this.loadmore.classList.add(loadmoreWrapper);const button=document.createElement("button");button.classList.add(loadmoreButtonCls);button.textContent=loadmoreText;this.loadmore.append(button);this.renderContainer.append(this.loadmore);this.checkLoadmore()} 160initScroll(){const lastItem=[...this.renderContainer.children].reverse().find((item)=>!item.classList.contains(this._statics.errorMessageCls)&&item!==this.loadmore);if(!lastItem)return;const observer=new IntersectionObserver((entries,observer)=>{if(!entries[0].isIntersecting)return;observer.disconnect();if(this._events["change.before"]){this.emit("change.before","add","scroll")} 161switch(this.type){case "external":this.rendersettings.options.offset=this.rendersettings.options.offset+this.rendersettings.options.limit;break;case "dynamic":default:this.rendersettings.pageno=parseInt(this.rendersettings.pageno)+1;break} 162this.loadEntries("add","scroll")});observer.observe(lastItem)} 163initEvents(){if(this.loadmore){this.loadmore.addEventListener("click",(e)=>{if(!this.dynamicLoadmore){const button=e.target.closest(`.${this._statics.loadmoreButtonCls}`);if(!button)return} 164if(this._events["change.before"]){this.emit("change.before","add","loadmore")} 165switch(this.type){case "external":this.rendersettings.options.offset=this.rendersettings.options.offset+this.rendersettings.options.limit;break;case "dynamic":default:this.rendersettings.pageno=parseInt(this.rendersettings.pageno)+1;break} 166this.loadEntries("add","loadmore")})} 167if(this.resetButton){this.resetButton.addEventListener("click",()=>{this.reset()})}} 168loadFilter(filter){return new Promise((res,rej)=>{const filtersRenderSettings=this._deepMerge(this.rendersettings,{});filtersRenderSettings.returnType="filter";filtersRenderSettings.returnProperty=filter;this._fetchData(this.loadmoreUrl,this._objectToUrl(filtersRenderSettings)).then((response)=>{const data=JSON.parse(response);if(!data.success){throw new Error(data.message)} 169res(data.data)}).catch((err)=>{console.error(err);rej(err)})})} 170loadFilters(id){const filtersRenderSettings=this._deepMerge(this.rendersettings,{});filtersRenderSettings.returnType="filters";this._fetchData(this.loadmoreUrl,this._objectToUrl(filtersRenderSettings)).then((response)=>{const data=JSON.parse(response);if(!data.success){throw new Error(data.message)} 171this.categories=data.data;
171this.emit("rerender",this.categories,id)}).catch((err)=>console.error(err))} 172loadEntries(type,filter,id=null,replaceOnEmpty=!0){this.requests++;const addEntries=type==="add";const{hidden}=this._statics;if(this._environment.local&&this.type==="dynamic") 173this.rendersettings.list_nr_add=this.rendersettings.list_nr;this._fetchData(this.loadmoreUrl,this._objectToUrl(this.rendersettings)).then((response)=>{if(--this.requests>0)return;const data=JSON.parse(response);const formattedData=this._parseFetchResponse(data);const{html,empty,total}=formattedData;if(this._options.submitRerender&&this.type==="external"){this.loadFilters(id)} 174const isTemplate=this.renderContainer.nodeName==="TEMPLATE";if(html!==""){if(addEntries){if(this.loadmore&&!this.dynamicLoadmore){this.loadmore.insertAdjacentHTML("beforebegin",html)}else{if(isTemplate){const fragment=document.createRange().createContextualFragment(html);this.renderContainer.content.append(fragment)}else{this.renderContainer.insertAdjacentHTML("beforeend",html)}}}else{this._clearRender(isTemplate);
174if(this.loadmore&&!this.dynamicLoadmore){this.loadmore.insertAdjacentHTML("beforebegin",html)}else{if(isTemplate){const fragment=document.createRange().createContextualFragment(html);this.renderContainer.content.append(fragment)}else{this.renderContainer.insertAdjacentHTML("afterbegin",html)}}} 175if(typeof AOS!=="undefined"&&AOS){AOS.refreshHard()} 176if(this._events.total){this._total=data.total;this.emit("total",total)} 177if(this._events.change){this.emit("change",type,formattedData,filter);this.emit("change.after",type,formattedData,filter)} 178if(this.loadmore){if(empty){this.loadmore.classList.add(hidden)}else{this.loadmore.classList.remove(hidden)}} 179if(this.onScroll){if(!empty){this.initScroll()}} 180this._hideErrorMessage()}else{if(replaceOnEmpty){this._clearRender(isTemplate);if(this.loadmore)this.loadmore.classList.add(hidden);if(this._events.total){this._total=data.total;this.emit("total",total)} 181if(this._events.change){this.emit("change","empty",data,filter);this.emit("change.after","empty",data,filter)} 182this._setErrorMessage()}else{if(this._events.change){this.emit("change","empty",data,filter);this.emit("change.after","empty",data,filter)}}}}).catch((err)=>console.error(err))} 183on(name,listener){if(!this._events[name]){this._events[name]=[]} 184this._events[name].push(listener)} 185removeListener(name,listenerToRemove){if(!this._events[name]){throw new Error(`Can't remove a listener. Event "${name}" doesn't exists.`)} 186const filterListeners=(listener)=>listener!==listenerToRemove;this._events[name]=this._events[name].filter(filterListeners)} 187emit(name,...data){if(!this._events[name]){console.info(`Event "${name}" has no listeners.`);return} 188const fireCallbacks=(callback)=>{callback.call(this,...data)};this._events[name].forEach(fireCallbacks)} 189init(){const{structurePrefix}=this._statics;if(!this.render){this._warnMsg("el");return} 190this.connector=document.querySelector(`[data-render="${this.render.dataset.filter}"]`);if(!this.connector){const loadmore=this.render.querySelector(".load-more");if(!loadmore&&!this._options.forceInit)return} 191this.filterbar=document.querySelector(`[data-sm-filterbar][data-render="${this.render.dataset.filter}"]`);this.logic=this.filterbar?.dataset?.logic||this._options.logic;this.renderContainer=this.render.querySelector(`:scope > [class^="${structurePrefix}"]`)||this.render;try{this.rendersettings=JSON.parse(this.render.dataset[this._options.rendersettings]);this.categories=JSON.parse(this.render.dataset[this._options.categories])}catch(e){this._warnMsg("object");return} 192try{this.selectedfilters=JSON.parse(this.render.dataset[this._options.filters])}catch(e){this.selectedfilters=[]} 193this.type=this.rendersettings.hasOwnProperty("type")?this.rendersettings.type:"dynamic";switch(this.type){case "external":if(!this.rendersettings.hasOwnProperty("options")){this.rendersettings.options={limit:0,offset:0,sorts:[],}} 194if(!this.rendersettings.options.hasOwnProperty("limit")) 195this.rendersettings.options.limit=0;if(!this.rendersettings.options.hasOwnProperty("offset")) 196this.rendersettings.options.offset=0;if(!this.rendersettings.options.hasOwnProperty("sorts")) 197this.rendersettings.options.sorts=[];if(this.rendersettings.options.limit===0) 198this.rendersettings.options.limit=this._options.defaultExternalLimit;this.rendersettings.page_id=sw_var_pid;if(typeof sw_var_extcon_id!=="undefined") 199this.rendersettings.page_entry_id=sw_var_extcon_id;break;case "dynamic":default:this.rendersettings.list_filters=this.rendersettings.list_filters||this.selectedfilters.map((filter)=>"filter_"+filter.id+" = `"+filter.value+"` AND ").join("");this.rendersettings.sw_var_lid=this.rendersettings.sw_var_lid||sw_var_lid;this.rendersettings.session=!1;break} 200this.rendersettingsStart=JSON.stringify(this.rendersettings);this._environment=this._detectEnvironment();this.isLoading=!1;this.requests=0;this.params={};this._filters={};this._fieldFilters={};this._searchFilter={};this._orderFilters={};this._connectedFilters={};this._activeFilters={};this._total=null;this._limit=null;this.loadmoreUrl=this._getEndpoint();this.loadmore=document.querySelector(`[data-loadmore][data-render="${this.renderID}"]`);this.loadmoreCheck=!1;this.onScroll=!1;this.resetButton=document.querySelector(`[data-reset][data-render="${this.renderID}"]`);if(this.loadmore){this.dynamicLoadmore=!0;this.loadmoreCheck=!0;this._detectLoadmore();this.checkLoadmore()}else if(this._options.loadmore){if(this._detectLoadmore()){this.loadmoreCheck=!0;if(this.onScroll)this.checkLoadmore();else this.initLoadmore()}} 201if(this._environment.local){this._detectErrors()} 202this.error=document.querySelector(`[data-error][data-render="${this.renderID}"]`);if(!this.error)this._createErrorMessage();if(this._options.designMode&&this._environment.local) 203this.error.style.setProperty("display","block","important");this.initEvents();this.render.SM_Filter=this;
203const initEvent=new Event("init");this.render.dispatchEvent(initEvent);if(this._events.init){this.emit("init")}} 204isSubmitRerenderEnabled(){return this._options.submitRerender&&this.type==="external"} 205fetchData(object){return new Promise((resolve,reject)=>{this._fetchData(this.loadmoreUrl,this._objectToUrl(object)).then((response)=>{try{const data=JSON.parse(response);resolve({success:!0,data:data,})}catch(e){resolve({success:!1,data:response,})}}).catch((err)=>reject(err))})} 206getCategories(){if(!this.categories)return null;return this.categories} 207getType(){if(!this.type)return null;return this.type} 208getFilters(){return{filters:JSON.parse(JSON.stringify(this._filters)),fields:JSON.parse(JSON.stringify(this._fieldFilters)),search:JSON.parse(JSON.stringify(this._searchFilter)),orders:JSON.parse(JSON.stringify(this._orderFilters)),connected:JSON.parse(JSON.stringify(this._connectedFilters)),}} 209getPropertyBounds(property){return this._getPropertyBounds(property)} 210getRendersettings(){return this.rendersettings} 211getTotal(){return this._total} 212getActiveFilters(){return this._activeFilters} 213setParameters(alias,params){this.params[alias]=params;this._setURLParams()} 214deleteParameters(alias){this.params[alias]=new URLSearchParams();this._setURLParams()} 215updateParameters(){this._setURLParams()} 216setFilter(id,filterstring,submit=!0,activeFilters=[]){this._activeFilters[id]=activeFilters;if(filterstring===""||filterstring.length===0) 217delete this._filters[id];else this._filters[id]=filterstring;if(this._events["filter.set"]){this.emit("filter.set",id,activeFilters)} 218if(submit)this.submit(id);} 219clearInitialFilters(){this.rendersettingsStart=JSON.parse(this.rendersettingsStart);this.rendersettingsStart.list_cat="";this.rendersettingsStart=JSON.stringify(this.rendersettingsStart)} 220clearInitialFieldFilters(){this.rendersettingsStart=JSON.parse(this.rendersettingsStart);this.rendersettingsStart.list_filters="";this.rendersettingsStart=JSON.stringify(this.rendersettingsStart)} 221setFieldFilter(id,filterstring,submit=!0,replaceOnEmpty=!0){if(filterstring==="")delete this._fieldFilters[id];else this._fieldFilters[id]=filterstring;if(submit)this.submit(id,replaceOnEmpty);} 222setSubmitType(type){if(!["auto","change","submit"].includes(type))return;this.submitType=type} 223setLimit(limit,submit=!1){this._limit=limit;if(submit)this.submit();} 224resetLimit(submit=!1){this._limit=null;if(submit)this.submit();} 225setSearchFilter(value,properties,submit=!0){if(value==="")this._searchFilter={};else this._searchFilter={value:value,properties:properties,};if(submit)this.submit("search");} 226setOrderFilter(id,filterstring,submit=!0){if(filterstring==="")delete this._orderFilters[id];else this._orderFilters[id]=filterstring;if(submit)this.submit(id);} 227setConnectedFilter(filterobject,submit=!0){if(Object.keys(filterobject)===0)delete this._connectedFilters;else this._connectedFilters=filterobject;if(submit)this.submit();} 228setPage(page,type="replace",event="pagination"){this.rendersettings=JSON.parse(this.rendersettingsStart);switch(this.type){case "external":this._createExternalFilterstring(this.logic.toLowerCase());this.rendersettings.options.offset=Math.floor(this.rendersettings.options.limit*(page-1));break;case "dynamic":default:this._createDynamicFilterstring(this.logic);this.rendersettings.pageno=page;break} 229if(this._events["change.before"]){this.emit("change.before",type,event,page)} 230this.loadEntries(type,event)} 231setView(quantity){let activePage=1;let activeLimit=0;switch(this.type){case "external":activeLimit=this.rendersettings.options.limit;activePage=Math.floor(this.rendersettings.options.offset/activeLimit)+1;this.rendersettings.options.limit=quantity;break;case "dynamic":default:activeLimit=this.rendersettings.list_nr;activePage=this.rendersettings.pageno;this.rendersettings.list_nr=quantity;break}} 232reset(){if(this._events["reset.before"]){this.emit("reset.before")} 233this._filters={};this._fieldFilters={};this._searchFilter={};this._orderFilters={};this._connectedFilters={};this._activeFilters={};this._limit=null;this._createFilterstring(this.logic);
233if(this._events.reset){this.emit("reset")}} 234submit(id=null,replaceOnEmpty=!0){this._createFilterstring(this.logic,id,replaceOnEmpty)}}
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.