// gEl('aladeclasa').classList.add('geta');
     // gEl('aladeclasa').classList.remove('geta');

//mobile
function gEl(id){
    return document.getElementById(id);
}
function gElClass(clasa){
    return  document.getElementsByClassName(clasa);
    
}
let burger =  gEl('hamburger')
if(burger)
burger.addEventListener('click', function() {
    if(this.classList.contains('close')){
            closeMenu(this)
    }else{
            openMenu(this)
    }
});

function openMenu(t){
    t.classList.add('close');
    gEl('nav').classList.add('navVisible');
    gEl('body').classList.add('hideOverflow');
    
}
function closeMenu(t){
    t.classList.remove('close');
    gEl('nav').classList.remove('navVisible');
    gEl('body').classList.remove('hideOverflow');
    
    if(!t.classList.contains('close')){
        gEl('nav').classList.remove('navsubmenu');
        Array.from(gElClass('subMenu')).forEach(elem => elem.style.display = "none");
        Array.from(gElClass('subnavs')).forEach(elem => elem.style.display = "block");
        Array.from(gElClass('aparent')).forEach(elem => elem.style.display = "");
    }
}

function closeMinicart(event){
    if(event.target.id == 'overlay'){
		if(gEl('cartBox').classList.contains('cartShow')){
        closeCart();}
		if(gEl('tabelMarimi')){
			if(gEl('tabelMarimi').style.display=='block'){
		gEl('tabelMarimi').style.display='none';
		gEl('body').classList.remove('hideOverflow');
	 gEl('overlay').classList.remove('overlayed');
		}
		}
    }
    
}

let ocart =  gEl('openCart')
if(ocart)
ocart.addEventListener('click', function() {
    refreshCart();
   gEl('cartBox').classList.add('cartShow');
    gEl('body').classList.add('hideOverflow');
    gEl('overlay').classList.add('overlayed');
    });

let ccart = gEl('closeCart');
if(ccart)
ccart.addEventListener('click', function() {
    gEl('cartBox').classList.remove('cartShow');
	 gEl('body').classList.remove('hideOverflow');
	 gEl('overlay').classList.remove('overlayed');
});


Array.from(gElClass('aparent')).forEach(elem => {
    if(window.innerWidth < 1080){
        elem.addEventListener('click', function(e) {
            e.stopPropagation();
            e.preventDefault();
           

     
            
            displaySubMenu(this);
        });
    }
})
Array.from(gElClass('backMenu')).forEach(elem => {
    
    if(window.innerWidth < 1080){
        elem.addEventListener('click', function(e) {
           e.preventDefault();
           e.stopPropagation();
           e.stopImmediatePropagation();
           
            restoreSubMenu(this);
        });
    }
})
function restoreSubMenu(t){
    
    let sbc = t.attributes['data-subchild'].value;
    
    gEl('auleu-'+sbc).style.display = 'flex';
    
    Array.from(gElClass('subnavs')).forEach(subs=>{
        
       // let sbid = subs.attributes['data-subchilds'].value;
        //if(sbc != sbid){
            subs.style.display = 'block';
        //}
    });
    gEl('subSubNav'+sbc).style.display = 'none';
	 gEl('nav').classList.remove('navsubmenu');
}
function displaySubMenu(t){

    let sbc = t.attributes['data-subchilds'].value;
	let prnt = t.attributes['data-parent'].value;

    gEl('auleu-'+sbc).style.display = 'none';
    
    Array.from(gElClass('subnavs')).forEach(subs=>{
        let sbid = subs.attributes['data-subchilds'].value;
        let prr = subs.dataset['parent'];
        if(sbc != sbid && prr == prnt){
        
            subs.style.display= 'none';
        }
    });
    gEl('subSubNav'+sbc).style.display = 'block';
     gEl('nav').classList.add('navsubmenu');
}
//all
gEl('closeParent').addEventListener('click', function() {
this.parentElement.classList.remove("slideTop");
gEl('overlay').classList.remove('overlayed');
gEl('body').classList.remove('hideOverflow');
});




let srcelem = gEl('openSearch')
if(srcelem)
    srcelem.addEventListener('click', function() {
        localCall("getPopulars", '', msg => {
            let html = '';
            Object.values(msg).forEach(elemop => {
                html += '<li data-path="'+elemop.slug+'" data-fid="'+elemop.familyId+'">\
                <a href="'+elemop.slug+'" title="'+elemop.name+'">\
                  <span class="productHolder" data-fid="'+elemop.familyId+'" id="pictf-'+elemop.familyId+'">\
                    <picture class="productImage">\
                      <source srcset="'+elemop.thumb+'.webp" type="image/webp">\
                      <img src="'+elemop.thumb+'.jpg" type="image/jpeg" alt="'+elemop.name+'">\
                    </picture>\
                   </span>\
                </a>\
                <div class="productTitle">\
                    <h3> <a href="'+elemop.slug+'" title="'+elemop.name+'">'+elemop.name+'</a></h3>\
                </div>\
                    <span class="price"> '+elemop.price+' lei </span>\
                </li>';
            });
            let popul = document.getElementById('popularsList');
            if(popul) popul.innerHTML = html;

        }, fail => {

        });

        gEl('searchBox').classList.add('slideTop');

        gEl('body').classList.add('hideOverflow');
        gEl('cartBox').classList.remove('cartShow');
       setTimeout(() => gEl('cauta').focus(),500);
});

function clearMainFor(){
    Array.from(document.getElementsByClassName('genderS')).forEach(selector => selector.parentNode.classList.remove('selected'));

   
}

    
    Array.from(document.getElementsByClassName('genderS')).forEach(selector =>{
   
        selector.addEventListener('click', function(event){
            let whm = this.attributes['data-switch'].value;

            if(window.innerWidth < 1080){
                event.preventDefault();

                gEl('nav').classList.remove('navsubmenu');

          
            Array.from(gElClass('mainMenu')).forEach(msub=> msub.style.display = 'none');

          
            let showM = gElClass(whm);
            if(showM)
            Array.from(showM).forEach(vsm => vsm.style.display = "block");

           
        }
          
            clearMainFor();

            this.parentNode.classList.add('selected');
            setCookie('pentru', whm.toLowerCase(), 60);
            let bgg = document.getElementById('gender');
            if(bgg){
                bgg.classList.remove('barbatiActiv');
                bgg.classList.remove('femeiActiv');
                bgg.classList.remove('copiiActiv');
                bgg.classList.add((whm.toLowerCase())+'Activ');
            }
        
		//	window.location.reload();

        });
     
    
    });


function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "{}";
}
function closeEscape(e){
    if(e.keyCode == 27){
        closeCart();
	}
}
function closeCart(){
    gEl('cartBox').classList.remove('cartShow');
    gEl('body').classList.remove('hideOverflow');
    gEl('overlay').classList.remove('overlayed');
}
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function showDeliveryTime(msg){
    
    try{
        if(typeof msg.estimatLivrare === 'undefined') return;
        let where=  document.getElementById('deliveryEstimate');
        if (where){
            where.innerHTML = msg.estimatLivrare;
        }
    }catch(e){
        console.log(e,msg);
    }
    
}
function applyAddToCart(msg){

	displayMiniCart(msg);
	displayMiniCartCount(msg);
	let ecart = gEl('cartBox');
    if(ecart)  ecart.classList.add('cartShow');
}
function failGetCart(){
    console.log('fail get cart');
}
function refreshCart(){
    localCall("getCart", '', applyAddToCart, failGetCart);
}
function getCart(){
    
    localCall("getCart", '', displayMiniCart, failGetCart);

}
function displayMiniCartCount(msg){
    let cc =  gEl('cartcount');
  
  
    if(typeof showDeliveryTime !== 'undefined'){
        showDeliveryTime(msg);
    }
    if(!cc) return
    cc.innerHTML = msg.totalQuantity;

}
function getCartCount(){
    localCall("getCartCount", '', displayMiniCartCount, failGetCart);
    return;
  

}
function removeMiniCartProduct(cid, name){
        name = name.replace(/'/, "");
         name = name.replace("&#039;","");

        if(confirm("Stergeti produsul: "+name+"?")){
            localCall("removeCartProduct", 'cid='+cid, getCart, getCart, "GET");
        }
    
}

function displayMiniCart(msg){

    let cartc = gEl('cartCount');
    if(cartc)  cartc.innerHTML = msg.totalQuantity+" produs"+(parseInt(msg.totalQuantity) > 1?"e":"");
    let minicart  = gEl('cartContent');
    if(!minicart){
        minicart  = gEl('continutCos');
        if(minicart)
        displayProductSummary(msg);
        return;
        
    }
    if(minicart){


    minicart.innerHTML = '';
    let gotProducts = false;
	if(Object.keys(msg.items).length == 0){
   
		minicart.innerHTML = '<div class="noProducts flex fcenter fwrap"><span>Nu aveti nici un articol in cosul de cumparaturi</span><a href="reduceri" class="callto lightButton">Vezi reducerile</a></div>';
	}else{
		
	htmlToContent = '<div class="cartItems">';
     gotProducts =  Object.entries(msg.items).sort((a, b) => parseInt(a[0]) < parseInt(b[0]) ? 1 : (parseInt(a[0]) > parseInt(b[0]) ? -1 : 0) );
     gotProducts.forEach(([pId,product])=>{
		var sizes='';
	    if (product.size){var sizes='<li> Mărime: '+product.size+'</li>';}
		htmlToContent += '<div class="flex fspace cartItem" data-productid="'+pId+'">\
		<div class="flex itemDetails fwrap"><a title="'+product.name+'" href="'+product.slug+'"><img loading="lazy" src="'+product.thumb+'.webp" alt="'+product.name+'" type="image/webp"></a>\
			<ul>\
	            <li class="productTitle"><a title="'+product.name+'" href="'+product.slug+'">'+product.name+'</a></li>'+sizes+'	<li>';
        if(product.indisponibil){
            htmlToContent += '<li class="warningBlock">Produsul nu se mai găsește în stoc!</li>';
        }else{
            htmlToContent +='Cantitate: '+product.quantity+'</li>';
        }
        let pname =product.name.replace(/'/, '');
        
        pname = pname.replace("&#039;","");

        htmlToContent += '<li><span class="removeProduct" onclick="removeMiniCartProduct('+product.id+', \''+(pname)+'\')" data-name="'+pname+'" data-cid="'+product.id+'">Elimina</span></li></ul>\
		</div><div class="pricesBlock">';
		
        if(product.discountvalue > 0){
			htmlToContent += '<span class="price salePrice">'+parseFloat(product.price * product.quantity).toFixed(2)+' lei</span>';
            htmlToContent += '<span class="price cutThrough">'+parseFloat(product.priceD * product.quantity).toFixed(2)+' lei</span>';   
            htmlToContent += '<span class="price discount">-'+parseFloat(product.discountvalue * product.quantity).toFixed(2)+' lei</span>';   
        }else{
            if(parseFloat(product.priceS) > parseFloat(product.price)){
				htmlToContent += '<span class="price salePrice">'+parseFloat(product.price * product.quantity).toFixed(2)+' lei</span>';
                htmlToContent += '<span class="price cutThrough">'+parseFloat(product.priceS * product.quantity).toFixed(2)+' lei</span>';        
            }
			else{htmlToContent += '<span class="price">'+parseFloat(product.price * product.quantity).toFixed(2)+' lei</span>';}
        }
		
     

        htmlToContent +=  '</div></div>';
    

	});
    htmlToContent += '</div>';

	minicart.innerHTML = htmlToContent;
	let cartBottom  = gEl('bottomCart');
    if(cartBottom){
    cartBottom.innerHTML = '';
	let voucherString = '';
	Object.entries(msg.vouchers).forEach(([vId,voucher]) => {
		voucherString += '<div class="flex fspace acenter deliveryCart">Voucher: '+voucher.cod+'<span>-'+(voucher.evalue).toFixed(2)+' Lei</span> </div>';
	}); 
	deliveryCost = "Gratuită";
	if(parseInt(msg.deliveryitems[1].value)>0){deliveryCost = msg.deliveryitems[1].value+" Lei";}
	cartBottom.innerHTML += voucherString;
	cartBottom.innerHTML += '<div class="flex fspace acenter deliveryCart">Livrare <span id="deliveryCost">'+deliveryCost+'</span></div><div class="flex fspace acenter subTotal">Total <span id="subTotal">'+parseFloat(msg.totalPrice).toFixed(2)+' Lei</span></div>';
	cartBottom.innerHTML += '<a title="Finalizare comanda" href="finalizare-comanda" class="callto">Finalizare comanda</a><a title="Vezi cosul" href="cosul-meu" class="callto lightButton">Vezi coșul</a>\
	';
    }}

   

	freeShipping = 200;

	if(msg.totalPrice < freeShipping){
		bar = msg.totalPrice / freeShipping * 100;
		//$('#miniCart').append('<div class="transportGratuit">Primeste transport gratuit<span class="progress"><span style="width:'+ bar +'%">'+msg.totalPrice+' lei </span>'+freeShipping+' lei </span></div>');	
	}else{
	//	$('#miniCart').append('<div class="transportGratuit green">Felicitari! Transportul pentru aceasta comanda este gratuit.</div>');}
	//	$('#miniCart').append('<a href="/cosul-meu" class="callto">Vezi cosul</a><a href="/finalizare-comanda" class="callto">Finalizare comanda</a>');

	//	$('#cartItems').html(msg.totalQuantity);
		
		//$('.removeProduct').off('click');
		//$('.removeProduct').on('click', removeFromCart);

	}

	//$('.showUnder').click(function(){
	//		$(this).toggleClass('minus');
	//		$(this).next().slideToggle(300);
	//});



    try{
        let upselitems= document.getElementById('cartUpsell');
        if(upselitems){
            if(!Object.values(JSON.parse(getCookie('suggoff'))).length){
                getSuggestions(gotProducts);
            }
        }
    }catch{
        console.log('error in cookie');
    }
}
//minicart.style.display = 'block';

}
function getSuggestions(ids){
    let skipfam = ids.map(elem => 'skipfam[]='+elem[1].familyId).join('&');
    let colors =[];
    let brands =[];
    let sizes =[];
    let upselld = document.getElementById('cartUpsell');
    let upselitems= document.getElementById('upsellItems');
    if(upselitems){
        upselitems.innerHTML = '';
        upselld.display = 'none';
        localCall("getSuggestions",skipfam , displaySuggestions, fail=>console.log('no suggestions'), "GET");
    }

}
function displaySuggestions(response){
    let upselitems= document.getElementById('upsellItems');
    if(upselitems){

        Object.values(response).forEach(prod => {
            let updiv = document.createElement('div');
            updiv.classList.add('upsellItem');
            updiv.innerHTML = '<a href="'+prod.slug+'" class="productHolder" title="'+prod.name+'">\
                <picture class="productImage">\
                    <source srcset="'+prod.thumb+'.webp" type="image/webp">\
                    <img src="'+prod.thumb+'.jpg" type="image/jpeg" alt="'+prod.name+'">\
                 </picture>\
                <span class="productTitle">'+prod.name+'</span>\
                <span class="price"> '+prod.price+' lei </span> \
            </a>';
            upselitems.appendChild(updiv);
        });
        let upselld = document.getElementById('cartUpsell');
        if(upselld) upselld.style.display = '';
        
        
    }
}

function putSecondPict(msg){
    Object.values(msg.items).forEach(pict => {
        let elemP = gEl('pictf-'+pict.id);
        if(elemP){
            let np = document.createElement('picture');
            np.classList.add('image2');
            let pna= pict.name.split('.');
            pna.pop();
            const basename = pna.join('.');
            np.innerHTML = '<source srcset="'+thumbsPath+''+pict.id+'/'+basename+'.webp" type="image/webp">\
            <img src="'+thumbsPath+''+pict.id+'/'+basename+'.jpg" type="image/jpeg" alt="">';
            elemP.prepend(np);
        }
    });

    Array.from(gElClass('productImage')).forEach(elem => {
        if(elem.children.length == 1){
            let dpn = elem.children[0].cloneNode(true);
            dpn.classList.remove('image1');
            dpn.classList.add('image2');
            elem.append(dpn);
        }
    });

}
function getSecondPicture(){
    
    let aFids = Array.from(gElClass('productImage')).map(elem => {
        if(typeof elem.attributes['data-fid'] !== 'undefined') return elem.dataset['fid'] ;
        return 0;
    }).filter(elem=> elem != 0);
    if(aFids.length)
    localCall('getSecondPicture', aFids.map(elem => 'fid[]='+elem).join('&'), putSecondPict, msg=>console.log('no second pict') ) ;


}

function getProductsVariations(){
    let aFids = Array.from(gElClass('productDisplay')).map(elem => {
        if(typeof elem.attributes['data-fid'] !== 'undefined') return elem.attributes['data-fid'].value ;
        return 0;
    }).filter(elem=> elem != 0);
    localCall('getProductsVariations', aFids.map(elem => 'id[]='+elem).join('&'), showProductVariations, msg=>console.log('no second pict') ) ;
}
function getProductsVariations_black(){
    let aFids = Array.from(gElClass('productDisplay')).map(elem => {
        if(typeof elem.attributes['data-fid'] !== 'undefined') return elem.attributes['data-fid'].value ;
        return 0;
    }).filter(elem=> elem != 0);
    localCall('getProductsVariations', aFids.map(elem => 'id[]='+elem).join('&')+"&black=1", showProductVariations_black, msg=>console.log('no second pict') ) ;
}
function getUniversalSizeOn(){
    let usqp = new URLSearchParams(window.location.search);
    return usqp.getAll('x[]');

}
function showProductVariations(msg){
    let usOn = getUniversalSizeOn();


     Array.from(gElClass('productDisplay')).forEach(elem => {
        if(typeof elem.attributes['data-fid'] == 'undefined') return false;
        const fid = elem.attributes['data-fid'].value ;
        if(typeof msg.items[fid] === 'undefined') return false;
        
        const slug = elem.attributes['data-path'].value.split('?')[0] ;

        let gotSizes = Object.values(msg.items[fid]).map(sid => (
            { id:sid.id
            ,uSizeId: sid.uSizeId 
            , name: ((typeof attrValNames[sid.sizeId] !== 'undefined')?attrValNames[sid.sizeId].value:' &nbsp; ' ) 
            , showOrder: ((typeof attrValNames[sid.sizeId] !== 'undefined')?attrValNames[sid.sizeId].showOrder:'0') }
            
        )).sort(
                (a, b) => a.showOrder != '0' ?  (parseInt(a.showOrder) < parseInt(b.showOrder) ? -1 : parseInt(a.showOrder) > parseInt(b.showOrder) ? 1 : 0)  : (a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) )
            );
            let extraElem = 0;
            if(usOn.length){
                let tmp = gotSizes.filter(size => usOn.includes(size.uSizeId));
                if(tmp){
                    extraElem = gotSizes.length - tmp.length;
                    gotSizes = tmp;
                }
            }else{

                if(gotSizes.length > 3 ){
                    extraElem = gotSizes.length-3;
                    gotSizes = gotSizes.slice(0,3);
                    
                    
                }
            }
        let output = gotSizes.map(sid => '<a data-ev="'+sid.showOrder+'" href="'+slug+'?pid='+sid.id+'">'+sid.name+'</a>');
        if(extraElem){
            output.push('<a class="moreSizesAvail" data-ev="0" href="'+slug+'">+'+extraElem+'</a>');
        }
        
        
        elem.querySelector('.famsizes').innerHTML = output.join('');


        
     });

}
function showProductVariations_black(msg){
    Array.from(gElClass('productDisplay')).forEach(elem => {
        if(typeof elem.attributes['data-fid'] == 'undefined') return false;
        const fid = elem.attributes['data-fid'].value ;
        if(typeof msg.items[fid] === 'undefined') return false;
        
        const slug = elem.attributes['data-path'].value.split('?')[0] ;

        let gotSizes = Object.values(msg.items[fid]).map(sid => ({id:sid.id
            , name: ((typeof attrValNames[sid.sizeId] !== 'undefined')?attrValNames[sid.sizeId].value:'FARA' ) 
            , showOrder: ((typeof attrValNames[sid.sizeId] !== 'undefined')?attrValNames[sid.sizeId].showOrder:'0') }
            )).sort(
                (a, b) => a.showOrder != '0' ?  (parseInt(a.showOrder) < parseInt(b.showOrder) ? -1 : parseInt(a.showOrder) > parseInt(b.showOrder) ? 1 : 0)  : (a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) )
            );
            let extraElem = 0;
            if(gotSizes.length > 3 ){
                extraElem = gotSizes.length-3;
                gotSizes = gotSizes.slice(0,3);
                
                
            }

        let output = gotSizes.map(sid => '<a data-ev="'+sid.showOrder+'" href="'+slug+'?pid='+sid.id+'">'+sid.name+'</a>');
        if(extraElem){
            output.push('<a class="moreSizesAvail" data-ev="0" href="'+slug+'">+'+extraElem+'</a>');
        }
        
        
        elem.querySelector('.famsizes').innerHTML = output.join('');


        
     });

     return;
     Array.from(gElClass('productDisplay')).forEach(elem => {
        if(typeof elem.attributes['data-fid'] == 'undefined') return false;
        const fid = elem.attributes['data-fid'].value ;
        if(typeof msg.items[fid] === 'undefined') return false;
        
        const slug = elem.attributes['data-path'].value ;
      
        
        let output = Object.values(msg.items[fid]).map(sid => ({id:sid.id, name: (typeof attrValNames[sid.sizeId] !== 'undefined')?attrValNames[sid.sizeId].value:'FARA' })).sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : (a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0) ).map(sid => '<span>'+sid.name+'</span>');
        
        
        elem.querySelector('.famsizes').innerHTML = output.join('');


        
     });

}

var HtmlEntities = function() {};

HtmlEntities.map = {
    "'": "&apos;",
    "<": "&lt;",
    ">": "&gt;",
    " ": "&nbsp;",
    "¡": "&iexcl;",
    "¢": "&cent;",
    "£": "&pound;",
    "¤": "&curren;",
    "¥": "&yen;",
    "¦": "&brvbar;",
    "§": "&sect;",
    "¨": "&uml;",
    "©": "&copy;",
    "ª": "&ordf;",
    "«": "&laquo;",
    "¬": "&not;",
    "®": "&reg;",
    "¯": "&macr;",
    "°": "&deg;",
    "±": "&plusmn;",
    "²": "&sup2;",
    "³": "&sup3;",
    "´": "&acute;",
    "µ": "&micro;",
    "¶": "&para;",
    "·": "&middot;",
    "¸": "&cedil;",
    "¹": "&sup1;",
    "º": "&ordm;",
    "»": "&raquo;",
    "¼": "&frac14;",
    "½": "&frac12;",
    "¾": "&frac34;",
    "¿": "&iquest;",
    "À": "&Agrave;",
    "Á": "&Aacute;",
    "Â": "&Acirc;",
    "Ã": "&Atilde;",
    "Ä": "&Auml;",
    "Å": "&Aring;",
    "Æ": "&AElig;",
    "Ç": "&Ccedil;",
    "È": "&Egrave;",
    "É": "&Eacute;",
    "Ê": "&Ecirc;",
    "Ë": "&Euml;",
    "Ì": "&Igrave;",
    "Í": "&Iacute;",
    "Î": "&Icirc;",
    "Ï": "&Iuml;",
    "Ð": "&ETH;",
    "Ñ": "&Ntilde;",
    "Ò": "&Ograve;",
    "Ó": "&Oacute;",
    "Ô": "&Ocirc;",
    "Õ": "&Otilde;",
    "Ö": "&Ouml;",
    "×": "&times;",
    "Ø": "&Oslash;",
    "Ù": "&Ugrave;",
    "Ú": "&Uacute;",
    "Û": "&Ucirc;",
    "Ü": "&Uuml;",
    "Ý": "&Yacute;",
    "Þ": "&THORN;",
    "ß": "&szlig;",
    "à": "&agrave;",
    "á": "&aacute;",
    "â": "&acirc;",
    "ã": "&atilde;",
    "ä": "&auml;",
    "å": "&aring;",
    "æ": "&aelig;",
    "ç": "&ccedil;",
    "è": "&egrave;",
    "é": "&eacute;",
    "ê": "&ecirc;",
    "ë": "&euml;",
    "ì": "&igrave;",
    "í": "&iacute;",
    "î": "&icirc;",
    "ï": "&iuml;",
    "ð": "&eth;",
    "ñ": "&ntilde;",
    "ò": "&ograve;",
    "ó": "&oacute;",
    "ô": "&ocirc;",
    "õ": "&otilde;",
    "ö": "&ouml;",
    "÷": "&divide;",
    "ø": "&oslash;",
    "ù": "&ugrave;",
    "ú": "&uacute;",
    "û": "&ucirc;",
    "ü": "&uuml;",
    "ý": "&yacute;",
    "þ": "&thorn;",
    "ÿ": "&yuml;",
    "Œ": "&OElig;",
    "œ": "&oelig;",
    "Š": "&Scaron;",
    "š": "&scaron;",
    "Ÿ": "&Yuml;",
    "ƒ": "&fnof;",
    "ˆ": "&circ;",
    "˜": "&tilde;",
    "Α": "&Alpha;",
    "Β": "&Beta;",
    "Γ": "&Gamma;",
    "Δ": "&Delta;",
    "Ε": "&Epsilon;",
    "Ζ": "&Zeta;",
    "Η": "&Eta;",
    "Θ": "&Theta;",
    "Ι": "&Iota;",
    "Κ": "&Kappa;",
    "Λ": "&Lambda;",
    "Μ": "&Mu;",
    "Ν": "&Nu;",
    "Ξ": "&Xi;",
    "Ο": "&Omicron;",
    "Π": "&Pi;",
    "Ρ": "&Rho;",
    "Σ": "&Sigma;",
    "Τ": "&Tau;",
    "Υ": "&Upsilon;",
    "Φ": "&Phi;",
    "Χ": "&Chi;",
    "Ψ": "&Psi;",
    "Ω": "&Omega;",
    "α": "&alpha;",
    "β": "&beta;",
    "γ": "&gamma;",
    "δ": "&delta;",
    "ε": "&epsilon;",
    "ζ": "&zeta;",
    "η": "&eta;",
    "θ": "&theta;",
    "ι": "&iota;",
    "κ": "&kappa;",
    "λ": "&lambda;",
    "μ": "&mu;",
    "ν": "&nu;",
    "ξ": "&xi;",
    "ο": "&omicron;",
    "π": "&pi;",
    "ρ": "&rho;",
    "ς": "&sigmaf;",
    "σ": "&sigma;",
    "τ": "&tau;",
    "υ": "&upsilon;",
    "φ": "&phi;",
    "χ": "&chi;",
    "ψ": "&psi;",
    "ω": "&omega;",
    "ϑ": "&thetasym;",
    "ϒ": "&Upsih;",
    "ϖ": "&piv;",
    "–": "&ndash;",
    "—": "&mdash;",
    "‘": "&lsquo;",
    "’": "&rsquo;",
    "‚": "&sbquo;",
    "“": "&ldquo;",
    "”": "&rdquo;",
    "„": "&bdquo;",
    "†": "&dagger;",
    "‡": "&Dagger;",
    "•": "&bull;",
    "…": "&hellip;",
    "‰": "&permil;",
    "′": "&prime;",
    "″": "&Prime;",
    "‹": "&lsaquo;",
    "›": "&rsaquo;",
    "‾": "&oline;",
    "⁄": "&frasl;",
    "€": "&euro;",
    "ℑ": "&image;",
    "℘": "&weierp;",
    "ℜ": "&real;",
    "™": "&trade;",
    "ℵ": "&alefsym;",
    "←": "&larr;",
    "↑": "&uarr;",
    "→": "&rarr;",
    "↓": "&darr;",
    "↔": "&harr;",
    "↵": "&crarr;",
    "⇐": "&lArr;",
    "⇑": "&UArr;",
    "⇒": "&rArr;",
    "⇓": "&dArr;",
    "⇔": "&hArr;",
    "∀": "&forall;",
    "∂": "&part;",
    "∃": "&exist;",
    "∅": "&empty;",
    "∇": "&nabla;",
    "∈": "&isin;",
    "∉": "&notin;",
    "∋": "&ni;",
    "∏": "&prod;",
    "∑": "&sum;",
    "−": "&minus;",
    "∗": "&lowast;",
    "√": "&radic;",
    "∝": "&prop;",
    "∞": "&infin;",
    "∠": "&ang;",
    "∧": "&and;",
    "∨": "&or;",
    "∩": "&cap;",
    "∪": "&cup;",
    "∫": "&int;",
    "∴": "&there4;",
    "∼": "&sim;",
    "≅": "&cong;",
    "≈": "&asymp;",
    "≠": "&ne;",
    "≡": "&equiv;",
    "≤": "&le;",
    "≥": "&ge;",
    "⊂": "&sub;",
    "⊃": "&sup;",
    "⊄": "&nsub;",
    "⊆": "&sube;",
    "⊇": "&supe;",
    "⊕": "&oplus;",
    "⊗": "&otimes;",
    "⊥": "&perp;",
    "⋅": "&sdot;",
    "⌈": "&lceil;",
    "⌉": "&rceil;",
    "⌊": "&lfloor;",
    "⌋": "&rfloor;",
    "⟨": "&lang;",
    "⟩": "&rang;",
    "◊": "&loz;",
    "♠": "&spades;",
    "♣": "&clubs;",
    "♥": "&hearts;",
    "♦": "&diams;"
};

HtmlEntities.decode = function(string) {
    var entityMap = HtmlEntities.map;
    for (var key in entityMap) {
        var entity = entityMap[key];
        var regex = new RegExp(entity, 'g');
        string = string.replace(regex, key);
    }
    string = string.replace(/&quot;/g, '"');
    string = string.replace(/&amp;/g, '&');
    return string;
}

HtmlEntities.encode = function(string) {
    var entityMap = HtmlEntities.map;
    string = string.replace(/&/g, '&amp;');
    string = string.replace(/"/g, '&quot;');
    for (var key in entityMap) {
        var entity = entityMap[key];
        var regex = new RegExp(key, 'g');
        string = string.replace(regex, entity);
    }
    return string;
}

function popupSubscribeNewsletter(){
    let formElement = document.forms['popupSubscribe'];
    
    let formData = new FormData(formElement);

    if(formElement.checkValidity()){
        localCall("subscribeNewsletter",formData, msg => {
            let suc = gEl('popupnewsSuccess');
            let fail = gEl('popupnewsWarning');
                if(msg.insert > 0 ){
                    setCookie('inscris', "1", 15);

                    if(fail) fail.style.display = 'none';
                    if(suc) suc.style.display = '';

                }else{
       
                    if(fail) fail.style.display = '';
                    if(suc) suc.style.display = 'none';
                }
        }, msg => {console.log(msg); }, 'POST');
        
    }else{
        formElement.reportValidity();
    }
}

function subscribeNewsletter(){
    let formElement = document.forms['subscribe'];
    let formData = new FormData(formElement);

    if(formElement.checkValidity()){
        localCall("subscribeNewsletter",formData, msg => {
            let suc = gEl('newsSuccess');
            let fail = gEl('newsWarning');
                if(msg.insert > 0 ){
                   
                    if(fail) fail.style.display = 'none';
                    if(suc) suc.style.display = '';

                }else{
       
                    if(fail) fail.style.display = '';
                    if(suc) suc.style.display = 'none';
                }
        }, msg => {console.log(msg); }, 'POST');
        
    }else{
        formElement.reportValidity();
    }
}

function displaySearchResults(msg){
    let sug = document.getElementById('sugestii');
    if(!sug) return false;
	sug.innerHTML = '';
	sugg = '';
    Object.values(msg.items).forEach(item => {
        sugg += '<li><a href="'+item.slug+'" title="'+item.name+'"><span class="productHolder"><picture class="productImage"><img src="'+item.thumb+'.jpg"></picture></span></a><div class="productTitle"><a href="'+item.slug+'" title="'+item.name+'">'+item.name+'</a></div><span class="price finalPrice">'+item.price+' lei</span></li>';
    });
	sug.innerHTML += '<span class="miniTitle">Produse sugerate</span><ul class="productList grid grid-6">'+sugg+'</ul>';
	sug.innerHTML +='<div class="centered"><a href="cautare?produs='+msg.cauta+'" class="allResults">Toate rezultatele</a></div>';
}
var debounceSearch = false;
function searchForProduct(){
    if(debounceSearch) clearTimeout(debounceSearch);
    debounceSearch = setTimeout(()=>{

        if(this.value.length > 3){
            localCall('search', 'seek='+this.value, displaySearchResults, msg=>{console.log(msg)});

        }

    }, 300);
    
}
function getEventPath(e) {
    var path = [];
    var currentElem = e.target;
    while (currentElem) {
      path.push(currentElem);
      currentElem = currentElem.parentElement;
    }
    if (path.indexOf(window) === -1 && path.indexOf(document) === -1)
      path.push(document);
    if (path.indexOf(window) === -1)
      path.push(window);
    return path;
  }
function checkAddtoWishlist(e){
    let are = getEventPath(e).filter(elem => typeof elem.classList !=='undefined' && (elem.classList.contains('addToFavorite') || elem.classList.contains('toWishlist')));
    if(are.length){
        let wish = are.pop();
        if(typeof wish.attributes['data-productid'] !== 'undefined'){
            let famid = wish.attributes['data-productid'].value;
            let familyId = wish.dataset['fid'];
            localCall('addToWishlist', {fid:famid}, msg => {
                if(msg.status == 1){
                    wish.classList.add('wished');
                    (rtbhEvents = window.rtbhEvents || []).push(
                        {
                        eventType: 'wishlist',
                        offerId: (familyId).toString()
                        },
                        {
                        eventType: 'uid',
                        id: getCookie('idVisit')
                        });

                }else{
                    wish.classList.remove('wished');
                    let infav = document.getElementById('wishitem-'+msg.fid);
                    if(infav) infav.remove();
                        
                    
                }
                let wiscounte = document.getElementById('wishcount')
                if(wiscounte){
                wiscounte.innerHTML = Object.keys(JSON.parse(getCookie('wish'))).length;
                }
            }, msg=>{console.log(msg)}, "POST");
        }
    }
}
function accountUser(fbresponse){
    localCall('login', fbresponse, success=>{
        location.href = 'contul-meu';
    }, failF = false, mode= 'POST')

}
function finalAccountUser(fbresponse){
    
    localCall('login', fbresponse, success=>{
        location.href = 'finalizare-comanda';
    }, failF = false, mode= 'POST')

}
function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
}
function submitContact(e) {
    if( !document.getElementById("contact-form").checkValidity()){
        document.getElementById("contact-form").reportValidity();
        return;
    }
    document.getElementById('tokenulcontact').value = e;
    document.getElementById("contact-form").submit();
}
function getSimilarProducts(ids = []){
    if(!ids.length) return;
    
    localCall("getSimilarProducts", ids.map(id => 'ids[]='+id).join('&'), msg => {
        if(typeof displaySimilarProductsDis !== 'undefined')
        displaySimilarProductsDis(msg);
     
    }, emsg=>{
        console.log(emsg);
    })
}