/*
 * Custom code goes here.
 * A template should always ship with an empty custom.js
 */
 
// faddons 
!function(f){f.fn.textfill=function(i){var r=f.extend({debug:!1,maxFontPixels:40,minFontPixels:4,innerTag:"span",widthOnly:!1,success:null,fail:null,complete:null,explicitWidth:null,explicitHeight:null,changeLineHeight:!1,truncateOnFail:!1,allowOverflow:!1},i);function c(){r.debug&&"undefined"!=typeof console&&void 0!==console.debug&&console.debug.apply(console,arguments)}function u(i,e,t,n,l,s){function h(i,e){var t=" / ";return e<i?t=" > ":i==e&&(t=" = "),t}c("[TextFill] "+i+" { font-size: "+e.css("font-size")+",Height: "+e.height()+"px "+h(e.height(),t)+t+"px,Width: "+e.width()+h(e.width(),n)+n+",minFontPixels: "+l+"px, maxFontPixels: "+s+"px }")}function x(i,e,t,n,l,s,h,o){for(u(i,e,l,s,h,o);h<Math.floor(o)-1;){var a=Math.floor((h+o)/2);e.css("font-size",a);var r=t.call(e);if(r<=n){if(h=a,r==n)break}else o=a;u(i,e,l,s,h,o)}return e.css("font-size",o),t.call(e)<=n&&u(i+"* ",e,l,s,h=o,o),h}return c("[TextFill] Start Debug"),this.each(function(){var i=f(r.innerTag+":first",this);if(c("[TextFill] Inner text: "+i.text()),c("[TextFill] All options: ",r),c("[TextFill] Maximum sizes: { Height: "+e+"px, Width: "+t+"px }"),!i.is(":visible"))return r.fail&&r.fail(this),void c("[TextFill] Failure { Current Width: "+i.width()+", Maximum Width: "+t+", Current Height: "+i.height()+", Maximum Height: "+e+" }");var e=r.explicitHeight||f(this).height(),t=r.explicitWidth||f(this).width(),n=i.css("font-size"),l=parseFloat(i.css("line-height"))/parseFloat(n),s=r.minFontPixels,h=r.maxFontPixels<=0?e:r.maxFontPixels,o=void 0;r.widthOnly?i.css("white-space","nowrap"):o=x("Height",i,f.fn.height,e,e,t,s,h);var a=void 0,a=x("Width",i,f.fn.width,t,e,t,s,h);r.widthOnly?(i.css({"font-size":a}),r.changeLineHeight&&i.parent().css("line-height",l*a+"px")):(a=Math.min(o,a),i.css("font-size",a),r.changeLineHeight&&i.parent().css("line-height",l*a+"px")),c("[TextFill] Finished { Old font-size: "+n+", New font-size: "+i.css("font-size")+" }"),i.width()>t&&!r.allowOverflow||i.height()>e&&!r.widthOnly&&!r.allowOverflow?(i.css("font-size",n),r.fail&&r.fail(this),c("[TextFill] Failure { Current Width: "+i.width()+", Maximum Width: "+t+", Current Height: "+i.height()+", Maximum Height: "+e+" }")):r.success&&r.success(this)}),r.complete&&r.complete(this),c("[TextFill] End Debug"),this}}("undefined"!=typeof module&&module.exports?require("jquery"):window.jQuery);
 
 
alert = function(s) { console.log(s); };
$(function(){
	$('.openPopCons').click(function(){ $('.popup-consegna').removeClass('hide'); });
	$('.popup-consegna .overlay').click(function(){ $('.popup-consegna').addClass('hide'); });
	
	if($(".already-in-cart").length>0){
		$(".js-mailalert").remove();
	}
	if($('body').attr('id')=='product'){
		var title=$('#content-wrapper .product_header_container .page-title').text();
		$('.social-sharing ul').append($('<li><a href="mailto:?subject=Guarda '+title+' su technocity.it&body='+title+' ('+window.location.href+')" title="Invia email" target="_blank" rel="noopener noreferrer"><i class="fa fa-envelope-o" aria-hidden="true"></i></a></li><li><a class="btnPrintPage" href="#" title="Stampa" rel="noopener noreferrer"><i class="fa fa-print" aria-hidden="true"></i></a></li>'));

		$('.btnPrintPage').on('click',function(e){ window.print(); e.preventDefault(); e.stopPropagation(); return false; });

		$(".product-actions .social-sharing").hide();
		$(".technocity-social-plugins").html('<span class="social-sharing">'+$('.social-sharing').html()+'</span>');

		if($(".js-mailalert").length>0 && $(".technocity-mailalert").length>0){
			var jsMailAlertURL = $(".js-mailalert").data('url');
			$(".js-mailalert").hide();
			var jsMailAlertContent = $(".js-mailalert").html();
			$(".js-mailalert").remove();
			$(".technocity-mailalert").html("<div class='js-mailalert' data-url='"+jsMailAlertURL+"' >"+jsMailAlertContent+"</div>");
			$(".js-mailalert").find('input[type="submit"]').attr('type','button');
		}

		new Swiper("#product-images-large",{loop:!1,effect:"fade",fadeEffect:{crossFade:!0},preloadImages:!1,lazy:{loadPrevNext:!0},navigation:{nextEl:".swiper-button-next",prevEl:".swiper-button-prev"}})
	}
	$(document).keydown(function(e){
	    if(e.which === 123)
	       return false;
	});
	$(document).bind("contextmenu",function(e) { 
	   // e.preventDefault();
	});
	$(document).keyup(function(evtobj) {     
        if (!(evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)){
    		if (evtobj.keyCode == 16) {return false}
            if (evtobj.keyCode == 17) {return false}
    		//$("body").append(evtobj.keyCode + " ");
        }
	});
	if($('body').attr('id')=='index'/* || $('body').attr('id')=='product'*/){
		$('.catParent').each(function(){
			var c=$(this).text().trim(),
				e=$('#iqitmegamenu-horizontal a:contains("'+c+'")').parent().parent().parent().parent(),
				el=e.find('.cbp-category-title')
				el2=e.find('.cbp-column-title');
			if(el.length>0){
				txt=el.first().text().trim();
				$(this).text(txt.replace('nvidia','Schede Video',txt.replace('Stampanti, Scanner e Consumabili','Stampanti')));
			}
			else if(el2.length>0){
				txt=el2.first().text().trim();
				$(this).text(txt.replace('nvidia','Schede Video',txt.replace('Stampanti, Scanner e Consumabili','Stampanti')));
			}
			else{
				el=e.parent().parent().parent().parent().parent().parent().find('.cbp-tab-title');
				txt=el.first().text().trim();
				$(this).text(txt.replace('nvidia','Schede Video',txt.replace('Stampanti, Scanner e Consumabili','Stampanti')));
			}
		});
	}
	else setInterval(function(){ $('.catParent').each(function(){ $(this).text(''); }); },200);
	$('.decimal').each(function(){ $(this).text($(this).text().replace(/ €/g,'€')); });
	setTimeout(function(){
		if($('.logo.img-fluid').attr('src')=='/img/technocity-logo-white.png')
			$('body').append($('<style>.product-features>dl.data-sheet dd.value{color:#fff}\
				p.rate span{border:0!important}\
				.product-accessories .product-price-and-shipping .euro{color:#fff}\
				.product-accessories .block-title,.product-accessories .product-title a{color:#fff!important}\
				.easyzoom-flyout{background-color:black!important}\
				.btn-primary,.btn-primary.disabled,.btn-primary:disabled{background:#2e2e2e}\
				.product-sidebar{background-color:#1d1d1d}\
				.product-features>dl.data-sheet dt.name:nth-of-type(2n+1), .product-features>dl.data-sheet dd.value:nth-of-type(2n+1){background-color:transparent}\
				.ritNegozio{margin-bottom:0.55rem}\
				@media (max-width: 600px){\
					.product-features>dl.data-sheet dd.value {\
					    border-left: 1px solid #282828;\
					}\
				}\
			</style>'));
	},300);
	document.getElementById("footer").innerHTML+='<div style="position: fixed; bottom: 40px; right: 40px; z-index: 9;" class="f-icon f-ic-whatsapp right"> <a href="https://api.whatsapp.com/send?phone=+393245472874" target="_blank" rel="noopener noreferrer"><img src="https://romabout.com/wp-content/uploads/2020/03/whatsapp-logo.png" alt="whatsapp" width="50" height="50"></a></div>';
	
	$('#view_product_details').on('click', function(){
		var top_menu_height = $('#iqitmegamenu-wrapper').height();
		$('html, body').animate({scrollTop: $('#product-details-tab').offset().top - top_menu_height }, 'slow');
	});

	//Remove any block on "removeAll" button (once the button is displayed is because there are products in cart).
	if($(".cart-detailed-actions #removeAll")){
		$(".cart-detailed-actions #removeAll").removeClass('disabled');
	}

	//Fix the Already on Cart issue related to modal
	prestashop.on('updatedProduct',function(e){	
		if($('.ritNegozio').length==0){
			if(typeof e.product_add_to_cart != 'undefined'){
				$('.product-add-to-cart').html(e.product_add_to_cart);
			}
		}
		if($(".already-in-cart").length>0){
			$(".js-mailalert").remove();
		}
	});


	
	
	// faddons
	/*
	$('.product-miniature-grid .product-title').textfill({
		minFontPixels:8,
		maxFontPixels: 14,
		innerTag: 'a',
		widthOnly:true
	});	
	*/

	if($("body.cms-id-13").length>0){
		$("img.logo.img-fluid").attr('src','/img/technocity-logo-white.png');
	}
	if($("body.cms-id-14").length>0 || $("body.cms-id-15").length>0 || $("body.cms-id-16").length>0 || $("body.cms-id-17").length>0 || $("body.cms-id-19").length>0 ){
		$("#desktop_logo img.logo.img-fluid").attr('src','/img/technocity-logo-white.png');
		//$('#iqitmegamenu-horizontal .cbp-hrmenu > ul').prepend("<li><a href='/' target='_top'>"+$('.logo.img-fluid')[0].outerHTML+"</a></li>");
		$( window ).on('scroll',function() {
			if($(window).scrollTop()>100){
				$("#iqitmegamenu-wrapper").addClass('stick');
			}else{
				$("#iqitmegamenu-wrapper").removeClass('stick');
			}
		});
		var lastMenuOption = null;
		$('.cbp-hrmenu-tab').on('mouseenter',function(){
			lastMenuOption = this
		});
		$('.cbp-hrmenu-tab').on('mouseout',function(){
			setTimeout(function(){
				if($('.cbp-hrsub:hover').length == 0 && $('.cbp-hrmenu-tab:hover').length == 0){
					$('.cbp-hropen').removeClass('cbp-hropen');
				}else if(lastMenuOption!=null){
					$('.cbp-hropen').removeClass('cbp-hropen');
					$(lastMenuOption).addClass('cbp-hropen');
				}
			},100);
		});

		function sameHeightBoxes(){
    
			$('.assistenza-items-list').each(function(i,item){
				$(item).find('.elementor-widget-image-box').each(function(ii,item2){
					if($(item2).attr('style')!=null){
						$(item2).attr('style',$(item2).attr('style').replace('height','heightOLD'));
					}
				});
				if($(window).width()>767){
					var maxHeight=0
					$(item).find('.elementor-widget-image-box').each(function(ii,item2){
						if(maxHeight < $(item2).height()){
							maxHeight = $(item2).height();
						}
					});
					$(item).find('.elementor-widget-image-box').each(function(ii,item2){
						$(item2).css('height',maxHeight+"px");
					});
				}
			});
		}
		$(document).ready(function() {
			$(window).resize(function() {
				sameHeightBoxes();
			});
			sameHeightBoxes();
		});
	}
		


	if($('.jpgtopng').length>0){

		$('.jpgtopng img').each(function(i,item){
			console.log(item);
			$(item).on('load',function(){
			
				if(!$(item).hasClass('transparency_aplied')){
					var canvas = document.createElement('canvas');
					
					canvas.id = 'tempCanvas_'+$(item).attr('src');
					document.body.appendChild(canvas);
					var ctx = canvas.getContext("2d");
					var image = item;
					canvas.height = $(item).height();
					canvas.width = $(item).width();
					ctx.drawImage(image,0,0);
				
					var imgd = ctx.getImageData(0, 0, canvas.width, canvas.height),
						pix = imgd.data,
						newColor = {r:0,g:0,b:0, a:0};
				
					for (var i = 0, n = pix.length; i <n; i += 4) {
						var r = pix[i],
								g = pix[i+1],
								b = pix[i+2];
				
							// If its white then change it
							if(r >=220 && g >= 220 && b >= 220){ 
								// Change the white to whatever.
								pix[i] = newColor.r;
								pix[i+1] = newColor.g;
								pix[i+2] = newColor.b;
								pix[i+3] = newColor.a;
							}
					}
					ctx.putImageData(imgd, 0, 0);
					$(item).addClass('transparency_aplied');
					$(item).attr('src',canvas.toDataURL("image/png"));
					// console.log(canvas.toDataURL("image/png"));
					canvas.remove();
				}
			});
		});
		
		
	}

	if($('meta[name="discount_percentage"]').length>0){
		$('.product-miniature-layout-2').each(function(i,item){
			if($(item).find('.product-flags .discount').length>0 && $(item).find('.regular-price').length>0){
				regPrice = $(item).find('.regular-price').html().replace('.','').replace(',','.');
				currPrice = $(item).find('.product-price').attr('content');
				regPrice = regPrice.replace(/[^\d.-]/g, '');
				if(regPrice>0){
					percent = 100 - parseInt(currPrice*100/regPrice,10); 
					if(percent>0 && percent<=60){
						$(item).find('.product-flags .discount').html(percent+" %");
					}
				}
			}else if($(item).find('.product-flags .discount').length>0 && $(item).find('.regular-price').length==0 && $(item).find('.non').length>0){
				$(item).find('.product-flags .discount').remove();
			}
		});
		if($('body#product').length>0){
			if($('body#product').find('.product-sidebar .regular-price').length>0 && $('.product-cover .product-flags .discount').length>0 ){
				regPrice = $('.product-sidebar').find('.regular-price').html().replace('.','').replace(',','.');
				currPrice =$('.product-sidebar').find('.product-price').attr('content');
				regPrice = regPrice.replace(/[^\d.-]/g, '');
				if(regPrice>0){
					percent = 100 - parseInt(currPrice*100/regPrice,10); 
					if(percent>0 && percent<=60){
						$(".product-cover").find('.product-flags .discount').html(percent+" %");
					}
				}
			}else if($('.product-cover .product-flags .discount').length>0 && $('.product-sidebar').find('.regular-price').length==0 && $('.product-sidebar').find('.non')){
				$('.product-cover .product-flags .discount').remove();
			}
		}
	}
	if($(".product-flags .discount").length>0){
		$(".product-flags .discount").css('opacity',1);
	}


	
	if($('.TechnocityLazy').length>0){
        $('.TechnocityLazy').each(function(i,item){
            if($(item).data('src') != null && $(item).data('src') != $(item).attr('src')){
                $(item).attr('src',$(item).data('src'));
            }
        });
    }

	if($("body#checkout").length>0){
		$(document).on('click',function(){
			try{
				if(prestashop.cart.subtotals.shipping.amount==0){
					$('#cart-subtotal-shipping .value').html('Ritiro in Negozio Gratuito');
				}else{
					$('#cart-subtotal-shipping .value').html(prestashop.cart.subtotals.shipping.value);
				}
			}catch(e){}
		});
		try{
			$('#cart-subtotal-shipping .value').show();
			if(prestashop.cart.subtotals.shipping.amount==0){
				$('#cart-subtotal-shipping .value').html('Ritiro in Negozio Gratuito');
			}else{
				$('#cart-subtotal-shipping .value').html(prestashop.cart.subtotals.shipping.value);
			}
			if($('.cart-summary-totals .cart-summary-line').not('.cart-total').find('.value').html().trim()=='€'){
				$('.cart-summary-totals .cart-summary-line').not('.cart-total').remove();
			}
		}catch(e){}
	}
	
	sameHeightProductMiniature();
	$(window).on('resize',function(){
		sameHeightProductMiniature();
	});
});

function clearCart(){
	$.ajax({
		url: "/carrello?action=show&emptyCart=1",
	  }).done(function() {
		location.reload();
	  });
	
}

function sameHeightProductMiniature(){
	$('.swiper-wrapper').each(function(){
		$('.swiper-slide',this).each(function(){
			$(this).find('.product-miniature').css('height',"auto");
		});
		
		let maxHeight = 0;
		$('.swiper-slide',this).each(function(){
			if($(this).find('.product-miniature').height() > maxHeight ){
				maxHeight = $(this).find('.product-miniature').height();
			}
		});
		$('.swiper-slide',this).each(function(){
			$(this).find('.product-miniature').css('height',maxHeight);
		});
	});
}

window.addEventListener('load',function () {


	//Corregir paginacion en los productos

	jQuery('.pagination a').click(function(){
		
		var enlace = this.href;
		
		window.location = enlace;

	});

	//Ocultar corazones

	jQuery(".material-icons:contains('favorite_border')").hide();




},false);





