var moveBiens = null;
var moveBien2 = null;
var sToGalerie = null;
var sToCompletion = null;
var map;
$(document).ready(function()
{
	// CAPTCHA ----------------------------
	$("#captchagc > img:nth-of-type(1)").draggable({ revert: true, containment: "parent" });
	$("#captchagc > img + div").droppable({ 
		accept: "#captchagc > img:nth-of-type(1)", 
		activeClass: "accept", 
		hoverClass: "hover", 
		drop: function(event, ui)
		{
			$("#captchagc").addClass("valid");
			$.getJSON("/ajax/form.php", function(data){
				if(data.result == 1)
				{
					var result = true;
					$("#captchagc").closest("form").find("input:required,select:required,textarea:required").each(function()
					{							
						if($(this).val().trim() == "" || ($(this).attr("type") == "checkbox" && $(this).prop("checked") == false))
						{
							if($(this).attr("type") == "checkbox") $(this).parent().css("border","1px solid #FF0000");
							$(this).css("border","1px solid #FF0000");
							$(this).on("click.captcha", function()
							{
								$(this).css("border", "");
								$(this).off("click.captcha");
								if($(this).attr("type") == "checkbox") $(this).parent().css("border", "");
							});
							result = false;
						}
					}).promise().done(function()
					{
						if(result)
						{
							$("#captchagc").append("<i class='fas fa-spinner-third fa-spin'></i>");
							$("#form_contact").submit();
						}
						else
						{
							$($("#captchagc > i").get(2)).remove();
							$("#captchagc").removeClass("valid");
						}
					});					
				}
				else
				{
					alert("Une erreur s'est produite lors de l'envoi de votre message");
				}
			}).fail(function(){ alert("Une erreur s'est produite lors de l'envoi de votre message"); });
		}
	});
	//----------------------------	
	//$(document).off("scroll").off("click", ".burger").off("click", "#menu > ul > li > a").off("mousedown touchstart", ".galerie-biens, .galerie-videos, .galerie-agences").off("mousemove touchmove", "body").off("mouseup touchend", ".galerie-biens, .galerie-videos, .galerie-agences").off("click", ".bien").off("click", ".galerie-biens > .fa-angle-right, .galerie-videos > .fa-angle-right, .galerie-agences > .fa-angle-right").off("click", ".galerie-biens > .fa-angle-left, .galerie-videos > .fa-angle-left, .galerie-agences > .fa-angle-left").off("blur", ".input input[type='text'],.input textarea").off("click", "[rel='text']").off("click", "[rel='img']").off("click", "a.video").off("click", ".accordeon:not(.accordeon-fixe) > li > div:first-child").off("click", "a[href^='#']").off("click", ".completion-budget").off("keydown", ".completion-budget + ul input").off("click", ".completion-budget + ul a").off("keydown", ".completion-cp-ville").off("keyup", ".completion-cp-ville").off("click", "#recherche > div > div > ul > li:not(:first-child)").off("click", "#recherche form a.criteres, #recherche #recherche_criteres a.annuler").off("submit", "#recherche form").off("click", "a").off("click", "#recherche button");
	//$(window).off("hashchange");

	$(document).on("scroll", function()
	{
		//if(location.hash != "") history.pushState("", document.title, window.location.pathname + window.location.search);

		var scroll = $(document).scrollTop();

		if(scroll > 1 && !$('header').hasClass("scroll")) 
		{
			$("header").addClass("scroll");
		}
		else if(scroll < 1 && $("header").hasClass("scroll"))
		{
			$("header").removeClass("scroll");
		}

		if($(".carte-compteur").length > 0)
		{
			$("span.carte-compteur,.carte-compteur > span").each(function()
			{
				if(scroll+$(window).height()-$(this).outerHeight(true) > $(this).offset().top && !$(this).hasClass("go"))
				{
					$(this).addClass("go");
					var $this = $(this);
					jQuery({ Counter: 0 }).animate(
						{ Counter: $this.text().replace(/ +/g,"") }, 
						{
							duration: 1700,
							easing: 'swing',
							step: function()
							{
								$this.text(Math.ceil(this.Counter).toLocaleString());
							}
						}
					);
				}
			});
		}

	}).trigger("scroll").on("click", ".burger", function(event)
	{
		event.preventDefault();
		//$("body").toggleClass("nav-open nav-close");
		if($("body").hasClass("nav-open")) $("body").addClass("nav-close").removeClass("nav-open");
		else $("body").addClass("nav-open").removeClass("nav-close");
 	}).on("click", "#menu > .recherche", function(event)
	{
		event.preventDefault();
		$("#recherche").toggle();
		$("html,body").animate({ "scrollTop":0 });
 	}).on("click", "#menu > ul > li > a", function()
 	{
		if($(this).attr("href").indexOf("#") != -1)
		{
			//$("body").toggleClass("nav-open nav-close");
			if($("body").hasClass("nav-open")) $("body").addClass("nav-close").removeClass("nav-open");
			else $("body").addClass("nav-open").removeClass("nav-close");
		}
 	}).on("mousedown touchstart", ".galerie-biens, .galerie-videos, .galerie-agences, .galerie-texte, .galerie-avis", function(event)
	{
		if($(event.target).hasClass("fa-angle-right") || $(event.target).hasClass("fa-angle-left")) return false;
		// event.stopPropagation();
		// event.preventDefault();

		moveBiens = $(this);
		$(this).data("xstart", getTranslateX($(this).find("ul").get(0)));
		$(this).data("xmousestart", event.changedTouches ? event.changedTouches[0].pageX : event.pageX);
	}).on("mousemove touchmove", "body", function(event)
	{
		if($(event.target).hasClass("fa-angle-right") || $(event.target).hasClass("fa-angle-left")) return false;
		if(moveBiens != null)
		{
			if(moveBiens.data("xmousestart") != (event.changedTouches ? event.changedTouches[0].pageX : event.pageX))
			{
				moveBien2 = true;
				event.stopPropagation();
				event.preventDefault();
			}
			if(Math.abs(parseInt(moveBiens.data("xmousestart"))-(event.changedTouches ? event.changedTouches[0].pageX : event.pageX)) > 20 && $(window).width() <= 430) $("body").css("overflow-y", "hidden");
			var pos = (parseInt(moveBiens.data("xstart"))-((parseInt(moveBiens.data("xmousestart"))-(event.changedTouches ? event.changedTouches[0].pageX : event.pageX))));
			var xend = 0;
			var pos2 = pos+(parseInt(moveBiens.data("xmousestart"))-(event.changedTouches ? event.changedTouches[0].pageX : event.pageX) > 0 ? -120 : 120);
			if(pos2+parseInt(moveBiens.find("ul").width())-20 < parseInt(moveBiens.width()))
			{
				xend = -parseInt(moveBiens.find("ul").width())+parseInt(moveBiens.width())+20;
				moveBiens.data("xend", xend);
			}
			else if(pos2 <= 0)
			{
				xend = pos;				
				moveBiens.data("xend", (pos2 != 0 ? Math.round(pos2/moveBiens.find("ul > li").outerWidth())*moveBiens.find("ul > li").outerWidth() : 0));
			}
			moveBiens.find("ul").css("transform", "translateX("+xend+"px)");
			//moveBiens.find("ul").data("pos", xend);

			moveBiens.on("mouseleave", function()
			{
				if(null != moveBiens)
				{
					moveBiens.off("mouseleave");
					moveBiens.trigger("mouseup");
				}
			});			
		}
	}).on("mouseup touchend", ".galerie-biens, .galerie-videos, .galerie-agences, .galerie-textes, .galerie-avis", function(event)
	{
		$("body").css("overflow-y", "auto");
		if(null != moveBiens)
		{
			moveBiens.find("ul").css("transform", "translateX("+moveBiens.data("xend")+"px)");
			moveBiens.find("ul").data("pos", moveBiens.data("xend"));
			//console.log("move:"+moveBiens.data("xend"));

			if(moveBiens.data("xend") <= parseInt(moveBiens.width()+20)-parseInt(moveBiens.children("ul").width()))
			{
				moveBiens.children(".fa-angle-right").addClass("disable");
			}
			else
			{
				moveBiens.children(".fa-angle-right").removeClass("disable");
			}
			if(moveBiens.data("xend") >= 0)
			{
				moveBiens.children(".fa-angle-left").addClass("disable");
			}
			else
			{
				moveBiens.children(".fa-angle-left").removeClass("disable");
			}
			moveBiens = null;
			setTimeout(function(){ moveBien2 = null; }, 1000);
		}
	}).on("click", ".bien", function(event)
	{
		console.log("moveBien2:"+moveBien2);
		if(moveBien2 != null)
		{
			event.preventDefault();
			event.stopPropagation();
		}
	}).on("click", ".galerie-biens > .fa-angle-right, .galerie-videos > .fa-angle-right, .galerie-agences > .fa-angle-right, .galerie-textes > .fa-angle-right, .galerie-avis > .fa-angle-right", function(event)
	{
		event.preventDefault();
		event.stopPropagation();

		var pos = getTranslateX($(this).prev().get(0));
		var posdata = parseInt($(this).prev().data("pos"));
		if(!isNaN(posdata)) pos = posdata;
		if(pos >= parseInt($(this).parent().width()+20)-parseInt($(this).prev().width()))
		{
			pos -= $(this).prev().find("> li").outerWidth();

			$(this).prev().css("transform", "translateX("+pos+"px)");
			$(this).prev().data("pos", pos);
			//console.log("right:"+pos);
		}
		if(pos <= parseInt($(this).parent().width()+20)-parseInt($(this).prev().width()))
		{
			$(this).addClass("disable");
		}
		$(this).prev().prev().removeClass("disable");
	}).on("click", ".galerie-biens > .fa-angle-left, .galerie-videos > .fa-angle-left, .galerie-agences > .fa-angle-left, .galerie-textes > .fa-angle-left, .galerie-avis > .fa-angle-left", function(event)
	{
		event.preventDefault();
		event.stopPropagation();
		moveBiens = null;

		var pos = getTranslateX($(this).next().get(0));
		var posdata = parseInt($(this).next().data("pos"));
		if(!isNaN(posdata)) pos = posdata;
		if(pos < 0)
		{
			pos += $(this).next().find("> li").outerWidth();

			$(this).next().css("transform", "translateX("+pos+"px)");
			$(this).next().data("pos", pos);
			//console.log("left:"+pos);
		}
		if(pos >= 0)
		{
			$(this).addClass("disable");
		}
		$(this).next().next().removeClass("disable");
	}).on("blur", ".input input[type='text'],.input textarea", function()
	{
		if($(this).val() != "") $(this).addClass("complet");
		else $(this).removeClass("complet");
	})/*.on("click", ".galerie-photos .galerie-photos-miniatures li", function()
	{
		if(null != sToGalerie) clearTimeout(sToGalerie);
		$(this).closest(".galerie-photos-miniatures").prev().find("img:not(:first-child)").remove();
		var apercu = $(this).closest(".galerie-photos-miniatures").prev().find("img:first-child");
		var apercu2 = apercu.clone();
		apercu2.attr("src", $(this).children("img").attr("src"));
		apercu.after(apercu2);
		apercu2.on("load", function()
		{
			apercu.css("opacity",0);
			sToGalerie = setTimeout(function(){ apercu.remove(); }, 1000);			
		}).each(function()
		{
			if(this.complete)
			{
				$(this).trigger('load');
			}
		});

		$(this).addClass("select").siblings().removeClass("select");
		$(this).closest(".galerie-photos").data("img", $(this).prevAll().length+1);
	})*/.on("click", "[rel='text']", function()
	{
		var pop = $("<div class='popbox'></div>");
		var text = $(this).prevAll(".popbox-text").html();
		pop.append(text);
		$("body").append(pop);
		pop.addClass("show");
		pop.on("click", function(event)
		{
			if($(event.target).hasClass("popbox"))
			{
				$(this).addClass("hide");
				setTimeout(function(){ $(".popbox").remove(); }, 500);
			}
		});
		pop.find(".fa-times").on("click", function(event)
		{
			$(event.target).closest(".popbox").addClass("hide");
			setTimeout(function(){ $(".popbox").remove(); }, 500);
		});
	}).on("click", "[rel='img']", function()
	{
		if($(this).is("i")) var img = $(this).prev("img");
		else if($(this).is("a")) var img = $(this).find("img");
		if($(this).hasClass("galerie-photos-photo"))
		{
			var imgs = $(this).next().find("li:not(.video):not(.visite) img");
		}
		else if($(this).hasClass("galerie-images-image"))
		{
			var imgs = $(this).closest("ul").find("li:not(.video):not(.visite) img");
		}
		img.css("opacity", 1);
		imgbig = img.clone();

		var pop = $("<div class='popbox'></div>");
		imgbig.css({ opacity:0, left:img.offset().left, top:img.offset().top-$(document).scrollTop(), maxWidth:img.width(), maxHeight:img.height() });
		pop.append(imgbig);	

		if(undefined != imgs)
		{
			var prev = $("<i class='far fa-angle-left'></i>");
			var next = $("<i class='far fa-angle-right'></i>");
			pop.append(prev);
			pop.append(next);
			prev.on("click", function(event)
			{
				event.preventDefault();
				event.stopPropagation();
				for(var i = 0 ; i < imgs.length ; i++)
				{
					if($(imgs[i]).attr("src") == imgbig.attr("src"))
					{
						if(i-1 >= 0) imgbig.attr("src", $(imgs[i-1]).attr("src"));
						else imgbig.attr("src", $(imgs[imgs.length-1]).attr("src"));
						break;
					}
				}
			});
			next.on("click", function(event)
			{
				event.preventDefault();
				event.stopPropagation();
				for(var i = 0 ; i < imgs.length ; i++)
				{
					if($(imgs[i]).attr("src") == imgbig.attr("src"))
					{
						if(i+1 <= imgs.length-1) imgbig.attr("src", $(imgs[i+1]).attr("src"));
						else imgbig.attr("src", $(imgs[0]).attr("src"));
						break;
					}
				}
			});
		}
		
		imgbig.on("load", function()
		{
			pop.addClass("show");
			imgbig.css("opacity", 1);
			imgbig.addClass("centre");
			pop.on("click", function()
			{
				$(this).addClass("hide");
				$(this).find("img").removeClass("centre");
				setTimeout(function(){ $(".popbox").remove(); }, 500);
			});
		}).each(function()
		{
			if(this.complete)
			{
				$(this).trigger('load');
			}
		});

		$("body").append(pop);
		if($(this).is("a")) return false;
	}).on("click", "a.video", function(event)
	{
		event.preventDefault();
		event.stopPropagation();

		var videobig = "<iframe class='centre' width='560' height='315' src='"+$(this).attr("href")+"?color=white&autoplay=1&rel=0' title='YouTube video player' frameborder='0' allow='accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture' allowfullscreen></iframe>";
		var pop = $("<div class='popbox'></div>");
		pop.append(videobig);	

		pop.addClass("show");
		pop.on("click", function()
		{
			$(this).addClass("hide");
			setTimeout(function(){ $(".popbox").remove(); }, 500);
		});

		$("body").append(pop);
		if($(this).is("a")) return false;
	}).on("click", ".accordeon:not(.accordeon-fixe) > li > div:first-child", function()
	{
		$(this).closest("li").siblings().find("> div:first-child + div").slideUp();
		$(this).closest("li").siblings().find(".handle .fa-chevron-up").addClass("fa-chevron-down").removeClass("fa-chevron-up");

		if($(this).next().is(":hidden"))
		{
			$(this).closest("li").find(".handle .fa-chevron-down").addClass("fa-chevron-up").removeClass("fa-chevron-down");
			$(this).next().slideDown();
		}
		else
		{
			$(this).closest("li").find(".handle .fa-chevron-up").addClass("fa-chevron-down").removeClass("fa-chevron-up");
			$(this).next().slideUp();
		}
	}).on("click", "a[href^='#']", function()
	{
		$(window).trigger("hashchange");
	}).on("click", ".completion-budget", function()
	{
		var select = $(this).next("ul");
		if(!select.is(":visible"))
		{
			select.css({ left:$(this).position().left, top:$(this).position().top+$(this).outerHeight()+(($(this).outerHeight(true)-$(this).outerHeight())/2), minWidth:$(this).outerWidth(true) });
			select.show();
			select.find("> li:first-child > input").focus();
		}
		else
		{
			select.hide();			
		}
	}).on("keydown", ".completion-budget + ul input", function()
	{
		if(event.keyCode == 13)
		{
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
	}).on("click", ".completion-budget + ul a", function()
	{
		var input = $(this).closest("ul").prev();
		var select = $(this).closest("ul");

		var min = select.find("> li:first-child input").val().replace(/\D/g, "");
		var max = select.find("> li:first-child + li input").val().replace(/\D/g, "");
		if(min != "" && max != "")
		{
			if(isNaN(parseInt(min))) min = "";
			if(isNaN(parseInt(max))) max = "";
		}
		else if(min != "")
		{
			if(isNaN(parseInt(min))) min = "";
		}
		else if(max != "")
		{
			if(isNaN(parseInt(max))) max = "";
		}

		if(min != "" && max != "")
		{
			input.val("Entre "+min+" € et "+max+" €");
		}
		else if(min != "")
		{
			input.val("Minimum "+min+" €");
		}
		else if(max != "")
		{
			input.val(max+" € maximum");
		}
		
		select.hide();
	}).on("keydown", ".completion-cp-ville", function(event)
	{
		var search = $(this).val();
		if(event.keyCode == 13)
		{
			var select = $(this).next("ul");
			if(select.find("> li:first-child").length > 0) select.find("> li:first-child").trigger("click");
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
	}).on("keyup", ".completion-cp-ville", function(event)
	{
		var search = $(this).val();
		if(event.keyCode == 13)
		{
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		var select = $(this).next("ul");		
		if(select.length == 0) $(this).after($("<ul></ul>"));
		select.css({ left:$(this).position().left, top:$(this).position().top+$(this).outerHeight()+(($(this).outerHeight(true)-$(this).outerHeight())/2), minWidth:$(this).outerWidth(true) });

		$("body").on("click.completion-cp-ville", function()
		{
			$("body").off("click.completion-cp-ville");
			$(".completion-cp-ville").prev("input[type='hidden']").val("");
			$(".completion-cp-ville").val("");
			$(".completion-cp-ville").next("ul").remove();
		});

		if(null != sToCompletion) clearTimeout(sToCompletion);
		sToCompletion = setTimeout(function()
		{
			$.getJSON("/ajax/completion-ville.php", { q:search }, function(data)
			{
				select.html("");
				var result = false;
				if(data.result == 0)
				{
					for(var i = 0 ; i < data.geo.length ; i++)
					{
						var item = $("<li data-value='"+data.geo[i].value+"'>"+data.geo[i].label+"</li>");
						item.on("click", function(event)
						{
							event.preventDefault();
							event.stopPropagation();
							$(this).parent().prev().prev("input[type='hidden']").val($(this).data("value"));
							$(this).parent().prev().val($(this).html());
							$(this).parent().remove();
							$("body").off("click.completion-cp-ville");
						});
					    select.append(item);
						result = true;
					}
				}

				if(result == false) select.html("<li>Aucun résultat</li>");
			});
		},
		500);
	}).on("click", "#recherche > div > div > ul > li:not(:first-child)", function()
	{
		$(this).addClass("select").siblings().removeClass("select");
	}).on("click", "#recherche form a.criteres, #recherche #recherche_criteres a.annuler", function()
	{
		if($(this).closest("form").find("a.criteres").find("i.fa-angle-down").length > 0)
		{
			$(this).closest("form").find("a.criteres").html("Moins de critères <i class='far fa-fw fa-angle-up highlight'></i>");
		}
		else
		{
			$(this).closest("form").find("a.criteres").html("Plus de critères <i class='far fa-fw fa-angle-down highlight'></i>");
		}
		$("#recherche_criteres").toggle();
	}).on("submit", "#recherche form", function(event)
	{
		event.stopPropagation();
		event.preventDefault();
		var filtre = "";
		var form = $(this).closest("form"); 
		var intention = form.prev().find("li.select").data("intention");
		var typologie = $(this).find("select[name='typologie']").val();
		var ville = $(this).find("input[name='ville']").val();

		$(this).find("[name^='filtres']").each(function()
		{
			if($(this).is("select") && $(this).val() != "") filtre += (filtre != "" ? "," : "")+$(this).attr("name").replace("filtres[","").replace("]","")+"="+$(this).val();
			if($(this).is("input[type='text']") && $(this).val() != "") filtre += (filtre != "" ? "," : "")+$(this).attr("name").replace("filtres[","").replace("]","")+"="+$(this).val();
			if($(this).is("input[type='checkbox']") && $(this).is(":checked")) filtre += (filtre != "" ? "," : "")+$(this).attr("name").replace("filtres[","").replace("]","")+"="+$(this).val();
		}).promise().done(function()
		{
			var url = "";
			if(form.data("agence") && "" == ville && "" == typologie) url = "./"+form.data("agence")+"/"+(intention == "achat" ? "acheter" : "louer");
			else url = "/recherche"+("" != intention ? "/"+intention : "")+("" != typologie ? "/"+typologie : "/tous-types")+("" != ville ? "/"+ville : "");
			if(filtre != "") url = url+"?filtres="+filtre;
			location = url;
		});

		return false;
	});

	if($(".galerie-photos").length > 0)
	{
		$(".galerie-photos").CJSlider();
	}
	if($(".slider").length > 0)
	{
		$(".slider").CJSlider();
	}

	if($("#contact-map").length > 0)
	{
		
		map = L.map('contact-map', { gestureHandling: true }).setView([48.829677,2.2560898], 16);
		L.tileLayer('https://cartopixel.com:8888/styles/default/{z}/{x}/{y}@2x.png', {
		    attribution: '',
		     maxZoom: 18,
		    format: 'image/png',
			style: 'normal'
		}).addTo(map);

		/*map = L.map('contact-map', { gestureHandling: true }).setView([48.829677,2.2560898], 16);
		L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
		    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
		    maxZoom: 18,
		    id: 'mapbox/streets-v11',
		    tileSize: 512,
		    zoomOffset: -1,
		    accessToken: 'sk.eyJ1IjoiZ2VuY29udGFjdCIsImEiOiJjbDJlc3l6cGgwMnJ0M2lvM293OXcyaW93In0.63hLT6DkVugZfU6jSwoxrA'
		}).addTo(map);*/

		var marker = L.marker([48.829677,2.2560898], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'
		    })
		}).addTo(map);

	}
	/*if($("#annonce-map").length > 0)
	{
		map = L.map('annonce-map', { gestureHandling: true }).setView([48.5256534,2.6828956], 15);
		L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
		    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
		    maxZoom: 18,
		    id: 'mapbox/streets-v11',
		    tileSize: 512,
		    zoomOffset: -1,
		    accessToken: 'sk.eyJ1IjoiZ2VuY29udGFjdCIsImEiOiJjbDJlc3l6cGgwMnJ0M2lvM293OXcyaW93In0.63hLT6DkVugZfU6jSwoxrA'
		}).addTo(map);

		var marker = L.marker([48.5258534,2.6828956], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'
		    })
		}).addTo(map);

	}*/
	// if($("#annonces-map").length > 0)
	// {
	// 	map = L.map('annonces-map', { gestureHandling: true }).setView([48.5256534,2.6828956], 15);
	// 	L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
	// 	    attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
	// 	    maxZoom: 18,
	// 	    id: 'mapbox/streets-v11',
	// 	    tileSize: 512,
	// 	    zoomOffset: -1,
	// 	    accessToken: 'sk.eyJ1IjoiZ2VuY29udGFjdCIsImEiOiJjbDJlc3l6cGgwMnJ0M2lvM293OXcyaW93In0.63hLT6DkVugZfU6jSwoxrA'
	// 	}).addTo(map);

		/*var marker = L.marker([48.5258534,2.6828956], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'+
		              '<span>1 650 €</span>'
		    })
		}).addTo(map);

		marker = L.marker([48.5288534,2.6858956], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'+
		              '<span>1 651 €</span>'
		    })
		}).addTo(map);

		marker = L.marker([48.5228534,2.6838956], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'+
		              '<span>1 652 €</span>'
		    })
		}).addTo(map);

		marker = L.marker([48.5220534,2.6898956], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'+
		              '<span>1 653 €</span>'
		    })
		}).addTo(map);

		marker = L.marker([48.5200534,2.6898956], {
		    icon: new L.DivIcon({
		        className: 'leaflet-icon',
		        html: '<img src="/img/map-marker-icon.png"/>'+
		              '<span>1 654 €</span>'
		    })
		}).addTo(map);*/
	// }

	$(window).on("hashchange",function(){
		setTimeout(function(){
			if(location.hash != "" && location.hash != "#_=_" && $("[data-ancre='"+(location.hash.substring(1))+"']").length > 0) $("html,body").animate({ "scrollTop":$("[data-ancre='"+location.hash.substring(1)+"']").offset().top-($(window).width() <= 860 ? 0 : $("#site > header").height()) }, 1000);
			if(location.hash == "#bienvenue") $("html,body").animate({ "scrollTop":0 });
		},1000);
	}).trigger("hashchange");

	$(document).on("click", "a", function()
	{
		if(typeof dataLayer == 'object')
		{
			if(undefined != $(this).attr("href") && moveBien2 == null)
			{
				var position = "";
				if($(this).closest("#menu").length > 0) position = "menu";
				else if($(this).closest("header").length > 0) position = "header";
				else if($(this).closest("#content").length > 0) position = "content";
				else if($(this).closest("footer").length > 0) position = "footer";
				var btn = $(this).text();
				if($(this).find(".bouton").length == 1) btn = $(this).find(".bouton").text();

				dataLayer.push({
					event: "clickSite",    
					clickName: btn,
					clickPosition: position
				});
				console.log("clickSite: "+btn+" ("+position+")");

				if(position == "menu")
				{
					dataLayer.push({
						event: "mainMenuClickLev1",    
						mainMenuClickElement: btn
					});
					console.log("mainMenuClickLev1: "+btn);
				}
			}
			else if($(this).hasClass("criteres"))
			{
				dataLayer.push({
					event: "searchAdvancedFilters",    
				});
				console.log("searchAdvancedFilters: .criteres");
			}
		}
	}).on("click", "#recherche button", function()
	{
		if(typeof dataLayer == 'object')
		{			
			dataLayer.push({
				event: "searchEngineSearch",  
				searchButtonName: $(this).text(),
				searchEnginePosition: location.href == "https://www.ladresse.com/" ? "homepage" : "agencypage",
				searchNeedType: $("#recherche > div > div > ul > li.select").text(),
				searchCity: $("#recherche input[name='ville']").val(),
				searchPropertyType: $("#recherche select[name='typologie']").val(),
				searchBudget: parseInt($("#recherche input[name='filtres[budget]']").val())
			});
			console.log("searchEngineSearch: "+$(this).text());
		}
	});	

	$(document).on("click", ".bouton.jeu-rugby", function()
	{
		setCookie('jr-start', 1, 60);
	}).on("click", "img[class^='jeu-rugby-trouvaille']", function()
	{
		let trouvailles = getCookie('jr-trouvailles');
		let agence = getCookie('jr-agence');
		if(!trouvailles) trouvailles = [];
		else trouvailles = JSON.parse(trouvailles);
		trouvailles[$(this).attr("class").replace('jeu-rugby-trouvaille','')] = $(this).attr("src").replace("/img/", "").replace("img/", "").replace("obj-", "").replace(".png", "");
		
		setCookie("jr-trouvailles", JSON.stringify(trouvailles), 60);


		var pop = $("<div class='popbox'></div>");
		var title = $("<div class='popbox-title'>Bravo !<i class='fal fa-times'></i></div>");
		var content = $("<div class='popbox-content center'></div>");
		var text = $("<div></div>");
		var img = $(this).clone();
		var itrouvailles = trouvailles.filter(function(element)
		{
		    return element !== null;
		}).length;
		img.removeClass(function(index, className) {
			return (className.match(/\bjeu-rugby-trouvaille\S+/g) || []).join(' ');
		});
		content.append("Bravo ! Vous avez trouvé un objet rugby l'Adresse !<br>");
		content.append(img);
		content.append("<br>"+(itrouvailles == 4 ? "Vous les avez tous trouvé !<br><a href='"+(agence?location.href.replace("/acheter","").replace("/louer","")+"/":"")+"jeu' class='bouton'>Inscrivez-vous maintenant au tirage au sort</a>" : "Il ne vous en reste plus que "+(4-itrouvailles)+" à trouver"));
		if(itrouvailles < 4) content.append("<br><a class='bouton close'>Continuer à chercher</a> <a href='"+(agence?location.href.replace("/acheter","").replace("/louer","")+"/":"")+"jeu' class='bouton'>Voir mes objets trouvés</a>");

		text.append(title);
		text.append(content);

		pop.append(text);

		$("body").append(pop);
		pop.addClass("show");
		pop.on("click", function(event)
		{
			if($(event.target).hasClass("popbox"))
			{
				$(this).addClass("hide");
				setTimeout(function(){ $(".popbox").remove(); }, 500);
			}
		});
		pop.find(".fa-times,.close").on("click", function(event)
		{
			$(event.target).closest(".popbox").addClass("hide");
			setTimeout(function(){ $(".popbox").remove(); }, 500);
		});
	});
});


function getCookie(name)
{
    const cookies = document.cookie.split('; ')
    const value = cookies
        .find(c => c.startsWith(name + "="))
        ?.split('=')[1]
    if (value === undefined) {
        return null
    } 
    return decodeURIComponent(value)
}

function setCookie(name, value, days)
{
    const date = new Date()
    date.setDate(date.getDate() + days)
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${date.toUTCString()}; path=/` 
}

function getTranslateX(myElement)
{
	var style = window.getComputedStyle(myElement);
	var matrix = new WebKitCSSMatrix(style.transform);
	return matrix.m41;
}