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

	if(localStorage.getItem("qcld_google_maponly_undefined_check") != 1 && sld_variables.map_privacy_policies == 'on' ){
	//var google = undefined;
		jQuery('#sbd_maponly_container').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_maponly_container').hide();
	}

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

		localStorage.setItem("qcld_google_maponly_undefined_check", 1);
		location.reload(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);
	}
	

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

var mapCreate_mapOnly = null;
var markerClusters;
var maplatlang;
var sbd_map_fitbounds = sld_variables.sbd_map_fitbounds;

var lat = parseInt(sld_variables.latitute);
var lon = parseInt(sld_variables.longitute);

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

	mapCreate_mapOnly = L.map('sbd_maponly_container').setView([sld_variables.latitute, sld_variables.longitute], parseInt(sld_variables.zoom));
	markerClusters = L.markerClusterGroup(); 


	var minZoomVal = 2; 

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

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

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


 	if(document.getElementById("sbd_maponly_container")!==null){
		mymapLoop(all_items);
	}

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

}


function mapinitialize() {
	
	mymapLoop(all_items);	
	
}               

function mymapLoop (items) {
	
	mapmarkers = [];
	
	items.forEach(function(item) {
		//console.log(item);
		if(item.latitude!=''){
			
			var markericon = '';
			if(sld_variables_maponly.global_marker!=''){
				markericon = sld_variables_maponly.global_marker;
			}
			if(typeof(item.paid)!='undefined' && item.paid!=''){
				markericon = sld_variables_maponly.paid_marker_default; //default paid marker
				if(sld_variables_maponly.paid_marker!=''){
					markericon = sld_variables_maponly.paid_marker; // If paid marker is set then override the default
				}
			}

			if(typeof(item.markericon)!='undefined' && item.markericon!=''){
				markericon = item.markericon; // If icon is set in the item it self. Most priority.
			}
			
			var icon = markericon;
			
			
			icon_html = "";
			if(item.item_details_page!=''){
				icon_html +='<p><a href="'+item.item_details_page+'"><i class="fa fa-external-link-square fa-external-link-square-alt"></i></a></p>';
			}
			if(item.phone!=''){
				icon_html +='<p><a href="tel:'+item.phone+'"><i class="fa fa-phone"></i></a></p>';
			}
			if(item.link!=''){
				icon_html +='<p><a href="'+item.link+'" target="_blank"><i class="fa fa-link"></i></a></p>';
			}
			if(item.facebook!=''){
				icon_html +='<p><a target="_blank" href="'+item.facebook+'"><i class="fa fa-facebook"></i></a></p>';
			}
			if(item.yelp!=''){
				icon_html +='<p><a target="_blank" href="'+item.yelp+'"><i class="fa fa-yelp"></i></a></p>';
			}
			if(item.email!=''){
				icon_html +='<p><a href="mailto:'+item.email+'"><i class="fa fa-envelope"></i></a></p>';
			}
			if(item.linkedin!=''){
				icon_html +='<p><a target="_blank" href="'+item.linkedin+'"><i class="fa fa-linkedin-square fa-linkedin"></i></a></p>';
			}
			if(item.twitter!=''){
				icon_html +='<p><a target="_blank" href="'+item.twitter+'"><i class="fa fa-twitter-square"></i></a></p>';
			}
			if(item.custom_body_icon!=''){
				icon_html +=item.custom_body_icon;
			}
			
			var others_info = '';
			if(item.location!=''){
				others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+item.location+"</p>";
			}
			if(item.phone!=''){
				others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+item.phone+"</p>";
			}
			if(item.business!=''){
				others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+item.business+"</p>";
			}
			if(item.custom_body_content!=''){
				others_info +=item.custom_body_content;
			}
			

			maplatlang = mapinfoWindow(marker, map, item.title, item.fulladdress, item.link, item.subtitle, item.image, icon_html, others_info);

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

				if( icon != '' ){

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

					var marker = L.marker([ item.latitude, item.longitude ],{title:item.map_marker_id, icon: myIcon } ); 

				}else{

					var marker = L.marker([ item.latitude, item.longitude ],{title:item.map_marker_id} ); 
				}

				if( sld_variables_maponly.cluster == true ){
 
					marker.addTo(mapCreate_mapOnly).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).openPopup();
					
				}else{

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

				var isClicked = false;

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

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


				    },
				    
				});

			/*
			var group = new L.featureGroup(markers);
			mapCreate_mapOnly.fitBounds(group.getBounds().pad(1));

			if( sbd_map_fitbounds != 'on' ){
				mapCreate_mapOnly.setZoom(parseInt(sld_variables.zoom));
			}
			*/

			if( sbd_map_fitbounds == 'on' ){

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

			}else{

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

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


		}
		
	});
	

}

function mapinfoWindow(marker, map, title, address, url, subtitle, imgurl='', icons, others_info){
    // google.maps.event.addListener(marker, 'click', function () {
		var contentString = "<div>";
		
		if(imgurl!='' && !sld_variables_maponly.image_infowindow){
			contentString += "<div class='sbd_pop_img'><img src='"+imgurl+"' /></div>";
		}
		
        contentString += "<div class='sbd_pop_text'><h3>" + title + "</h3><p>" + subtitle + "</p>";
		
		if(address!=''){
			contentString+="<p><b><i class='fa fa-map-marker fa-map-marker-alt' aria-hidden='true'></i> </b>" + address + "</p>";
		}
		if(others_info!=''){
			contentString+=others_info;
		}
		
        /*if(url!='' && url.length > 2){
			contentString +="<a href='" + url + "' target='_blank'>View Site</a></div></div>"
		}*/
		
		contentString +="</div></div>"
		contentString +="<div class='sbd_bottom_area_marker'>"+icons+"</div>";
		
		contentString+="</div></div>";

	return contentString;
}

function clearmarker(){

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

}

function sbdradius_(){
}

jQuery('.sbd_radius_find').on('click',function(){
	//alert('working');
	//console.log('working con');
	var address = jQuery('.sbd_location_name:visible').val();
	var data_lat = jQuery('.sbd_location_name:visible').attr('data-lat');
	var data_lang = jQuery('.sbd_location_name:visible').attr('data-lon');
	var radiusi = jQuery('.sbd_distance:visible').val();
	
	if(address==''){
		alert(sld_variables.distance_location_text);
		return;
	}
	
	if(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;
	

	//geocoder.geocode( { 'address': address}, function(results, status) {
	if (data_lat !==null && data_lang !==null  ){
		  

		if (mapCreate_mapOnly.hasLayer(circle)) mapCreate_mapOnly.removeLayer(circle);

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

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

		clearmarker();
		
		all_items.forEach(function(item){
			if(item.latitude!=''){
				//if (google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(item.latitude,item.longitude),searchCenter) < radius) {
					
					var markericon = '';
					if(sld_variables_maponly.global_marker!=''){
						markericon = sld_variables_maponly.global_marker;
					}
					if(typeof(item.paid)!='undefined' && item.paid!=''){
						markericon = sld_variables_maponly.paid_marker_default; //default paid marker
						if(sld_variables_maponly.paid_marker!=''){
							markericon = sld_variables_maponly.paid_marker; // If paid marker is set then override the default
						}
					}

					if(typeof(item.markericon)!='undefined' && item.markericon!=''){
						markericon = item.markericon; // If icon is set in the item it self. Most priority.
					}
					var icon = markericon;
					
					icon_html = "";
					if(item.item_details_page!=''){
						icon_html +='<p><a href="'+item.item_details_page+'"><i class="fa fa-external-link-square fa-external-link-square-alt"></i></a></p>';
					}
					if(item.phone!=''){
						icon_html +='<p><a href="tel:'+item.phone+'"><i class="fa fa-phone"></i></a></p>';
					}
					if(item.link!=''){
						icon_html +='<p><a href="'+item.link+'" target="_blank"><i class="fa fa-link"></i></a></p>';
					}
					if(item.facebook!=''){
						icon_html +='<p><a target="_blank" href="'+item.facebook+'"><i class="fa fa-facebook"></i></a></p>';
					}
					if(item.yelp!=''){
						icon_html +='<p><a target="_blank" href="'+item.yelp+'"><i class="fa fa-yelp"></i></a></p>';
					}
					if(item.email!=''){
						icon_html +='<p><a href="mailto:'+item.email+'"><i class="fa fa-envelope"></i></a></p>';
					}
					if(item.linkedin!=''){
						icon_html +='<p><a target="_blank" href="'+item.linkedin+'"><i class="fa fa-linkedin-square fa-linkedin"></i></a></p>';
					}
					if(item.twitter!=''){
						icon_html +='<p><a target="_blank" href="'+item.twitter+'"><i class="fa fa-twitter-square"></i></a></p>';
					}
					if(item.custom_body_icon!=''){
						icon_html +=item.custom_body_icon;
					}
			
					var others_info = '';
					if(item.location!=''){
						others_info +="<p><b><i class='fa fa-location-arrow' aria-hidden='true'></i> </b>"+item.location+"</p>";
					}
					if(item.phone!=''){
						others_info +="<p><b><i class='fa fa-phone' aria-hidden='true'></i> </b>"+item.phone+"</p>";
					}
					if(item.business!=''){
						others_info +="<p><b><i class='fa fa-clock-o fa-clock' aria-hidden='true'></i> </b>"+item.business+"</p>";
					}
					if(item.custom_body_content!=''){
						others_info +=item.custom_body_content;
					}

					let circleCenter = circle.getLatLng();

					maplatlang = mapinfoWindow(marker, map, item.title, item.fulladdress, item.link, item.subtitle, item.image, icon_html, others_info);

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

					if( icon != '' ){

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

						var marker = L.marker([ item.latitude, item.longitude ],{title:item.map_marker_id, icon: myIcon } ); 

					}else{

						var marker = L.marker([ item.latitude, item.longitude ],{title:item.map_marker_id} ); 
					}
					
					let markerPos = marker.getLatLng();

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

						if( sld_variables_maponly.cluster == true ){
		 
							marker.addTo(mapCreate_mapOnly).bindPopup(maplatlang, {closeOnClick: true, autoClose: true, showOnMouseOver: true, autoPan:false} ).closePopup();
							
						}else{

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

						}

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


							var isClicked = false;

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

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


							    },
							    
							});

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

						mapCreate_mapOnly.setView(circleCenter);
						
						
					}

    				
				
			}
				
		})
		
		//map.fitBounds(circle.getBounds());
		
	  } else {
		console.log('Geocode was not successful for the following reason: ' + status);
		setTimeout(function(){
			sbdradius_();
		}, 1500);
	  }


});
function sbdclearradius_(){
}
jQuery('.sbd_radius_clear').on('click', function(){
	
	if (circle != undefined) {
      mapCreate_mapOnly.removeLayer(circle);
    }
	clearmarker();
	mapinitialize();
});


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

	var filterName = $(this).attr("data-filter");
	//constructing new array out of the main array.
	var filterarray = [];
	all_items.forEach(function(item) {
		if(filterName==item.filter){
			filterarray.push(item);
		}
	})

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

    if( filterName == "all" ){
        
		mymapLoop(all_items);
		
    }else{

		mymapLoop(filterarray);
	}
	



})

	//search directory items
	$(".pd_maponly_search_filter").keyup(function(){

		clearmarker();
 
        // Retrieve the input field text and reset the count to zero
        var filter = $(this).val(), count = 0;
        
		//constructing new array out of the main array.
		var filterarray = [];
		all_items.forEach(function(item) {
			if(item.searchcontent.search(new RegExp(filter, "i")) >= 0){
				filterarray.push(item);
			}
		})
		mymapLoop(filterarray);
 
    });
	
	//tag filter functionality
	$(document).on("click",".sbd-tag-filter-area a", function(event){
		
		event.preventDefault();

		clearmarker();

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

		//constructing new array out of the main array.
		var filterarray = [];
		all_items.forEach(function(item) {
			if(item.tags.search(new RegExp(filter, "i")) >= 0){
				filterarray.push(item);
			}
		})
		mymapLoop(filterarray);
		

	})


});
