
var targetMarker=1;
var drawnItems = new L.FeatureGroup();
 var drawControl;   
 var mapstatus=0;
 var showTimeline=0;
 var time_selected=-1;
 
var previousData='';
 var oms;
 var prData= [];
 
    var ws;

function connect()
{
	 ws = new WebSocket('wss://ws.landingtutorial.com:6060?code='+$('#mapcode').val()+'&clientSide=1&og=1');
					  
	  ws.onopen = () => {
		
		console.log("Connected");
	  }
	  ws.onmessage = (message) => {
		  
		
		  
		  try{
			  var data=JSON.parse(message.data);
			  console.log(data);
			  update(data);
			
		  }catch(err){console.log(err);}
	  }
     ws.onclose = function(e) {
		console.log('Socket is closed. Reconnect will be attempted in 1 second.', e.reason);
		setTimeout(function() {
		  connect();
		}, 1000);
    };
}

function init () { // eslint-disable-line no-unused-vars


	connect();
	
	 setTimeout(function() {
		  location.reload();
		}, 120000);
	

  newheight=$("#dropmap_list").height()-( $(document).height()-$(window).height());

	if (newheight<200)
		newheight=200;

$("#dropmap_list").height(newheight);



  
 /* if ( (typeof $("#mapversion").val() === "undefined" ) )
	{
		showLogin();
		return;
	}
  */
  
  var img = [
    8192, // original width of image
    8192 // original height of image
  ]

  // create the map
  map = L.map('map', {minZoom: 1, maxZoom : 6,zoomSnap:0.05})
  // assign map and image dimensions
   rc = new L.RasterCoords(map, img)
  map.setView(rc.unproject([img[0] / 2, img[1] / 2]), map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false))

 oms = new OverlappingMarkerSpiderfier(map );

	var popup = new L.Popup();
	oms.addListener('click', function(marker) {
	  popup.setContent(marker.desc);
	  popup.setLatLng(marker.getLatLng());
	  map.openPopup(popup);
	  console.log("YOP");
	});

  // set marker at the image bound edges
  layerBounds = L.layerGroup([
  ])
  map.addLayer(layerBounds)


	
  
 sidebar = L.control.sidebar({ container: 'sidebar' });//.addTo(map);
     map.addLayer(drawnItems);
      drawControl = new L.Control.Draw({
         edit: {
             featureGroup: drawnItems
         },
		  draw : {
			marker: {
			  icon:  blue_pointer
			},
		  },

     });
    // map.addControl(drawControl);
	 
	 
	 
	 
	  map.on(L.Draw.Event.CREATED, function (event) {
        var layer = event.layer;

			event.layer.options.color = $('#ucolor').val();
			event.layer.options.weight =5;
			event.layer.options.fillOpacity=0.4;
			
			drawnItems.eachLayer(function(layer) {
				if (layer.layerID == $('#uid').val()) {
					drawnItems.removeLayer(layer);
					try{oms.removeMarker(layer);}catch(err){};														
										
				}
				if (layer.layerID == "icon_"+$('#uid').val()) {
					drawnItems.removeLayer(layer);
					try{oms.removeMarker(layer);}catch(err){};														
										
				}
				
				
			});

		 layer.layerID= $('#uid').val();
		
        drawnItems.addLayer(layer);
		//popupContent="<span class='player_name_tooltip' >"+$("#uname").val()+"</span>";
		//layer.bindTooltip(popupContent);
		//alert(typeof layer.getCenter);
		centerx=0;
		centery=0;
		
		if (typeof layer.getCenter === 'function')
		{
		
			 if (($('#uav').val()!=null) && ($('#uav').val()!="")&& ($('#uav').val()!="default")&& ($('#uav').val()!="null"))
				url=$('#uav').val();
			//	url='https://cdn.discordapp.com/avatars/'+$('#uid').val()+'/'+$('#uav').val()+'.jpeg';
			else
				url='img/default_spot.png';
			var myIcon = L.divIcon({iconAnchor:   [24, 24],tooltipAnchor :  [24, 0],zIndexOffset:1000,className: 'my-div-icon',html:'<img  style="position:absolute;display:block;z-index:1010;border: 4px solid '+$('#ucolor').val()+';border-radius: 50%;width:40px;height:40px" src="'+url+'"/>'});

			var polygon1 = L.marker(layer.getCenter(),{icon:myIcon});
			polygon1.layerID = "icon_"+$('#uid').val();
			polygon1.on('click', function(e) {playerid=$(this)[0].layerID.replace("icon_","");$("#click_user_"+playerid).click();});
			
			drawnItems.addLayer(polygon1);
			oms.addMarker(polygon1);			
			
			center=rc.project(layer.getCenter());
			
			
			
		}
		else{
			
	
			center=rc.project(layer.getLatLng());
		}
	
		
		var shape = layer.toGeoJSON()
		var shape_for_db = JSON.stringify(shape);
		
		$.ajax('hooks/adddropspot.php?status=1&data='+JSON.stringify(shape)+'&mapid='+$('#mapcode').val()+"&userid="+$('#uid').val()+"&centerx="+parseFloat(center.x/8192.0)+"&centery="+parseFloat(center.y/8192.0)+"&loggedin="+$("#mapversion").val(), // request url
			{
			dataType: 'json',
			success: function (data, status, xhr) {// success callback function
			
		
			
			
			}
		});		
				
				
		
		});
		
		map.on('resize', function (e) {
		
		
				map.setMinZoom( map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false) );
		});

		
  
	map.on('draw:deleted', function (e) {
         var layers = e.layers;
         layers.eachLayer(function (layer) {
             //do whatever you want; most likely save back to db
			 
			 var shape = layer.toGeoJSON()
			 var shape_for_db = JSON.stringify(shape);
				console.log(shape_for_db);
         });
     });
 




	showNames();
  
// SideBar

  // the tile layer containing the image generated with gdal2tiles --leaflet ...
  L.tileLayer('./'+tiles_location_scrims+'/{z}/{x}/{y}.png?version=365642', {
    noWrap: true,
    attribution: '<a href="landingtutorial.com/home">landingtutorial.com</a>'
  }).addTo(map)
	
    
	$('.leaflet-control-attribution').html('').hide();
   



	map.setMinZoom( map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false));
	map.setZoom( map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false));
	
	
	$(window).resize(function () {
		
		newheight=$("#dropmap_list").height()-( $(document).height()-$(window).height());


		if (newheight<200)
				newheight=200;

		$("#dropmap_list").height(newheight);
		
		
			map.setMinZoom( map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false));
		
		   $('.ui-dialog:not(#sharedialog)').css({
				'width': $(window).width(),
				'height': $(window).height(),
				'left': '0px',
				'top':'0px'
		   });
		   
		   
	$( ".leaflet-control-zoom").html("");
	
		 //  $("#page").css({'height': $(window).height()*0.9});
		   $( "#waitdialog" ).css("height", $( "#map" ).css("height"));	   
			$( "#waitdialog" ).css("width", $( "#map" ).css("width"));	   
			$( "#waitdialog" ).css("top", $( "#page" ).css("margin-top"));
		
		 map.invalidateSize(true);
		 
		  if ($("#settingSpots").val()==1)
			initSpots();
		 
}).resize();

	//listDropMaps();
	$('.blue_pointer').hide();
	$("#bottom_button").hide();	

   map.invalidateSize(true);
   
   
   var table = $("#player_table").stupidtable();
	table.bind('aftertablesort', function (event, data) {
    // data.column - the index of the column sorted after a click
    // data.direction - the sorting direction (either asc or desc)
    // data.$th - the th element (in jQuery wrapper)
    // $(this) - this table object
	$("#table_direction").val(data.direction);
    $("#table_column").val(data.column);
    console.log("The sorting direction: " + data.direction);
    console.log("The column index: " + data.column);
	});
   //update();
   updatePR();
 

 
   
   
$("#icon2").attr("onclick","window.location.replace(\"https://landingtutorial.com\");");


}

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}
var drawtool=0;


jQuery.expr[':'].focus = function( elem ) {
  return elem === document.activeElement && ( elem.type || elem.href );
};

function update(data)
{
	
	try{
							total_players=0;
							marked_players=0;
							admin=0;
							 hasPR=0;
							
							$("#dropmap_list").html("");
							var menulist="";
							
							//if (!$("#maptitle").is(":focus")) {
							  $("#topmap_title").html(data['map']['name']);
							 
							  
							  
							//}
							
							var returnedsId = [];
							for ( i=0;i<data['mapitems'].length;i++)
							{
								total_players++;
								
								if (data['mapitems'][i]['data']!="")
									marked_players++;
						
								if (data['map']['usecolor_player']==0)
									data['mapitems'][i]['color']="cb273b";
						
									
								
								returnedsId.push(data['mapitems'][i]['discordid']);
								done=0;
								drawnItems.eachLayer(function(layer) {
									if (layer.layerID == data['mapitems'][i]['discordid']) {
										
										if ( data['mapitems'][i]['status']==0  )
										{
											drawnItems.eachLayer(function(layer1) {
												if (layer1.layerID == "icon_"+data['mapitems'][i]['discordid']) {
													drawnItems.removeLayer(layer1);
													try{oms.removeMarker(layer1);}catch(err){};														
										
												}
											});
											
											drawnItems.removeLayer(layer);
											try{oms.removeMarker(layer);}catch(err){};														
										
											done=1;
										}
										else
										{
											if (data['mapitems'][i]['data']!="")
											{
												if (data['map']['usecolor_player']==0)
													data['mapitems'][i]['color']="cb273b";
						
												var shape = layer.toGeoJSON()
												var shape_for_db = JSON.stringify(shape);
												if (JSON.stringify( layer.toGeoJSON()) != data['mapitems'][i]['data'] )
												{
													drawnItems.eachLayer(function(layer1) {
															if (layer1.layerID == "icon_"+data['mapitems'][i]['discordid']) {
																drawnItems.removeLayer(layer1);
																try{oms.removeMarker(layer1);}catch(err){};														
										
															}
														});
													drawnItems.removeLayer(layer);
													try{oms.removeMarker(layer);}catch(err){};														
										
													try{
													json=JSON.parse(data['mapitems'][i]['data']);
													if (json.geometry.type=='Point')
													  {
														 
														  var coords=json.geometry.coordinates[0];
														  
														  if ((data['mapitems'][i]['avatar']!=null) && (data['mapitems'][i]['avatar']!="")&& (data['mapitems'][i]['avatar']!="null"))
																url=data['mapitems'][i]['avatar'];
															//	url='https://cdn.discordapp.com/avatars/'+data['mapitems'][i]['discordid']+'/'+data['mapitems'][i]['avatar']+'.jpeg';
															else
																url='img/default_spot.png';

															
														
															var html_txt='<div style="text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;position:absolute;left:-20px;font-family: \'Evogria\', sans-serif; top:24px;z-index:1011;width:80px;height:24px;font-size: 10pt; font-family: \'Evogria\', sans-serif;background-color:rgba(0,0,0,0.1);color:#FFFFFF;white-space: nowrap;display:inline-block;padding-left:4px;padding-right:4px;">'+data['mapitems'][i]['name']+'</div>';
															var myIcon = L.divIcon({iconAnchor:   [24, 24],tooltipAnchor :  [24, 0],zIndexOffset:1000,className: 'my-div-icon',html:html_txt+'<img  style="position:absolute;display:block;z-index:1010;border: 4px solid #'+data['mapitems'][i]['color']+';border-radius: 50%;width:40px;height:40px" src="'+url+'"/>'});
	
														  
														var polygon = L.marker([json.geometry.coordinates[1],json.geometry.coordinates[0]],{icon:myIcon});
														polygon.layerID = data['mapitems'][i]['discordid'];
														polygon.on('click', function(e) {playerid=$(this)[0].layerID.replace("icon_","");$("#click_user_"+playerid).click();});
			
														drawnItems.addLayer(polygon);
														oms.addMarker(polygon);
														
														//popupContent="<span class='player_name_tooltip' >"+data['mapitems'][i]['name']+"</span>";
														
														//if (admin==1)
														//	popupContent="<span class='player_name_tooltip' >"+data['mapitems'][i]['name']+"<br>#"+data['mapitems'][i]['discordid']+"</span>";
														
														//polygon.bindTooltip(popupContent);
														//if (admin==1)
														//	polygon.bindPopup(popupContent)
													  }
													  else
													  {
														 
														var coords=json.geometry.coordinates[0];
														var latLong = [];
														for (j=0;j<coords.length;j++)
															latLong.push([coords[j][1],coords[j][0]]);
														var polygon = L.polygon(latLong);
														
														polygon.options.color = "#"+data['mapitems'][i]['color'];
														polygon.options.weight =3;
														polygon.options.fillOpacity=0.4;
														
														polygon.layerID = data['mapitems'][i]['discordid'];
														drawnItems.addLayer(polygon);
														//popupContent="<span class='player_name_tooltip' >"+data['mapitems'][i]['name']+"</span>";
														
														 if ((data['mapitems'][i]['avatar']!=null) && (data['mapitems'][i]['avatar']!="")&& (data['mapitems'][i]['avatar']!="null"))
															url=data['mapitems'][i]['avatar'];
															//url='https://cdn.discordapp.com/avatars/'+data['mapitems'][i]['discordid']+'/'+data['mapitems'][i]['avatar']+'.jpeg';
														else
															url='img/default_spot.png';
														var html_txt='<div style="text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;position:absolute;left:-20px;font-family: \'Evogria\', sans-serif; top:24px;z-index:1011;width:80px;height:24px;font-size: 10pt; font-family: \'Evogria\', sans-serif;background-color:rgba(0,0,0,0.1);color:#FFFFFF;white-space: nowrap;display:inline-block;padding-left:4px;padding-right:4px;">'+data['mapitems'][i]['name']+'</div>';
														var myIcon = L.divIcon({iconAnchor:   [24, 24],zIndexOffset:1000,tooltipAnchor :  [24, 0],className: 'my-div-icon',html:html_txt+'<img  style="position:absolute;display:block;z-index:1010;border: 2px solid #'+data['mapitems'][i]['color']+';border-radius: 50%;width:40px;height:40px" src="'+url+'"/>'});

														var polygon1 = L.marker(polygon.getCenter(),{icon:myIcon});
														polygon1.layerID = "icon_"+data['mapitems'][i]['discordid'];
														polygon1.on('click', function(e) {playerid=$(this)[0].layerID.replace("icon_","");$("#click_user_"+playerid).click();});
														//polygon1.bindTooltip(popupContent);
														oms.addMarker(polygon1);
														
														drawnItems.addLayer(polygon1);														
														
														
														
														
													  }
													  }catch(err){console.log(err);}
												}
											}
											done=1;
										}
									}
									
									
								  });
								  if (done==0)
								  {
									   if (data['mapitems'][i]['data']!="")
									   {
											if (data['map']['usecolor_player']==0)
												data['mapitems'][i]['color']="cb273b";
						
										  try{
											  json=JSON.parse(data['mapitems'][i]['data']);
											  if (json.geometry.type=='Point')
											  {
												
												  var coords=json.geometry.coordinates[0];
												  
												if ((data['mapitems'][i]['avatar']!=null) && (data['mapitems'][i]['avatar']!="")&& (data['mapitems'][i]['avatar']!="null"))
													url=data['mapitems'][i]['avatar'];
												//	url='https://cdn.discordapp.com/avatars/'+data['mapitems'][i]['discordid']+'/'+data['mapitems'][i]['avatar']+'.jpeg';
												else
													url='img/default_spot.png';

												var html_txt='<div style="text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;position:absolute;left:-20px;font-family: \'Evogria\', sans-serif; top:24px;z-index:1011;width:80px;height:24px;font-size: 10pt; font-family: \'Evogria\', sans-serif;background-color:rgba(0,0,0,0.1);color:#FFFFFF;white-space: nowrap;display:inline-block;padding-left:4px;padding-right:4px;">'+data['mapitems'][i]['name']+'</div>';
												var myIcon = L.divIcon({iconAnchor:   [24, 24],zIndexOffset:1000,tooltipAnchor :  [24, 0],className: 'my-div-icon',html:html_txt+'<img  style="position:absolute;display:block;z-index:1010;border: 4px solid #'+data['mapitems'][i]['color']+';border-radius: 50%;width:40px;height:40px" src="'+url+'"/>'});

												  
												var polygon = L.marker([json.geometry.coordinates[1],json.geometry.coordinates[0]],{icon:myIcon});
												polygon.layerID = data['mapitems'][i]['discordid'];
												polygon.on('click', function(e) {playerid=$(this)[0].layerID.replace("icon_","");$("#click_user_"+playerid).click();});
				
												drawnItems.addLayer(polygon);
												oms.addMarker(polygon);
												
												//popupContent="<span class='player_name_tooltip' >"+data['mapitems'][i]['name']+"</span>";
												//if (admin==1)
												//	popupContent="<span class='player_name_tooltip' >"+data['mapitems'][i]['name']+"<br>#"+data['mapitems'][i]['discordid']+"</span>";
												//if (admin==1)
												//	polygon.bindPopup(popupContent)
												//polygon.bindTooltip(popupContent);
											  }
											  else
											  {
												  
												var coords=json.geometry.coordinates[0];
												var latLong = [];
												for (j=0;j<coords.length;j++)
													latLong.push([coords[j][1],coords[j][0]]);
												var polygon = L.polygon(latLong);
												
												polygon.options.color = "#"+data['mapitems'][i]['color'];
												polygon.options.weight =3;
												polygon.options.fillOpacity=0.4;
												
												polygon.layerID = data['mapitems'][i]['discordid'];
												drawnItems.addLayer(polygon);
												//popupContent="<span class='player_name_tooltip' >"+data['mapitems'][i]['name']+"</span>";
												
												 if ((data['mapitems'][i]['avatar']!=null) && (data['mapitems'][i]['avatar']!="")&& (data['mapitems'][i]['avatar']!="null"))
													url=data['mapitems'][i]['avatar'];
												//	url='https://cdn.discordapp.com/avatars/'+data['mapitems'][i]['discordid']+'/'+data['mapitems'][i]['avatar']+'.jpeg';
												else
													url='img/default_spot.png';
												var html_txt='<div style="text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;position:absolute;left:-20px;font-family: \'Evogria\', sans-serif; top:24px;z-index:1011;width:80px;height:24px;font-size: 10pt; font-family: \'Evogria\', sans-serif;background-color:rgba(0,0,0,0.1);color:#FFFFFF;white-space: nowrap;display:inline-block;padding-left:4px;padding-right:4px;">'+data['mapitems'][i]['name']+'</div>';
												var myIcon = L.divIcon({iconAnchor:   [24, 24],tooltipAnchor :  [24, 0],zIndexOffset:1000,className: 'my-div-icon',html:html_txt+'<img  style="position:absolute;display:block;z-index:1010;border: 2px solid #'+data['mapitems'][i]['color']+';border-radius: 50%;width:40px;height:40px" src="'+url+'"/>'});

												var polygon1 = L.marker(polygon.getCenter(),{icon:myIcon});
												polygon1.layerID = "icon_"+data['mapitems'][i]['discordid'];
												polygon1.on('click', function(e) {playerid=$(this)[0].layerID.replace("icon_","");$("#click_user_"+playerid).click();});
												//polygon1.bindTooltip(popupContent);
												oms.addMarker(polygon1);
												drawnItems.addLayer(polygon1);			
												
												
											  }
										  }catch(err){console.log(err);}
									   }
								  }
								  
								// lock
	
								
								  
								// menu
								menulist+="<tr class='list_item ";
									 
									 
									 
									if (data['mapitems'][i]['discordid'] == $("#uid").val())
										menulist+= " item_selected ";
									
									menulist+= "' id='user_"+data['mapitems'][i]['discordid']+"' ";
									
									var clickAction="";

									clickAction+= " onclick=\"clickPin('"+data['mapitems'][i]['discordid']+"','"+data['mapitems'][i]['color']+"','"+data['mapitems'][i]['avatar']+"','"+data['mapitems'][i]['status']+"');  \" ";
									var hidden_item="<input type='hidden' id='click_user_"+data['mapitems'][i]['discordid']+"' "+clickAction+" >";
									clickAction= " onclick=\"clickPin('"+data['mapitems'][i]['discordid']+"','"+data['mapitems'][i]['color']+"','"+data['mapitems'][i]['avatar']+"','"+data['mapitems'][i]['status']+"'); moveToPin('"+data['mapitems'][i]['discordid']+"','"+data['mapitems'][i]['color']+"','"+data['mapitems'][i]['avatar']+"','"+data['mapitems'][i]['status']+"');  \" ";
									
									menulist+= "style='color:#"+data['mapitems'][i]['color']+";";
									menulist+= "cursor:pointer;";
									menulist+= "'"; 
									
									
									img="<img src='";
									if (data['mapitems'][i]['avatar']!='null')
										img+=data['mapitems'][i]['avatar'];
									//	img+='https://cdn.discordapp.com/avatars/'+data['mapitems'][i]['discordid']+'/'+data['mapitems'][i]['avatar']+'.jpeg';
									else
										img+='img/default_spot.png';
									
									img+="' style='border: 2px solid #"+data['mapitems'][i]['color']+";border-radius: 50%;width:20px;height:20px' border='0'/> ";
									
									
									menulist+= " onmouseover=\" hoverPin('"+data['mapitems'][i]['discordid']+"');\" onmouseout=\" unhoverPin('"+data['mapitems'][i]['discordid']+"'); \"><td align='center' "+clickAction+" >"+img+"</td><td  "+clickAction+"  id='username_"+data['mapitems'][i]['discordid']+"' >"+data['mapitems'][i]['name']+"</td>"; 
									// add time here
									addedtime=new Date(data['mapitems'][i]['added'].replace(" ","T")+"Z");
									hours=addedtime.getHours()
									if (hours<10)
										hours="0"+hours;
									mins=addedtime.getMinutes()
									if (mins<10)
										mins="0"+mins;
									secs=addedtime.getSeconds()
									if (secs<10)
										secs="0"+secs;
									//menulist+="<td "+clickAction+"  align='center' style='font-size:8pt;'>"+hours+":"+mins+":"+secs+"</td>"
									//menulist+=hidden_item;
									
									pval=data['mapitems'][i]['placement'];
									if (data['mapitems'][i]['placement']==-1)
									{
										pval=10000;
										data['mapitems'][i]['placement']="";
									}
									if (typeof data['mapitems'][i]['placement'] !== 'undefined')
										menulist+="<td "+clickAction+"  align='center' style='font-size:8pt;' data-sort-value='"+pval+"'>"+data['mapitems'][i]['placement']+"</td>"
									else
										menulist+="<td "+clickAction+"  align='center' style='font-size:8pt;' data-sort-value='"+pval+"'> </td>"
									
									var pr=parseInt(data['mapitems'][i]['pr']);
									
									if (typeof pr !== 'undefined')
									{
										
										
										prData[data['mapitems'][i]['discordid']]= [];
										prData[data['mapitems'][i]['discordid']]['placement']=data['mapitems'][i]['placement'];
										prData[data['mapitems'][i]['discordid']]['pr']=pr;
										prData[data['mapitems'][i]['discordid']]['joined']=hours+":"+mins+":"+secs;
										prData[data['mapitems'][i]['discordid']]['avatar']=data['mapitems'][i]['avatar'];
										prData[data['mapitems'][i]['discordid']]['name']=data['mapitems'][i]['ename'];
										prData[data['mapitems'][i]['discordid']]['team']=[];
										kk=0;
										if (data['mapitems'][i]['pr_teammate1']!=-1)
										{
											prData[data['mapitems'][i]['discordid']]['team'][kk]=[];
											prData[data['mapitems'][i]['discordid']]['team'][kk]['name']=data['mapitems'][i]['ename1'];
											prData[data['mapitems'][i]['discordid']]['team'][kk]['pr']=data['mapitems'][i]['pr_teammate1'];
											kk++;
											pr+=parseInt(data['mapitems'][i]['pr_teammate1']);
										}
										if (data['mapitems'][i]['pr_teammate2']!=-1)
										{
											prData[data['mapitems'][i]['discordid']]['team'][kk]=[];
											prData[data['mapitems'][i]['discordid']]['team'][kk]['name']=data['mapitems'][i]['ename2'];
											prData[data['mapitems'][i]['discordid']]['team'][kk]['pr']=data['mapitems'][i]['pr_teammate2'];
											kk++;
											pr+=parseInt(data['mapitems'][i]['pr_teammate2']);
										}
										if (data['mapitems'][i]['pr_teammate3']!=-1)
										{
											prData[data['mapitems'][i]['discordid']]['team'][kk]=[];
											prData[data['mapitems'][i]['discordid']]['team'][kk]['name']=data['mapitems'][i]['ename3'];
											prData[data['mapitems'][i]['discordid']]['team'][kk]['pr']=data['mapitems'][i]['pr_teammate3'];
											kk++;
											pr+=parseInt(data['mapitems'][i]['pr_teammate3']);
										}
										var prVal=pr
										if(pr!=-1)
											hasPR=1;
										else
											pr="";
										
										
										menulist+="<td  "+clickAction+" align='center' style='font-size:8pt;' data-sort-value='"+prVal+"'>"+pr.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+"</td>"
										
									}
									
										
										
									menulist+="</tr>"

									
								  
							}
							
							
							
							
							if (hasPR==1)
								tableHead="<table id='player_table' width='100%'><thead><tr><th width='26px'></th><th  data-sort=\"string\" style='cursor:pointer;padding-left:5px;padding-right:5px;' >Name</th><th data-sort=\"int\" style='padding-left:2px;padding-right:2px;text-align:center;cursor:pointer;'>Placement</th><th data-sort=\"int\" style='padding-left:2px;padding-right:2px;text-align:center;cursor:pointer;'>Team PR</th></tr></thead>"
							else
								tableHead="<table id='player_table' width='100%'><thead><tr><th width='26px'></th><th  data-sort=\"string\" style='cursor:pointer;padding-left:5px;padding-right:5px;' >Name</th><th data-sort=\"string\" style='padding-left:2px;padding-right:2px;text-align:center;cursor:pointer;'>Placement</th></tr></thead>"
							
							
							$("#dropmap_list").html(tableHead+menulist+"</table>"+"<div id='team_table'></div>");
								
								
												
								
							 var table = $("#player_table").stupidtable();
								table.bind('aftertablesort', function (event, data) {
								// data.column - the index of the column sorted after a click
								// data.direction - the sorting direction (either asc or desc)
								// data.$th - the th element (in jQuery wrapper)
								// $(this) - this table object
								$("#table_direction").val(data.direction);
								$("#table_column").val(data.column);
								console.log("The sorting direction: " + data.direction);
								console.log("The column index: " + data.column);
								});
	
							try{
							if ($("#table_column").val()!="")
							{
								var $th_to_sort = table.find("thead th").eq($("#table_column").val());
								//$th_to_sort.stupidsort();
								$th_to_sort.stupidsort($("#table_direction").val());
							}
								} catch(err){console.log(err);}
							
							
							
						

							// You can also force a direction.
							

							drawnItems.eachLayer(function(layer) {
								if (layer.layerID.indexOf("icon_")==-1)
									if(jQuery.inArray(layer.layerID, returnedsId) == -1)
									{
										drawnItems.removeLayer(layer);
										try{oms.removeMarker(layer);}catch(err){};														
										
										drawnItems.eachLayer(function(layer1) {
																if (layer1.layerID == "icon_"+layer.layerID) {
																	drawnItems.removeLayer(layer1);
																	try{oms.removeMarker(layer1);}catch(err){};														
										
																}
															});
									
									}
									  });
							
		
		//drawnItems.eachLayer(function(layer) {layer.fire('click');});
		oms.Spread();
		
		}catch(err){};	
}



function hoverSearch()
{
	$("#search_icon").attr('src','img/search_hover.png');
}
function unhoverSearch()
{
	$("#search_icon").attr('src','img/search.png');
}

function hoverName()
{
	$("#name_icon").attr('src','img/name_hover.png');
}
function unhoverName()
{
	$("#name_icon").attr('src','img/name.png');
}


function hoverPin(id)
{
	drawnItems.eachLayer(function(layer) {
		if (layer.layerID == id) {
			layer.openTooltip();
		}
	});
										
}

function unhoverPin(id)
{
	drawnItems.eachLayer(function(layer) {
		if (layer.layerID == id) {
			layer.closeTooltip();
		}
	});
										
}

function clickPin(id,color,avatar,stat)
{
	
	$('.item_selected').removeClass('item_selected');
	$('#user_'+id).addClass('item_selected');
	$('#uid').val(id);
	 showPlayer(id,avatar);
	
					
}
function showPlayer(id)
{

	str='<div align="left" onclick="hidePlayer();" style="font-family: evogria,sans-serif;padding-left:10px;padding-top:4px;font-size:12px;cursor:pointer;">Back to List</div>';
	
	str+='<br><div align="center"><table style="font-family: evogria,sans-serif;"><tr><td align="center" style="color:#FFFFFF;font-size:20px;"> &nbsp;'+prData[id]['name']+'</td></tr>';
	if (prData[id]['pr']!=-1)
	{
		if (prData[id]['name']!="")
			str+='<tr style="margin-top:4px;cursor:pointer;"><td  align="center" onclick=\'showTRN("https://fortnitetracker.com/profile/all/'+prData[id]['name']+'");\'><span  style="color: #337ab7;">PR:&nbsp;'+prData[id]['pr'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'&nbsp;<img src="img/fortnite_tracker.jpg" style="border-radius: 50%;width:32px;height:auto;" border="0"/></span></td></tr>';
		else
			str+='<tr style="margin-top:4px;"><td  align="center"  style="color: #337ab7;">PR:&nbsp;'+prData[id]['pr'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+'&nbsp;<img src="img/fortnite_tracker.jpg" style="border-radius: 50%;width:32px;height:auto;" border="0"/></td></tr>';
	}
	str+='</table></div>'
	if (prData[id]['placement']!="")
		str+='<br><div style="text-align:left;font-family: evogria,sans-serif;margin-left:10px;color:#CCCCCC;"><span style="border-bottom: 3px solid #34ff80;">Placement:</span> &nbsp; '+prData[id]['placement']+'</div>';
	str+='<br><div style="text-align:left;font-family: evogria,sans-serif;margin-left:10px;color:#CCCCCC;"><span style="border-bottom: 3px solid #34ff80;">Registered at:</span> &nbsp; '+prData[id]['joined']+'</div>';
			
	for (i=0;i<prData[id]['team'].length;i++)
		if (prData[id]['team'][i]['pr']!=-1)
		{
			if (i==0)
				str+='<br><div style="text-align:left;font-family: evogria,sans-serif;margin-left:10px;color:#CCCCCC;"><span style="border-bottom: 3px solid #34ff80;">Team:</span></div>';
			str+='<div style="margin-top:10px;color:#CCCCCC;"><table width="100%"  style="font-family: evogria,sans-serif;cursor:pointer;"><tr><td align="left" style="color:#CCCCCC;padding-left:20px;margin-right:4px;"> &nbsp;'+prData[id]['team'][i]['name']+'</td>';
			if (prData[id]['team'][i]['name']!="")
				str+='<td  align="left" onclick=\'showTRN("https://fortnitetracker.com/profile/all/'+prData[id]['team'][i]['name']+'");\'><span style="color: #337ab7;">PR:&nbsp;'+prData[id]['team'][i]['pr'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+' &nbsp;<img src="img/fortnite_tracker.jpg" style="border-radius: 50%;width:32px;height:auto;" border="0"/> </span></td></tr>';
			else
				str+='<td  align="left"  style="color: #337ab7;">PR:&nbsp;'+prData[id]['team'][i]['pr'].toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")+' &nbsp;<img src="img/fortnite_tracker.jpg" style="border-radius: 50%;width:32px;height:auto;" border="0"/></td></tr>';
				
			str+='</table></div>'
		}
	
	
	$("#team_table").html(str);

	$("#team_table").show();
	$("#player_table").hide();
	$("#players_summary").hide();
	$("#dropmap_title").hide();

}
function hidePlayer()
{
	$("#team_table").html("");
	$("#timeline_table").hide();
	$("#player_table").show();
	$("#players_summary").show();
	$("#dropmap_title").show();
	hideLeaderboard();
}

function showTRN(url)
{
	if ($("#tournamentid").val()==0)
		return;
		
	 $("#leaderboard_frame").attr("src", url);
	$( "#leaderboard_dialog" ).dialog({
		dialogClass: "no-close leader_dialog",
		resizable: false,
		width: "100%",
	});
	
	$( "#leaderboard_dialog" ).show();	   
	
	
}


function moveToPin(id,color,avatar,stat)
{
	
	done=0;
		drawnItems.eachLayer(function(layer) {
				if (layer.layerID == "icon_"+$('#uid').val()) {
					 map.setView(layer.getLatLng(),5);
					done =1;
				}
			});							

	if (done==0)
		drawnItems.eachLayer(function(layer) {
				if (layer.layerID == $('#uid').val()) {
					 map.setView(layer.getLatLng(),5);
				}
			});		
							
}

function showNames()
{

            $.ajax('ajax/namesLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                loc=d[i].split(',');
								if (loc.length==3)
								{
									var pos= rc.unproject( [loc[1]*8192,loc[2]*8192] );
									var myIcon = L.divIcon({draggable:false,className: 'names',interactive:false,iconSize:[48,48],zIndexOffset:400,iconAnchor:[24, 24],html: '<span class="names" style="color:#ffffff;z-index:100">' + loc[0] + '</span>'});
									var marker = new L.marker(pos, {draggable:false,icon: myIcon,interactive:false}); //opacity may be set to zero
									marker.addTo(map);
									
								}
                            }
							
                        }
            });
			
}


function hover_icon(element) {
	

		document.getElementById("hover_text").innerHTML =document.getElementById(element.id+"_text").value;
	
	
  element.setAttribute('src', 'img/amazon_hover.png');
}

function unhover_icon(element) {
	
  //document.getElementById("hover_text").innerHTML ="<b>H</b>OVER FOR SOME DESCRIPTION";
	
}


function showLogin()
{
	/*
	$( "#logindialog" ).dialog({
		dialogClass: "no-close",
		resizable: false,
		width: "30%",
	});
	
	$( "#logindialog" ).show();	   
	*/
	/*
	var date = new Date();
	var minutes = 30;
	date.setTime(date.getTime() + (minutes * 60 * 1000));
	Cookies.set('membership_status', '1', {expires: date}); 
		*/  
		
		console.log("showLogin");
	$('#logindialog').iziModal('open');
console.log("showLogin 1");
}


function hideLogin()
{
	   
	 // $( "#logindialog" ).dialog( "close" );
	  	  
	$('#logindialog').iziModal('close');
	window.location.replace("https://www.landingtutorial.com");
}




function showLeaderboard()
{
	if ($("#tournamentid").val()==0)
		return;
		
	window.open("https://yunite.xyz/leaderboard/"+$("#tournamentid").val(),"_blank");	
	
/*	
	 $("#leaderboard_frame").attr("src", "https://yunite.xyz/leaderboard/"+$("#tournamentid").val());
	$( "#leaderboard_dialog" ).dialog({
		dialogClass: "no-close leader_dialog",
		resizable: false,
		width: "100%",
	});
	
	$( "#leaderboard_dialog" ).show();	 
*/	
	
	
}

function hideLeaderboard()
{
	 $( "#leaderboard_dialog" ).dialog( "close" );
	 
	
	
}

async function updatePR()
{
	
	//$.ajax('hooks/getdropspot.php?mapid='+$('#mapcode').val(), // request url
    $.ajax('hooks/lobby_PR.php?code='+$('#mapcode').val(), // request url
                {
						cache: false,
						dataType: 'json',
						async: true,
						error: function ( error) {
								
						},
                        success: function (data, status, xhr) {// success callback function
						

						
						}
            });
}


