
jQuery(document).ready(function($){

var sbd_enable_map_addr_phone_clickable = sld_variables.pd_enable_map_addr_phone_clickable;
var sbd_map_fitbounds = sld_variables.sbd_map_fitbounds;
var disableAutoPan = sld_variables.pd_enable_map_autopan;
if( disableAutoPan != 'off' ){
	disableAutoPan = false;
}else{
	disableAutoPan = true;
}
var sbd_custom_marker_image_width = 30;
if( (sld_variables.sbd_custom_marker_image_width !== 'undefined') && (typeof Number(sld_variables.sbd_custom_marker_image_width) == 'number') ){
	sbd_custom_marker_image_width = Number(sld_variables.sbd_custom_marker_image_width);
	// alert();
}
var sbd_custom_marker_image_height = 30;
if( (sld_variables.sbd_custom_marker_image_height !== 'undefined') && (typeof Number(sld_variables.sbd_custom_marker_image_height) == 'number') ){
	sbd_custom_marker_image_height = Number(sld_variables.sbd_custom_marker_image_height);
}
// console.log('sbd_custom_marker_image_width' );
// console.log(sbd_custom_marker_image_width);


if(localStorage.getItem("qcld_google_undefined_check") != 1 && sld_variables.map_privacy_policies == 'on' ){
	//var google = undefined;
	jQuery('#sbd_all_location').after('<div class="qcld_gdpr_check"> <span>'+sld_variables.qcld_google_check_lang+'</span> <span class="qcld_gdpr_check_click"> '+sld_variables.qcld_google_load_map_lang+' </span></div>');
	jQuery('#sbd_all_location').hide();
}

$(document).on("click",".qcld_gdpr_check_click", function(event){

	localStorage.setItem("qcld_google_undefined_check", 1);
	location.reload(true);
});




// var pd_snazzymap_js = pd_snazzymap_js.pd_snazzymap_js;

	if(cluster.map == 'true' && document.getElementById("sbd_all_location")!==null){

		var geocoder;
		var map;
		var circle;
		var circle = null;
		var markers = [];
		var iw;

		var mapCreate = null;
		var markerClusters;
		var maplatlang;
		var lat = parseInt(sld_variables.latitute);
		var lon = parseInt(sld_variables.longitute);

	  	mapCreate = L.map('sbd_all_location').setView([sld_variables.latitute, sld_variables.longitute], parseInt(sld_variables.zoom));

	  	markerClusters = L.markerClusterGroup(); 



		var minZoomVal = 2; 

		if(cluster.map_fullwidth == 'true'){
			var minZoomVal = 3; 
		}

		if(cluster.map_position == 'right'){
			var minZoomVal = 2; 
		}

	  	L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
			minZoom: minZoomVal,
			maxZoom: 50,
			attribution: '',
			key: 'BC9A493B41014CAABB98F0471D759707'
		}).addTo(mapCreate);

		 //  mapCreate.setZoom(8);
	
		initMapForSBD();
		
		 //  mapCreate.setZoom(20);

		setTimeout(function () {
		   mapCreate.invalidateSize(true);
		}, 1000);

	}

	// Fonction d'initialisation de la carte
	function initMapForSBD() {

	  	myLoopLatLangs(mapCreate);

	}

	function myLoopLatLangs(mapCreate){
		//if( typeof google !== 'undefined' ){
			
			
		jQuery("#sbdopd-list-holder ul li").each(function(){
			var obj = jQuery(this);
		
			var icons = obj.find('.pd-bottom-area').clone();
			icons.find('.pd-map').removeClass('open-mpf-sld-link');
		
			if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
				icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
				icons.find('.pd-map').attr("target", "_blank");
			}
			icons.find('.open-mpf-sld-link').remove();
			icons.find('.pd-map').remove();
			icons = icons.html();
			
			var custom_content = obj.find('.sbd_custom_content').clone();
			custom_content = custom_content.html();
			//others information
			var others_info = '';
			if(obj.attr('data-local')!=''){
				others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
			}
			if(obj.attr('data-phone')!=''){
				if( sbd_enable_map_addr_phone_clickable == 'on' ){
					others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
				}else{
					others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
				}
			}
			if(obj.attr('data-businesshour')!=''){
				others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
			}
		
		
			var imgurl = '';
			if(obj.find('img').length>0){
				imgurl = obj.find('img').attr('src');
			}
			
			var target = '';
			
			if(typeof(obj.find('a').attr('target'))!=='undefined'){
				target = 'target="_blank"';
			}
			if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
				target = 'target="_blank"';
			}

							
			var	maplatlang = '';

			if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
				// i++;

				var locations = obj.attr('data-latlon');
				var latlng = locations.split(',');
				var title = obj.attr('data-title');
				var address = obj.attr('data-address');
				var url;

				if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
					url = obj.find('a').attr('href');
				}else{
					url = obj.attr('data-url');
				}
				
				var subtitle = obj.attr('data-subtitle');
				var markericon = '';
				
				
				if(sld_variables.global_marker!=''){
					markericon = sld_variables.global_marker;
				}
				if( typeof(obj.attr('data-paid')) != 'undefined' && obj.attr('data-paid') !='' ){
					markericon = sld_variables.paid_marker_default; //default paid marker
					if( sld_variables.paid_marker !='' ){
						markericon = sld_variables.paid_marker; // If paid marker is set then override the default
					}
				}

				if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
					markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
				}

				var map_marker_id = jQuery(this).attr('id');
				var icon = markericon;

				maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

				mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

				if( icon != '' ){

					var myIcon = L.icon({
					  iconUrl: icon,
					  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
					  iconAnchor: [25, 50],
					  popupAnchor: [-10, -50],
					});

					var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

				}else{

					var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
				}

				if( sbd_map_fitbounds == 'on' ){
 
					marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
					
				}else{

					marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
				}
				
				markerClusters.clearLayers();
				markers.push(marker);

				var isClicked = false;

				marker.on({
				    mouseover: function(e){

				        for (var i in markers){
				            var markerID = markers[i].options.title;
				            if (markerID == e.target.options.title ){
				            	mapCreate.setView(markers[i]._latlng);
				                markers[i].openPopup();
				        		
				            }else{
				                markers[i].closePopup();
				            };
				        }


				    },
				    
				});


			}


			})


			//mapCreate.addLayer(group);
			//mapCreate.getMinZoom(22);

			if( sbd_map_fitbounds == 'on' ){

				//mapCreate.locate({setView: true, maxZoom: parseInt(sld_variables.zoom) });

				var group = new L.featureGroup(markers);
				mapCreate.fitBounds(group.getBounds(), {minZoom: parseInt(sld_variables.zoom),padding: [0, 0] });

			}else{

				var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
		    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
		    	bounds = new L.LatLngBounds(southWest, northEast);
				mapCreate.fitBounds(bounds, {padding: [50, 50]});
				mapCreate.setZoom(parseInt(sld_variables.zoom));

			}

			// mapCreate.getBoundsZoom(group.getBounds());
			//if( sbd_map_fitbounds != 'on' ){
				//mapCreate.setView(group.getBounds());
			//}

	

	}



	$(document).ready(function(){
		setTimeout(function(){
			jQuery('.qc-grid').packery({
		      itemSelector: '.qc-grid-item',
		      gutter: 10
		    });
		    //console.log('resize');
		}, 3000);
	});

	$(window).resize(function(){
		setTimeout(function(){
			jQuery('.qc-grid').packery({
		      itemSelector: '.qc-grid-item',
		      gutter: 10
		    });
		    //console.log('resize');
		}, 500);
	});


	function infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id) {
	
			
		var html = "<div>";
		
		if(imgurl!='' && !cluster.image_infowindow){
			html += "<div class='sbd_pop_img'><img src='"+imgurl+"' /></div>";
		}
		
      	html += "<div class='sbd_pop_text'><h3>" + title + "</h3><p>" + subtitle + "</p>";
		
		if(address!=''){
			if( sbd_enable_map_addr_phone_clickable == 'on' ){
				 html+="<p><b><i class='fa fa-map-marker fa-map-marker-alt' aria-hidden='true'></i> </b><a href='http://maps.google.com/maps?q=" + encodeURIComponent( address ) + "' target='_blank'>" + address + "</a></p>";
			}else{
				html+="<p><b><i class='fa fa-map-marker fa-map-marker-alt' aria-hidden='true'></i> </b>" + address + "</p>";				
			}
		}
		if(others_info!=''){
			html+=others_info;
		}
		if(custom_content!='' && typeof(custom_content)!='undefined'){
			html+=custom_content;
		}
		
		html +="</div></div>";
		if(url!='' && url.length > 2){
			html +="<a class='sbd_marker_more_detailss' href='" + url + "' "+ target +" data-id='" + map_marker_id + "' >"+sld_variables.view_details+"</a>";
		}else{
			//html +="<a class='sbd_marker_more_details' data-id='" + map_marker_id + "' href='#' >"+sld_variables.view_details+"</a>";
		}
		html +="<div class='sbd_bottom_area_marker'>"+icons+"</div>";	
				
		html+="</div></div>";
				
		return html;


	}


	function SBDselectOpenStreetMarker(id, status){

        for (var i in markers){
            var markerID = markers[i].options.title;
            if (markerID == id && status == "start"){
                markers[i].openPopup();
        		
            }else{
                markers[i].closePopup();
            };
        }
    }
    

   /* $(document).on('mouseover mousemove','.qc-grid-item ul li a:first-of-type',function(){
		if( cluster.map == 'true'  && sld_variables.pd_enable_map_autopan == 'on' ){
			var selectorID = jQuery(this).closest('li').attr('id');
			console.log(selectorID);
			SBDselectOpenStreetMarker(selectorID, 'start');
		}
	});*/

    $(document).on('mouseover mousemove','.qc-grid-item ul li',function(){
		if( cluster.map == 'true' && sld_variables.pd_enable_map_autopan == 'on' ){
			var selectorID = jQuery(this).attr('id');
			SBDselectOpenStreetMarker( selectorID, 'start');
		}
	});

    function SBDOpenStreetRemoveAllMarkers(){

	    for(var i = 0; i < markers.length; i++){
		    mapCreate.removeLayer(markers[i]);
		}

	}
	
	
    $(".pd_search_filter").keyup(function(){
 
        // Retrieve the input field text and reset the count to zero
        var filter = $(this).val(), count = 0;
        
			if(jQuery('#sbd_all_location').length>0){
			  	SBDOpenStreetRemoveAllMarkers();
			}

        // Loop through the comment list
        $("#sbdopd-list-holder ul li").each(function(){

            var dataTitleTxt = $(this).children('a').attr('data-title');
            var dataurl = $(this).find('a').attr('href');
            var datatag = $(this).find('a').attr('data-tag');
			
            if( typeof(dataurl) == 'undefined' ){
                dataurl = "-----";
            }
						if( typeof(datatag) == 'undefined' ){
                datatag = "-----";
            }


            if( typeof(dataTitleTxt) == 'undefined' ){
                dataTitleTxt = "-----";
            }

            var parentH3 = $(this).parentsUntil('.qc-grid-item').children('h3').text();
 
            // If the list item does not contain the text phrase fade it out
            if ($(this).text().search(new RegExp(filter, "i")) < 0 && dataurl.search(new RegExp(filter, "i")) < 0 && dataTitleTxt.search(new RegExp(filter, "i")) < 0 && parentH3.search(new RegExp(filter, "i")) < 0 && datatag.search(new RegExp(filter, "i")) < 0 ) {
                $(this).fadeOut();
				$(this).removeClass("showMe").addClass('hideMe');		
 
            // Show the list item if the phrase matches and increase the count by 1
            }
            else {
                $(this).show();
				$(this).addClass("showMe").removeClass('hideMe');
                count++;
                //if( typeof google !== 'undefined' ){
					if(jQuery('#sbd_all_location').length>0){
						var obj = $(this);

						
						var icons = obj.find('.pd-bottom-area').clone();
						icons.find('.pd-map').removeClass('open-mpf-sld-link');
			
						if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
							icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
							icons.find('.pd-map').attr("target", "_blank");
						}
						icons.find('.open-mpf-sld-link').remove();
						icons.find('.pd-map').remove();
						icons = icons.html();
						
						var custom_content = obj.find('.sbd_custom_content').clone();
						custom_content = custom_content.html();
						//others information
						var others_info = '';
						if(obj.attr('data-local')!=''){
							others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
						}
						if(obj.attr('data-phone')!=''){
							if( sbd_enable_map_addr_phone_clickable == 'on' ){
								others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
							}else{
								others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
							}
						}
						if(obj.attr('data-businesshour')!=''){
							others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
						}
						
						
						var imgurl = '';
						if(obj.find('img').length>0){
							imgurl = obj.find('img').attr('src');
						}
						var target = '';
			
						if(typeof(obj.find('a').attr('target'))!=='undefined'){
							target = 'target="_blank"';
						}
						if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
							target = 'target="_blank"';
						}
						if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined' ){
							
							var locations = obj.attr('data-latlon');
							var latlng = locations.split(',');
							var title = obj.attr('data-title');
							var address = obj.attr('data-address');
							var url;
							if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
								url = obj.find('a').attr('href');
							}else{
								url = obj.attr('data-url');
							}
							var subtitle = obj.attr('data-subtitle');
							var markericon = '';
							if(sld_variables.global_marker!=''){
								markericon = sld_variables.global_marker;
							}
							if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
								markericon = sld_variables.paid_marker_default; //default paid marker
								if(sld_variables.paid_marker!=''){
									markericon = sld_variables.paid_marker; // If paid marker is set then override the default
								}
							}

							if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
								markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
							}
							var map_marker_id = jQuery(this).attr('id');
							var icon = markericon;

							maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

							mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

							if( icon != '' ){

								var myIcon = L.icon({
								  iconUrl: icon,
								  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
								  iconAnchor: [25, 50],
								  popupAnchor: [-10, -50],
								});

								var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

							}else{

								var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
							}


							if( sbd_map_fitbounds == 'on' ){
			 
								marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
								
							}else{

								marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
							}


							markerClusters.clearLayers();
							markers.push(marker);

							var isClicked = false;

							marker.on({
			                    mouseover: function(e) {

			                        for (var i in markers){
			                            var markerID = markers[i].options.title;
			                            if (markerID == e.target.options.title ){
			                            	mapCreate.setView(markers[i]._latlng);
			                                markers[i].openPopup();
			                                
			                            }else{
			                                markers[i].closePopup();
			                            };
			                        }


			                    },
			                    
			                });


						}

						//var group = new L.featureGroup(markers);
						//mapCreate.fitBounds(group.getBounds().pad(0.5));

						if( sbd_map_fitbounds == 'on' ){

							var group = new L.featureGroup(markers);
							mapCreate.fitBounds(group.getBounds());

						}else{

							var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
					    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
					    	bounds = new L.LatLngBounds(southWest, northEast);
							mapCreate.fitBounds(bounds, {padding: [50, 50]});

							mapCreate.setZoom(parseInt(sld_variables.zoom));
						}


					}
				//}
				
            }
        });



		var visibleItems = 0;
		$(".qcpd-single-list-pd, .qc-sbd-single-item-11, .qcpd-single-list-pd-1, .opd-list-pd-style-8, .opd-list-pd-style-9, .pd-container").each(function(){
            
			visibleItems = $(this).find("li.showMe").length;
			
			//console.log(visibleItems);
			
			if(visibleItems==0){
				$(this).hide();
				jQuery(this).parent('.qc-grid-item').addClass('sbd_hide_main_parent');
			}else{
				$(this).show();
				jQuery(this).parent('.qc-grid-item').removeClass('sbd_hide_main_parent');
			}
		});
		if(visibleItems==0){
			// map.setZoom(2);
		}


		
		var invisibleItems = jQuery('.hideMe');
		$('.qc-grid').packery({
          itemSelector: '.qc-grid-item',
          gutter: 10
        });

		if( typeof google !== 'undefined'  && cluster.map == 'true' ){
			/*
			google.maps.event.addListener(map, "click", function(event) {
				
				jQuery('.gm-style-iw').each(function(){
					jQuery(this).next().click();
				})
				
			});
			*/
		}

		jQuery(window).trigger('resize');
 
    });

    $('#live-search').on('submit',function(e){
        e.preventDefault();
    })

    $('#captcha_reload').on('click', function(e){
        e.preventDefault();
        $.post(
            ajaxurl,
            {
                action : 'qcld_pd_change_captcha1',
            },
            function(data){
                var json = $.parseJSON(data);
                $('#pd_captcha_image_register').attr('src', json.url);
				$('#pdccode_register').val(json.code);
            }
        );
    })
	$('#captcha_reload1').on('click', function(e){
        e.preventDefault();
        $.post(
            ajaxurl,
            {
                action : 'qcld_pd_change_captcha1',
            },
            function(data){
				var json = $.parseJSON(data);
                $('#pd_captcha_image').attr('src', json.url);
				$('#pdccode').val(json.code);
            }
        );
    })
	

	
	$('#sbd_full_address').on('focusout', function(e){
		var objc = $(this);
		var geocoder = new google.maps.Geocoder();
		var address = objc.val();

		geocoder.geocode( { 'address': address}, function(results, status) {

		if (status == google.maps.GeocoderStatus.OK) {
			var latitude = results[0].geometry.location.lat();
			var longitude = results[0].geometry.location.lng();
			
			$('#sbd_lat').val(latitude);
			$('#sbd_long').val(longitude);
			
			
		}else{
			console.log('Unable to retrive lat, lng from this address');
		}
		
		}); 
		
	})
	
	$('#sbd_full_address').on('focus', function(e){
		
		var objc = $(this);
		var input = document.getElementById(objc.attr('id'));
		var autocomplete = new google.maps.places.Autocomplete(input);
		var geocoder = new google.maps.Geocoder;
		autocomplete.addListener('place_changed', function() {
          
			var place = autocomplete.getPlace();

			if (!place.place_id) {
			return;
			}

			geocoder.geocode({'placeId': place.place_id}, function(results, status) {

				if (status !== 'OK') {
				  alert('Geocoder failed due to: ' + status);
				  return;
				}
				//console.log(results[0].geometry.location.lat());
				var latitude = results[0].geometry.location.lat();
				var longitude = results[0].geometry.location.lng();
				
				$('#sbd_lat').val(latitude);
				$('#sbd_long').val(longitude);

			})
			
		})
		
	})


jQuery('.sbd_radius_find').on('click',function(){

	jQuery('.qcpd-single-list-pd').removeAttr("style");
	jQuery('.qc-grid-item ul li').removeAttr("style");

	jQuery('#distance_no_result_found').remove();
	if( jQuery('#sbd_all_location').length>0 ){
		if(sld_variables.sbd_combine_distant_tag_live_search == "on"){
			jQuery('.sbd-tag-filter-area.pd_tag_filter-active').removeClass('pd_tag_filter-active').trigger('click');
			var search_filter = jQuery('.pd_search_filter').val();
			if( search_filter != '' ){
				jQuery('.pd_search_filter').trigger('keyup');
			}
		}


		var address = jQuery('.sbd_location_name:visible').val();
		var data_lat = jQuery('.sbd_location_name:visible').attr('data-lat');
		var data_lang = jQuery('.sbd_location_name:visible').attr('data-lon');
		var radiusi = jQuery('.sbd_distance:visible').val();
		
		//console.log(address); // var address = obj.attr('data-address');
		if( address == undefined || address == ''){
			alert(sld_variables.distance_location_text);
			return;
		}
		
		if( radiusi == undefined || radiusi==''){
			alert(sld_variables.distance_value_text);
			return;
		}
		
		if(jQuery('.sdb_distance_cal').val()=='miles'){
			radiusi = radiusi*1.60934;
		}
		

		var radius = parseInt(radiusi, 10)*1000;
		
		//if(jQuery('#sbd_all_location').length>0){
			
			SBDOpenStreetRemoveAllMarkers();
			
		//}
		var counter = 0;
	
		if (data_lat !==null && data_lang !==null  ){
			  
			if (mapCreate.hasLayer(circle)) mapCreate.removeLayer(circle);

			if (circle != undefined) {
		      	mapCreate.removeLayer(circle);
		    }

			circle = L.circle([ data_lat, data_lang ], radius, {
	            color: sld_variables.radius_circle_color,
	            fillColor: sld_variables.radius_circle_color,
	            fillOpacity: 0.35
	        }).addTo(mapCreate);

			
			var list_selector = ".qc-grid-item ul li";
			if(sld_variables.sbd_combine_distant_tag_live_search == "on"){
				if( jQuery('.pdp-holder').is(':visible') ){
					list_selector = ".qc-grid-item ul li";
				}else{
					list_selector = ".qc-grid-item ul li:visible";
				}
			}
			jQuery(list_selector).each(function(){
				
				var obj = jQuery(this);
				
				var icons = obj.find('.pd-bottom-area').clone();
				icons.find('.pd-map').removeClass('open-mpf-sld-link');
			
				if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
					icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
					icons.find('.pd-map').attr("target", "_blank");
				}
				icons.find('.open-mpf-sld-link').remove();
				icons.find('.pd-map').remove();
				icons = icons.html();
				
				var custom_content = obj.find('.sbd_custom_content').clone();
				custom_content = custom_content.html();
				//others information
				var others_info = '';
				if(obj.attr('data-local')!=''){
					others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
				}
				if(obj.attr('data-phone')!=''){
					if( sbd_enable_map_addr_phone_clickable == 'on' ){
						others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
					}else{
						others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
					}
				}
				if(obj.attr('data-businesshour')!=''){
					others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
				}
				
				
				var imgurl = '';
				if(obj.find('img').length>0){
					imgurl = obj.find('img').attr('src');
				}
				var target = '';
			
				if(typeof(obj.find('a').attr('target'))!=='undefined'){
					target = 'target="_blank"';
				}
				if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
							target = 'target="_blank"';
						}
				if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
					i++;
					
					var locations = obj.attr('data-latlon');
					var latlng = locations.split(',');
					var title = obj.attr('data-title');
					var address = obj.attr('data-address');
					var url;
					if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
						url = obj.find('a').attr('href');
					}else{
						url = obj.attr('data-url');
					}
					var subtitle = obj.attr('data-subtitle');
					var markericon = '';
					if(sld_variables.global_marker!=''){
						markericon = sld_variables.global_marker;
					}
					if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
						markericon = sld_variables.paid_marker_default; //default paid marker
						if(sld_variables.paid_marker!=''){
							markericon = sld_variables.paid_marker; // If paid marker is set then override the default
						}
					}

					if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
						markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
					}

    				let circleCenter = circle.getLatLng();

					var map_marker_id = jQuery(this).attr('id');
					var icon = markericon;

					maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

					//mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

					mapCreate.setView([ data_lat, data_lang], mapCreate.getZoom());

					if( icon != '' ){

						var myIcon = L.icon({
						  iconUrl: icon,
						  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
						  iconAnchor: [25, 50],
						  popupAnchor: [-10, -50],
						});

						var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

					}else{

						var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
					}
					
					let markerPos = marker.getLatLng();

					if ( circleCenter.distanceTo(markerPos) < circle.getRadius() ) {

						if( sbd_map_fitbounds == 'on' ){
		 
							marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
							
						}else{

							marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();

						}

						markerClusters.clearLayers();
						markers.push(marker);

						var isClicked = false;

						marker.on({
						    mouseover: function(e) {

						        for (var i in markers){
						            var markerID = markers[i].options.title;
						            if (markerID == e.target.options.title ){
						            	mapCreate.setView(markers[i]._latlng);
						                markers[i].openPopup();
						        		
						            }else{
						                markers[i].closePopup();
						            };
						        }


						    },
						    
						});

						var group = new L.featureGroup(markers);
						mapCreate.fitBounds(group.getBounds().pad(0.5));



						mapCreate.setView(circleCenter);
						
						obj.removeClass("showMe");
						obj.show();
						obj.addClass("showMe");
						
					}else{
						obj.fadeOut();
						obj.hide();
						obj.removeClass("showMe");	
					}
					

					
				}else{
					obj.fadeOut();
					obj.hide();
					obj.removeClass("showMe");	
				}
				
			});
			
			if(cluster.pagination=='true'){
				jQuery('.pdp-holder').hide();
			}
			
			//map.fitBounds(circle.getBounds());
			setTimeout(function(){
				var visibleItems = 0;
				var totalvisibleitem = 0;
				jQuery(".qcpd-single-list-pd, .qcpd-single-list-pd-1, .opd-list-pd-style-8, .opd-list-pd-style-9, .pd-container, .qc-sbd-single-item-11, .qc-sld-masonary-15").each(function(){
					
					visibleItems = jQuery(this).find("li.showMe").length;
					totalvisibleitem += jQuery(this).find("li.showMe").length;
					
					//console.log(visibleItems);
					
					if(visibleItems==0){
						jQuery(this).hide();
						
					}else{
						jQuery(this).show();
					}
				});
				

				setTimeout(function(){
					jQuery('.qc-grid').packery({
					  itemSelector: '.qc-grid-item',
					  gutter: 10
					});
					setTimeout(function(){
						if(totalvisibleitem==0){
							// alert(sld_variables.distance_no_result_text);
							jQuery('#sbdopd-list-holder').append('<h2 id="distance_no_result_found">'+sld_variables.distance_no_result_text+'</h2>');
						}
					},500)
					
				},1000)
			},1000)
			
			
		  } else {
			console.log('Geocode was not successful for the following reason: ' + status);
			counter++;
			
		  }

		// });
		
	}	
	
	return;
})


jQuery('.sbd_radius_clear').on('click', function(){
	if( jQuery('#sbd_all_location').length>0 ){

		var obj = jQuery(this);
		jQuery('.qcld_pd_tabcontent:visible .sbd_location_name').val('');
		jQuery('.qcld_pd_tabcontent:visible .sbd_distance').val('');

		if (circle != undefined) {
	      mapCreate.removeLayer(circle);
	    }

		//if (circle) circle.setMap(null);
		jQuery(".qcpd-single-list-pd, .qcpd-single-list-pd-1, .opd-list-pd-style-8, .opd-list-pd-style-9, .pd-container").each(function(){
			
			jQuery(this).show();
			
		});
		
		jQuery(".qcld_pd_tabcontent:visible .qc-grid-item ul li").each(function(){
			
			jQuery(this).show();
			
		})
		
		// if (mapCreate.hasLayer(circle)) mapCreate.removeLayer(circle);
		
		clearmarker();
		myLoop();
		setTimeout(function(){
			jQuery('.qc-grid').packery({
			  itemSelector: '.qc-grid-item',
			  gutter: 10
			});
		},1000)
	}
});

function clearmarker(){

    for(var i = 0; i < markers.length; i++){
	    mapCreate.removeLayer(markers[i]);
	}

}

var i = 0;                     

function myLoop () {

		jQuery("#sbdopd-list-holder ul li").each(function(){
			var obj = jQuery(this);
			
			obj.addClass("showMe").removeClass('hideMe');
			obj.show();

			var icons = obj.find('.pd-bottom-area').clone();
			icons.find('.pd-map').removeClass('open-mpf-sld-link');
			
			if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
				icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
				icons.find('.pd-map').attr("target", "_blank");
			}
			
			
			icons.find('.open-mpf-sld-link').remove();
			icons.find('.pd-map').remove();
			icons = icons.html();
			
			var custom_content = obj.find('.sbd_custom_content').clone();
			custom_content = custom_content.html();
			//others information
			var others_info = '';
			if(obj.attr('data-local')!=''){
				others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
			}
			if(obj.attr('data-phone')!=''){
				if( sbd_enable_map_addr_phone_clickable == 'on' ){
					others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
				}else{
					others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
				}
			}
			if(obj.attr('data-businesshour')!=''){
				others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
			}
			
			
			var imgurl = '';
			if(obj.find('img').length>0){
				imgurl = obj.find('img').attr('src');
			}
			
			var target = '';
			
			if(typeof(obj.find('a').attr('target'))!=='undefined'){
				target = 'target="_blank"';
			}
			if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
				target = 'target="_blank"';
			}
			
			if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
				i++;
				
				var locations = obj.attr('data-latlon');
				var latlng = locations.split(',');
				var title = obj.attr('data-title');
				var address = obj.attr('data-address');
				var url;
				if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
					url = obj.find('a').attr('href');
				}else{
					url = obj.attr('data-url');
				}
				
				var subtitle = obj.attr('data-subtitle');
				var markericon = '';
				
				if(sld_variables.global_marker!=''){
					markericon = sld_variables.global_marker;
				}
				if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
					markericon = sld_variables.paid_marker_default; //default paid marker
					if(sld_variables.paid_marker!=''){
						markericon = sld_variables.paid_marker; // If paid marker is set then override the default
					}
				}

				if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
					markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
				}

				var map_marker_id = jQuery(this).attr('id');
				var icon = markericon;
					
				maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

				mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

				if( icon != '' ){

					var myIcon = L.icon({
					  iconUrl: icon,
					  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
					  iconAnchor: [25, 50],
					  popupAnchor: [-10, -50],
					});

					var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

				}else{

					var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
				}

				if( sbd_map_fitbounds == 'on' ){
 
					marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
					
				}else{

					marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
				}

				markerClusters.clearLayers();
				markers.push(marker);

				var isClicked = false;

				marker.on({
				    mouseover: function(e) {

				        for (var i in markers){
				            var markerID = markers[i].options.title;
				            if (markerID == e.target.options.title ){
				            	mapCreate.setView(markers[i]._latlng);
				                markers[i].openPopup();
				        		
				            }else{
				                markers[i].closePopup();
				            };
				        }


				    },
				    
				});

				/*var group = new L.featureGroup(markers);
				mapCreate.fitBounds(group.getBounds().pad(0.5));
				if( sbd_map_fitbounds != 'on' ){
					mapCreate.setZoom(parseInt(sld_variables.zoom));
				}	*/		



				if( sbd_map_fitbounds == 'on' ){

					var group = new L.featureGroup(markers);
					mapCreate.fitBounds(group.getBounds());

				}else{

					var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
			    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
			    	bounds = new L.LatLngBounds(southWest, northEast);
					mapCreate.fitBounds(bounds, {padding: [50, 50]});

					mapCreate.setZoom(parseInt(sld_variables.zoom));
				}




				
			}
			
		})

		
}


//Filter Directory Lists
$(document).on("click",".sbd-filter-area a", function(event){

	var sbd_mode='';
	//markers = [];
	if( jQuery(this).parent('.sbd-filter-area').parent().hasClass('qcld_pd_tabcontent') ){
		sbd_mode='categoryTab';
		return false;
	}

	if($('.pd_tag_filter').length>0){
		if( $('.pd_tag_filter:not(:first)').hasClass('pd_tag_filter-active') ){
			$('.pd_tag_filter:first-of-type').addClass('pd_tag_filter-active').click();
		}else{
			$('.pd_tag_filter:first-of-type').removeClass('pd_tag_filter-active').click();
		}
	}
	
		if($('.sbd_tag_filter_select').length > 0){
			$('.sbd_tag_filter_select').val('').change();
		}

    event.preventDefault();
    //if( typeof google !== 'undefined' ){
		if(jQuery('#sbd_all_location').length>0){
			
			SBDOpenStreetRemoveAllMarkers();
		}
	//}
    var filterName = $(this).attr("data-filter");

    $(".sbd-filter-area a").removeClass("filter-active");
    $(this).addClass("filter-active");

    if( filterName == "all" )
    {
        $("#sbdopd-list-holder .qc-grid-item").css("display", "block");
		if(jQuery('#sbd_all_location').length>0){
			myLoop();
		}
    }
    else
    {

        $("#sbdopd-list-holder .qc-grid-item").css("display", "none");
        $("#sbdopd-list-holder .qc-grid-item."+filterName+"").css("display", "block");
		if(jQuery('#sbd_all_location').length>0){
			// jQuery("#sbdopd-list-holder ."+filterName+" ul li").each(function(){ remove this to display only visible items on map after tag filter trigger
			jQuery("#sbdopd-list-holder ."+filterName+" ul li:visible").each(function(){
				var obj = jQuery(this);
				
				var icons = obj.find('.pd-bottom-area').clone();
				icons.find('.pd-map').removeClass('open-mpf-sld-link');
				
				//if( typeof google !== 'undefined' ){
					if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
					icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
					icons.find('.pd-map').attr("target", "_blank");
					}
					icons.find('.open-mpf-sld-link').remove();
					icons.find('.pd-map').remove();
					icons = icons.html();
					
					var custom_content = obj.find('.sbd_custom_content').clone();
					custom_content = custom_content.html();
					//others information
					var others_info = '';
					if(obj.attr('data-local')!=''){
						others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
					}
					if(obj.attr('data-phone')!=''){
						if( sbd_enable_map_addr_phone_clickable == 'on' ){
							others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
						}else{
							others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
						}
					}
					if(obj.attr('data-businesshour')!=''){
						others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
					}
					
					var imgurl = '';
					if(obj.find('img').length>0){
						imgurl = obj.find('img').attr('src');
					}
					
					var target = '';
		
					if(typeof(obj.find('a').attr('target'))!=='undefined'){
						target = 'target="_blank"';
					}
					if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
						target = 'target="_blank"';
					}
					
					if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
						var locations = obj.attr('data-latlon');
						var latlng = locations.split(',');
						var title = obj.attr('data-title');
						var address = obj.attr('data-address');
						var url;
						if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
							url = obj.find('a').attr('href');
						}else{
							url = obj.attr('data-url');
						}
						var subtitle = obj.attr('data-subtitle');
						var markericon = '';
						if(sld_variables.global_marker!=''){
							markericon = sld_variables.global_marker;
						}
						if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
							markericon = sld_variables.paid_marker_default; //default paid marker
							if(sld_variables.paid_marker!=''){
								markericon = sld_variables.paid_marker; // If paid marker is set then override the default
							}
						}

						if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
							markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
						}
						var map_marker_id = jQuery(this).attr('id');
						var icon = markericon;

						maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

						mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

						if( icon != '' ){

							var myIcon = L.icon({
							  iconUrl: icon,
							  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
							  iconAnchor: [25, 50],
							  popupAnchor: [-10, -50],
							});

							var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

						}else{

							var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
						}
						
						let markerPos = marker.getLatLng();

							if( sbd_map_fitbounds == 'on' ){
			 
								marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
								
							}else{

								marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();

							}

						markerClusters.clearLayers();
						markers.push(marker);

						var isClicked = false;

						marker.on({
						    mouseover: function(e) {

						        for (var i in markers){
						            var markerID = markers[i].options.title;
						            if (markerID == e.target.options.title ){
						            	mapCreate.setView(markers[i]._latlng);
						                markers[i].openPopup();
						        		
						            }else{
						                markers[i].closePopup();
						            };
						        }


						    },
						    
						});

						/*
						var group = new L.featureGroup(markers);
						mapCreate.fitBounds(group.getBounds().pad(0.5));
						if( sbd_map_fitbounds != 'on' ){
							mapCreate.setZoom(parseInt(sld_variables.zoom));
						}
						*/



						if( sbd_map_fitbounds == 'on' ){

							var group = new L.featureGroup(markers);
							mapCreate.fitBounds(group.getBounds());

						}else{

							var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
					    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
					    	bounds = new L.LatLngBounds(southWest, northEast);
							mapCreate.fitBounds(bounds, {padding: [50, 50]});

							mapCreate.setZoom(parseInt(sld_variables.zoom));
						}



						
					}
				//}
				
			})
		}
    }

    $('.qc-grid').packery({
      itemSelector: '.qc-grid-item',
      gutter: 10
    });
	if($('.qcld_pd_tab').length<1){
		/*if( typeof google !== 'undefined' && cluster.map == 'true' ){
			google.maps.event.addListener(map, "click", function(event) {
				
				jQuery('.gm-style-iw').each(function(){
					jQuery(this).next().click();
				})
				
			});
		}*/
	}
	

});


	$(document).on("change",".sbd-filter-area-select-desktop select,.sbd-filter-area-select-mobile select",function(){
		var value = jQuery(this).val();
		if( value != 'all' ){
			value = "opd-list-id-"+value;
		}
		console.log(value);
		jQuery('.sbd-filter-area a[data-filter="'+value+'"]').trigger('click');
	});

		var filter = [];

	$(document).on("click",".sbd-tag-filter-area a", function(event){
		
		event.preventDefault();


		var combined_search = 0;
		if(sld_variables.sbd_combine_distant_tag_live_search == "on"){
			var location_name = jQuery('#sbd_location_name').val();
			var distance = jQuery('.sbd_distance').val();
			if( location_name != '' && distance != '' && event.type == 'click' ){
				combined_search = 1;
			}
		}
		
		var mapIDselector = 'sbd_all_location';
        var sbd_mode='';
		if( jQuery(this).parent('.sbd-tag-filter-area').parent().hasClass('qcld_pd_tabcontent') ){
			var mapIDselector = jQuery('.sbd_map:visible').attr('id');
			sbd_mode='categoryTab';
			return;

		}
		

        $(this).toggleClass("pd_tag_filter-active");
		
		// Retrieve the input field text and reset the count to zero
        //var filter = $(this).attr('data-tag'), count = 0;

        var currently_tag = $(this).attr('data-tag');
		if( !currently_tag && $(this).hasClass('pd_tag_filter-active') ){
			currently_tag = 'all';
			filter = [];
		}
		// console.log(currently_tag);

		var inclusive_tag_filter = sld_variables.inclusive_tag_filter;
		// var inclusive_tag_filter = 'off';

		if( inclusive_tag_filter == 'on' && currently_tag == 'all' ){
			jQuery(this).siblings('.pd_tag_filter').removeClass('pd_tag_filter-active');
		}

        if( sbd_mode == 'categoryTab' ){
	        filter = [];
	        jQuery('.sbd-tag-filter-area:visible .pd_tag_filter-active').each(function(){
        		var current_tag = $(this).attr('data-tag');
        		filter.push(current_tag);
	        });

	        var count = 0;
	        var search_term = new RegExp(filter.join('|'), "i");
        }else{    	
	        var current_tag = $(this).attr('data-tag');
	        if($(this).hasClass('pd_tag_filter-active')){
	        	filter.push(current_tag);
			}else{
				var index = filter.indexOf(current_tag);
			    if (index > -1) {
			       filter.splice(index, 1);
			    }
			}
	        var count = 0;

	        //Deselct "All" when clicked on any other tag
	        if( current_tag ){
	        	filter = filter.filter(function(item, pos) {
				    return item;
				});
				jQuery(this).siblings().eq(0).removeClass('pd_tag_filter-active');
	        }

	        //Remove Duplicate Element from the Array
	        if( filter.length > 0 ){
		        filter = filter.filter(function(item, pos) {
				    return filter.indexOf(item) == pos;
				});
	        }

	        if( inclusive_tag_filter == 'on' ){
	        	var search_term = new RegExp(filter.join('|'), "ig");
	        }else{
	        	var search_term = new RegExp(filter.join('|'), "i");
	        }
	  		//   search_term = search_term.filter(function (el) {
			//   return el != null;
			// });
        }

        if( inclusive_tag_filter == 'on' && currently_tag != 'all' && filter.length > 0 ){
			
			for (var i = 0; i <= filter.length; i++) {
				if( filter[i] && filter[i] != '' ){
					jQuery('.pd_tag_filter[data-tag="'+filter[i]+'"]').addClass('pd_tag_filter-active');
				}
				// console.log('tag ');
				// console.log(jQuery('.pd_tag_filter[data-tag='+filter[i]+']').text());
			}
		}
         // console.log(filter);
         // console.log(filter.length);
         // console.log('search_term');
         // console.log(search_term);

        if( cluster.map=='true' ){
			if(jQuery('#'+mapIDselector).length>0 && combined_search == 0){
				SBDOpenStreetRemoveAllMarkers();
			}
		}
        // Loop through the comment list
        var loopedItemSeclector = "#sbdopd-list-holder ul li";
        if( sbd_mode == 'categoryTab' ){
        	loopedItemSeclector = ".qcld_pd_tabcontent:visible .qc-grid ul li";
        	if( $(loopedItemSeclector).length == 0 ){
        		loopedItemSeclector = ".qcld_pd_tabcontent:visible .qcpd-list-hoder ul li";
        	}
        }
        $(loopedItemSeclector).each(function(){

            var dataTitleTxt = $(this).find('a').attr('data-tag');

            if( typeof(dataTitleTxt) == 'undefined' ){
                dataTitleTxt = "-----";
            }

            // Check inclusive Tag Filter
 			if( inclusive_tag_filter == 'on' && currently_tag != 'all' ){

 				// var checked_array = dataTitleTxt.match(search_term);
 				var main_array = dataTitleTxt.split(',');
 				var match_array = qcsbd_CheckArray(main_array, filter);
 				// If the list item does not contain the text phrase fade it out
	            if ( match_array ) {
	    //         	console.log('=================');
 				// console.log(match_array);
 				// console.log(main_array);
 				// console.log(checked_array);
	 				$(this).show();
					$(this).addClass("showMe");

					var filterButton = $('.sbd-filter-area').find('.filter-active:not([data-filter="all"])');
					if( sbd_mode == 'categoryTab' ){
						filterButton = $('qcld_pd_tabcontent:visible').find('.sbd-filter-area').find('.filter-active:not([data-filter="all"])');
					}
					if( filterButton.length ){
						if($(this).parents('.qc-grid-item').is(':hidden')){
							return;
						}
					}
	                count++;
	               // if( typeof google !== 'undefined' ){
						if(jQuery('#'+mapIDselector).length>0 && combined_search == 0){
							var obj = $(this);
							
							var icons = obj.find('.pd-bottom-area').clone();
							icons.find('.pd-map').removeClass('open-mpf-sld-link');
				
							if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
								icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
								icons.find('.pd-map').attr("target", "_blank");
							}
							icons.find('.open-mpf-sld-link').remove();
							icons.find('.pd-map').remove();
							icons = icons.html();
							
							var custom_content = obj.find('.sbd_custom_content').clone();
							custom_content = custom_content.html();
							//others information
							var others_info = '';
							if(obj.attr('data-local')!=''){
								others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
							}
							if(obj.attr('data-phone')!=''){
								if( sbd_enable_map_addr_phone_clickable == 'on' ){
									others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
								}else{
									others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
								}
							}
							if(obj.attr('data-businesshour')!=''){
								others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
							}
							
							var imgurl = '';
							if(obj.find('img').length>0){
								imgurl = obj.find('img').attr('src');
							}
							var target = '';
				
							if(typeof(obj.find('a').attr('target'))!=='undefined'){
								target = 'target="_blank"';
							}
							if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
								target = 'target="_blank"';
							}
							
							if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
								
								var locations = obj.attr('data-latlon');
								var latlng = locations.split(',');
								var title = obj.attr('data-title');
								var address = obj.attr('data-address');
								var url;
								if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
									url = obj.find('a').attr('href');
								}else{
									url = obj.attr('data-url');
								}
								var subtitle = obj.attr('data-subtitle');
								var markericon = '';
								if(sld_variables.global_marker!=''){
									markericon = sld_variables.global_marker;
								}
								if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
									markericon = sld_variables.paid_marker_default; //default paid marker
									if(sld_variables.paid_marker!=''){
										markericon = sld_variables.paid_marker; // If paid marker is set then override the default
									}
								}

								if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
									markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
								}
								var map_marker_id = jQuery(this).attr('id');
								var icon = markericon;

								maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

								mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

								if( icon != '' ){

									var myIcon = L.icon({
									  iconUrl: icon,
									  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
									  iconAnchor: [25, 50],
									  popupAnchor: [-10, -50],
									});

									var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

								}else{

									var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
								}
								
								let markerPos = marker.getLatLng();

									if( sbd_map_fitbounds == 'on' ){
					 
										marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
										
									}else{

										marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();

									}

								markerClusters.clearLayers();
								markers.push(marker);



								var isClicked = false;

								marker.on({
								    mouseover: function(e) {

								        for (var i in markers){
								            var markerID = markers[i].options.title;
								            if (markerID == e.target.options.title ){
								            	mapCreate.setView(markers[i]._latlng);
								                markers[i].openPopup();
								        		
								            }else{
								                markers[i].closePopup();
								            };
								        }

								    },
								    
								});

								/*var group = new L.featureGroup(markers);
								mapCreate.fitBounds(group.getBounds().pad(0.5));
								if( sbd_map_fitbounds != 'on' ){
									mapCreate.setZoom(parseInt(sld_variables.zoom));
								}*/



								if( sbd_map_fitbounds == 'on' ){

									var group = new L.featureGroup(markers);
									mapCreate.fitBounds(group.getBounds());

								}else{

									var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
							    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
							    	bounds = new L.LatLngBounds(southWest, northEast);
									mapCreate.fitBounds(bounds, {padding: [50, 50]});

									mapCreate.setZoom(parseInt(sld_variables.zoom));
								}




							}
						}
					//}
	            // Show the list item if the phrase matches and increase the count by 1
	            }
	            else {
					$(this).fadeOut();
					$(this).removeClass("showMe");		
					
	            }
 			}

 			if( inclusive_tag_filter != 'on' || currently_tag == 'all' ){
 				// If the list item does not contain the text phrase fade it out
	            if ( dataTitleTxt.search( search_term ) < 0 ) {
	                $(this).fadeOut();
					$(this).removeClass("showMe");		
	 
	            // Show the list item if the phrase matches and increase the count by 1
	            }
	            else {
	                $(this).show();
					$(this).addClass("showMe");

					var filterButton = $('.sbd-filter-area').find('.filter-active:not([data-filter="all"])');
					if( sbd_mode == 'categoryTab' ){
						filterButton = $('qcld_pd_tabcontent:visible').find('.sbd-filter-area').find('.filter-active:not([data-filter="all"])');
					}
					if( filterButton.length ){
						if($(this).parents('.qc-grid-item').is(':hidden')){
							return;
						}
					}
	                count++;
					if(jQuery('#'+mapIDselector).length>0 && combined_search == 0){
						var obj = $(this);
						
						var icons = obj.find('.pd-bottom-area').clone();
						icons.find('.pd-map').removeClass('open-mpf-sld-link');
						
						if( typeof google !== 'undefined' ){	
							if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
								icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
								icons.find('.pd-map').attr("target", "_blank");
							}
							icons.find('.open-mpf-sld-link').remove();
							icons.find('.pd-map').remove();
							icons = icons.html();
							
							var custom_content = obj.find('.sbd_custom_content').clone();
							custom_content = custom_content.html();
							//others information
							var others_info = '';
							if(obj.attr('data-local')!=''){
								others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
							}
							if(obj.attr('data-phone')!=''){
								if( sbd_enable_map_addr_phone_clickable == 'on' ){
									others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
								}else{
									others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
								}
							}
							if(obj.attr('data-businesshour')!=''){
								others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
							}
							
							var imgurl = '';
							if(obj.find('img').length>0){
								imgurl = obj.find('img').attr('src');
							}
							var target = '';
				
							if(typeof(obj.find('a').attr('target'))!=='undefined'){
								target = 'target="_blank"';
							}
							if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
								target = 'target="_blank"';
							}
							
							if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
								
								var locations = obj.attr('data-latlon');
								var latlng = locations.split(',');
								var title = obj.attr('data-title');
								var address = obj.attr('data-address');
								var url;
								if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
									url = obj.find('a').attr('href');
								}else{
									url = obj.attr('data-url');
								}
								var subtitle = obj.attr('data-subtitle');
								var markericon = '';
								if(sld_variables.global_marker!=''){
									markericon = sld_variables.global_marker;
								}
								if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
									markericon = sld_variables.paid_marker_default; //default paid marker
									if(sld_variables.paid_marker!=''){
										markericon = sld_variables.paid_marker; // If paid marker is set then override the default
									}
								}

								if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
									markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
								}
								var map_marker_id = jQuery(this).attr('id');
								var icon = markericon;

								maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

								mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

								if( icon != '' ){

									var myIcon = L.icon({
									  iconUrl: icon,
									  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
									  iconAnchor: [25, 50],
									  popupAnchor: [-10, -50],
									});

									var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

								}else{

									var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
								}
								
								let markerPos = marker.getLatLng();

									if( sbd_map_fitbounds == 'on' ){
					 
										marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
										
									}else{

										marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();

									}

								markerClusters.clearLayers();
								markers.push(marker);


								var isClicked = false;

								marker.on({
								    mouseover: function(e) {

								        for (var i in markers){
								            var markerID = markers[i].options.title;
								            if (markerID == e.target.options.title ){
								            	mapCreate.setView(markers[i]._latlng);
								                markers[i].openPopup();
								        		
								            }else{
								                markers[i].closePopup();
								            };
								        }


								    },
								    
								});

								/*var group = new L.featureGroup(markers);
								mapCreate.fitBounds(group.getBounds().pad(0.5));
								if( sbd_map_fitbounds != 'on' ){
									mapCreate.setZoom(parseInt(sld_variables.zoom));
								}*/



								if( sbd_map_fitbounds == 'on' ){

									var group = new L.featureGroup(markers);
									mapCreate.fitBounds(group.getBounds());

								}else{

									var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
							    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
							    	bounds = new L.LatLngBounds(southWest, northEast);
									mapCreate.fitBounds(bounds, {padding: [50, 50]});

									mapCreate.setZoom(parseInt(sld_variables.zoom));
								}




							}
						}
					}
					
	            }
 			}
        });

		var singleItemSelector = $(".qcpd-single-list-pd, .qc-sbd-single-item-11, .qcpd-single-list-pd-1, .opd-list-pd-style-8, .opd-list-pd-style-9, .pd-container");
		if( sbd_mode == 'categoryTab' ){
			singleItemSelector = $('.qcld_pd_tabcontent:visible').find(".qcpd-single-list-pd, .qcpd-single-list-pd-1, .opd-list-pd-style-8, .opd-list-pd-style-9, .pd-container");
		}
		singleItemSelector.each(function(){
            //if( $(this).is(':visible') ){ // add this condition to display result from only visible list
				var visibleItems = $(this).find("li.showMe").length;
				
				//console.log(visibleItems);
				
				if(visibleItems==0){
					$(this).hide();
				}else{
					$(this).show();
				}
            //}
		});

		
		setTimeout(function(e){
			$grid = $('.qc-grid');
			$grid.packery('destroy').packery({
			  itemSelector: '.qc-grid-item',
			  gutter: 10
			});
		},1000);
		
		$grid = $('.qc-grid');
		$grid.packery('destroy').packery({
		  itemSelector: '.qc-grid-item',
		  gutter: 10
		});

		/*if( typeof google !== 'undefined' ){
			if( typeof map !== 'undefined' ){
				google.maps.event.addListener(map, "click", function(event) {
					
					jQuery('.gm-style-iw').each(function(){
						jQuery(this).next().click();
					})
					
				});
			}
		}*/
		

		if( combined_search == 1 ){
			setTimeout(function(){
				sbdradius_();
			}, 500)
		}
	});


//tag filter dropdown
$(document).on("change",".sbd_tag_filter_select", function(event){
	
	event.preventDefault();

	if(cluster.pagination=='true'){

			jQuery('.pdp-holder').show();
			jQuery(".qc-grid-item ul").each(function(){
				$("#"+jQuery(this).attr('id').replace("list", "holder")).jPages("destroy");
					
			})
		}

	var tag_select_box = jQuery(this);
	
	// Retrieve the input field text and reset the count to zero
    var filter = this.value, count = 0;

    var map_selector = 'sbd_all_location';
	if( tag_select_box.parents('.sbd_tag_filter_dropdown').parent().hasClass('qcld_pd_tabcontent') ){
		map_selector = tag_select_box.parents('.sbd_tag_filter_dropdown').siblings('.sbd_map').attr('id');
	}
	
	if(jQuery('#'+map_selector).length>0){
		

		SBDOpenStreetRemoveAllMarkers();

	}
	
		// Loop through the comment list
		$("#sbdopd-list-holder ul li").each(function(){
		
			var dataTitleTxt = $(this).find('a').attr('data-tag');

			if( typeof(dataTitleTxt) == 'undefined' ){
				dataTitleTxt = "-----";
			}

 
			// If the list item does not contain the text phrase fade it out
			if ( dataTitleTxt.search(new RegExp(filter, "i")) < 0 ) {
				$(this).fadeOut();
				$(this).removeClass("showMe");		
 
			// Show the list item if the phrase matches and increase the count by 1
			}
			else {
				$(this).show();
				$(this).addClass("showMe");
				count++;

				map_selector = 'sbd_all_location';
				if( tag_select_box.parents('.sbd_tag_filter_dropdown').parent().hasClass('qcld_pd_tabcontent') ){
					map_selector = tag_select_box.parents('.sbd_tag_filter_dropdown').siblings('.sbd_map').attr('id');
				}
				//if( typeof google !== 'undefined' ){
					//console.log('map_selector '+map_selector);
					if(jQuery('#'+map_selector).length>0){
						var obj = $(this);
						if( obj.hasClass('showMe') && obj.parent().parent().parent().is(':visible') ){
							
							var icons = obj.find('.pd-bottom-area').clone();
							icons.find('.pd-map').removeClass('open-mpf-sld-link');
				
							if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
								icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(obj.attr('data-address'))+"");
								icons.find('.pd-map').attr("target", "_blank");
							}
							icons.find('.open-mpf-sld-link').remove();
							icons.find('.pd-map').remove();
							icons = icons.html();
							
							var custom_content = obj.find('.sbd_custom_content').clone();
							custom_content = custom_content.html();
							//others information
							var others_info = '';
							if(obj.attr('data-local')!=''){
								others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+obj.attr('data-local')+"</p>";
							}
							if(obj.attr('data-phone')!=''){
								if( sbd_enable_map_addr_phone_clickable == 'on' ){
									others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+obj.attr('data-phone')+"'>"+obj.attr('data-phone')+"</a></p>";
								}else{
									others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+obj.attr('data-phone')+"</p>";
								}
							}
							if(obj.attr('data-businesshour')!=''){
								others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+obj.attr('data-businesshour')+"</p>";
							}
							
							var imgurl = '';
							if(obj.find('img').length>0){
								imgurl = obj.find('img').attr('src');
							}
							var target = '';
				
							if(typeof(obj.find('a').attr('target'))!=='undefined'){
								target = 'target="_blank"';
							}
							if(typeof(obj.find('a').attr('data-newtab'))!=='undefined'){
								target = 'target="_blank"';
							}
							
							if(obj.attr('data-latlon')!=='' && typeof(obj.attr('data-latlon'))!=='undefined'){
								
								var locations = obj.attr('data-latlon');
								var latlng = locations.split(',');
								var title = obj.attr('data-title');
								var address = obj.attr('data-address');
								var url;
								if(typeof(obj.find('a').attr('href'))!=='undefined' && obj.find('a').is('a:not([href^="#"])') && obj.find('a').is('a:not([href^="tel"])')){
									url = obj.find('a').attr('href');
								}else{
									url = obj.attr('data-url');
								}
								var subtitle = obj.attr('data-subtitle');
								var markericon = '';
								if(sld_variables.global_marker!=''){
									markericon = sld_variables.global_marker;
								}
								if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
									markericon = sld_variables.paid_marker_default; //default paid marker
									if(sld_variables.paid_marker!=''){
										markericon = sld_variables.paid_marker; // If paid marker is set then override the default
									}
								}

								if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
									markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
								}
								var map_marker_id = jQuery(this).attr('id');
								var icon = markericon;

								maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

								mapCreate.panTo(new L.LatLng(sld_variables.latitute, sld_variables.longitute), parseInt(sld_variables.zoom));

								if( icon != '' ){

									var myIcon = L.icon({
									  iconUrl: icon,
									  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
									  iconAnchor: [25, 50],
									  popupAnchor: [-10, -50],
									});

									var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id, icon: myIcon } ); 

								}else{

									var marker = L.marker([ latlng[0], latlng[1] ],{title:map_marker_id} ); 
								}
								
								let markerPos = marker.getLatLng();

									if( sbd_map_fitbounds == 'on' ){
					 
										marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
										
									}else{

										marker.addTo(mapCreate).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();

									}

								markerClusters.clearLayers();
								markers.push(marker);


								var isClicked = false;

								marker.on({
								    mouseover: function(e) {

								        for (var i in markers){
								            var markerID = markers[i].options.title;
								            if (markerID == e.target.options.title ){
								            	mapCreate.setView(markers[i]._latlng);
								                markers[i].openPopup();
								        		
								            }else{
								                markers[i].closePopup();
								            };
								        }


								    },
								    
								});

								/*var group = new L.featureGroup(markers);
								mapCreate.fitBounds(group.getBounds().pad(0.5));
								if( sbd_map_fitbounds != 'on' ){
									mapCreate.setZoom(parseInt(sld_variables.zoom));
								}*/



								if( sbd_map_fitbounds == 'on' ){

									var group = new L.featureGroup(markers);
									mapCreate.fitBounds(group.getBounds());

								}else{

									var southWest = new L.LatLng(markers[0]._latlng.lat, markers[0]._latlng.lng),
							    	northEast = new L.LatLng(markers[1]._latlng.lat, markers[1]._latlng.lng),
							    	bounds = new L.LatLngBounds(southWest, northEast);
									mapCreate.fitBounds(bounds, {padding: [50, 50]});

									mapCreate.setZoom(parseInt(sld_variables.zoom));
								}


							}
						}
						
					}
				//}
				
			}
		});
		
		$(".qcpd-single-list-pd, .qcpd-single-list-pd-1, .opd-list-pd-style-8, .opd-list-pd-style-9, .pd-container").each(function(){
			
			var visibleItems = $(this).find("li.showMe").length;
			
			//console.log(visibleItems);
			
			if(visibleItems==0){
				$(this).hide();
				$(this).parent('.qc-grid-item').hide();
			}else{
				$(this).show();
				$(this).parent('.qc-grid-item').show();
			}
		});

		setTimeout(function(e){
			
			if(cluster.pagination=='true'){
	
				jQuery('.pdp-holder').show();
				jQuery(".qc-grid-item ul").each(function(){
						$("#"+jQuery(this).attr('id').replace("list", "holder")).jPages({
							containerID : jQuery(this).attr('id'),
							perPage : cluster.per_page,
						});
				})
			}
			
			
			$grid = $('.qc-grid');
			$grid.packery('destroy').packery({
			  itemSelector: '.qc-grid-item',
			  gutter: 10
			});
		},1000);
		
		$grid = $('.qc-grid');
		$grid.packery('destroy').packery({
		  itemSelector: '.qc-grid-item',
		  gutter: 10
		});

		/*if( typeof google !== 'undefined' ){
			google.maps.event.addListener(map, "click", function(event) {
				
				jQuery('.gm-style-iw').each(function(){
					jQuery(this).next().click();
				})
				
			});
		}*/

	});

  	//UpvoteCount
	$(document).on("click",".sbd-upvote-btn", function(event){
    
		var chk = $(this);
		event.preventDefault();

		if ( chk.data('requestRunning') ) {
			return;
		}

		chk.data('requestRunning', true);
		
		if($(this).hasClass('pd_upvote_animation')){
			$(this).removeClass('pd_upvote_animation')
		}
		
		$(this).addClass('pd_upvote_animation');
		
        var data_id = $(this).attr("data-post-id");
        var data_title = $(this).attr("data-item-title");
        var data_link = $(this).attr("data-item-link");

        var parentLI = $(this).closest('li').attr("id");

        var selectorBody = $('.qc-grid-item span[data-post-id="'+data_id+'"][data-item-title="'+data_title+'"][data-item-link="'+data_link+'"]');

        var selectorWidget = $('.widget span[data-post-id="'+data_id+'"][data-item-title="'+data_title+'"][data-item-link="'+data_link+'"]');

        var bodyLiId = $(".qc-grid-item").find(selectorBody).closest('li').attr("id");
        var WidgetLiId = $(selectorWidget).closest('li').attr("id");

        //alert( bodyLiId );

        $.post(ajaxurl, {            
            action: 'qcpd_upvote_action', 
            post_id: data_id,
            meta_title: data_title,
            meta_link: data_link,
            li_id: parentLI,
            security: qc_sbd_get_ajax_nonce
                
        }, function(data) {
            var json = $.parseJSON(data);
            //console.log(json.cookies);
            //console.log(json.exists);
            if( json.vote_status == 'success' )
            {
                $('#'+parentLI+' .upvote-section .upvote-count').html(json.votes);
                $('#'+parentLI+' .upvote-section .sbd-upvote-btn').css("color", "green");
                $('#'+parentLI+' .upvote-section .upvote-count').css("color", "green");

                $('#'+bodyLiId+' .upvote-section .upvote-count').html(json.votes);
                $('#'+bodyLiId+' .upvote-section .sbd-upvote-btn').css("color", "green");
                $('#'+bodyLiId+' .upvote-section .upvote-count').css("color", "green");

                $('#'+WidgetLiId+' .upvote-section .upvote-count').html(json.votes);
                $('#'+WidgetLiId+' .upvote-section .sbd-upvote-btn').css("color", "green");
                $('#'+WidgetLiId+' .upvote-section .upvote-count').css("color", "green");
            }
        });
       
    });
	
	$(document).on("click",".pd-sbd-upvote-btn-single", function(event){
		
		var chk = $(this);
		event.preventDefault();

		if ( chk.data('requestRunning') ) {
			return;
		}

		chk.data('requestRunning', true);
		
		if($(this).hasClass('pd_upvote_animation')){
			$(this).removeClass('pd_upvote_animation')
		}
		$(this).addClass('pd_upvote_animation');
        var data_id = $(this).attr("data-post-id");
        var data_title = $(this).attr("data-item-title");
        var data_link = $(this).attr("data-item-link");
		var uniqueId = $(this).attr("data-unique");
        //alert( bodyLiId );
        $.post(ajaxurl, {            
            action: 'qcpd_upvote_action', 
            post_id: data_id,
            meta_title: data_title,
            meta_link: data_link,
            li_id: '',
			uniqueid: uniqueId,
            security: qc_sbd_get_ajax_nonce
                
        }, function(data) {
            var json = $.parseJSON(data);
            //console.log(json.cookies);
            //console.log(json.exists);
            if( json.vote_status == 'success' ){

                $('.upvote-section-style-single .upvote-count').html(json.votes);
                $('.upvote-section-style-single .upvote-on').css("color", "green");
                $('.upvote-section-style-single .upvote-count').css("color", "green");

            }
        });
       
    });
	$(document).on('click','.bookmark-btn',function(event){

		event.preventDefault();
		var data_id = $(this).attr("data-post-id");
        var item_code = $(this).attr("data-item-code");
		var is_bookmarked = $(this).attr("data-is-bookmarked");
		var li_id = $(this).attr('data-li-id');
		
		var parentLi = $(this).closest('li').attr('id');
		
		var obj = $(this);
		
		if(!bookmark.is_user_logged_in){
			if(typeof login_url_pd ==="undefined" || login_url_pd==''){
				if(typeof(pduserMessage)!=="undefined" && pduserMessage!==''){
					alert(pduserMessage);
				}else{
					alert('You need to log in to add items to your favorite list.');
				}
				
			}else{
				
				if(typeof(pduserMessage)!=="undefined" && pduserMessage!==''){
					
					if (confirm(pduserMessage)) {
						window.location.href = login_url_pd;
					} else {
						// Do nothing!
					}	
					
				}else{
					if (confirm('You need to log in to add items to your favorite list.')) {
						window.location.href = login_url_pd;
					} else {
						// Do nothing!
					}	
				}
				
							
			}
		}else{
			
			if(is_bookmarked==0){
				
				$.post(ajaxurl, {
				action: 'qcpd_bookmark_insert_action', 
				post_id: data_id,
				item_code: item_code,
				userid: bookmark.userid,

				}, function(data) {
					
					obj.attr('data-is-bookmarked',1);
					obj.children().removeClass('fa-star-o').addClass('fa-star');
					
					if(typeof(template)!=="undefined"){
						var newliid = parentLi+'_clone';
						var cloneElem = $('#'+parentLi).clone();
						
						cloneElem.prop({ id: newliid});
						cloneElem.find('.upvote-section').remove();
						cloneElem.find('.bookmark-section').find('span').attr("data-li-id",newliid);
						cloneElem.find('.bookmark-section').find('span').find('i').removeClass('fa-star').addClass('fa-times-circle');
						cloneElem.prependTo("#pd_bookmark_ul");
						$('.qc-grid').packery({
						  itemSelector: '.qc-grid-item',
						  gutter: 10
						});
					}
					
					
				});
				
			}else{
				$.post(ajaxurl, {
				action: 'qcpd_bookmark_remove_action', 
				post_id: data_id,
				item_code: item_code,
				userid: bookmark.userid,

				}, function(data) {
					if(typeof li_id === "undefined" || li_id==''){
						obj.attr('data-is-bookmarked',0);
						obj.children().removeClass('fa-star').addClass('fa-star-o');
					}else{
						obj.closest('li').remove();
						$('.qc-grid').packery({
						  itemSelector: '.qc-grid-item',
						  gutter: 10
						});
					}
					
					
				});
			}
			
			
			
		}
		
	});


	$(document).on("click",".open-mpf-sld-link", function(e){
		e.preventDefault();
		var obj = $(this);
		var getParent = obj.closest('li');
		var mailto = 'false';
		if( jQuery(this).data('mailto') == true ){
			mailto = 'true';
		}

		
		var data_id = $(this).attr("data-post-id");
        var data_title = $(this).attr("data-item-title");
        var data_link = $(this).attr("data-item-link");
		var container = $(this).attr("data-mfp-src");

		var locations = getParent.attr('data-latlon');
		var title = getParent.attr('data-title');
		var address = getParent.attr('data-address');
		var url;



		var icons = getParent.find('.pd-bottom-area').clone();
		icons.find('.pd-map').removeClass('open-mpf-sld-link');
	
		if(typeof(getParent.attr('data-address'))!=='undefined' && getParent.attr('data-address')!=''){
			icons.find('.pd-map').attr("href", "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(getParent.attr('data-address'))+"");
			icons.find('.pd-map').attr("target", "_blank");
		}
		icons.find('.open-mpf-sld-link').remove();
		icons.find('.pd-map').remove();
		icons = icons.html();
		
		var custom_content = obj.find('.sbd_custom_content').clone();
		custom_content = custom_content.html();
		//others information
		var others_info = '';
		if(getParent.attr('data-local')!=''){
			others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+getParent.attr('data-local')+"</p>";
		}
		if(getParent.attr('data-phone')!=''){
			if( sbd_enable_map_addr_phone_clickable == 'on' ){
				others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b><a href='tel:"+getParent.attr('data-phone')+"'>"+getParent.attr('data-phone')+"</a></p>";
			}else{
				others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+getParent.attr('data-phone')+"</p>";
			}
		}
		if(obj.attr('data-businesshour')!=''){
			others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+getParent.attr('data-businesshour')+"</p>";
		}
	
	
		var imgurl = '';
		if(getParent.find('img').length>0){
			imgurl = getParent.find('img').attr('src');
		}
		
		var target = '';
		
		if(typeof(getParent.find('a').attr('target'))!=='undefined'){
			target = 'target="_blank"';
		}
		if(typeof(getParent.find('a').attr('data-newtab'))!=='undefined'){
			target = 'target="_blank"';
		}

		if(typeof(getParent.find('a').attr('href'))!=='undefined' && getParent.find('a').is('a:not([href^="#"])') && getParent.find('a').is('a:not([href^="tel"])')){
			url = getParent.find('a').attr('href');
		}else{
			url = getParent.attr('data-url');
		}
		
		var subtitle = getParent.attr('data-subtitle');

		var popup_map = "true";
		if($('.pd-map')[0]){
			popup_map = "true";
		}else{
			popup_map = "false";
		}
		
		var upvote = 'on';
		if(jQuery('.upvote-btn').length<1){
			var upvote = 'off';
		}
		
		$.post(ajaxurl, {            
            action: 'qcpd_load_long_description', 
            post_id: data_id,
            meta_title: data_title,
            meta_link: data_link,
			popup_map: popup_map,
			upvote: upvote,
			mailto: mailto

        }, function(data) {
			$(container+' .sbd_business_container').html(data);

			//if( typeof google !== 'undefined' ){
				if(typeof getParent.attr('data-latlon') !== 'undefined' || getParent.attr('data-latlon')!=''){
					latlng = getParent.attr('data-latlon').split(',');

		 			mapCreates = L.map('pd_popup_map_container').setView([sld_variables.latitute, sld_variables.longitute], parseInt(sld_variables.zoom));
				  	L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
						attribution: '',
						minZoom: 1,
						maxZoom: 50,
						key: 'BC9A493B41014CAABB98F0471D759707'
					}).addTo(mapCreates);
					var markericon = $(this).parent().data('marker');
					var map_marker_id = obj.parent().attr('id');
					var icon = markericon;

					maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

					mapCreates.panTo(new L.LatLng( latlng[0], latlng[1] ), parseInt(sld_variables.zoom) );

					if( icon != '' ){

						var myIcon = L.icon({
						  iconUrl: icon,
						  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
						  iconAnchor: [25, 50],
						  popupAnchor: [-10, -50],
						});

						var marker = L.marker( [ latlng[0], latlng[1] ] ); 

					}else{

						var marker = L.marker( [ latlng[0], latlng[1] ] ); 
					}
					
					let markerPos = marker.getLatLng();

					if( sbd_map_fitbounds == 'on' ){
	 
						marker.addTo(mapCreates).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
						
					}else{

						marker.addTo(mapCreates).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();

					}

					markers.push(marker);

					mapCreates.setView(latlng);

					
				}else{

					latlng = getParent.attr('data-latlon').split(',');

		 			mapCreates = L.map('pd_popup_map_container').setView([sld_variables.latitute, sld_variables.longitute], parseInt(sld_variables.zoom));
				  	L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
						attribution: '',
						minZoom: 1,
						maxZoom: 50,
						key: 'BC9A493B41014CAABB98F0471D759707',
					}).addTo(mapCreates);
					var icon = markericon;
					var map_marker_id = obj.parent().attr('id');

					maplatlang = infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info, map_marker_id);

					mapCreates.panTo(new L.LatLng(latlng[0], latlng[1]), parseInt(sld_variables.zoom));

					if( icon != '' ){

						var myIcon = L.icon({
						  iconUrl: icon,
						  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
						  iconAnchor: [25, 50],
						  popupAnchor: [-10, -50],
						});

						var marker = L.marker([ latlng[0], latlng[1] ] ); 

					}else{

						var marker = L.marker([ latlng[0], latlng[1] ]); 
					}
					
					let markerPos = marker.getLatLng();

						if( sbd_map_fitbounds == 'on' ){
		 
							marker.addTo(mapCreates).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).openPopup();
							
						}else{

							marker.addTo(mapCreates).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).openPopup();

						}

					markers.push(marker);

					mapCreates.setView(latlng);


				}
			//}
			
        });
	});

	$('.open-mpf-sld-link').magnificPopup({
	  type:'inline',
	  midClick: true
	});
	$('.open-mpf-sbd').magnificPopup({
	  type:'inline',
	  midClick: true
	});

	function qcsbd_CheckArray(array1, array2){
		if( Array.isArray(array1) && Array.isArray(array2) ){
			//return array1.length === array2.length && array1.sort().every(function(value, index) { return value === array2.sort()[index]});
			return array2.every(function (v) {
		        return array1.includes(v);
		    });
		}else{
			return false;
		}
	}


	jQuery(document).on('click', '.sbd_email_form' , function(e){
		e.preventDefault();
		e.stopPropagation();
        var obj = $(this);

		if(sld_variables.mailto_send_email == 'on'){

			var send_email = obj.attr('data-email');
			window.location = 'mailto:' + send_email;
			return false;
		}

		jQuery('#sbd_email_name').val('');
		jQuery('#sbd_email_email').val('');
		jQuery('#sbd_email_subject').val('');
		jQuery('#sbd_email_message').val('');
		jQuery('#pdcode').val('');
		jQuery('#sbd_email_to').val(obj.attr('data-email'));
		jQuery('#sbd_email_status').html('');
		var sbd_email_title 	= obj.closest('li').attr('data-title')
		var sbd_email_subtitle 	= obj.closest('li').attr('data-subtitle')
	  	jQuery('#sbd_email_title').val('');
	  	jQuery('#sbd_email_title').val(sbd_email_title);
	  	jQuery('#sbd_email_subtitle').val('');
	  	jQuery('#sbd_email_subtitle').val(sbd_email_subtitle);
		jQuery.magnificPopup.open({
		  items: {
			src: '#sbd_email_form'
		  },
		  type: 'inline'
		});
		jQuery('#captcha_reload1').click();
		
		
		
	});

 	jQuery( "#sbd_email_form_id" ).submit(function( event ) {	

	  event.preventDefault();
	  jQuery('#sbd_email_loading').hide();
	  jQuery( "#sbd_email_status" ).html('');
	  var name = jQuery('#sbd_email_name').val();
	  var email = jQuery('#sbd_email_email').val();
	  var subject = jQuery('#sbd_email_subject').val();
	  var message = jQuery('#sbd_email_message').val();
	  var to = jQuery('#sbd_email_to').val();
	  var pdcode = jQuery('#pdcode').val();
	  var pdccode = jQuery('#pdccode').val();
	  var sbd_email_title = jQuery('#sbd_email_title').val();
	  var sbd_email_subtitle = jQuery('#sbd_email_subtitle').val();
	  var error = false;
	  if(name==''){
		  alert('Please provide the name');
		  error = true;
	  }
	  if(email==''){
		  alert('please provide the email');
		  error = true;
	  }
	  if(subject==''){
		  alert('please provide the subject');
		  error = true;
	  }
	  if(message==''){
		  alert('please provide the message content');
		  error = true;
	  }
	  if(pdcode==''){
		  alert('please provide the Captcha code');
		  error = true;
	  }
	  
		if(error==false){
			jQuery('#sbd_email_loading').show();
			var data = {
			  'name':name,
			  'email':email,
			  'to': to,
			  'subject': subject,
			  'message': message,
			  'sbd_email_title': sbd_email_title,
			  'sbd_email_subtitle': sbd_email_subtitle,
			}
			if( jQuery(this).find('#pdcode').length > 0 ){
				data.captcha = pdcode;
				data.ccaptcha = pdccode;
			}

			if( jQuery(this).find('.sbd-ajaxmail-recaptcha').length > 0 ){
				var recaptcha = $('#g-recaptcha-response').val();
				data.recaptcha = recaptcha;
			}

			$.post(
				ajaxurl,
				{
					action : 'qcld_pd_send_visitors_email',
					data: data,
					security: sld_variables.qcajax_nonce
				},
				function(data){
					jQuery('#sbd_email_loading').hide();
					var json = $.parseJSON(data);
					if(json.status){
						jQuery( "#sbd_email_status" ).html(sld_variables.email_sent);
					}else{
						jQuery( "#sbd_email_status" ).html(json.message);
					}
					
				}
			);
		}
	  
	});


	jQuery('.pd-map').on('click', function(e)  {
		//if( typeof google !== 'undefined' ){
	        e.preventDefault();
			e.stopPropagation();
	        var obj = $(this);
			var address = obj.attr('full-address');
			var mapId = obj.attr('data-mfp-src');
			
			var markericon = '';
			if(sld_variables.global_marker!=''){
				markericon = sld_variables.global_marker;
			}
			if(typeof(obj.attr('data-paid'))!='undefined' && obj.attr('data-paid')!=''){
				markericon = sld_variables.paid_marker_default; //default paid marker
				if(sld_variables.paid_marker!=''){
					markericon = sld_variables.paid_marker; // If paid marker is set then override the default
				}
			}

			if(typeof(obj.attr('data-marker'))!='undefined' && obj.attr('data-marker')!=''){
				markericon = obj.attr('data-marker'); // If icon is set in the item it self. Most priority.
			}
			//var mapDiv = jQuery(mapId).children().attr('id');
			
			
			
			var mapDiv = jQuery(mapId).find('.pd_map_container').attr('id');
			jQuery('#'+mapDiv).height('400px');
	        //First initial address
	        var toAddress = address;


			//var find_latlang = "https://nominatim.openstreetmap.org/search?limit=1&q="+encodeURIComponent(toAddress);
			var find_latlang = "https://nominatim.openstreetmap.org/search?format=json&limit=1&q="+encodeURIComponent(toAddress);
			$.getJSON( find_latlang, {
			    format: "json"
			}).done(function( data ) {

				if(data[0].lat != 'undefined' && data[0].lon != 'undefined'){


		 			var mapCreates = L.map(mapDiv).setView([data[0].lat, data[0].lon], parseInt(sld_variables.zoom));
				  	L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
						attribution: '',
						minZoom: 1,
						maxZoom: 50,
						key: 'BC9A493B41014CAABB98F0471D759707',
					}).addTo(mapCreates);
					var icon = markericon;

					if( icon != '' ){

						var myIcon = L.icon({
						  iconUrl: icon,
						  iconSize: [sbd_custom_marker_image_width, sbd_custom_marker_image_height],
						  iconAnchor: [25, 50],
						  popupAnchor: [-10, -50],
						});

						var marker = L.marker([ data[0].lat, data[0].lon ] ).addTo(mapCreates); 

					}else{

						var marker = L.marker([ data[0].lat, data[0].lon ]).addTo(mapCreates); 
					}
					
					let markerPos = marker.getLatLng();

					markers.push(marker);

					// var urlData = "https://www.openstreetmap.org/#map=15/"+data[0].lat+ "/"+ data[0].lon;
					var urlData = "https://www.openstreetmap.org/?mlat="+data[0].lat+"&mlon="+data[0].lon+"#map=15/"+data[0].lat+ "/"+ data[0].lon;

					$('a.sbd_direction_btn').attr("href", urlData);
				}

			});

	        	


		// }
    });
	
	
	$('#pd_enable_recurring').on('click', function(){
		
        if(this.checked){
            $('#paypalProcessor').hide();
            $('#paypalProcessor_recurring').show();
		}
        else{
            $('#paypalProcessor').show();
            $('#paypalProcessor_recurring').hide();
		}
		
	})
	

	
	
});
	


function sbdradius_(){
}


function sbdclearradius_(){
	
}


jQuery(document).ready(function($){
	$(document).on("click",".sbd_marker_more_details",function(){
		var value = jQuery(this).attr('data-id');
		jQuery('#'+value + ' > a.open-mpf-sld-link' ).trigger('click');

	});
});



