

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();
	}

// var pd_snazzymap_js = pd_snazzymap_js.pd_snazzymap_js;
jQuery(document).ready(function($){


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

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

	jQuery('input[name="pd_default_tags_other"]').on('change',function(){
		if (jQuery(this).is(':checked')) {
			jQuery('.pd_default_tags_input').show();
		}else{
			jQuery('.pd_default_tags_input').hide();
		}
	});
	
	jQuery('.sbd_main_wrapper').each(function(){
		var main_wrapper = jQuery(this);
		if( main_wrapper.hasClass('sbd-distance-order') ){
			if (navigator.geolocation) {
		        navigator.geolocation.getCurrentPosition(function (position) {  
		            var current_latitude = position.coords.latitude;
		            var current_longitude = position.coords.longitude;
		            console.log(current_latitude+', '+current_longitude);
					main_wrapper.find('#sbdopd-list-holder ul li').each(function(){
						var obj = jQuery(this);
		            	var locations = obj.attr('data-latlon');
						var latlng = locations.split(',');
		            	var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(current_latitude, current_longitude), new google.maps.LatLng(latlng[0],latlng[1]));
						if( jQuery.isNumeric( distance ) ){
							obj.attr('data-searched-distance',distance);
							// var searched_distance = obj.attr('data-searched-distance');
							// console.log('searched_distance');
							// console.log(searched_distance);
						}else{
							obj.attr('data-searched-distance','9999999999999999');
						}						
					});
				// $(".listitems.autosort").each(function(){
					main_wrapper.find('ul').each(function(){
						jQuery(this).addClass('test');
					    jQuery(this).html(jQuery(this).children('li').sort(function(a, b){
					        return (jQuery(b).attr('data-searched-distance')) < (jQuery(a).attr('data-searched-distance')) ? 1 : -1;
					    }));
					});
				// });
		        });
		    }
		}
	});

	$('#sld_claim_list').on('change',function(e){
		e.preventDefault();
		if($(this).val()!==''){
			$.post(
				ajaxurl,
				{
					action : 'qcld_sbd_show_list_item',
					listid: $(this).val()
				},
				function(data){
					$('#sld_list_item').html(data);
				}
			);
		}else{
			$('#sld_list_item').html('');
		}
		
	})
    
    //Masonary Grid
    var $grid = $('.qc-grid').packery({
      itemSelector: '.qc-grid-item',
      gutter: 10
    });

	if(typeof(cluster)!='undefined' && cluster.main_click==3){
		
		jQuery("#sbdopd-list-holder ul li").on('click', function(e){
			
			// e.preventDefault();
			if( typeof google !== 'undefined' ){
				if(jQuery('#sbd_all_location').length>0){
					map = new google.maps.Map(
					document.getElementById("sbd_all_location"), {
						center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
						zoom: parseInt(sld_variables.zoom),
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						gestureHandling: 'cooperative'
					});
					if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
						map.setOptions({styles: pd_snazzymap_js});
					}
					oms = new OverlappingMarkerSpiderfier(map, {
					  markersWontMove: true,
					  markersWontHide: true,
					  basicFormatEvents: true
					});
				}
				
				
				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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
					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;
					if( markericon != '' ){
						icon = {
							url: markericon, // url
							scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
							origin: new google.maps.Point(0,0), // origin
							anchor: new google.maps.Point(0, 0) // anchor
						};
					}
					
					var marker = new google.maps.Marker({
						map: map,
						icon: icon,
						scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height),
						position:  new google.maps.LatLng(latlng[0],latlng[1]),
						title: title,
						animation: google.maps.Animation.DROP,
						address: address,
						url: url,
						mapSelectorID: map_marker_id
					});
					markers.push(marker);
					infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
					if( sbd_map_fitbounds == 'on' ){
						bounds.extend(marker.getPosition());
						map.fitBounds(bounds);
					}
					
					
				}
			}
		})
		
		
	}

    //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){
			//$('.pd_tag_filter:first-of-type').removeClass('pd_tag_filter-active').click();
			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){
				map = new google.maps.Map(
				document.getElementById("sbd_all_location"), {
					center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
					zoom: parseInt(sld_variables.zoom),
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					gestureHandling: 'cooperative'
				});
				if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
					map.setOptions({styles: pd_snazzymap_js});
				}
				oms = new OverlappingMarkerSpiderfier(map, {
				  markersWontMove: true,
				  markersWontHide: true,
				  basicFormatEvents: true
				});
			}

		//	if( sbd_map_fitbounds == 'on' ){
				var bounds = new google.maps.LatLngBounds();
			//}

		}
        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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
							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;
							if( markericon != '' ){
								icon = {
									url: markericon, // url
									scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
									origin: new google.maps.Point(0,0), // origin
									anchor: new google.maps.Point(0, 0) // anchor
								};
							}
							var marker = new google.maps.Marker({
								icon:icon,
								map: map,
								position:  new google.maps.LatLng(latlng[0],latlng[1]),
								title: title,
								animation: google.maps.Animation.DROP,
								address: address,
								url: url,
								mapSelectorID: map_marker_id
							});
							markers.push(marker);
							
							//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
							infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
							bounds.extend(marker.getPosition());
							// if( sbd_map_fitbounds == 'on' ){
								map.fitBounds(bounds);
							// }
							
						}
					}
					
				})
			}
        }

        $('.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();
					})
					
				});
			}
		}
		

    });


	jQuery(document).on('click','.pdp-holder a', function(event){

		event.preventDefault();
		markers = [];
		
		if(jQuery('#sbd_all_location').length>0){
			//google map code
			map = new google.maps.Map(
			document.getElementById("sbd_all_location"), {
				center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
				zoom: parseInt(sld_variables.zoom),
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				gestureHandling: 'cooperative'
			});
			if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
				map.setOptions({styles: pd_snazzymap_js});
			}
			oms = new OverlappingMarkerSpiderfier(map, {
			  markersWontMove: true,
			  markersWontHide: true,
			  basicFormatEvents: true
			});
		}
	

				var filterName = $(this).text();

					var parentDom = $(this).closest('.qcpd-single-list-pd').find('ul li:visible').not('.jp-hidden');
					var parentDom = $('.qcpd-single-list-pd ul li');

					$(parentDom).each(function(){
						
					var obj = $(this);
					if( !obj.hasClass('jp-hidden') && 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 google !== 'undefined' ){
						if(typeof(obj.attr('data-address'))!=='undefined' && obj.attr('data-address')!=''){
							icons.find('.pd-map').attr("href", "https://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
							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;
							if( markericon != '' ){
								icon = {
									url: markericon, // url
									scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
									origin: new google.maps.Point(0,0), // origin
									anchor: new google.maps.Point(0, 0) // anchor
								};
							}
							var marker = new google.maps.Marker({
								icon:icon,
								map: map,
								position:  new google.maps.LatLng(latlng[0],latlng[1]),
								title: title,
								animation: google.maps.Animation.DROP,
								address: address,
								url: url,
								mapSelectorID: map_marker_id
							});
							markers.push(marker);
							
							//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
							infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
							bounds.extend(marker.getPosition());
							// if( sbd_map_fitbounds == 'on' ){
								map.fitBounds(bounds);
							// }
							
						}
					}
						
						
					}


				});


			//}

			 	$('.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();
							})
							
						});
					}
				}
				
				jQuery(window).trigger('resize');

	})




	$(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';
		}
		

        //$(".sbd-tag-filter-area a").removeClass("pd_tag_filter-active");
        //$(this).addClass("pd_tag_filter-active");
        $(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( inclusive_tag_filter != 'on' ){
				jQuery('.pd_tag_filter').removeClass('pd_tag_filter-active');
				jQuery(this).addClass('pd_tag_filter-active');

					markers = [];
			
					if(jQuery('#sbd_all_location').length>0){
						//google map code
						map = new google.maps.Map(
						document.getElementById("sbd_all_location"), {
							center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
							zoom: parseInt(sld_variables.zoom),
							mapTypeId: google.maps.MapTypeId.ROADMAP,
							gestureHandling: 'cooperative'
						});
						if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
							map.setOptions({styles: pd_snazzymap_js});
						}
						oms = new OverlappingMarkerSpiderfier(map, {
						  markersWontMove: true,
						  markersWontHide: true,
						  basicFormatEvents: true
						});
					}

				//	if( sbd_map_fitbounds == 'on' ){
						var bounds = new google.maps.LatLngBounds();
				//	}

			}

        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 if(sld_variables.sbd_combine_distant_tag_live_search != "on"){
							var search_term = new RegExp(filter.join('|'), "i");
							filter = [];

	        }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( typeof google !== 'undefined'  && cluster.map=='true' ){
					if(jQuery('#'+mapIDselector).length>0 && combined_search == 0){
						//google map code
						markers=[];
						map = new google.maps.Map(
						document.getElementById(mapIDselector), {
							center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
							zoom: parseInt(sld_variables.zoom),
							mapTypeId: google.maps.MapTypeId.ROADMAP,
							gestureHandling: 'cooperative'
						});

						if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
							map.setOptions({styles: pd_snazzymap_js});
						}
						
						oms = new OverlappingMarkerSpiderfier(map, {
						  markersWontMove: true,
						  markersWontHide: true,
						  basicFormatEvents: true
						});
					}

					
					//if( sbd_map_fitbounds == 'on' ){
						var bounds = new google.maps.LatLngBounds();
					//}
				}
        // 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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
								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;
								if( markericon != '' ){
									icon = {
										url: markericon, // url
										scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
										origin: new google.maps.Point(0,0), // origin
										anchor: new google.maps.Point(0, 0) // anchor
									};
								}
								var marker = new google.maps.Marker({
									icon:icon,
									map: map,
									position:  new google.maps.LatLng(latlng[0],latlng[1]),
									title: title,
									animation: google.maps.Animation.DROP,
									address: address,
									url: url,
									mapSelectorID: map_marker_id
								});
								markers.push(marker);
								//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
								infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
								bounds.extend(marker.getPosition());
								//if( sbd_map_fitbounds == 'on' ){
									map.fitBounds(bounds);
								//}
							}
						}
					}
	            // 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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
												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;
												if( markericon != '' ){
													icon = {
														url: markericon, // url
														scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
														origin: new google.maps.Point(0,0), // origin
														anchor: new google.maps.Point(0, 0) // anchor
													};
												}
												var marker = new google.maps.Marker({
													icon:icon,
													map: map,
													position:  new google.maps.LatLng(latlng[0],latlng[1]),
													title: title,
													animation: google.maps.Animation.DROP,
													address: address,
													url: url,
													mapSelectorID: map_marker_id
												});
												markers.push(marker);
												//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
												infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
												bounds.extend(marker.getPosition());
												//if( sbd_map_fitbounds == 'on' ){
													map.fitBounds(bounds);
												//}
											}
										}
									}
					
	            }
 			}
        });

		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;
				
				
				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( typeof google !== 'undefined' ){
			if(jQuery('#'+map_selector).length>0){
				//google map code
				map = new google.maps.Map(
				document.getElementById(map_selector), {
					center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
					zoom: parseInt(sld_variables.zoom),
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					gestureHandling: 'cooperative'
				});

				if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
					map.setOptions({styles: pd_snazzymap_js});
				}
				
				oms = new OverlappingMarkerSpiderfier(map, {
				  markersWontMove: true,
				  markersWontHide: true,
				  basicFormatEvents: true
				});
			}
		}
			// 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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
									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;
									if( markericon != '' ){
										icon = {
											url: markericon, // url
											scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
											origin: new google.maps.Point(0,0), // origin
											anchor: new google.maps.Point(0, 0) // anchor
										};
									}
									var marker = new google.maps.Marker({
										icon:icon,
										map: map,
										position:  new google.maps.LatLng(latlng[0],latlng[1]),
										title: title,
										animation: google.maps.Animation.DROP,
										address: address,
										url: url,
										mapSelectorID: map_marker_id
									});
									//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
									infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
									bounds.extend(marker.getPosition());
									// if( sbd_map_fitbounds == 'on' ){
										map.fitBounds(bounds);
									// }
								}
							}
							
						}
					}
					
				}
			});
			
			$(".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);
            //console.log(parentLI);
            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);
            
            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 markericon = '';

		markericon = $(this).parent().data('marker');
		
		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')!=''){
					pos = getParent.attr('data-latlon').split(',');
					var myLatlng = new google.maps.LatLng(pos[0],pos[1]);
					 var myOptions = {
						 zoom: parseInt(sld_variables.popup_zoom),
						 center: myLatlng,
						 mapTypeId: google.maps.MapTypeId.ROADMAP,
						 gestureHandling: 'cooperative'
						 }
					  map = new google.maps.Map(document.getElementById("pd_popup_map_container"), myOptions);
						var icon = markericon;
						if( markericon != '' ){
							icon = {
								url: markericon, // url
								scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
								origin: new google.maps.Point(0,0), // origin
								anchor: new google.maps.Point(0, 0) // anchor
							};
						}
						if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
							map.setOptions({styles: pd_snazzymap_js});
						}
					  var marker = new google.maps.Marker({
					  	  icon:icon,
						  position: myLatlng, 
						  map: map,
					  title:data_title
					 });
					
				}else{
					
					pos = getParent.attr('data-latlon').split(',');
					var myLatlng = new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute));
					 var myOptions = {
						 zoom: parseInt(sld_variables.popup_zoom),
						 center: myLatlng,
						 mapTypeId: google.maps.MapTypeId.ROADMAP,
						 gestureHandling: 'cooperative'
						 }
					  map = new google.maps.Map(document.getElementById("pd_popup_map_container"), myOptions);
					  if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
							map.setOptions({styles: pd_snazzymap_js});
						}
						var icon = markericon;
						if( markericon != '' ){
							icon = {
								url: markericon, // url
								scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
								origin: new google.maps.Point(0,0), // origin
								anchor: new google.maps.Point(0, 0) // anchor
							};
						}
					  var marker = new google.maps.Marker({
					  	  icon:icon,
						  position: myLatlng, 
						  map: map,
					  title:data_title
					 });
				}
			}
			
        });
	});

	jQuery(document).on('click', '.style-7 .item-list-title', function(e){
		if( jQuery(this).parents('.ilist-item-main').find('.feature-img-box').parent('a').hasClass('open-mpf-sld-link') ){
			e.preventDefault();
			e.stopPropagation();
			jQuery(this).parents('.ilist-item-main').find('.open-mpf-sld-link').trigger('click');
		}
	});
	
	/*$('.testclass').click(function(e){
		e.preventDefault();
		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");
		
		$.post(ajaxurl, {            
            action: 'qcpd_load_long_description', 
            post_id: data_id,
            meta_title: data_title,
            meta_link: data_link,

        }, function(data) {
			$(container+' .sbd_business_container').html(data);
        });
	})*/
	
	$('.open-mpf-sld-link').magnificPopup({
	  type:'inline',
	  midClick: true
	});
	$('.open-mpf-sbd').magnificPopup({
	  type:'inline',
	  midClick: true
	});
	/*$('.sbd_email_form').magnificPopup({
	  type:'inline',
	  midClick: true
	});*/
	
	/*$('.fa-map').click(function(e){
		var obj = $(this).parent();
		var address = obj.attr('full-address');
		var mapId = obj.attr('data-mfp-src');
		var geocoder;
		var map;
		var mapDiv = mapId.replace(/^#+/i, '');
		
		var mapcontainer = jQuery('#'+mapDiv+' > .pd_map_container').attr('id');
		var toAddress = address;
		
		geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(40.84, 14.25);
		var myOptions = {
			zoom: sld_variables.zoom,
			center: latlng,
			mapTypeControl: true,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
			navigationControl: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		
		map = new google.maps.Map(document.getElementById(mapcontainer), myOptions);
		if (geocoder) {
		  geocoder.geocode( { 'address': toAddress}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
			  if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
			  map.setCenter(results[0].geometry.location);

				var infowindow = new google.maps.InfoWindow(
					{ content: '<b>'+toAddress+'</b>',
					  size: new google.maps.Size(150,50)
					});

				var marker = new google.maps.Marker({
					position: results[0].geometry.location,
					map: map, 
					title:toAddress
				}); 
				google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(map,marker);
				});

			  } else {
				alert("No results found");
			  }
			} else {
			  alert("Geocode was not successful for the following reason: " + status);
			}
		  });
		}
	})*/
	

	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');
	        //options from google map
	        var myOptions = {
	            zoom: parseInt(sld_variables.zoom),
	            center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
	            mapTypeId: google.maps.MapTypeId.ROADMAP,
				gestureHandling: 'cooperative'
	        };
	        //First initial address
	        var toAddress = address;
	        //console.log(toAddress);

	        //finding user geo location
	        navigator.geolocation.getCurrentPosition(function(position) {
				//console.log(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
	            var geocoder = new google.maps.Geocoder();
	            geocoder.geocode({
	                    "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
	                },
	                function(results, status) {
	                    if (status == google.maps.GeocoderStatus.OK){
	                        var fromAddress =  results[0].formatted_address;
	                        
	                        var directionsRequest = {
	                            origin: fromAddress,
	                            destination: toAddress,
	                            travelMode: google.maps.DirectionsTravelMode.DRIVING,
	                            unitSystem: google.maps.UnitSystem.METRIC
	                        };
	                        var mapObject = new google.maps.Map(document.getElementById(mapDiv), myOptions);
	                        var directionsService = new google.maps.DirectionsService();
	                        directionsService.route(
	                            directionsRequest,
	                            function(response, status)
	                            {
	                            	console.log('response');
	                            	console.log(response);
	                            	if( response.status == 'OK' ){
		                                if (status == google.maps.DirectionsStatus.OK)
		                                {
		                                    new google.maps.DirectionsRenderer({
		                                        map: mapObject,
		                                        directions: response
		                                    });
		                                }
		                                else{
		                                    jQuery("#error").append("Unable to retrieve your route<br />");
		                                }
	                            	}else{
	                                    alert("Unable to retrieve your route. The Destination is too long.");
	                                    
	                                }
	                            }
	                        );
	                    }else{
	                       console.log("Unable to retrieve your address");
	                    }
	                });
	        },
	        function(positionError){
	            console.log("Error: "+ positionError.message);
	        },
	        {
	            enableHighAccuracy: true,
	            timeout: 10 * 1000 // 10 seconds
	        });

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

});


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


	if(sld_variables.pd_enable_autocomplete_search == 'on'){
    	$(".pd_search_filter").autocomplete({
    	
        source: function(request, response) {
        		if(request.term.length < 2 ){
							$('.live_search_loader').remove();
							$('#live-search').removeClass('live_search_loader_wrap');
            	return;
        		}
        		$('#live-search').addClass('live_search_loader_wrap');
        		$('.live_search_loader').remove();
        		$('.pd_search_filter').after('<i class="live_search_loader"></i>');
            $.post( ajaxurl,
						{
							action : 'qcpd_ajax_live_search_functions',
							search: request.term,
						},
						function(data){
							response($.parseJSON(data));
							$('.live_search_loader').remove();
							$('#live-search').removeClass('live_search_loader_wrap');
						}
					);

        },
        select: function (event, ui) {
            $('.pd_search_filter').val(ui.item.label); // display the selected text
            jQuery('.pd_search_filter').trigger('keyup');
            return false;
        },
        focus: function(event, ui){
            $(".pd_search_filter").val(ui.item.label);
            return false;
        },

    	});

	}


    $(".pd_search_filter").keyup(function(){
        // Retrieve the input field text and reset the count to zero
        var filter = $(this).val(), count = 0;
        if( typeof google !== 'undefined' ){
			if(jQuery('#sbd_all_location').length>0){
				//google map code
				markers = [];
				map = new google.maps.Map(
				document.getElementById("sbd_all_location"), {
					center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
					zoom: parseInt(sld_variables.zoom),
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					gestureHandling: 'cooperative'
				});
				if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
					map.setOptions({styles: pd_snazzymap_js});
				}
				oms = new OverlappingMarkerSpiderfier(map, {
				  markersWontMove: true,
				  markersWontHide: true,
				  basicFormatEvents: true
				});


				if( sbd_map_fitbounds == 'on' ){
					var bounds = new google.maps.LatLngBounds();
				}


			}
		}
        // 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');
						// console.log(dataurl);


            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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
							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;
							if( markericon != '' ){
								icon = {
									url: markericon, // url
									scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
									origin: new google.maps.Point(0,0), // origin
									anchor: new google.maps.Point(0, 0) // anchor
								};
							}
							var marker = new google.maps.Marker({
								icon:icon,
								map: map,
								position:  new google.maps.LatLng(latlng[0],latlng[1]),
								title: title,
								animation: google.maps.Animation.DROP,
								address: address,
								url: url,
								mapSelectorID: map_marker_id
							});
							markers.push(marker);
							//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
							infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
							bounds.extend(marker.getPosition());
							// if( sbd_map_fitbounds == 'on' ){
								map.fitBounds(bounds);
							// }
						}
					}
				}
				
            }
        });
		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);
		}

		// jQuery('.qcpd-single-list-pd').each(function(){
		// 	if( jQuery(this).is(':hidden') ){
		// 		jQuery(this).parent().addClass('sbd_hide_main_parent');
		// 	}else{
		// 		jQuery(this).parent().removeClass('sbd_hide_main_parent');
		// 	}
		// });
		
		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(window).resize(function(){
		setTimeout(function(){
			jQuery('.qc-grid').packery({
		      itemSelector: '.qc-grid-item',
		      gutter: 10
		    });
		    console.log('resize');
		}, 500);
	});
	
});



if( typeof google !== 'undefined' ){
	if(cluster.map == 'true'){

		var geocoder;
		var map;
		var circle = null;
		var markers = [];
		var iw;
		var bounds = new google.maps.LatLngBounds();
		if(document.getElementById("sbd_all_location")!==null){
			google.maps.event.addDomListener(window, "load", initialize);
		}
		var oms;
		initialize();

	}

}

function initialize() {
	if( typeof google !== 'undefined' ){
		var map_styles = [];

		if( sld_variables.enable_landmarks == 'off' ){
			map_styles = [
			  {
			    "featureType": "administrative",
			    "elementType": "geometry",
			    "stylers": [
			      {
			        "visibility": "off"
			      }
			    ]
			  },
			  {
			    "featureType": "poi",
			    "stylers": [
			      {
			        "visibility": "off"
			      }
			    ]
			  },
			  {
			    "featureType": "road",
			    "elementType": "labels.icon",
			    "stylers": [
			      {
			        "visibility": "off"
			      }
			    ]
			  },
			  {
			    "featureType": "transit",
			    "stylers": [
			      {
			        "visibility": "off"
			      }
			    ]
			  }
			];
		}else{
			map_styles = [];
		}
		
		if(jQuery('#sbd_all_location').length>0){
			
			map = new google.maps.Map(
			document.getElementById("sbd_all_location"), {
			  center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
			  zoom: parseInt(sld_variables.zoom),
			  mapTypeId: google.maps.MapTypeId.ROADMAP,
			  gestureHandling: 'cooperative',
			  styles: map_styles,
			  // styles: pd_snazzymap_js
			});
			if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
				map.setOptions({styles: pd_snazzymap_js});
			}
			geocoder = new google.maps.Geocoder();
			oms = new OverlappingMarkerSpiderfier(map, {
			  markersWontMove: true,
			  markersWontHide: true,
			  basicFormatEvents: true
			});
			myLoop();
			
		}
	}
}
function clearmarker(){
	if( typeof google !== 'undefined' ){
		for (var i = 0; i < markers.length; i++) {
		  markers[i].setMap(null);
		}
	}
}

function sbdradius_(){


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

	jQuery('#distance_no_result_found').remove();
	if( typeof google !== 'undefined' ){
		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 radiusi = jQuery('.sbd_distance:visible').val();

		var sbd_location_name = jQuery('.sbd_location_name').length;
		var sbd_distance = jQuery('.sbd_distance').length;
		
		// console.log(address); // var address = obj.attr('data-address');
		if( (cluster.distance_search == 'true') && ( address == undefined || address == '' ) ){
			alert(sld_variables.distance_location_text);
			return;
		}
		
		if( (cluster.distance_search == 'true') && ( 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){
			//google map code
			map = new google.maps.Map(
			document.getElementById("sbd_all_location"), {
				center: new google.maps.LatLng(parseInt(sld_variables.latitute), parseInt(sld_variables.longitute)),
				zoom: parseInt(sld_variables.zoom),
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				gestureHandling: 'cooperative'
			});
			if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
				map.setOptions({styles: pd_snazzymap_js});
			}
			oms = new OverlappingMarkerSpiderfier(map, {
			  markersWontMove: true,
			  markersWontHide: true,
			  basicFormatEvents: true
			});
		}
		var counter = 0;
		geocoder.geocode( { 'address': address}, function(results, status) {
			console.log(status);
			console.log(google.maps.GeocoderStatus.OK);
		  if (status == google.maps.GeocoderStatus.OK){
			  
			map.setCenter(results[0].geometry.location);
			var searchCenter = results[0].geometry.location;
			
			/*
			var marker = new google.maps.Marker({
				map: map,
				position: results[0].geometry.location
			});
			*/
			if (circle) circle.setMap(null);
			circle = new google.maps.Circle({center:searchCenter,
											radius: radius,

											strokeColor: sld_variables.radius_circle_color,
											strokeOpacity: 0.8,
											strokeWeight: 2,
											fillColor: sld_variables.radius_circle_color,
											fillOpacity: 0.35,

											map: map});

			clearmarker();
			markers=[];
			
			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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
					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.
					}
					
					if (google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latlng[0],latlng[1]),searchCenter) < radius) {
						
						var map_marker_id = jQuery(this).attr('id');
						var icon = markericon;
						if( markericon != '' ){
							icon = {
								url: markericon, // url
								scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
								origin: new google.maps.Point(0,0), // origin
								anchor: new google.maps.Point(0, 0) // anchor
							};
						}
						var marker = new google.maps.Marker({
							map: map,
							icon: icon,
							position:  new google.maps.LatLng(latlng[0],latlng[1]),
							title: title,
							animation: google.maps.Animation.DROP,
							address: address,
							url: url,
							mapSelectorID: map_marker_id
						});
						markers.push(marker);
						//infoWindow(marker, map, title, address, url, subtitle, imgurl, target);
						infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
						bounds.extend(marker.getPosition());
						
						if( sbd_map_fitbounds == 'on' ){
							map.fitBounds(bounds);
						}
						
						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++;
			/*if(counter<2){
				setTimeout(function(){
					sbdradius_();
				}, 1500);
			}*/
		  }
		});
		
	}	
	
	return;
}

function sbdclearradius_(){
	if( typeof google !== 'undefined' ){
		var obj = jQuery(this);
		jQuery('.sbd_location_name').val('');
		jQuery('.sbd_distance').val('');
		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, .qc-sbd-single-item-11, .qc-sld-masonary-15").each(function(){
			
			jQuery(this).show();
			
		});

		jQuery(".qc-grid-item ul li").each(function(){
			jQuery(this).show();
		})
		
		clearmarker();
		myLoop ();

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

var i = 0;                     

function myLoop () {
	if( typeof google !== 'undefined' ){
		markers = [];
		
		jQuery("#sbdopd-list-holder ul li").each(function(){
			var obj = jQuery(this);
			
			
			//https://www.google.com/maps/dir/?api=1&origin=Space+Needle+Seattle+WA&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling
			
			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://www.google.com/maps/dir/?api=1&origin=none&destination="+encodeURIComponent(obj.attr('data-address'))+"&travelmode=driving");
				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;
					if( markericon != '' ){
						icon = {
							url: markericon, // url
							scaledSize: new google.maps.Size(sbd_custom_marker_image_width, sbd_custom_marker_image_height), // scaled size
							origin: new google.maps.Point(0,0), // origin
							anchor: new google.maps.Point(0, 0) // anchor
						};
					}
				var marker = new google.maps.Marker({
					map: map,
					icon: icon,
					position:  new google.maps.LatLng(latlng[0],latlng[1]),
					title: title,
					animation: google.maps.Animation.DROP,
					address: address,
					url: url,
					mapSelectorID: map_marker_id
				});
				markers.push(marker);
				infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info);
				bounds.extend(marker.getPosition());
				if( sbd_map_fitbounds == 'on' ){
					map.fitBounds(bounds);
				}
				
				
			}
			
		})

		// zoomChangeBoundsListener = 
		//     new google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
		//         if ( this.getZoom() ){   // or set a minimum
		//             this.setZoom(parseInt(sld_variables.zoom));  // set zoom here
		//         }
		// });

		// setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);

		if(markers.length==1){
			setTimeout(function(){
				map.setZoom(parseInt(sld_variables.zoom));
			}, 100)
		}
		
		if(cluster.cluster){
			var markerCluster = new MarkerClusterer(map, markers,
	            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
		}
		var default_lat = sld_variables.latitute;
		var default_long = sld_variables.longitute;

		if( (default_lat > -90 && default_lat < 90) && (default_long > -180 && default_long < 180) ){
			map.setCenter(new google.maps.LatLng(default_lat, default_long));
		}
		/*for(var i=0;i<all_locations.length;i++){
			markerAddress(all_locations, i);
		}*/
	}
}


function infoWindow(marker, map, title, address, url, subtitle, imgurl, target, icons, custom_content, others_info) {
	if( typeof google !== 'undefined' ){
	    google.maps.event.addListener(marker, 'mouseover', function(){
			
			if (iw) {
				iw.close();
			}
			
			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 style='text-align: center;display:block;font-weight: bold;' href='" + url + "' "+ target +">"+sld_variables.view_details+"</a>";
			}
			html +="<div class='sbd_bottom_area_marker'>"+icons+"</div>";	
					
			html+="</div></div>";
					
	        
			
			iw = new google.maps.InfoWindow({
	            content: html,
	            maxWidth: 230,
	            disableAutoPan: disableAutoPan
				
				
	        });
	        marker.setAnimation(google.maps.Animation.BOUNCE);
			iw.setZIndex(9999);
	        iw.open(map, marker);
			
	    });

	    // For Mobile Click Issue closne the same of mouseover
	    google.maps.event.addListener(marker, 'click', function(){
			if (iw) {
				iw.close();
			}
			
			
			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 style='text-align: center;display:block;font-weight: bold;' href='" + url + "' "+ target +">"+sld_variables.view_details+"</a>";
			}
			html +="<div class='sbd_bottom_area_marker'>"+icons+"</div>";	
					
			html+="</div></div>";
					
	        
			
			iw = new google.maps.InfoWindow({
	            content: html,
	            maxWidth: 230,
	            disableAutoPan: disableAutoPan
				
				
	        });
	        marker.setAnimation(null);
	        // marker.setAnimation(google.maps.Animation.BOUNCE);
			iw.setZIndex(9999);
	        iw.open(map, marker);
			
	    });

	    google.maps.event.addListener(marker, 'mouseout', function(){
	    	// iw.close();
	    	marker.setAnimation(null);
	    });
		oms.addMarker(marker);
	}
}

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

	$('.sbd_location_name').focus(function(){
		$('.sbd_current_location').show();
	})
	
	$('.sbd_location_name').blur(function(){
		setTimeout(function(){
			$('.sbd_current_location').hide();
		},400)
		
	})
	
	$(document).on('click','.sbd_current_location', function(e){
		if( typeof google !== 'undefined' ){
			if (navigator.geolocation){
			  navigator.geolocation.getCurrentPosition(showPosition);
			}
			else{
			  console.log('Geolocation is not supported by this browser.');
			}

			function showPosition(position){

				var geocoder = new google.maps.Geocoder();
				var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

			 if (geocoder) {
				geocoder.geocode({ 'latLng': latLng}, function (results, status) {
				   if (status == google.maps.GeocoderStatus.OK) {
					 console.log(results[0].formatted_address); 
					 $('.sbd_location_name').val(results[0].formatted_address);
				   }
				   else {
					console.log("Geocoding failed: " + status);
				   }
				}); //geocoder.geocode()
			  }      
			} //showPosition
		}
		
	})

	
	$(document).on('click', "#sbd_generate", function(e){
		var objc = $(this);
		
			
			if($('#sbd_item_link').val()!=''){
				var html = "<div id='sbd_ajax_preloader'><div class='sbd_ajax_loader'></div></div>";
				$('body').append(html);
				$.post(ajaxurl, {
				action: 'qcpd_generate_text', 
				url: $('#sbd_item_link').val(),
				},
				function(data) {
					
					$('#sbd_ajax_preloader').remove();
					var data = JSON.parse(data);
					$('#sbd_title').val(data.title)
					$('#sbd_subtitle').val(data.description)
					
				});
				
			}else{
				alert('Item link field cannot left empty!');
			}

		
	})
	
	$( ".sbd_filter_toggle" ).click(function() {
	  $( ".sbd_filter_parent" ).slideToggle( "fast", function() {
		// Animation complete.
	  });
	});
	
	
	
	$("body").on('focus', ".sbd_location_name", function(e){
		
		var objc = $(this);
		var input = document.getElementById(objc.attr('id'));
		if( typeof google !== 'undefined' ){
			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();
					
					objc.closest('.cmb_metabox').find('#qcpd_item_latitude input').val(latitude);
					objc.closest('.cmb_metabox').find('#qcpd_item_longitude input').val(longitude);

				})*/
				
			})
		}
	})
	$(document).on('click','#pd_tag_select', function(){
		$('#'+$('#pd-tags').attr('data')).val($('#pdtagvalue').val());
		$('#fa-field-modal-tag').remove();
	})
	
	/*$(document).on('click', '#item_tags', function(e){
		var elem = $(this);
		var elemid = this.id;
		$.post(ajaxurl, {
			action: 'qcpd_tag_pd_page', 
			
			},
			
		function(data) {
			
			$('#main-footer').append(data);
			$('#pdtagvalue').val(elem.val());
			$('#pd-tags').attr('data', elemid);
			
			//console.log($(data).find('.fa-field-modal-title').text());

			$('#pd-tags').tagInput();
			$('.labelinput').focus();
			$.post(ajaxurl, {
			action: 'qcpd_search_pd_tags', 
			},
			
			function(data) {
				console.log(data);
				
				$('.labelinput').autocomplete({
					  source: data.split(','),
					  
				});					
				
			});
				

			
		});
		
	})*/


	
	
	
})



jQuery('.sbd-single-item-map').each(function(){
	if( typeof google !== 'undefined' ){
		var item_id=jQuery(this).attr('id');
		sbd_single_item_initMap(item_id);
	}
});
 function sbd_single_item_initMap(map_id) {
 	// jQuery('#'+map_id).height('400px');
 	var latitude = parseFloat(jQuery('#'+map_id).siblings('.sbd-single-item').attr('data-latitude'));
 	var longitude = parseFloat(jQuery('#'+map_id).siblings('.sbd-single-item').attr('data-longitude'));
    var uluru = {lat: latitude, lng: longitude};
    var map = new google.maps.Map(document.getElementById(map_id), {
      zoom: parseInt(sld_variables.zoom),
      center: uluru
    });

    if( (typeof pd_snazzymap_js === "object" || typeof pd_snazzymap_js === 'function') && (pd_snazzymap_js !== null) ){
		map.setOptions({styles: pd_snazzymap_js});
	}

    var contentString = '<div class="sbd-single-item-infoWindow">'+jQuery('#'+map_id).siblings('.sbd-single-item').html()+'</div>';
    var map_title = jQuery('#'+map_id).siblings('.sbd-single-item').find('.sbd-single-item-title').text();

    var infowindow = new google.maps.InfoWindow({
      content: contentString,
      disableAutoPan: disableAutoPan
    });

    var marker = new google.maps.Marker({
      position: uluru,
      map: map,
      title: map_title
    });
    marker.addListener('click', function() {
      infowindow.open(map, marker);
    });
    infowindow.open(map, marker);
}


//Validation for Latitude and Longitude on admin edit post
jQuery(document).ready(function(){
	if( typeof google !== 'undefined' ){
		jQuery("body").on('keyup focusout keypress', "input[name*='[qcpd_item_latitude]']", function(e){
			var val = jQuery(this).val();
			var error = 0;
			var error_code = '';

			if( val.trim() ){
				if( !jQuery(this).parent('.field-item').next().hasClass('sbd_error_field') ){
					jQuery(this).parent('.field-item').after('<p class="sbd_error_field"></p>');
				}
				if( isNaN(val) ){
					error = 1;
					error_code = 'NaN';
				}
				if( error == 1 && error_code == 'NaN' ){

				}else{
					if( val > -90 && val < 90 ){
						//console.log('latitude is valid');
					}else{
						error = 1;
						error_code = 'invalid_lat';
					}
				}
				if( error == 1 ){
					console.log(error_code);
					jQuery(this).parent('.field-item').next('.sbd_error_field').html('Please enter a valid Latitude');
					jQuery(this).parents('form#post').attr('onsubmit', 'return false');
					jQuery(this).parents('form#post').find('#publish').attr('disabled', true);
				}
			}
			if( error == 0 ){
				jQuery(this).parent('.field-item').next('.sbd_error_field').remove();
				if( !jQuery("input[name*='[qcpd_item_longitude]']").parent('.field-item').next().hasClass('sbd_error_field') ){			
					jQuery(this).parents('form#post').removeAttr('onsubmit');
					jQuery(this).parents('form#post').find('#publish').removeAttr('disabled').removeClass('disabled');
				}
			}
		});

		jQuery("body").on('keyup focusout keypress', "input[name*='[qcpd_item_longitude]']", function(e){
			var val = jQuery(this).val();
			var error = 0;
			var error_code = '';

			if( val.trim() ){
				if( !jQuery(this).parent('.field-item').next().hasClass('sbd_error_field') ){
					jQuery(this).parent('.field-item').after('<p class="sbd_error_field"></p>');
				}
				if( isNaN(val) ){
					error = 1;
					error_code = 'NaN';
				}
				if( error == 1 && error_code == 'NaN' ){

				}else{
					if( val > -180 && val < 180 ){
						//console.log('longitude is valid');
					}else{
						error = 1;
						error_code = 'invalid_long';
					}
				}
				if( error == 1 ){
					console.log(error_code);
					jQuery(this).parent('.field-item').next('.sbd_error_field').html('Please enter a valid Longitude');
					jQuery(this).parents('form#post').attr('onsubmit', 'return false');
					jQuery(this).parents('form#post').find('#publish').attr('disabled', true);
				}
			}
			if( error == 0){
				jQuery(this).parent('.field-item').next('.sbd_error_field').remove();
				if( !jQuery("input[name*='[qcpd_item_latitude]']").parent('.field-item').next().hasClass('sbd_error_field') ){
					jQuery(this).parents('form#post').removeAttr('onsubmit');
					jQuery(this).parents('form#post').find('#publish').removeAttr('disabled').removeClass('disabled');
				}
			}
		});

		jQuery('.sbd-frontend-submission-form').on('submit', function(e){
			var lat_error = 0;
			var lat_error_code = '';

			var long_error = 0;
			var long_error_code = '';

			var latitude = jQuery(this).find('input[name="item_latitude"]').val();
			var longitude = jQuery(this).find('input[name="item_longitude"]').val();
			if( latitude > -90 && latitude < 90 ){
				//console.log('latitude is valid');
			}else{
				lat_error = 1;
				lat_error_code = 'invalid_lat';
			}

			if( longitude > -180 && longitude < 180 ){
				//console.log('longitude is valid');
			}else{
				long_error = 1;
				long_error_code = 'invalid_long';
			}

			if( !latitude  ){
				lat_error = 1;
				lat_error_code = 'invalid_lat';
			}

			if( !longitude  ){
				long_error = 1;
				long_error_code = 'invalid_long';
			}

			if(  lat_error == 1 || long_error == 1  ){
				if( jQuery(this).find('input[name="item_latitude"]').siblings('label').find('.pd_required').length > 0 ){
					if( lat_error_code == 'invalid_lat' ){
						e.preventDefault();
						alert("Invalid Latitude. Please Enter a valid Latitude");
					}
				}
				if( jQuery(this).find('input[name="item_longitude"]').siblings('label').find('.pd_required').length > 0 ){
					if( long_error_code == 'invalid_long' ){
						e.preventDefault();
						alert("Invalid Longitude. Please Enter a valid Longitude");
					}
				}
			}
		});
	}
});
	
jQuery('.qc-grid-item ul li a:first-of-type').on('mouseover mousemove', function(){
	if( typeof google !== 'undefined' && cluster.map == 'true'  && cluster.map_marker_scroll == 'true' ){
		var selectorID = jQuery(this).parent('li').attr('id');
		SBDselectMarker( selectorID, 'start');
	}
});

jQuery('.qc-grid-item ul li a:first-of-type').on('mouseout', function(){
	if( typeof google !== 'undefined' && cluster.map == 'true' && cluster.map_marker_scroll == 'true' ){
		var selectorID = jQuery(this).parent('li').attr('id');
		SBDselectMarker( selectorID, 'stop');
	}
});

function SBDselectMarker(mapSelectorID, status) {
	if( typeof google !== 'undefined' ){
	  var i, len, map_marker;

	  // Find the correct map_marker to change based on the storeId.
	  for (i = 0; i < markers.length; i++) {
	    if (markers[i].mapSelectorID == mapSelectorID) {
	      map_marker = markers[i];
	      if (status == "start") {
	        map_marker.setAnimation(google.maps.Animation.BOUNCE);
	        google.maps.event.trigger(map_marker, 'mouseover');
	        // map.setCenter(map_marker.getPosition());
	      } else {
	        map_marker.setAnimation(null);
	        // iw.close();
	      }
	    }
	  }
  	}
}


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

	});
});



