
const seasonsListNames = [
    
      "All season",
         "Primăvară",
       "Vară"	,
       "Toamnă",
         "Iarnă",
         "Primăvară/Vară",
        "Toamnă/Iarnă",
         "Primăvară/Toamnă"

];
function productTemplate(item){
    let htmlTo = '<li class="productDisplay" data-path="'+item.slug+'" data-fid="'+item.familyId+'">\
    <a href="'+item.slug+'" title="'+item.name+'">\
    <span class="productHolder" data-fid="'+item.familyId+'"  id="pictf-'+item.familyId+'">\
		<picture class="productImage" data-fid="'+item.familyId+'">\
            <source srcset="'+item.thumb+'.webp" type="image/webp">\
            <img src="'+item.thumb+'.jpg" type="image/jpeg" alt="'+item.name+'">\
        </picture>';
		  if(parseFloat(item.priceS) > parseFloat(item.price)){
			  if(parseFloat(item.supersale)){
				  htmlTo += '  <span class="supersale"><i class="crs s-24 thunderIcon white"></i> -'+(100 - (item.price * 100 / item.priceS)).toFixed(0)+' %</span>';
			  } else{
			 htmlTo += ' <span class="savings">Economisește '+(item.priceS - item.price).toFixed(0)+' lei</span>';
			  }
		  }
htmlTo += '</span></a>\
     <div class="productTitle">\
	<h3><a href="'+item.slug+'" title="'+item.name+'">'+item.name+'</a></h3></div>\
	<span class="prices">';
        if(parseFloat(item.priceS) > parseFloat(item.price)){
        htmlTo += '<span class="price salePrice">'+item.price+' lei </span>';
		 if(!parseFloat(item.supersale)){
		htmlTo += '<span class="saleLabel">- '+(100 - (item.price * 100 / item.priceS)).toFixed(0)+' %</span>';
		 }
		htmlTo += '<span class="price cutThrough">'+item.priceS+' lei</span>';
        }else{
			htmlTo += '<span class="price">'+item.price+' lei</span>';
            if(parseInt(item.priceL)){ 
                htmlTo += '<span class="price rrp">RRP: '+item.priceL+' lei</span>';
                }
        }
		
		
		  htmlTo += '</span>\
      <span class="tooltip flex fwrap famsizes sizes" id="sizesFamId-'+item.familyId+'"></span>\
    </li>';
    return htmlTo;
}

function markWishList(){
    const wgo = getCookie('wish');
   
        const listaJson = JSON.parse(wgo);
      
            let inWish = Object.keys(listaJson).map( p => parseInt(p));
            if(inWish.length > 0){
                
                Array.from(document.getElementsByClassName('toWishlist')).forEach(inwl => {
                    const productid = inwl.dataset['productid'];
                    if(productid && inWish.includes(parseInt(productid))){
                        inwl.classList.add('wished');
                    }
                });
            }
        
        
    
}
function filterProducts(t){
    let value = t.value;
    //let fid = t.attributes['data-fid'].value;
    let filterGroup = t.dataset['filtergroup'];
        if(filterGroup == 's'){
           
        if(t.checked){

            if(typeof appliedFilters['s'] === 'undefined') appliedFilters['s'] = [];
            appliedFilters['s'].push(parseInt(value));
          

      }else{
          if(typeof appliedFilters['s'] !== 'undefined') 
          appliedFilters['s'] = appliedFilters['s'].filter(x => x != value);
      }

        }
    let fig = filterGroup;

    
        if(t.checked){
            if(typeof appliedFilters['f'+fig] === 'undefined') appliedFilters['f'+fig] = [];
            appliedFilters['f'+fig].push(parseInt(value));

        }else{
            if(typeof appliedFilters['f'+fig] !== 'undefined') 
            appliedFilters['f'+fig] = appliedFilters['f'+fig].filter(x => x != value);
        }
        if(fig == 1){
         fillSizeFilter(filtruSize.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
        }
        if(fig == 2){
            fillBrandFilter(filterBrands.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
        }
        if(fig == 5){
            fillMaterialFilter(filtruMaterial.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
        }
        if(fig == 3){
            fillColorFilter(filtruCuloare.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
        }
    
    if(fig == 'c'){
        if(t.checked){
            
            if(typeof appliedFilters['c'] === 'undefined') appliedFilters['c'] = [];
            
            appliedFilters['c'].push(parseInt(value));
            

        }else{
            if(typeof appliedFilters['c'] !== 'undefined') 
            appliedFilters['c'] = appliedFilters['c'].filter(x => x != value);
        }
        fillCategoryFilter(filterCategories.filter(id => (id > 0 && typeof assideCats[id] !== 'undefined' )).map(id => ({id:id, name:assideCats[id].name})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
       
       
    }
    if(fig == -1){
        
        if(t.checked){
          
            if(typeof appliedFilters['pf'] === 'undefined') appliedFilters['pf'] = [];
              appliedFilters['pf'].push(parseInt(value));
            

        }else{
            if(typeof appliedFilters['pf'] !== 'undefined') 
            appliedFilters['pf'] = appliedFilters['pf'].filter(x => x != value);
        }
        fillPriceFilter();
        fillSeasonFilter(filterSezoane);
       
       
    }
   // let filterurl = makeQueryParamNoCat(Object.entries(appliedFilters));
    //console.log(filterurl);

    

    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");

}
function showProducts(msg, t){
    
    let htmlContent = '';
    if(!msg.items.length){
        htmlContent = "Nu am gasit nici un produs!"
    }

    let listaA = document.getElementById('showresults');
    if(!listaA) return false;
    let htmlContentArray = [];
    for(item of msg.items){
        

        htmlContentArray.push(productTemplate(item));


    }
    listaA.innerHTML = htmlContentArray.join('');
    let tpp =  document.getElementById('countProducts');
    if(tpp){
        tpp.innerHTML =  msg.total+' produs'+((msg.total>1)?"e":'');
    }
    let cnt = document.getElementById('arataNrProdFilter'); 
    if(cnt){
        cnt.innerHTML =  "Arata ("+msg.total+' produs'+((msg.total>1)?"e":'')+")";
    }

    if(window.innerWidth > 1080 && msg.items.length){
            setTimeout(getSecondPicture, 100);
    }

    markWishList();
    updatePagination(msg);
    updateFilters(msg, t);
    if(msg.items.length){
    getProductsVariations();
    }
}

function makeQueryParamNoCat(appliedFiltersNoCat, excluded = [], exclgrup = false){
    try{
         return appliedFiltersNoCat.map( ([k,a]) => (a.length && k != 'cids' && k != 'collection'  && k != 'type' && typeof a === 'object') 
    ? a.map(v => ( (exclgrup != k  || !exclgrup) && !excluded.includes(v) ) ? k+'[]='+v : null).filter( a => a).join('&')
    : ((a.length && k != 'collection' && k != 'cids' && k != 'type') ? ( k+'='+a ) : false) ).filter(a => a).join('&');
    }catch(e){
        
        console.log(e,appliedFiltersNoCat);
        return '';
    }
}

function makeQueryParam(){
    return Object.entries(appliedFilters).map( ([k,a]) => (a.length  && typeof a === 'object')? a.map(v =>  k+'[]='+v ).join('&'):((a.length )? ( k+'='+a ): false)).filter(a => a).join('&');
}

function updatePagination(msg){
    let paginationEl = document.getElementById('pagination');
    if(!paginationEl) return false;

    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let exclude = 0;
    let validPath = [];

    basepath.forEach(trep => {
        let miurl = trep.match(/\-m([0-9]+)$/);
        if(miurl){
            exclude = parseInt(miurl[1]);
           
            //validPath.push(trep);
        }
        let biurl = trep.match(/\-b([0-9]+)$/);
        if(biurl){
          //  exclude = parseInt(biurl[1]);
          
        }
        else{
            if(!miurl || appliedFilters.f5.includes(parseInt(miurl[1])))
            validPath.push(trep);
        }
       
    });
    let fullPath = validPath.filter(pat => pat !== null).join('/');

    const qcst = makeQueryParamNoCat(Object.entries(appliedFilters));
    


    paginationEl.innerHTML = '';
    for(let i = 1; i <= msg.pagini; i++){
        if(i == 1 || (i<(msg.p+3) && i>(msg.p-3)) || i == msg.pagini) { 
            if(msg.p == i){
                paginationEl.innerHTML += '<li class="current"><span>1</span></li>';
                if(msg.p > 3){
                    paginationEl.innerHTML += '<li class=""><span>...</span></li>';
                }
            }else{
                paginationEl.innerHTML += '<li><a class="" href="'+fullPath+'?p='+(i)+''+( qcst!='' ?  '&'+qcst : '')+'">'+(i)+'</a></li>';
            }
        }
    }
    if(msg.pagini > msg.p){
        paginationEl.innerHTML += '<li class="next"><a class="" href="'+fullPath+'?p='+(msg.p+1)+'&'+( qcst!='' ?  '&'+qcst : '')+'"><i class="crsIcon s-8 downIcon"></i></a></li>';
    }

}
function fillBrandFilter(aBrands){
    let brandFilter = document.getElementById('brandFilter');
    if(!brandFilter) return;
    let brandFilterSelected = document.getElementById('selectedBrandFilter');
    
    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let exclude = 0;
    let validPath = [];

    basepath.forEach(trep => {
        let miurl = trep.match(/\-m([0-9]+)$/);
        if(miurl){
            exclude = parseInt(miurl[1]);
           
            //validPath.push(trep);
        }
        let biurl = trep.match(/\-b([0-9]+)$/);
        if(biurl){
          //  exclude = parseInt(biurl[1]);
          
        }
        else{
            if(!miurl || appliedFilters.f5.includes(parseInt(miurl[1])))
            validPath.push(trep);
        }
       
    });
    //let fullPath = validPath.filter(pat => pat !== null).join('/');
    let fullPath = baseUrlPath;

    let qcst ='';// makeQueryParamNoCat(Object.entries(appliedFilters), exclude);

    if(brandFilter){
        brandFilter.innerHTML = '';
        let aBrandFilterHtml = [];
       let aSelectedBrandFilterHtml = [];
		document.getElementById('selFilterBrand').classList.add('noshow');

        appliedFilters.f2.forEach(sid => {
            let fname = attrValNames[sid].value;
            if(window.innerWidth > 1080){
               
                qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [parseInt(sid), exclude]);
                if(qcst != '') qcst = "?" + qcst;
                aSelectedBrandFilterHtml.push('<a data-valuetxt="'+fname+'" class="  standardF checkMe checkF" href="'+fullPath+''+qcst+'" title="'+fname+'">'+fname+'</a>');
            }else{
               
                aSelectedBrandFilterHtml.push('<label data-valuetxt="'+fname+'" class="filterFamily2 standardF checkMe  sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f2[]" data-fid="'+sid+'" id="fiv-'+sid+'" data-filtergroup="2" value="'+sid+'">'+fname+'<span></span></label>');
            }
        })
        if(brandFilterSelected){
            brandFilterSelected.innerHTML = '';
            brandFilterSelected.innerHTML = aSelectedBrandFilterHtml.join('');
        }
if(appliedFilters.f2.length){document.getElementById('selFilterBrand').classList.remove('noshow');}
if(!appliedFilters.f2.length){
    Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == 2){
        rest.style.display = "none";
    }
    } )
}
        for(const sid of aBrands){
            let checked = appliedFilters.f2.includes(parseInt(sid.id)) ? "checked" : "";
            let fname = sid.name;
            let bid = parseInt(sid.id);
            let gurl = !checked ? '/'+(cleanUnwantedChars(HtmlEntities.decode(fname))) : '';
            if(checked){
               
              //  brandFilterSelected.innerHTML += '<a data-valuetxt="'+fname+'" class="  standardF checkMe checkF" href="'+fullPath+gurl+''+qcst+'" title="'+fname+'">'+fname+'</a>';
              if(window.innerWidth > 1080){
                    qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [bid, exclude]);
                    if(qcst != '') qcst = "?" + qcst;
                    aBrandFilterHtml.push('<a data-valuetxt="'+fname+'" class="  filterFamily2 standardF checkMe checkF" href="'+fullPath+gurl+''+qcst+'" title="'+fname+'">'+fname+'</a>');
              }else{
                    aBrandFilterHtml.push( '<label data-valuetxt="'+fname+'" class="filterFamily2 standardF checkMe  sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f2[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="2" value="'+bid+'">'+fname+'<span></span></label>');
              }
            }else{
                
                if(window.innerWidth > 1080){
                    qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [exclude]);
                    if(qcst != '') qcst = "?" + qcst;
                    aBrandFilterHtml.push('<a data-valuetxt="'+fname+'" class="  filterFamily2 standardF  checkF" href="'+fullPath+gurl+''+qcst+'" title="'+fname+'">'+fname+'</a>');
                }else{
                    aBrandFilterHtml.push('<label data-valuetxt="'+fname+'" class="filterFamily2 standardF   sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="f2[]" data-fid="'+bid+'" id="fivl-'+bid+'" data-filtergroup="2" value="'+bid+'">'+fname+'<span></span></label>');
                }
            }
            
            
        }
        brandFilter.innerHTML = aBrandFilterHtml.join('');

    }
}
function fillSizeFilter(aSizes){
    let sizeFilter = document.getElementById('sizeFilter');
    let sizeFilterSelected = document.getElementById('selectedSizeFilter');
    
    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let exclude = 0;
    if(typeof basepath[1] !== 'undefined') {
        let biurl = basepath[1].match(/\-b([0-9]+)$/);
        if(biurl)
            exclude = biurl[1];

    }

    let qcst ='';// makeQueryParamNoCat(Object.entries(appliedFilters), exclude);

    if(sizeFilter){
        sizeFilter.innerHTML = '';
        sizeFilterSelected.innerHTML = '';
        let aSelectedSizeFilterHtml = [];
        let aSizeFilterHtml = [];
document.getElementById('selFilterSize').classList.add('noshow');
        appliedFilters.f1.forEach(bid => {
            let fname = attrValNames[bid].value;
            aSelectedSizeFilterHtml.push('<label data-valuetxt="'+fname+'" class="filterFamily1 standardF checkMe  sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f1[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="1" value="'+bid+'">'+fname+'<span></span></label>');
        })
        sizeFilterSelected.innerHTML = aSelectedSizeFilterHtml.join('');
if(appliedFilters.f1.length){document.getElementById('selFilterSize').classList.remove('noshow');}
if(!appliedFilters.f1.length){
    Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == 1){
        rest.style.display = "none";
    }
    } )
}
        for(const sid of aSizes){
            
            let checked = appliedFilters.f1.includes(parseInt(sid.id)) ? true : false;
            let fname = sid.name;
            let bid = sid.id;
        //    / let gurl = !checked ? '/'+(cleanUnwantedChars(reverseEntities(fname)))+'-b'+bid : '';
            if(checked){
               // qcst = makeQueryParamNoCat(Object.entries(appliedFilters), bid);
              // sizeFilterSelected.innerHTML += '<label data-valuetxt="'+fname+'" class="filterFamily1 standardF checkMe  sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f1[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="1" value="'+bid+'">'+fname+'<span></span></label>';
              aSizeFilterHtml.push('<label data-valuetxt="'+fname+'" class="filterFamily1 standardF checkMe sizeF "><input checked autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="f1[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="1" value="'+bid+'">'+fname+'<span></span></label>');
            }else{
               // qcst = makeQueryParamNoCat(Object.entries(appliedFilters), 0);
               aSizeFilterHtml.push('<label data-valuetxt="'+fname+'" class="filterFamily1 standardF sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="f1[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="1" value="'+bid+'">'+fname+'<span></span></label>');
            }
            
            
        }
        sizeFilter.innerHTML = aSizeFilterHtml.join('');
    }
}

function fillColorFilter(aColors){
    let colorFilter = document.getElementById('colorFilter');
    let colorFilterSelected = document.getElementById('colorSizeFilter');
    
    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let exclude = 0;
    if(typeof basepath[1] !== 'undefined') {
        let biurl = basepath[1].match(/\-b([0-9]+)$/);
        if(biurl)
            exclude = biurl[1];

    }

    let qcst ='';// makeQueryParamNoCat(Object.entries(appliedFilters), exclude);

    if(colorFilter){
        colorFilter.innerHTML = '';
        colorFilterSelected.innerHTML = '';
		document.getElementById('selFilterColor').classList.add('noshow');
        appliedFilters.f3.forEach(bid => {
            let fname = attrValNames[bid].value;
            let classname = fname.toLowerCase().replace(' ', '');
            colorFilterSelected.innerHTML +='<label data-valuetxt="'+fname+'" class="filterFamily3 standardF checkMe  checkF colorF '+classname+' "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f3[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="3" value="'+bid+'">'+fname+'</label>';
        })
if(appliedFilters.f3.length){document.getElementById('selFilterColor').classList.remove('noshow');}
if(!appliedFilters.f3.length){
    Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == 3){
        rest.style.display = "none";
    }
    } )
}
        for(const sid of aColors){
            
            let checked = appliedFilters.f3.includes(parseInt(sid.id)) ? true : false;
            let fname = sid.name;
            let bid = sid.id;
            let classname = fname.toLowerCase().replace(' ', '');
        //    / let gurl = !checked ? '/'+(cleanUnwantedChars(reverseEntities(fname)))+'-b'+bid : '';
            if(checked){
               // qcst = makeQueryParamNoCat(Object.entries(appliedFilters), bid);
             //  colorFilterSelected.innerHTML += '<label data-valuetxt="'+fname+'" class="filterFamily3 standardF checkMe  checkF colorF '+classname+' "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f3[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="3" value="'+bid+'">'+fname+'</label>';
               colorFilter.innerHTML += '<label title="'+(fname)+'" data-valuetxt="'+fname+'" class="filterFamily3 standardF checkF checkMe colorF '+classname+' "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f3[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="3" value="'+bid+'">'+fname+'</label>';
            }else{
               // qcst = makeQueryParamNoCat(Object.entries(appliedFilters), 0);
               colorFilter.innerHTML += '<label title="'+(fname)+'" data-valuetxt="'+fname+'" class="filterFamily3 standardF checkF colorF '+classname+' "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="f3[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="3" value="'+bid+'">'+fname+'</label>';
            }
            
            
        }
    }
}
function fillMaterialFilter(aMaterials){
    let materialFilter = document.getElementById('materialFilter');
    let materialFilterSelected = document.getElementById('selectedMaterialFilter');
    
    let remainngPath = location.pathname.replace(baseUrlPath,'');
  

    //let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let basepath = remainngPath.split('/').filter(b => b.trim() != '');
    let exclude = 0;
    let validPath = [];
    biurl = false;
    basepath.forEach(trep => {
       // filterBrands.forEach(id => {
            
            //attrValNames[id].value
       // })

        let miurl = trep.match(/\-m([0-9]+)$/);
      
            if(!biurl || appliedFilters.f2.includes(parseInt(biurl[1])))
            validPath.push(trep);
    
    });
    //let fullPath = validPath.filter(pat => pat !== null).join('/');
    let fullPath = baseUrlPath;


    let qcst ='';// makeQueryParamNoCat(Object.entries(appliedFilters), exclude);

    if(materialFilter){
        materialFilter.innerHTML = '';
        materialFilterSelected.innerHTML = '';
		document.getElementById('selFilterMaterial').classList.add('noshow');
        appliedFilters.f5.forEach(sid => {
            let fname = attrValNames[sid].value;
            if(window.innerWidth > 1080){
                qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [sid, exclude]);
                if(qcst != '') qcst = "?" + qcst;
                materialFilterSelected.innerHTML += '<a data-valuetxt="'+fname+'" class="  standardF checkMe checkF" href="'+fullPath+''+qcst+'" title="'+fname+'">'+fname+'</a>';
            }else{

                materialFilterSelected.innerHTML += '<label data-valuetxt="'+fname+'" class="filterFamily5 standardF checkMe  sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f5[]" data-fid="'+sid+'" id="fiv-'+sid+'" data-filtergroup="5" value="'+sid+'">'+fname+'<span></span></label>';
            }
        })
if(appliedFilters.f5.length){document.getElementById('selFilterMaterial').classList.remove('noshow');}

if(!appliedFilters.f5.length){
    Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == 5){
        rest.style.display = "none";
    }
    } )
}

        for(const sid of aMaterials){
            let checked = appliedFilters.f5.includes(parseInt(sid.id)) ? "checked" : "";
            let fname = sid.name;
            let bid = parseInt(sid.id);
            let gurl = !checked ? '/'+(cleanUnwantedChars(HtmlEntities.decode(fname))): '';

            if(checked){
              //  qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [bid,exclude]);
              //  if(qcst != '') qcst = "?" + qcst;
                //materialFilterSelected.innerHTML += '<a data-valuetxt="'+fname+'" class="  standardF checkMe checkF" href="'+fullPath+gurl+''+qcst+'" title="'+fname+'">'+fname+'</a>';
                
                if(window.innerWidth > 1080){
                    qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [bid, exclude]);
                if(qcst != '') qcst = "?" + qcst;
                    materialFilter.innerHTML += '<a data-valuetxt="'+fname+'" class=" filterFamily5 standardF checkMe  checkF" href="'+fullPath+gurl+''+qcst+'" title="'+fname+'">'+fname+'</a>';
                }else{
                    materialFilter.innerHTML += '<label data-valuetxt="'+fname+'" class="filterFamily5 standardF checkMe  sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="f5[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="5" value="'+bid+'">'+fname+'<span></span></label>';
                }
            }else{
                if(window.innerWidth > 1080){
                    qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [exclude]);
                    if(qcst != '') qcst = "?" + qcst;
                    materialFilter.innerHTML += '<a data-valuetxt="'+fname+'" class=" filterFamily5 standardF  checkF" href="'+fullPath+gurl+''+qcst+'" title="'+fname+'">'+fname+'</a>';
                }else{
                    materialFilter.innerHTML += '<label data-valuetxt="'+fname+'" class="filterFamily5 standardF   sizeF "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="f5[]" data-fid="'+bid+'" id="fiv-'+bid+'" data-filtergroup="5" value="'+bid+'">'+fname+'<span></span></label>';
                }
            }
      
            
            
        }
    }
}

function fillPriceFilter(){
    let priceFilter = document.getElementById('priceFilter');
    //let priceFilterSelected = document.getElementById('selectedPriceFilter');

    priceFilter.innerHTML = '';
    if(parseInt(priceRange.min) <= 29){
        priceFilter.innerHTML +=  '<label data-valuetxt="Sub 29 Lei" class="cids standardF '+(appliedFilters.pf.includes(29)?"checkMe":"")+'  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" '+(appliedFilters.pf.includes(29)?"checked":"")+' data-fid="29" id="cid-29" data-filtergroup="-1" value="29">Pana in 29 Lei</label>';
    }
    if(parseInt(priceRange.min) <= 49){
        priceFilter.innerHTML +=  '<label data-valuetxt="Pana in 49 Lei" class="cids standardF '+(appliedFilters.pf.includes(49)?"checkMe":"")+'  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" '+(appliedFilters.pf.includes(49)?"checked":"")+' data-fid="49" id="cid-49" data-filtergroup="-1" value="49">Pana in 49 Lei</label>';
    }
    if(parseInt(priceRange.min) < 50){
       // priceFilter.innerHTML +=  '<label data-valuetxt="Sub 50 Lei" class="cids standardF '+(appliedFilters.pf.includes(50)?"checkMe":"")+'  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" '+(appliedFilters.pf.includes(50)?"checked":"")+' data-fid="50" id="cid-50" data-filtergroup="-1" value="50">Sub 50 Lei</label>';
    }
    if(parseInt(priceRange.min) <= 69){
        priceFilter.innerHTML +=  '<label data-valuetxt="Pana in 69 Lei" class="cids standardF '+(appliedFilters.pf.includes(69)?"checkMe":"")+'  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" '+(appliedFilters.pf.includes(69)?"checked":"")+' data-fid="69" id="cid-69" data-filtergroup="-1" value="69">Pana in  69 Lei</label>';
    }
    if((priceRange.max >  69 && priceRange.max < 100)  || (priceRange.max > 100 && priceRange.min < 100 ) ){
        priceFilter.innerHTML +=  '<label data-valuetxt="Intre 69 - 100 Lei" class="cids standardF '+(appliedFilters.pf.includes(100)?"checkMe":"")+'  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" '+(appliedFilters.pf.includes(100)?"checked":"")+' data-fid="100" id="cid-100" data-filtergroup="-1" value="100">Intre 69 - 100 Lei</label>';
    }
    if((priceRange.min >  100 && priceRange.min < 200) || (priceRange.max > 200 && priceRange.min < 200 )){
        priceFilter.innerHTML +=  '<label data-valuetxt="Intre 100 - 200 Lei" class="cids standardF  '+(appliedFilters.pf.includes(200)?"checkMe":"")+' checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" '+(appliedFilters.pf.includes(200)?"checked":"")+' data-fid="200" id="cid-200" data-filtergroup="-1" value="200">Intre 100 - 200 Lei</label>';
    }
    if(priceRange.max > 200){
        priceFilter.innerHTML +=  '<label data-valuetxt="Peste 200 lei" class="cids standardF '+(appliedFilters.pf.includes(201)?"checkMe":"")+'  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="price[]" data-fid="201" id="cid-201" '+(appliedFilters.pf.includes(201)?"checked":"")+' data-filtergroup="-1" value="201">Peste 200 Lei</label>';
    }
    if(!appliedFilters.pf.length){
        Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == '-1'){
            rest.style.display = "none";
        }
        } )
    }

}

function fillSeasonFilter(seasonsIn){
    return ;
    let priceFilter = document.getElementById('sezonFilter');
    priceFilter.innerHTML = '';

    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let fullPath = basepath.filter(pat => pat !== null).join('/');

    
    
    seasonsIn.forEach( (b) => {
            const ib = parseInt(b);
            qcst = makeQueryParamNoCat(Object.entries(appliedFilters), [ib], 's');
           
            const sn = seasonsListNames[ib];
            let checked = appliedFilters.s.includes(ib);
           
            let gurl = !checked ? '?s[]='+b : '';
            if(qcst != '') qcst = (!checked?"&":"?") + qcst;
            
            priceFilter.innerHTML +=  '<a data-valuetxt="'+(sn)+'" class="  filterFamily2 standardF '+(appliedFilters.s.includes(ib)?"checkMe":"")+' checkF" href="'+fullPath+gurl+''+qcst+'" title="'+(sn)+'">'+(sn)+'</a>';
        }); 
        if(!appliedFilters.s.length){
            Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == 's'){
                rest.style.display = "none";
            }
            } )
        }

       
    
 

}

function statusResetFilters(key){
    Array.from(document.getElementsByClassName('resetFilters')).forEach(rest => {if(rest.dataset['filtergroup'] == key){
        if(!appliedFilters[key].length){
            rest.style.display = "none";   
        }else{
            rest.style.display = "";
        }
        
    }
    } )
}

function fillCategoryFilter(aCategories){
    let categoryFilter = document.getElementById('categoryFilter');
    let categoryFilterSelected = document.getElementById('selectedCategoryFilter');
        
    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let exclude = 0;
    if(typeof basepath[1] !== 'undefined') {
        let biurl = basepath[1].match(/\-b([0-9]+)$/);
        if(biurl)
            exclude = biurl[1];

    }

    let qcst ='';// makeQueryParamNoCat(Object.entries(appliedFilters), exclude);

    if(categoryFilter){
        categoryFilter.innerHTML = '';
        categoryFilterSelected.innerHTML = '';
		document.getElementById('selFilterCat').classList.add('noshow');
        appliedFilters.c.filter(id => (id > 0 && typeof assideCats[id] !== 'undefined' )).map(id => ({id:id, name:assideCats[id].name})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ).forEach(sid => {
            let fname = sid.name;
            let bid = sid.id;
            categoryFilterSelected.innerHTML +=  '<label data-valuetxt="'+fname+'" class="cids standardF checkMe  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="categories[]" data-fid="'+bid+'" id="cid-'+bid+'" data-filtergroup="c" value="'+bid+'">'+fname+'</label>';
			

        })
		if(appliedFilters.c.length){document.getElementById('selFilterCat').classList.remove('noshow');}
        statusResetFilters('c');
        for(const sid of aCategories){
            let checked = appliedFilters.c.includes(parseInt(sid.id)) ? "checked" : "";
            let fname = sid.name;
            let bid = sid.id;
          //  let gurl = !checked ? '/'+(cleanUnwantedChars(HtmlEntities.decode(fname)))+'-b'+bid : '';
            if(checked){
                // qcst = makeQueryParamNoCat(Object.entries(appliedFilters), bid);
           //     categoryFilterSelected.innerHTML +=  '<label data-valuetxt="'+fname+'" class="cids standardF checkMe  checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked name="categories[]" data-fid="'+bid+'" id="cid-'+bid+'" data-filtergroup="0" value="'+bid+'">'+fname+'</label>';
                categoryFilter.innerHTML += '<label data-valuetxt="'+fname+'" class="cids standardF filterFamilyc  checkMe checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox" checked  name="categories[]" data-fid="'+bid+'" id="cid-'+bid+'" data-filtergroup="c" value="'+bid+'">'+fname+'</label>';
             }else{
              //   qcst = makeQueryParamNoCat(Object.entries(appliedFilters), 0);
              categoryFilter.innerHTML += '<label data-valuetxt="'+fname+'" class="cids standardF filterFamilyc checkF  "><input autocomplete="off" onchange="filterProducts(this)" type="checkbox"  name="categories[]" data-fid="'+bid+'" id="cid-'+bid+'" data-filtergroup="c" value="'+bid+'">'+fname+'</label>';
             }
            
            
        }
    }

}
function populateFilters (){
    fillBrandFilter(filterBrands.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));

    fillSizeFilter(filtruSize.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));

    fillColorFilter(filtruCuloare.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
    
    fillMaterialFilter(filtruMaterial.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));


    fillCategoryFilter(filterCategories.filter(id => (id > 0 && typeof assideCats[id] !== 'undefined' )).map(id => ({id:id, name:assideCats[id].name})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));

    fillPriceFilter();
    fillSeasonFilter(filterSezoane);


    updateFilterCount();
    
}
function updateFilters(msg, t){
    const filterClk =  t.attributes['data-filtergroup'].value;
    
    if(filterClk != 1 || !t.checked){
        if(filterClk != 1 )
            filtruSize = msg.sizeIds;
        fillSizeFilter(msg.sizeIds.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));
    }

    if(filterClk != 3 || !t.checked){
        if(filterClk != 3)
            filtruCuloare = msg.colorIds;
        fillColorFilter(msg.colorIds.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ));

    }

    if(filterClk != 2 || !t.checked){
        if(filterClk != 2)
            filterBrands = msg.brandIds;

        fillBrandFilter(msg.brandIds.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) )); 
        
    }
    if(filterClk != 5 || !t.checked){
        fillMaterialFilter(msg.materialIds.filter(id => (id > 0 && typeof attrValNames[id] !== 'undefined' )).map(id => ({id:id, name:attrValNames[id].value})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) )); 
    }
    if(filterClk != 0 || !t.checked){
        if(filterClk != 0 )
            filterCategories = msg.categories;
        fillCategoryFilter(msg.categories.filter(id => (id > 0 && typeof assideCats[id] !== 'undefined' )).map(id => ({id:id, name:assideCats[id].name})).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) )); 
    }
    if(filterClk != -1 || !t.checked){
        //if(filterClk != 0 )
          //  filterCategories = msg.categories;
            fillPriceFilter();
            
    }
    fillSeasonFilter(msg.seasons);
    
    updateFilterLinks();
    updateFilterCount();

}
function updateFilterCount(){
    if( document.getElementById('filterCount-1'))
        document.getElementById('filterCount-1').innerHTML = appliedFilters.f1.length ? ('<span class="filterCounter">'+appliedFilters.f1.length+'</span>') : '';
    if( document.getElementById('filterCount-2'))
        document.getElementById('filterCount-2').innerHTML = appliedFilters.f2.length ? ('<span class="filterCounter">'+appliedFilters.f2.length+'</span>') : '';
    if( document.getElementById('filterCount-3'))
        document.getElementById('filterCount-3').innerHTML = appliedFilters.f3.length ? ('<span class="filterCounter">'+appliedFilters.f3.length+'</span>') : '';
    if( document.getElementById('filterCount-5'))
        document.getElementById('filterCount-5').innerHTML = appliedFilters.f5.length ? ('<span class="filterCounter">'+appliedFilters.f5.length+'</span>') : '';
    if( document.getElementById('filterCount-c'))
        document.getElementById('filterCount-c').innerHTML = appliedFilters.c.length ? ('<span class="filterCounter">'+appliedFilters.c.length+'</span>') : '';
    if( document.getElementById('filterCount-pf'))
        document.getElementById('filterCount-pf').innerHTML = appliedFilters.pf.length ? ('<span class="filterCounter">'+appliedFilters.pf.length+'</span>') : '';
    if( document.getElementById('filterCount-s'))
        document.getElementById('filterCount-s').innerHTML = appliedFilters.s.length ? ('<span class="filterCounter">'+appliedFilters.s.length+'</span>') : '';

    let cfa = appliedFilters.f1.length+appliedFilters.f2.length+appliedFilters.f3.length+appliedFilters.f5.length+appliedFilters.c.length;
    if(afc = document.getElementById('allFiltercounter'))
     afc.innerHTML = cfa ? ''+cfa+'' : '0';
    
}
// doar pentru linkurile de sortare. acolo e bubita
function updateFilterLinks(){
    let basepath = location.pathname.split('/').filter(b => b.trim() != '');
    let exclude = [];
    let validPath = [];
    basepath.forEach(trep => {
        let biurl = trep.match(/\-b([0-9]+)$/);
        if(biurl){
            exclude.push(parseInt(biurl[1]));
            if(appliedFilters.f2.includes(parseInt(biurl[1])))
                validPath.push(trep);
        }
        
        let miurl = trep.match(/\-m([0-9]+)$/);
        if(miurl){
            exclude.push(parseInt(miurl[1]));
            if(appliedFilters.f5.includes(parseInt(miurl[1])))
            validPath.push(trep);
            
        }
        if(!miurl && !biurl){
            validPath.push(trep);
        }
    });

    let fullPath = validPath.filter(pat => pat !== null).join('/');
    let qcst = makeQueryParamNoCat(Object.entries(appliedFilters), exclude);
    //window.location.assign(fullPath+qcst);
    //history.pushState(null, null, "https://"+location.host+myJson.baseUrl);
    history.pushState(null, null, fullPath+'?'+qcst);
    Array.from(document.getElementsByClassName('filterURL')).forEach(alem => {

        const queryp = alem.href.split('?');
        let aquery = '';
        if(typeof queryp[1] !== 'undefined' ){
           let ceva =  queryp[1].split('&').filter(qs=> qs.match(/^ordonare/));
           if(ceva.length)
            aquery = "?"+ceva[0]+(qcst.length >0?"&":"");
        }
//       console.log(aquery, fullPath+aquery+qcst);
        
       alem.href = fullPath+aquery+qcst;

    })
}
function cleanUnwantedChars(value){
    value = value.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/[\W_]+/g,"-").replace(/\-\-+/g, '-').replace(/(^-+|-+$)/g, '').toLowerCase();
    
   return value;

}
function reverseEntities(str){
	const htmlEntities = {
    	"&amp;": "&",
    	"&lt;": "<",
    	"&gt;": ">" ,
    	"&quot;": '"',
    	"&apos;": "'" 
  };
  //return str.replace(/([&<>\"'])/g, match => htmlEntities[match]);
  return str.replace(/(\&amp;|\&lt;|\&gt;|\&quot;|\&apos;)/g, match => htmlEntities[match]);
}

function searchFilter(t, type){
    const lookfor = t.value.trim().toLowerCase();

    Array.from(document.getElementsByClassName('filterFamily'+type)).forEach(lbl => {
       
        const val = lbl.attributes['data-valuetxt'].value.toLowerCase();

        const reg = new RegExp('^'+lookfor+'', 'i');

        if(type == 0 ){
            let pass = false;
            val.split(' ').forEach(word => {
                if(word.match(reg)) pass = true;
            });
            if(pass) lbl.style.display ="";
            else lbl.style.display ="none";
        }else{
            if(val.match(reg)){
                lbl.style.display ="";
            }else{
                lbl.style.display ="none";
            }
        }
        
        
    });
}

function resetCategoryFilters(t){
    appliedFilters.c = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}
function resetSizeFilters(t){
    appliedFilters.f1 = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}
function resetColorFilters(t){
    appliedFilters.f3 = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}

function resetBrandFilters(t){
    appliedFilters.f2 = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}
function resetMaterialFilters(t){
    appliedFilters.f5 = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}
function resetPriceFilters(t){
    appliedFilters.pf = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}
function resetSeasonFilters(t){
    appliedFilters.s = [];
    localCall("filterProducts", makeQueryParam() , msg=>showProducts(msg, t), failGetCart, "GET");
}