// source --> https://www.lesmillepots.fr/wp-content/themes/hello-elementor-child/js/MSW_ajax.js?ver=97606ac7a9bf3f827314a728024685e0&#039; defer  

jQuery(document).ready(function($) {

	var show_notice = function( html_element, $target ) {
		if ( ! $target ) {
			$target = $( '.woocommerce-notices-wrapper:first' ) || $( '.cart-empty' ).closest( '.woocommerce' ) || $( '.woocommerce-cart-form' );
		}
		$target.prepend( html_element );
	};

	//Vérifier si la quantité est ok quand on update cart et trigger update cart si ok
	$("div.woocommerce").on("change", ".woocommerce-cart-form select.qty", function(e){

		$( '.woocommerce-cart-form , div.cart_totals ' ).block({
				message: null,
				overlayCSS: {
					background: '#fff',
					opacity: 0.7
				}
			});

		var product_cart_item_key = $(this).attr('name').replace('cart[' , '').replace('][qty]' , '');
		var quantite_produit = $(this).val();
		// alert(product_cart_item_key);
		// alert(quantite_produit);

		$.ajax( {
			type:     'POST',
			dataType: 'json',
			url:      MSW_nonce_URL.url,
			data: {
				action: "MSW_ajax_check_quantity_update_cart",
				security : MSW_nonce_URL.nonce,
				product_cart_item_key: product_cart_item_key,
				quantity: quantite_produit
			},
			success: function( response ) {
				
				// alert(response.passed_quantity);
				// alert(response.quantity);
				// alert(response.variation_id);
				// alert(response.product_id);

				if (response.error==true)
				{
					var error_message = '<ul class="woocommerce-error" role="alert"><li>Une erreur s\'est produite. Merci de rééssayer.</li></ul>';
				}
				else if (response.passed_quantity != true)
				{
					var error_message = '<ul class="woocommerce-error" role="alert"><li>'+response.passed_quantity+'</li></ul>';
				}
				
				if (error_message && error_message != '')
				{
					$( ".woocommerce-notices-wrapper" ).html( error_message );
					$( '.woocommerce-cart-form , div.cart_totals ' ).unblock();
				}
				else
				{
					// Auto update cart on quantity change
					$("[name=\"update_cart\"]").trigger("click");
				}
			},
		} );	
	});

	//Fonctionnalité d'ajout au panier en AJAX
	$(document).on("click", ".single_add_to_cart_button, ul.products li form.cart button" , function( e ) {

		if ( $( ".woocommerce .cart_empty_suggestion" ).length > 0 ) var cart_was_empty = true;
		else var cart_was_empty = false;
		
		e.preventDefault();

		if ( $( "#woosq-popup").length == 0) $('#MSW_overlay').css({'z-index':'9999','background-color':'rgba(0,0,0,0.5)','max-height': '2000px'});
		else
		{
			$("body .mfp-woosq .mfp-close").attr("disabled", true);
			$("body .mfp-woosq .mfp-close").attr('style' , 'background-color:#808080;');
			$( "#woosq-popup").prepend('<div id="MSW_wooqs_overlay"></div>');
		}

		var bouton_produit = e.target;
		
		//Si ca vient de la Wishlist
		if ( $(this).hasClass('add_from_wishlist') ) 
		{
			var form = e.target.closest('td.product-add-to-cart');
			var quantite_produit = $(form).find( "select.qty" ).val();
			var data_parent_id = $(this).attr('data-parent-id');

			//S'il y a un attr data-parent-id , l'id est une variation
			if (typeof data_parent_id !== typeof undefined && data_parent_id !== false)
			{
				var id_produit = data_parent_id;
				var variation_produit = $(this).attr('id');
			}
			//Sinon produit simple
			else
			{
				var id_produit = $(this).attr('id');
				var variation_produit = 0;
			}	
		}
		//Si ca vient des pages archive / single product / popup quick view
		else
		{
			var form = e.target.closest('form.cart');
			var id_produit = $(form).find('[name=add-to-cart]').val();
			var quantite_produit = $(form).find( "select.qty" ).val();
			var variation_produit = $(form).find('input[name=variation_id]').val() || 0;

			//Prevent si variations désactivées in loop archive
			if( typeof id_produit === 'undefined' )
			{
				//S'il s'agit d'un produit variable dont on affiche que la single variation
				if ( $(form).attr('action').substring(0, 4) == 'http')
				{
					var splitted = $(form).attr('action').split('&variation_id=');
					var splitted2 = splitted[1].split('&add-to-cart=');
					
					id_produit = splitted2[1]
					variation_produit = splitted2[0];
				}
				//S'il s'agit d'un produit simple
				else
				{
					var action_form = $(form).attr('action').split('add-to-cart=');
					id_produit = action_form[1];	
				}
			}
		}

		// alert('recherche...');
		// alert(id_produit);
		// alert(quantite_produit);
		// alert(variation_produit);

		var data = {
				action: 'MSW_ajax_add_to_cart',
				security : MSW_nonce_URL.nonce,
				product_id: id_produit,
				quantity: quantite_produit,
				variation_id: variation_produit,
			};

		$(document.body).trigger('adding_to_cart', [$(bouton_produit), data]);

		$.ajax({
			type: 'post',
			dataType: 'json',
			url: MSW_nonce_URL.url,
			data: data,
			success: function (response) {
				
				// alert('got response');
				// alert(response.quantite);
				// alert(response.quantite_panier);
				// alert(response.array_tmp);
				// alert(response.passed_quantity);
				// alert(response.thumbmail_popup);
				// alert(response.nb_items);
				// alert(response.variations);
				

				if ( $( "#woosq-popup").length == 0) $('#MSW_overlay').css({'z-index':'3','background-color':'transparent','max-height': '0px'});
				else
				{
					//Fermer la popup quick view		
					$.magnificPopup.close();

					setTimeout(function() { 
						$( "#woosq-popup #MSW_wooqs_overlay").remove(); 
						$("body .mfp-woosq .mfp-close").attr("disabled", false);
						$("body .mfp-woosq .mfp-close").attr('style' , 'background-color:#fff;');
					}, 500);	
				}
				
				if (response.error==true) 
				{
					if (response.passed_quantity != true)
					{
						var error_message = '<ul class="woocommerce-error" role="alert"><li>'+response.passed_quantity+'</li></ul>';
					}
					else
					{
						if (response.type_produit=='vrac' && response.stock < 1) var quantite_display = response.stock*1000 + 'g';
						else if (response.type_produit=='vrac' && response.stock >= 1) var quantite_display = response.stock + 'Kg';
						else var quantite_display = response.stock;
						
						if (response.quantite_panier!=null)
						{
							if (response.type_produit=='vrac' && response.quantite_panier < 1) var quantite_panier_display = response.quantite_panier*1000 + 'g';
							else if (response.type_produit=='vrac' && response.quantite_panier >= 1) var quantite_panier_display = response.quantite_panier + 'Kg';
							else var quantite_panier_display = response.quantite_panier;

							// show_notice( response );
							var error_message = '<ul class="woocommerce-error" role="alert"><li>Vous ne pouvez pas ajouter cette quantité dans le panier. Nous en avons '+quantite_display+' en stock et vous en avez déjà '+quantite_panier_display+' dans votre panier.</li></ul>';
						}
						else
						{
							// show_notice( response );
							var error_message = '<ul class="woocommerce-error" role="alert"><li>Vous ne pouvez pas ajouter cette quantité dans le panier. Nous n\'en avons plus que '+quantite_display+' en stock.</li></ul>';
						}
					}

					$( ".woocommerce-notices-wrapper" ).html( error_message );
				} 
				else 
				{
					//Si page panier et panier était vide, on reload la page
					if ( cart_was_empty == true)
					{
						window.location = 'https://www.lesmillepots.fr/mon-panier/';
						return false;
					}

					//Si on est sur la page panier on trigger update cart
					if ($("form.woocommerce-cart-form [name='update_cart']").length > 0 )
					{
						$("form.woocommerce-cart-form [name='update_cart']").removeAttr('disabled');
						$("form.woocommerce-cart-form [name='update_cart']").trigger("click");
						$("html, body").animate({ scrollTop: $('#container_panier').offset().top }, 500);
					}
					//Sinon animation + MAJ mini cart + MAJ data-counter nb items
					else 
					{
						
						var anim_duration = 0;
						
						//Si ca vient de la Wishlist, supprimer la ligne liée de la wishlist
						if ( $( "form#yith-wcwl-form .wishlist_table" ).length ) $( ".wishlist_table tbody tr#yith-wcwl-row-"+response.id_produit_panier ).remove();

						//Si popup after add to cart, afficher la popup
						var delay_popup_add_to_cart = 0;
						if ( $( "#woosq-popup").length > 0) delay_popup_add_to_cart = 500;
						
						setTimeout(function() {
							if ( $( "#MSW_popup_add_to_cart").length > 0)
							{
								var popup_clone = $( "#MSW_popup_add_to_cart").clone().css('display','block');

								if (response.type_produit == 'vrac')
								{
									if ( quantite_produit < 1 ) var quantite_formatted = quantite_produit*1000 + 'g de';
									else var quantite_formatted = quantite_produit + 'Kg de';

									var texte_quantite = '<p>ont bien été ajoutés à votre panier.</p>';
								}
								else
								{
									var quantite_formatted = quantite_produit + '&times ';
									
									if (quantite_produit == 1) var texte_quantite = '<p>a bien été ajouté à votre panier.</p>';
									else var texte_quantite = '<p>ont bien été ajoutés à votre panier.</p>';
								}

								var nb_points_gagnes = Math.floor( response.sous_total_unformatted );
								if ( nb_points_gagnes > 0 ) var texte_points_gagnes = '<p>En validant cette commande, vous gagnerez <strong>'+nb_points_gagnes+' points fidélité</strong>.</p>';
								else var texte_points_gagnes = '';

								var nb_points_fidelite = response.nb_points_fidelite;
								var nb_tranche_possible = Math.floor(nb_points_fidelite/200);
								var points_deductible = nb_tranche_possible*10;
								if ( nb_tranche_possible > 0 ) var texte_fidelite_acquise = '<p>Passez commande et obtenez <strong>'+points_deductible.toFixed(2)+'€</strong> de remise.</p>';
								else var texte_fidelite_acquise = '';

								var content_product = '<h2>'+quantite_formatted+' '+response.nom+'</h2>'+response.variations+texte_quantite+'<div class="container_infos_fidelite">'+texte_points_gagnes+texte_fidelite_acquise+'</div>';
								
								if ( response.thumbmail_popup == false ) var url_image = 'https://www.lesmillepots.fr/wp-content/uploads/2020/11/photo-a-venir-les-mille-pots-epicerie-vrac-molsheim-255x255.jpg';
								else var url_image = response.thumbmail_popup;
			

								$.magnificPopup.open({
									items: {
										src: popup_clone,
										type: 'inline',
										
									},

									mainClass: 'mfp-zoom-in',
									removalDelay: 160,
									fixedContentPos: true,
									callbacks: {
										open: function() {
											//Insertion du contenu
											$( "#MSW_popup_add_to_cart .thumbnail").html( '<img src='+url_image+' />' );
											$( "#MSW_popup_add_to_cart .content .product").html( content_product );
											$( "button.mfp-close" ).attr('title' , '');
											$( "button.mfp-close" ).html('');
										},
										close: function() {
											popup_clone.remove();
										}
									}
								});	
							}
						}, anim_duration+delay_popup_add_to_cart);
						
						
						
						
						
						
						
						
						
						//Animation d'ajout au panier bocal qui se déplace du select quantité au panier flottant
						
						// var cart = $('#elementor-menu-cart__toggle_button');
						// var cart_icone = $('#elementor-menu-cart__toggle_button .elementor-button-icon');

						// var imgtodrag = $('#image_add_to_cart');
						// var anim_duration = 0;

						// if (imgtodrag) 
						// {
							// var pos_left = $('body').width() / 2; pos_left-=20;
							// var pos_top = $(window).scrollTop() + ( $(window).height() / 2 ); pos_top-=31;
							
							// var width_final = 17;
							// var height_final = 27;
							
							// if (window.matchMedia("(max-width: 1024px)").matches)
							// {
								// var width_final = 16;
								// var height_final = 25;
							// }
							
							// if (window.matchMedia("(max-width: 767px)").matches)
							// {
								// var width_final = 20;
								// var height_final = 32;
							// }

							// anim_duration = 1000;

							// var imgclone = imgtodrag.clone()
							
								// .appendTo($('body'))

								// .css({
								// 'opacity': '1',
									// 'display': 'block',
									// 'position': 'absolute',
									// 'top': pos_top+'px',
									// 'left': pos_left+'px',
									// 'height': '63px',
									// 'width': '40px',
									// 'z-index': '99999'
							// })
								// .animate({
									// 'top': cart_icone.offset().top,
									// 'left': cart_icone.offset().left,
									// 'width': width_final,
									// 'height': height_final,
							// }, anim_duration, 'easeInOutExpo');

							// setTimeout(function () {
								// cart.css('transform','scale(1.2)');
							// }, anim_duration-100);
							
							// setTimeout(function () {
								// cart.css('transform','scale(1)');
							// }, anim_duration+200);

							// setTimeout(function() { 
								// imgclone.remove();	 
							// }, anim_duration);
						// }

						//Mise à jour du mini cart
						if ( typeof woocommerce_params !== 'undefined' )
						{				
							$.post(
								woocommerce_params.ajax_url,
								{'action': 'MSW_ajax_update_mini_cart'},
								function(response) {
									$('.widget_shopping_cart_content').html(response);
								}
							);
						}
						
						//Quantité data-counter icône
						setTimeout(function() {
							$( ".elementor-menu-cart__toggle .elementor-button-icon" ).attr('data-counter', response.nb_items);	 
						}, anim_duration+200);
					}
				}
			}
		});	
	});

	//Fonctionnalité de suppression du panier en AJAX
	$(document).on("click", ".elementor-menu-cart__product-remove a" , function( e ) {

		e.preventDefault();
		
		$('#MSW_overlay_cart').css({'background-color':'rgba(0,0,0,0.25)','max-height': '2000px'});

		var cart_item_key = $(this).attr("data-cart_item_key");

		$.ajax({
			type: 'POST',
			dataType: 'json',
			url: MSW_nonce_URL.url,
			data: {
				action: "MSW_ajax_product_remove",
				security : MSW_nonce_URL.nonce,
				cart_item_key: cart_item_key
			},
			success: function(response) {

				if ( ! response || response.removed == false )
				{
					$( ".woocommerce-notices-wrapper" ).html( '<ul class="woocommerce-error" role="alert"><li>Une erreur s\'est produite. Merci de réessayer.</li></ul>' );
					$('#MSW_overlay_cart').css({'background-color':'transparent','max-height': '0px'});
				}
				else
				{
					//Mise à jour du mini cart
					if ( typeof woocommerce_params !== 'undefined' )
					{
						$.post(
							woocommerce_params.ajax_url,
							{'action': 'MSW_ajax_update_mini_cart'},
							function(response) {
								$('.widget_shopping_cart_content').html(response);
								$('#MSW_overlay_cart').css({'background-color':'transparent','max-height': '0px'});
							}
						);
					}

					//Quantité data-counter icône
					$( ".elementor-menu-cart__toggle .elementor-button-icon" ).attr('data-counter', response.nb_items);
				}
			}
		});
	});
	
	
});