/*
 * @copyright 2015 commenthol
 * @license MIT
 */
/* globals L */

//TEST BEN
var busRoute=1; 
  var targetMarker=1; 
  var drawingBus=0;
  
  var busStart=1;
  var busStop=1;
  var busReverse=1;
  

var busRouteEdge=1;
var busRoutePath=1;
var rc;
var map;

var jumpMarker=1;
var deployMarker=1;
var deployMarkerImg=1;
var targetMarkerS=1;
var deployMarkerS=1;
var freefall=1;
var glide=1;


var timingMarkerS=1;
var timingMarker=1;
var timingLine=1;

var circle1=1;
var circle1_shadow=1;
var circle2=1;
var circleMarker1=1;
var circleMarker2=1;

var spotCircles=1;


  var layerBounds;
  var sidebar;
  
  var isMovingCircle=0;

  
  var boat_group;
  var heli_group;
var campfire_group;
var chug_group;
var mushroom_group;

var loot_group;
var chest_group;
var ammo_group;

var name_group;


 var aderror=0;


var isSharing=0;
var sharingcode="";

var startbusx_server=0;
var startbusy_server=0;
var stopbusx_server=0;
var stopbusy_server=0;

var spotShapes=1;
var spotLabels=1;
var spotTarget=1;
var spotTargets=1;
var spotNames=1;
var spotStatus=1;
var prevSpotPos=1;
var isDraggingSpot=0;
var isDoneSpotUpdating=1;
var lastSpotUpdate=0;

var autoUpdateSpotsStarted=0;

function showNavigation()
{
	if ($( "#navigation" ).css("opacity")!=1)
	{
		$( "#navigation" ).css("left",0);
		$( "#navigation" ).css("opacity",1);
	}
	else
	{
		$( "#navigation" ).css("left",-$( "#navigation" ).width()-30);
		$( "#navigation" ).css("opacity",0);
	}
	
	
}


function showHideBoat()
{
    
    if ($(".boat_marker")[0]){
        if ( $('.boat_marker').is(":visible") )
		{
            boat_group.clearLayers();
		}
        else
		{
            $('.boat_marker').show();
			$('.boats').show();
		}
    }
    else
        {
        
            $.ajax('ajax/boatLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

							boat_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'boats',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
							
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        boat_group.addLayer(L.marker(pos,{draggable:false,icon:boat_icon}));
                                        }
                            }
							map.addLayer(boat_group);
                        }
            });
        }
}

function showHideHeli()
{
    
    if ($(".heli_marker")[0]){
        if ( $('.heli_marker').is(":visible") )
		{
            heli_group.clearLayers();
		}
        else
		{
            $('.heli_marker').show();
			$('.helis').show();
		}
    }
    else
        {
        
            $.ajax('ajax/heliLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

							heli_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'helis',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
							
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        heli_group.addLayer(L.marker(pos,{draggable:false,icon:heli_icon}));
                                        }
                            }
							map.addLayer(heli_group);
                        }
            });
        }
}




function showHideCampfire()
{
    if ($(".campfire_marker")[0]){
        if ( $('.campfire_marker').is(":visible") )
           campfire_group.clearLayers();
        
    }
    else
        {
        
            $.ajax('ajax/campfireLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

						campfire_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'campfires',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
						
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        campfire_group.addLayer( L.marker(pos,{draggable:false,icon:campfire_icon}));
                                        }
                            }
							map.addLayer(campfire_group);
                        }
            });
        }
}



function showHideChug()
{
    
    if ($(".chug_marker")[0]){
        if ( $('.chug_marker').is(":visible") )
           chug_group.clearLayers();
    }
    else
        {
        
            $.ajax('ajax/chugLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

						chug_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'chugs',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        chug_group.addLayer(L.marker(pos,{draggable:false,icon:chug_icon}));
                                        }
                            }
							map.addLayer(chug_group);
                        }
            });
        }
}



function showHideMushroom()
{
    
    if ($(".mushroom_marker")[0]){
        if ( $('.mushroom_marker').is(":visible") )
            mushroom_group.clearLayers();
    }
    else
        {
        
            $.ajax('ajax/mushroomLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

						mushroom_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'mushrooms',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        mushroom_group.addLayer(L.marker(pos,{draggable:false,icon:mushroom_icon}));
                                        }
                            }
							map.addLayer(mushroom_group);
                        }
            });
        }
}


function showHideReboot()
{
    
    if ($(".reboot_marker")[0]){
        if ( $('.reboot_marker').is(":visible") )
            $('.reboot_marker').hide();
        else
            $('.reboot_marker').show();
    }
    else
        {
        
            $.ajax('ajax/rebootLocation.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==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        L.marker(pos,{draggable:false,icon:reboot_icon}).addTo(map);
                                        }
                            }

                        }
            });
        }
}



function showHideUpgrade()
{
    
    if ($(".upgrade_marker")[0]){
        if ( $('.upgrade_marker').is(":visible") )
            $('.upgrade_marker').hide();
        else
            $('.upgrade_marker').show();
    }
    else
        {
        
            $.ajax('ajax/upgradeLocation.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==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        L.marker(pos,{draggable:false,icon:upgrade_icon}).addTo(map);
                                        }
                            }

                        }
            });
        }
}

function showChest()
{
            $.ajax('ajax/chestLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

							chest_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'chests',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
							
							data = data.substring(data.indexOf("<body>") + 6);
							data = data.substring(0,data.indexOf("<") - 1);
						
							
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        chest_group.addLayer(L.marker(pos,{draggable:false,icon:chest_icon}));
                                        }
                            }
							map.addLayer(chest_group);
                        }
            });
}

function hideChest()
{
    if ($(".chest_marker")[0]){
        if ( $('.chest_marker').is(":visible") )
		{
            chest_group.clearLayers();
		} 
    }
	if ($(".chests")[0]){
        if ( $('.chests').is(":visible") )
		{
            chest_group.clearLayers();
		} 
    }
}

function showAmmo()
{
            $.ajax('ajax/ammoLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

							ammo_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'ammos',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
							
							data = data.substring(data.indexOf("<body>") + 6);
							data = data.substring(0,data.indexOf("<") - 1);
						
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        ammo_group.addLayer(L.marker(pos,{draggable:false,icon:ammo_icon}));
                                        }
                            }
							map.addLayer(ammo_group);
                        }
            });
}





function hideAmmo()
{
    if ($(".ammo_marker")[0]){
        if ( $('.ammo_marker').is(":visible") )
		{
            ammo_group.clearLayers();
		} 
    }
	if ($(".ammos")[0]){
        if ( $('.ammos').is(":visible") )
		{
            ammo_group.clearLayers();
		} 
    }
	
}


function showNames()
{
	
	
	if ($("#settingSpots").val()==1)
		return;
	
            $.ajax('ajax/namesLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function
							
							data = data.substring(data.indexOf("<body>") + 6);
							data = data.substring(0,data.indexOf("<") - 1);
						

                            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],iconAnchor:[24, 24],html: '<span class="names" style="color:#ffffff;zIndexOffset: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 hideNames()
{
   
	
}


function showLoot()
{
            $.ajax('ajax/lootLocation.php',   // request url
                    {
                        success: function (data, status, xhr) {// success callback function

							loot_group= L.markerClusterGroup({
								iconCreateFunction: function(cluster) {
									return L.divIcon({ className : 'loots',iconSize:[48,48],iconAnchor:[24, 24],html: '<b>' + cluster.getChildCount() + '</b>' });
								}
							});
							
							data = data.substring(data.indexOf("<body>") + 6);
							data = data.substring(0,data.indexOf("<") - 1);
						
							
                            var d= data.split('_');
                            for (i=0;i<d.length;i++)
                            {
                                        loc=d[i].split(',');
                                        if (loc.length==2)
                                        {
                                        var pos= rc.unproject( [loc[0]*8192,loc[1]*8192] );
                                        loot_group.addLayer(L.marker(pos,{draggable:false,icon:loot_icon}));
                                        }
                            }
							map.addLayer(loot_group);
                        }
            });
}

function hideLoot()
{
    if ($(".loot_marker")[0]){
        if ( $('.loot_marker').is(":visible") )
		{
            loot_group.clearLayers();
		} 
    }
	if ($(".loots")[0]){
        if ( $('.loots').is(":visible") )
		{
            loot_group.clearLayers();
		} 
    }
}



function showHideMarkers()
{
	if ( $('.white_pointer').is(":visible") )
	{
		$('.white_pointer').hide();
		$('.yellow_pointer').hide();
        $('.red_circle').hide();
        $('.parachute_pointer').hide();
		try {
			deployMarker.closePopup();
		}catch(err) {}
	}
	else
	{
		$('.white_pointer').show();
	}
	

}	

function hideRoute()
{
	$('.dropRoute').hide();
	$('.yellow_pointer').hide();
	$('.parachute_pointer').hide();
	$('.blue_circle').hide(); 
	$('.red_circle').hide(); 
	
	
    if (deployMarker!=1)
        deployMarker.closePopup();
	$("#autodeploy").html("");
}

function hideTiming()
{
	$('.timing_pointer').hide();
	$('.timing_circle').hide(); 
	$('.timingRoute').hide(); 
	 if (timingMarker!=1)
        timingMarker.closePopup();
}

function showTiming()
{
	$('.timing_pointer').show();
	$('.timing_circle').show(); 
	$('.timingRoute').show(); 

}

function hideBus()
{
	hideRoute();
	$('.bus_pointer').hide();
	$('.bus_path').hide();		
}


function showBus()
{
	
	$('.bus_pointer').show();
	$('.bus_path').show();		
}

function drawCircle1(second)
{



	if (second)
	{
		if (circle1!=1)
			circle1.remove();
		circle1=1;
		
		
		
		var pts=new Array();
		pts[0]=rc.unproject([ 8192, 0 ]);
		pts[1]=rc.unproject([ 0,0 ]);
		pts[2]=rc.unproject([ 0, 8192 ]);
		pts[3]=rc.unproject([ 8192,8192 ]);
		pts[4]=rc.unproject([ 8192, 0 ]);
					
		var centerX;
		var centerY;
		if (circleMarker1==1)
		{
			centerX=8192/2;
			centerY=8192/2;
		}
		else
		{
			var cent = rc.project( circleMarker1.getLatLng());
			centerX=cent.x;
			centerY=cent.y;
		}
		rad=8192*0.3;
				//var pts=new Array();
				 k=5;
				for (i=0;i<=2*Math.PI;i+=Math.PI/400)
				{
					pts[k]=rc.unproject([ centerX+rad*Math.cos(i), centerY+rad*Math.sin(i) ]);
					k++;
				}
				pts[k]=rc.unproject([ centerX+rad, centerY ]);
		if (circle1_shadow==1)
			circle1_shadow = L.polygon(pts, {stroke:false,color: 'black',smoothFactor:0,fillOpacity:0.5,fillRule:'nonzero',className:'circle1'}).addTo(map);
		else
			circle1_shadow.setLatLngs(pts);
		
				var pts=new Array();
				k=0;
				for (i=0;i<=2*Math.PI;i+=Math.PI/400)
				{
					pts[k]=rc.unproject([ centerX+rad*Math.cos(i), centerY+rad*Math.sin(i) ]);
					k++;
				}
				pts[k]=rc.unproject([ centerX+rad, centerY ]);
				if (circle1==1)
					circle1 = L.polygon(pts, {stroke:true,color: 'white',smoothFactor:0,fillOpacity:0,weight:2,fillRule:'nonzero',className:'circle1'}).addTo(map);
				else
					circle1.setLatLngs(pts);
		
		
		$(".center1").hide();
		$(".circle1").show();
	}
	else
	{
		if (circle1!=1)
		{
			circle1.remove();
			circle1=1;
		}
			
			if (circleMarker1!=1)
				L.setOptions(circleMarker1,{draggable:true});
		
		var pts=new Array();
		var centerX;
		var centerY;
		if (circleMarker1==1)
		{
			centerX=8192/2;
			centerY=8192/2;
		}
		else
		{
			var cent = rc.project( circleMarker1.getLatLng());
			centerX=cent.x;
			centerY=cent.y;
		}
		rad=8192*0.3;
				//var pts=new Array();
				 k=0;
				for (i=0;i<=2*Math.PI;i+=Math.PI/400)
				{
					pts[k]=rc.unproject([ centerX+rad*Math.cos(i), centerY+rad*Math.sin(i) ]);
					k++;
				}
				pts[k]=rc.unproject([ centerX+rad, centerY ]);
				if (circle1==1)
					circle1 = L.polygon(pts, {stroke:true,color: 'white',smoothFactor:0,fillOpacity:0,weight:2,fillRule:'nonzero',className:'circle1'}).addTo(map);
				else
					circle1.setLatLngs(pts);
		if (circleMarker1==1)		
			circleMarker1=L.marker(rc.unproject([ centerX, centerY ]),{draggable:true,icon:circle_pointer1}).addTo(map);
		else
			circleMarker1.setLatLng(rc.unproject([ centerX, centerY ]));
			
		circleMarker1.on('drag', function (event) {
				removeLikelihood();
				isMovingCircle=1;
				var cent = rc.project( circleMarker1.getLatLng());
				rad=8192*0.3;
					targ = rc.project( targetMarker.getLatLng());
					dist=Math.sqrt( (cent.x-targ.x )*(cent.x-targ.x )+(cent.y-targ.y )*(cent.y-targ.y ));
					if (dist>rad)
					{
						dx=( (targ.x-cent.x ) )/dist;
						dy=( (targ.y-cent.y ) )/dist;
						tmX=cent.x+dx*rad;
						tmY=cent.y+dy*rad;
						if (timingMarkerS==1)
							timingMarkerS=L.marker(rc.unproject([tmX,tmY]),{draggable:false,icon:timing_circle}).addTo(map);
						else
							timingMarkerS.setLatLng(rc.unproject([tmX,tmY]));
						
						if (timingMarker==1)
						{
							timingMarker=L.marker(rc.unproject([tmX,tmY]),{draggable:true,icon:timing_pointer}).addTo(map);
							timingMarker.on('drag', function (event) {
								var latlng = timingMarker.getLatLng();
								timingMarkerS.setLatLng(latlng);
								hideRoute();
								$("#selectedTool").val(2);
								
								if (timingLine==1)
								{
									timingLine=L.polyline([targetMarker.getLatLng(),[event.latlng.lat,event.latlng.lng] ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
								}
								else
								{
										var latlngs = timingLine.getLatLngs();
										latlngs[1]=[event.latlng.lat, event.latlng.lng];
										timingLine.setLatLngs(latlngs);
								}
								
								
							});
						 }
						else
							timingMarker.setLatLng(rc.unproject([tmX,tmY]));
							if (timingLine==1)
							{
								timingLine=L.polyline([targetMarker.getLatLng(),rc.unproject([tmX,tmY]) ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
							}
							else
							{
									var latlngs = timingLine.getLatLngs();
									latlngs[1]=rc.unproject([tmX,tmY]);
									timingLine.setLatLngs(latlngs);
							}
				
					}
				centerX=cent.x;
				centerY=cent.y;
				
				var pts=new Array();
				k=0;
				for (i=0;i<=2*Math.PI;i+=Math.PI/400)
				{
					pts[k]=rc.unproject([ centerX+rad*Math.cos(i), centerY+rad*Math.sin(i) ]);
					k++;
				}
				pts[k]=rc.unproject([ centerX+rad, centerY ]);
				circle1.setLatLngs(pts);
				
			});
		$(".center1").show();
		$(".circle1").show();
	}
}


function removeCircle()
{
	$(".center1").hide();
	$(".circle1").hide();
	$(".center2").hide();
	$(".circle2").hide();
	
}

function removeLikelihood()
{
	$(".spotcircle").hide();
	
	
}

function drawMapCircle(centerX,centerY,rad,p)
{
	var pts=new Array();
	k=0;
	for (a=0;a<=2*Math.PI;a+=Math.PI/400)
	{
		
		pts[k]=rc.unproject([ centerX+rad*Math.cos(a), centerY+rad*Math.sin(a) ]);
		k++;
	}
	pts[k]=rc.unproject([ centerX+rad, centerY ]);
	p.setLatLngs(pts);
}

function drawMapArc(centerX,centerY,rad,start,end,p)
{
	if (Math.abs(end-start)>Math.PI/2)
	{
		start+=2*Math.PI;
	}
	
	var pts=new Array();
	k=0;
	delt=(end-start)/100;
	if (start<end)
	{
		for (a=start;a<=end;a+=delt)
		{
			pts[k]=rc.unproject([ centerX+rad*Math.cos(a), centerY+rad*Math.sin(a) ]);
			k++;
		}
	}
	else
	{
		for (a=start;a>=end;a+=delt)
		{
			pts[k]=rc.unproject([ centerX+rad*Math.cos(a), centerY+rad*Math.sin(a) ]);
			k++;
		}
	}
	p.setLatLngs(pts);
}




function stormAnalyze1()
{
				var cent = rc.project( circleMarker1.getLatLng());
				circleR=8192*0.3;
				centerX=cent.x;
				centerY=cent.y;
				
				targ = rc.project( targetMarker.getLatLng());
					dist=Math.sqrt( (centerX-targ.x )*(centerX-targ.x )+(centerY-targ.y )*(centerY-targ.y ));
					if (dist>rad)
					{
						dx=( (targ.x-centerX ) )/dist;
						dy=( (targ.y-centerY ) )/dist;
						tmX=centerX+dx*rad;
						tmY=centerY+dy*rad;
						if (timingMarkerS==1)
							timingMarkerS=L.marker(rc.unproject([tmX,tmY]),{draggable:false,icon:timing_circle}).addTo(map);
						else
							timingMarkerS.setLatLng(rc.unproject([tmX,tmY]));
						
						if (timingMarker==1)
						{
							timingMarker=L.marker(rc.unproject([tmX,tmY]),{draggable:true,icon:timing_pointer}).addTo(map);
							timingMarker.on('drag', function (event) {
								var latlng = timingMarker.getLatLng();
								timingMarkerS.setLatLng(latlng);
								hideRoute();
								$("#selectedTool").val(2);
								
								if (timingLine==1)
								{
									timingLine=L.polyline([targetMarker.getLatLng(),[event.latlng.lat,event.latlng.lng] ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
								}
								else
								{
										var latlngs = timingLine.getLatLngs();
										latlngs[1]=[event.latlng.lat, event.latlng.lng];
										timingLine.setLatLngs(latlngs);
								}
								
								
							});
						 }
						else
							timingMarker.setLatLng(rc.unproject([tmX,tmY]));
							if (timingLine==1)
							{
								timingLine=L.polyline([targetMarker.getLatLng(),rc.unproject([tmX,tmY]) ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
							}
							else
							{
									var latlngs = timingLine.getLatLngs();
									latlngs[1]=rc.unproject([tmX,tmY]);
									timingLine.setLatLngs(latlngs);
							}
					}
				
				
				
				
				var latlngs = busRouteEdge.getLatLngs();
				var startB=rc.project(latlngs[0]);
				var stopB=rc.project(latlngs[1]);
				
				busStartX=startB.x/8192;
				busStartY=startB.y/8192;
				busStopX=stopB.x/8192;
				busStopY=stopB.y/8192;
				
			
			var tg = rc.project( targetMarker.getLatLng());
			var target_circle=	 Math.sqrt((tg.x - centerX) * (tg.x - centerX) + (tg.y - centerY) * (tg.y - centerY));
			
			if (spotCircles!=1)
			{
				if (spotCircles.length>0)
					for (jj=0;jj<spotCircles.length;jj++)
					{
						spotCircles[jj].remove();
					}
			}
			
			$.ajax('ajax/drop_spots1.php?busStartX='+busStartX+'&busStartY='+busStartY+'&busStopX='+busStopX+'&busStopY='+busStopY,   // request url
			{
				success: function (data, status, xhr) {// success callback function
					
				
					var d= data.split(';');
					
					spotCircles=new Array();
					kkk=0;
					for (i=0;i<d.length;i++)
					{
						var dd=d[i].split(',');
						if (dd.length==4)
						{
							x=dd[0]*8192;
							y=dd[1]*8192;
							n=dd[2];
							r=dd[3]*8192;
							dist = Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY));
							 if (dist < circleR) {
								 
								 if (target_circle< circleR)
								 {
									alpha=(32 + 128 * n / 6)/255;
									spotCircles[kkk]=L.polygon([[0,0]], {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
									drawMapCircle(x,y,r,spotCircles[kkk]);
									kkk++;
								 }
								 else
								 {
									targ = (180 / Math.PI * Math.atan2(tg.y- centerY, tg.x - centerX));
									curr = (180 / Math.PI * Math.atan2(y - centerY, x - centerX));
									if (Math.abs(curr - targ) < 40) {
										alpha=(32 + 128 * n / 6)/255;
										spotCircles[kkk]=L.polygon([[0,0]], {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
										drawMapCircle(x,y,r,spotCircles[kkk]);
										kkk++;
									}
								 }
							 }
							 else{
								vectX = (centerX - x) / dist;
								vectY = (centerY - y) / dist;

								perpX = -vectY;
								perpY = vectX;

								p1x = x + perpX * r;
								p1y = y  + perpY * r ;

								cx = centerX ;
								cy = centerY ;

								dist1 = Math.sqrt((p1x - cx) * (p1x - cx) + (p1y - cy) * (p1y - cy));
								dx = (cx - p1x) / dist1;
								dy = (cy - p1y) / dist1;

								p2x = x  - perpX * r;
								p2y = y  - perpY * r;

								dist1 = Math.sqrt((p2x - cx) * (p2x - cx) + (p2y - cy) * (p2y - cy));
								dx2 = (cx - p2x) / dist1;
								dy2 = (cy - p2y) / dist1;
								
								if (target_circle > circleR ) {
										 radius =  (circleR);
										 P1x = cx - dx * circleR;
										 P1y = cy - dy * circleR;
										 P2x = cx - dx2 * circleR ;
										 P2y = cy - dy2 * circleR ;
									
                                        targ = (180 / Math.PI * Math.atan2(tg.y - cy, tg.x  - cx));
                                        curr = (180 / Math.PI * Math.atan2(y  - cy, x - cx));
                                        if (Math.abs(curr - targ) < 20) {
											alpha=(32 + 128 * n / 6)/255;
											var pts=new Array();
											pts[0]=rc.unproject([ p2x, p2y ]);
											pts[1]=rc.unproject([ P2x, P2y ]);
											pts[2]=rc.unproject([ P1x, P1y ]);
											pts[3]=rc.unproject([ p1x, p1y ]);
											pts[4]=rc.unproject([ p2x, p2y ]);
											spotCircles[kkk]=L.polygon(pts, {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
											kkk++;
											
											for ( jj = 0; jj < n; jj++) {
												rr=(circleR + 0.005 * (jj+1) *8192);
												P1x = cx - dx * rr;
												P1y = cy - dy * rr;
												P2x = cx - dx2 * rr ;
												P2y = cy - dy2 * rr ;
												start = ( Math.atan2(P2y - cy, P2x - cx));
											    end = ( Math.atan2(P1y - cy, P1x - cx));
												spotCircles[kkk]=L.polyline([[0,0]], {stroke:true,color: 'white',weight:2,smoothFactor:0,className:'spotcircle'}).addTo(map);
												drawMapArc(cx,cy,rr,start,end,spotCircles[kkk]);
												kkk++;
											}
										}
                                    }
									else
									{
										for ( jj = 0; jj < n; jj++) {	
												rr=(circleR + 0.005 * (jj+1) *8192);
												P1x = cx - dx * rr;
												P1y = cy - dy * rr;
												P2x = cx - dx2 * rr ;
												P2y = cy - dy2 * rr ;
												start = ( Math.atan2(P2y - cy, P2x - cx));
											    end = ( Math.atan2(P1y - cy, P1x - cx));
												spotCircles[kkk]=L.polyline([[0,0]], {stroke:true,color: 'white',weight:2,smoothFactor:0,className:'spotcircle'}).addTo(map);
												drawMapArc(cx,cy,rr,start,end,spotCircles[kkk]);
												kkk++;
												
											}
									}
								
								 
								 
							 }
						}
					}
					
				$(".spotcircle").show();	
				},
					error: function (jqXhr, textStatus, errorMessage) { // error callback 
						alert('Error: ' + errorMessage);
					}
			
			});
	
                
	
	
	
	
	
}



function stormAnalyze2()
{
				var cent = rc.project( circleMarker2.getLatLng());
				circleR=8192*0.15;
				circleR1=8192*0.3;
				centerX=cent.x;
				centerY=cent.y;
				
				
				
					targ = rc.project( targetMarker.getLatLng());
					dist=Math.sqrt( (centerX-targ.x )*(centerX-targ.x )+(centerY-targ.y )*(centerY-targ.y ));
					if (dist>rad)
					{
						dx=( (targ.x-centerX ) )/dist;
						dy=( (targ.y-centerY ) )/dist;
						tmX=centerX+dx*rad;
						tmY=centerY+dy*rad;
						if (timingMarkerS==1)
							timingMarkerS=L.marker(rc.unproject([tmX,tmY]),{draggable:false,icon:timing_circle}).addTo(map);
						else
							timingMarkerS.setLatLng(rc.unproject([tmX,tmY]));
						
						if (timingMarker==1)
						{
							timingMarker=L.marker(rc.unproject([tmX,tmY]),{draggable:true,icon:timing_pointer}).addTo(map);
							timingMarker.on('drag', function (event) {
								var latlng = timingMarker.getLatLng();
								timingMarkerS.setLatLng(latlng);
								hideRoute();
								$("#selectedTool").val(2);
								
								if (timingLine==1)
								{
									timingLine=L.polyline([targetMarker.getLatLng(),[event.latlng.lat,event.latlng.lng] ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
								}
								else
								{
										var latlngs = timingLine.getLatLngs();
										latlngs[1]=[event.latlng.lat, event.latlng.lng];
										timingLine.setLatLngs(latlngs);
								}
								
								
							});
						 }
						else
							timingMarker.setLatLng(rc.unproject([tmX,tmY]));
							if (timingLine==1)
							{
								timingLine=L.polyline([targetMarker.getLatLng(),rc.unproject([tmX,tmY]) ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
							}
							else
							{
									var latlngs = timingLine.getLatLngs();
									latlngs[1]=rc.unproject([tmX,tmY]);
									timingLine.setLatLngs(latlngs);
							}
					}
				
				
				
				var cent = rc.project( circleMarker1.getLatLng());
				centerX1=cent.x;
				centerY1=cent.y;
				
				
				var latlngs = busRouteEdge.getLatLngs();
				var startB=rc.project(latlngs[0]);
				var stopB=rc.project(latlngs[1]);
				
				busStartX=startB.x/8192;
				busStartY=startB.y/8192;
				busStopX=stopB.x/8192;
				busStopY=stopB.y/8192;
				
			
			var tg = rc.project( targetMarker.getLatLng());
			var target_circle=	 Math.sqrt((tg.x - centerX) * (tg.x - centerX) + (tg.y - centerY) * (tg.y - centerY));
			
			if (spotCircles!=1)
			{
				if (spotCircles.length>0)
					for (jj=0;jj<spotCircles.length;jj++)
					{
						spotCircles[jj].remove();
					}
			}
			
			$.ajax('ajax/drop_spots1.php?busStartX='+busStartX+'&busStartY='+busStartY+'&busStopX='+busStopX+'&busStopY='+busStopY,   // request url
			{
				success: function (data, status, xhr) {// success callback function
					
				
					var d= data.split(';');
					
					spotCircles=new Array();
					kkk=0;
					for (i=0;i<d.length;i++)
					{
						var dd=d[i].split(',');
						if (dd.length==4)
						{
							x=dd[0]*8192;
							y=dd[1]*8192;
							n=dd[2];
							r=dd[3]*8192;
							dist = Math.sqrt((x - centerX) * (x - centerX) + (y - centerY) * (y - centerY));
							 if (dist < circleR) {
								 
								 if (target_circle< circleR)
								 {
									alpha=(32 + 128 * n / 6)/255;
									spotCircles[kkk]=L.polygon([[0,0]], {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
									drawMapCircle(x,y,r,spotCircles[kkk]);
									kkk++;
								 }
								 else
								 {
									targ = (180 / Math.PI * Math.atan2(tg.y- centerY, tg.x - centerX));
									curr = (180 / Math.PI * Math.atan2(y - centerY, x - centerX));
									if (Math.abs(curr - targ) < 40) {
										alpha=(32 + 128 * n / 6)/255;
										spotCircles[kkk]=L.polygon([[0,0]], {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
										drawMapCircle(x,y,r,spotCircles[kkk]);
										kkk++;
									}
								 }
							 }
							 else{
								vectX = (centerX - x) / dist;
								vectY = (centerY - y) / dist;

								perpX = -vectY;
								perpY = vectX;

								p1x = x + perpX * r;
								p1y = y  + perpY * r ;

								cx = centerX ;
								cy = centerY ;

								dist1 = Math.sqrt((p1x - cx) * (p1x - cx) + (p1y - cy) * (p1y - cy));
								dx = (cx - p1x) / dist1;
								dy = (cy - p1y) / dist1;

								p2x = x  - perpX * r;
								p2y = y  - perpY * r;

								dist1 = Math.sqrt((p2x - cx) * (p2x - cx) + (p2y - cy) * (p2y - cy));
								dx2 = (cx - p2x) / dist1;
								dy2 = (cy - p2y) / dist1;
								
								if (target_circle > circleR ) {
										 radius =  (circleR);
										 P1x = cx - dx * circleR;
										 P1y = cy - dy * circleR;
										 P2x = cx - dx2 * circleR ;
										 P2y = cy - dy2 * circleR ;
									
                                        targ = (180 / Math.PI * Math.atan2(tg.y - cy, tg.x  - cx));
                                        curr = (180 / Math.PI * Math.atan2(y  - cy, x - cx));
                                        if (Math.abs(curr - targ) < 20) {
											
											dist_storm1=Math.sqrt((x - centerX1) * (x - centerX1) + (y - centerY1) * (y - centerY1));
											
											if (dist_storm1<circleR1)
											{
												alpha=(32 + 128 * n / 6)/255;
												var pts=new Array();
												pts[0]=rc.unproject([ p2x, p2y ]);
												pts[1]=rc.unproject([ P2x, P2y ]);
												pts[2]=rc.unproject([ P1x, P1y ]);
												pts[3]=rc.unproject([ p1x, p1y ]);
												pts[4]=rc.unproject([ p2x, p2y ]);
												spotCircles[kkk]=L.polygon(pts, {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
												kkk++;
												
												for ( jj = 0; jj < n; jj++) {
													rr=(circleR + 0.005 * (jj+1) *8192);
													P1x = cx - dx * rr;
													P1y = cy - dy * rr;
													P2x = cx - dx2 * rr ;
													P2y = cy - dy2 * rr ;
													start = ( Math.atan2(P2y - cy, P2x - cx));
													end = ( Math.atan2(P1y - cy, P1x - cx));
													spotCircles[kkk]=L.polyline([[0,0]], {stroke:true,color: 'white',weight:2,smoothFactor:0,className:'spotcircle'}).addTo(map);
													drawMapArc(cx,cy,rr,start,end,spotCircles[kkk]);
													kkk++;
												}
											}
											else
											{
												 P3x = cx - dx * circleR  ;
                                                 P3y = cy - dy * circleR  ;

                                                 cx1=centerX1;
                                                 cy1=centerY1;
												
												
												ddd=Math.sqrt( (P3x-cx1)*(P3x-cx1)+(P3y-cy1)*(P3y-cy1) );
                                                rr=circleR;
                                                while (ddd<circleR1)
                                                {
                                                    rr+=0.001*8192;
                                                     P3x = cx - dx * (rr);
                                                     P3y = cy - dy * (rr);
                                                    ddd=Math.sqrt( (P3x-cx1)*(P3x-cx1)+(P3y-cy1)*(P3y-cy1) );
                                                }
												rr-=0.001*8192;
												P3x = cx - dx * (rr);
                                                P3y = cy - dy * (rr);
                                               
											   P4x = cx - dx2 * (circleR ) ;
                                                P4y = cy - dy2 * (circleR ) ;

                                                ddd=Math.sqrt( (P4x-cx1)*(P4x-cx1)+(P4y-cy1)*(P4y-cy1) );
                                                rr=circleR;

                                                while (ddd<circleR1)
                                                {
                                                    rr+=0.001*8192;
                                                    P4x = cx - dx2 * (rr);
                                                    P4y = cy - dy2 * (rr);
                                                    ddd=Math.sqrt( (P4x-cx1)*(P4x-cx1)+(P4y-cy1)*(P4y-cy1) );
                                                }
												rr-=0.001*8192;
                                                P4x = cx - dx2 * (rr);
                                                P4y = cy - dy2 * (rr);
												
												alpha=(32 + 128 * n / 6)/255;
												var pts=new Array();
												pts[0]=rc.unproject([ P1x, P1y ]);
												pts[1]=rc.unproject([ P2x, P2y ]);
												pts[2]=rc.unproject([ P4x, P4y ]);
												pts[3]=rc.unproject([ P3x, P3y ]);
												pts[4]=rc.unproject([ P1x, P1y ]);
												spotCircles[kkk]=L.polygon(pts, {stroke:true,color: 'red',weight:1,smoothFactor:0,fillOpacity:alpha,fillRule:'nonzero',className:'spotcircle'}).addTo(map);
												kkk++;
                                                
												for ( jj = 0; jj < n; jj++) {	
												rr=(circleR + 0.005 * (jj+1) *8192);
												P1x = cx - dx * rr;
												P1y = cy - dy * rr;
												P2x = cx - dx2 * rr ;
												P2y = cy - dy2 * rr ;
												start = ( Math.atan2(P2y - cy, P2x - cx));
											    end = ( Math.atan2(P1y - cy, P1x - cx));
												spotCircles[kkk]=L.polyline([[0,0]], {stroke:true,color: 'white',weight:2,smoothFactor:0,className:'spotcircle'}).addTo(map);
												drawMapArc(cx,cy,rr,start,end,spotCircles[kkk]);
												kkk++;
												
												}
											}
										}
                                    }
									else
									{
										for ( jj = 0; jj < n; jj++) {	
												rr=(circleR + 0.005 * (jj+1) *8192);
												P1x = cx - dx * rr;
												P1y = cy - dy * rr;
												P2x = cx - dx2 * rr ;
												P2y = cy - dy2 * rr ;
												start = ( Math.atan2(P2y - cy, P2x - cx));
											    end = ( Math.atan2(P1y - cy, P1x - cx));
												spotCircles[kkk]=L.polyline([[0,0]], {stroke:true,color: 'white',weight:2,smoothFactor:0,className:'spotcircle'}).addTo(map);
												drawMapArc(cx,cy,rr,start,end,spotCircles[kkk]);
												kkk++;
												
											}
									}
								
								 
								 
							 }
						}
					}
					
					$(".spotcircle").show();
	
				},
					error: function (jqXhr, textStatus, errorMessage) { // error callback 
						alert('Error: ' + errorMessage);
					}
			});
}



function drawCircle2()
{
	
	$(".center2").show();
	$(".circle2").show();
		var centerX;
		var centerY;
		if (circleMarker2==1)
		{
			var cent = rc.project( circleMarker1.getLatLng());
			centerX=cent.x;
			centerY=cent.y;
		}
		else
		{
			var cent = rc.project( circleMarker2.getLatLng());
			centerX=cent.x;
			centerY=cent.y;
		}

		var pts=new Array();
		rad=8192*0.15;
				//var pts=new Array();
				 k=0;
				for (i=0;i<=2*Math.PI;i+=Math.PI/400)
				{
					pts[k]=rc.unproject([ centerX+rad*Math.cos(i), centerY+rad*Math.sin(i) ]);
					k++;
				}
				pts[k]=rc.unproject([ centerX+rad, centerY ]);
				if (circle2==1)
					circle2 = L.polygon(pts, {stroke:true,color: 'white',smoothFactor:0,fillOpacity:0,weight:2,fillRule:'nonzero',className:'circle2'}).addTo(map);
				else
					circle2.setLatLngs(pts);
		if (circleMarker2==1)		
			circleMarker2=L.marker(rc.unproject([ centerX, centerY ]),{draggable:true,icon:circle_pointer2}).addTo(map);
		else
			circleMarker2.setLatLng(rc.unproject([ centerX, centerY ]));
			
		circleMarker2.on('drag', function (event) {
				removeLikelihood();
				isMovingCircle=1;
				var cent1 = rc.project( circleMarker1.getLatLng());
				
				var cent = rc.project( circleMarker2.getLatLng());
				rad=8192*0.15;
				dist=Math.sqrt( (cent.x-cent1.x )*(cent.x-cent1.x )+(cent.y-cent1.y )*(cent.y-cent1.y ));
				
				if (dist>=rad)
				{
					dx=( (cent.x-cent1.x ) )/dist;
					dy=( (cent.y-cent1.y ) )/dist;
					centerX=cent1.x+dx*rad;
					centerY=cent1.y+dy*rad;
					circleMarker2.setLatLng( rc.unproject([centerX,centerY]) );
				}
				else
				{
					centerX=cent.x;
					centerY=cent.y;
				}
				
					targ = rc.project( targetMarker.getLatLng());
					dist=Math.sqrt( (centerX-targ.x )*(centerX-targ.x )+(centerY-targ.y )*(centerY-targ.y ));
					if (dist>rad)
					{
						dx=( (targ.x-centerX ) )/dist;
						dy=( (targ.y-centerY ) )/dist;
						tmX=centerX+dx*rad;
						tmY=centerY+dy*rad;
						if (timingMarkerS==1)
							timingMarkerS=L.marker(rc.unproject([tmX,tmY]),{draggable:false,icon:timing_circle}).addTo(map);
						else
							timingMarkerS.setLatLng(rc.unproject([tmX,tmY]));
						
						if (timingMarker==1)
						{
							timingMarker=L.marker(rc.unproject([tmX,tmY]),{draggable:true,icon:timing_pointer}).addTo(map);
							timingMarker.on('drag', function (event) {
								var latlng = timingMarker.getLatLng();
								timingMarkerS.setLatLng(latlng);
								hideRoute();
								$("#selectedTool").val(2);
								
								if (timingLine==1)
								{
									timingLine=L.polyline([targetMarker.getLatLng(),[event.latlng.lat,event.latlng.lng] ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
								}
								else
								{
										var latlngs = timingLine.getLatLngs();
										latlngs[1]=[event.latlng.lat, event.latlng.lng];
										timingLine.setLatLngs(latlngs);
								}
								
								
							});
						 }
						else
							timingMarker.setLatLng(rc.unproject([tmX,tmY]));
							if (timingLine==1)
							{
								timingLine=L.polyline([targetMarker.getLatLng(),rc.unproject([tmX,tmY]) ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
							}
							else
							{
									var latlngs = timingLine.getLatLngs();
									latlngs[1]=rc.unproject([tmX,tmY]);
									timingLine.setLatLngs(latlngs);
							}
					}
				
				var pts=new Array();
				k=0;
				for (i=0;i<=2*Math.PI;i+=Math.PI/400)
				{
					pts[k]=rc.unproject([ centerX+rad*Math.cos(i), centerY+rad*Math.sin(i) ]);
					k++;
				}
				pts[k]=rc.unproject([ centerX+rad, centerY ]);
				circle2.setLatLngs(pts);
				
			});
			if (circleMarker1!=1)
				L.setOptions(circleMarker1,{draggable:false});
		$(".center1").hide();
	
}


function circle2_tool()
{
	$("#bottom_button").html("<a id='main_button' href='#' class='button  button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a><a id='storm_button1' href='#' class='button button_copilot'><b>S</b>TORM <b>A</b>NALYSIS</a>");
	$("#top_button").html("<a id='main_button1' href='#' class='button  button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a><a id='storm_button1' href='#' class='button button_copilot'><b>S</b>TORM <b>A</b>NALYSIS</a>");
	
	
	$("#main_button").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	$("#main_button1").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	$("#storm_button1").click(function(e) {
		   stormAnalyze2();
		   e.stopPropagation();
		});
		
		 $("#icon2").attr("onclick",' circle0_tool();');
	    $("#edit_img").attr("src", "img/circle1.png");
		$("#icon2_text").val("<b>T</b>AP TO SET A CIRCLE FOR ANALYSIS");
		
	
		
		
	drawCircle1(true);
	drawCircle2();
	/*
	sidebar.removePanel('storm');
	sidebar.addPanel({
		id:   'storm',
		tab:  '<img id="storm_button" src="img/storm2.png" border="0" style="max-width:90%;">',
		title: 'Storm Tool',
		button: function() {
						circle0_tool();
						},
						disabled: false,
					});	
	*/
}

function circle1_tool()
{
	$("#bottom_button").html("<a id='main_button' href='#' class='button  button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a><a id='storm_button1' href='#' class='button button_copilot'><b>S</b>TORM <b>A</b>NALYSIS</a>");
	$("#main_button").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	$("#top_button").html("<a id='main_button1' href='#' class='button  button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a><a id='storm_button1' href='#' class='button button_copilot'><b>S</b>TORM <b>A</b>NALYSIS</a>");
	$("#main_button1").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	$("#storm_button1").click(function(e) {
		   stormAnalyze1();
		   e.stopPropagation();
		});
		
		
	    $("#icon2").attr("onclick",' circle2_tool();');
	    $("#edit_img").attr("src", "img/circles.png");
		$("#icon2_text").val("<b>T</b>AP TO SET A CIRCLE FOR ANALYSIS");
		
	
		
	drawCircle1(false);
	/*
	sidebar.removePanel('storm');
	sidebar.addPanel({
		id:   'storm',
		tab:  '<img id="storm_button" src="img/storm1.png" border="0" style="max-width:90%;">',
		title: 'Storm Tool',
		button: function() {
						circle2_tool();
					},
						disabled: false,
					});	
					*/
}

function circle0_tool()
{
	$("#bottom_button").html("<a id='main_button' href='#' class='button button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a>");
	$("#top_button").html("<a id='main_button1' href='#' class='button button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a>");
	$("#main_button").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	$("#main_button1").click(function(e) {
		   go();
		   e.stopPropagation();
		});	
		 $("#icon2").attr("onclick",' circle1_tool();');
	    $("#edit_img").attr("src", "img/circle1.png");
		$("#icon2_text").val("<b>T</b>AP TO SET A CIRCLE FOR ANALYSIS");
		
	
		
	removeCircle();
	/*
	sidebar.removePanel('storm');
	sidebar.addPanel({
			id:   'storm',
			tab:  '<img id="storm_button" src="img/storm.png" border="0" style="max-width:90%;">',
			title: 'Storm Tool',
			button: function() {
				 circle1_tool()
			},
				disabled: false,
			});	
			*/
	
}

function noloot_tool()
{
	
	hideAmmo();
	hideLoot();
	hideChest();
	/*
	sidebar.removePanel('loot');
	*/
	if ($('#draw_bus').length==0){
	
	circ=0;
	if ( $('#storm_button').attr('src')=="img/storm1.png" )
		circ=1;
	
	if ( $('#storm_button').attr('src')=="img/storm2.png" )
		circ=2;
	/*
	sidebar.removePanel('storm');
*/
	//$("#icon3").attr("onclick",' chest_tool();');
	$(".chest_btn").off('click');
	$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 chest_tool();
					   
					});
	

			
	}
	else
	{
	//$("#icon3").attr("onclick",' chest_tool();');
	$(".chest_btn").off('click');
	$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 chest_tool();
					   
					});
	

	}
	
	
}

function chest_tool()
{
	hideAmmo();
	hideLoot();
	hideChest();
	showChest();
	/*
	sidebar.removePanel('loot');
	*/
	if ($('#draw_bus').length==0){
		
		
	circ=0;
	if ( $('#storm_button').attr('src')=="img/storm1.png" )
		circ=1;
	
	if ( $('#storm_button').attr('src')=="img/storm2.png" )
		circ=2;
	//$("#icon3").attr("onclick",' allloot_tool();');

	$(".chest_btn").off('click');
	$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 allloot_tool();
					   
					});
	



	}
	else
	{
	
	$(".chest_btn").off('click');
	$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 allloot_tool();
					   
					});
	
	//$("#icon3").attr("onclick",' allloot_tool();');
	
	}			
	
}
function allloot_tool()
{
	hideAmmo();
	hideLoot();
	hideChest();
	showChest();
	showLoot();
	showAmmo();
	
	if ($('#draw_bus').length==0){
		
		
	circ=0;
	if ( $('#storm_button').attr('src')=="img/storm1.png" )
		circ=1;
	
	if ( $('#storm_button').attr('src')=="img/storm2.png" )
		circ=2;
	
	//$("#icon3").attr("onclick",' noloot_tool();');
	
	$(".chest_btn").off('click');
	$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 noloot_tool();
					   
					});
	
	
	}
	else{
	
	
	//$("#icon3").attr("onclick",' noloot_tool();');
	$(".chest_btn").off('click');
	$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 noloot_tool();
					   
					});
	
			
	}
}

function switch_tools()
{
	/*
		sidebar.removePanel('twitter');
		sidebar.removePanel('switch_tools');
		sidebar.removePanel('draw_bus');
		sidebar.removePanel('hide_marker'); 
		*/
		/*sidebar.removePanel('favorite'); */
		
		
		$("#icon5").attr("onclick",' switch_bus();');
	    $("#tool_img").attr("src", "img/home.png");
		$("#icon5_text").val("<b>R</b>ETURN TO BUS DROP");
		
		$("#icon4").attr("onclick",'');
		$("#icon4_img").attr("src", "img/storm.png");
		$("#icon4_text").val("<b>S0</b>TORM FORECAST COMING SOON");
		$("#icon4").show();
		
		
	
		$("#icon2").attr("onclick",' circle1_tool();');
	    $("#edit_img").attr("src", "img/circle1.png");
		$("#icon2_text").val("<b>T</b>AP TO SET A CIRCLE FOR ANALYSIS");
		
	/*
		sidebar.addPanel({
			id:   'storm',
			tab:  '<img id="storm_button" src="img/storm.png" border="0" style="max-width:90%;">',
			title: 'Storm Tool',
			button: function() {
				 circle1_tool()
			},
				disabled: false,
			});	
			
			sidebar.addPanel({
                id:   'switch_bus',
                tab:  '<img id="switch_bus" src="img/battlebus.png" border="0" style="max-width:90%;">',
                title: 'Landing Tools',
				position: 'bottom',
                button: function() {
					switch_bus();
				
				},
                disabled: false,
            }).addPanel({
                id:   'twitter',
                tab:  '<img id="twitter" src="img/twitter.png" border="0" style="max-width:90%;padding-top:20px;">',
                title: 'Follow Us',
				className : 'twitter',
				position: 'bottom',
				button:"https://twitter.com/landing_app",
                link:"https://twitter.com/landing_app",
                disabled: false,
            });
			*/
			$("#selectedTool").val(2);
			showTiming();
			hideBus();
			
		
			$("#bottom_button").html("<a id='main_button' href='#' class='button  button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a>");
			$("#top_button").html("<a id='main_button1' href='#' class='button  button_copilot'><b>T</b>IME TO <b>D</b>ESTINATION</a>");
	$("#main_button").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	$("#main_button1").click(function(e) {
		   go();
		   e.stopPropagation();
		});
	
}

function switch_bus()
{
	
	removeCircle();
	removeLikelihood();
	/*
		sidebar.removePanel('twitter');
		sidebar.removePanel('switch_bus');
		sidebar.removePanel('storm');
		*/
			$("#icon5").attr("onclick",' switch_tools();');
		$("#tool_img").attr("src", "img/timer.png");
		$("#icon5_text").val("<b>T</b>IMER AND <b>S</b>TORM TOOLS");
		
	    $("#icon2").attr("onclick",' hideBus();$("#selectedTool").val(1);');
	    $("#edit_img").attr("src", "img/edit.png");
		$("#icon2_text").val("<b>T</b>AP AND <b>D</b>RAG TO SET THE BUS");
		
		//$("#icon4").attr("onclick",'showHideMarkers();');
		//$("#marker_img").attr("src", "img/marker.png");
		//$("#icon4_text").val("<b>S</b>HOW OR <b>H</b>IDE MARKER");
		$("#icon4").hide();
		
		
		/*
		sidebar.addPanel({
                id:   'switch_tools',
                tab:  '<img id="switch_tool" src="img/timer.png" border="0" style="max-width:90%;">',
                title: 'Switch Tool',
				position: 'bottom',
                button: function() {
					switch_tools();
				
				},
                disabled: false,
            }).addPanel({
                id:   'twitter',
                tab:  '<img id="twitter" src="img/twitter.png" border="0" style="max-width:90%;padding-top:20px;">',
                title: 'Follow Us',
				className : 'twitter',
				position: 'bottom',
				button:"https://twitter.com/landing_app",
                link:"https://twitter.com/landing_app",
                disabled: false,
            })
		*/
		 /*sidebar.addPanel({
                id:   'favorite',
                tab:  '<img id="favorite" src="img/favorite_default.png" border="0" style="max-width:90%;">',
                title: 'Favorite locations',
                disabled:true,
                pane: '<p>Coming Soon</p>',
            });
			
			 sidebar.addPanel({
                id:   'hide_marker',
                tab:  '<img id="hide_marker" src="img/hide_marker.png" border="0" style="max-width:90%;">',
                title: 'Hide marker',
                button: function() { showHideMarkers();},
                disabled: false,
			});
			sidebar.addPanel({
                id:   'draw_bus',
                tab:  '<img id="draw_bus" src="img/battlebus_edit.png" border="0" style="max-width:90%;">',
                title: 'Battle Bus Route',
                button: function() {  hideBus();$("#selectedTool").val(1);},
                disabled: false,
            });
			*/
			$("#selectedTool").val(0);
			showBus();
			hideTiming();
			$("#bottom_button").html("<a id='main_button' href='#' class='button button_copilot'><b>F</b>IND <b>B</b>EST <b>D</b>ROP</a>");
			$("#top_button").html("<a id='main_button1' href='#' class='button button_copilot'><b>F</b>IND <b>B</b>EST <b>D</b>ROP</a>");
			$("#main_button").click(function(e) {
		   go();
		   e.stopPropagation();
		});
		$("#main_button1").click(function(e) {
		   go();
		   e.stopPropagation();
		});
		
}


function initBus()
{
	
	
	var latlng = rc.unproject([2000,6000]);
	if (targetMarkerS==1)
			targetMarkerS=L.marker(latlng,{draggable:false,icon:white_circle}).addTo(map);
		else
			targetMarkerS.setLatLng(latlng);
		
		if (targetMarker==1)
		{
			targetMarker=L.marker(latlng,{draggable:true,icon:white_pointer}).addTo(map);
			targetMarker.on('drag', function (event) {
				removeLikelihood();
				
				var latlng = targetMarker.getLatLng();
				targetMarkerS.setLatLng(latlng);
				hideRoute();
				$("#selectedTool").val(0);
				if (timingLine==1)
				{
					if (timingMarker!=1)
					timingLine=L.polyline([latlng,timingMarker.getLatLng() ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
				}
				else
				{
						var latlngs = timingLine.getLatLngs();
						latlngs[0]=latlng;
						timingLine.setLatLngs(latlngs);
				}
				 setDefaultLocation();
				
			});
			targetMarker.on('dragend', function (event) {
			
			//go();
			});
		 }
		else
			targetMarker.setLatLng(latlng);
		
		
   var latlngs = [rc.unproject([2000,2000]),rc.unproject([6000,6000])];
			$("#selectedTool").val(0);
			
    busRoute=L.polyline(latlngs, {color: 'red',weight:'2',className:'busRoute'}).addTo(layerBounds);	
    
			if (busStart==1)
			{
				busStart=L.marker([latlngs[0].lat, latlngs[0].lng],{draggable:true,icon: bus_pointer}).addTo(map);
				 busStart.on('drag', function (event) {
					 	hideRoute();
					 var latlngs = busRoute.getLatLngs();
					latlngs[0]=[event.latlng.lat, event.latlng.lng];
					busRoute.setLatLngs(latlngs);
					
							var b=0.0001;
							var delta=0.0001;
							var latlngs = busRoute.getLatLngs();

							
							xStart=rc.project(latlngs[0]).x;
							xStop=rc.project(latlngs[1]).x;
							yStart=rc.project(latlngs[0]).y;
							yStop=rc.project(latlngs[1]).y;
							
							
							
							 if ((xStop - xStart) != 0) {
								delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
								b = parseFloat(yStop) - parseFloat(xStop * delta);
								
								if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
							 
							 var stop=rc.unproject([xStop, yStop]);
							 var start=rc.unproject([xStart, yStart]);
							if (busRouteEdge==1)
							{
								busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'0'}).addTo(layerBounds);			
							}
							else
							{
								busRouteEdge.setLatLngs([start,stop]);
							}
							Xmid=(xStop+xStart)/2;
							Ymid=(yStop+yStart)/2;
								
							if (busRoutePath==1)
							{
								busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
							}
							else
							{
								busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
							}
							
							fix_busPath();
					
				 });
			}
			
			if (busStop==1)
			{
				busStop=L.marker([latlngs[1].lat, latlngs[1].lng],{draggable:true,icon: bus_pointer}).addTo(map);
				 busStop.on('drag', function (event) {
					 	hideRoute();
					 var latlngs = busRoute.getLatLngs();
					latlngs[1]=[event.latlng.lat, event.latlng.lng];
					busRoute.setLatLngs(latlngs);
							var b=0.0001;
							var delta=0.0001;
							var latlngs = busRoute.getLatLngs();

							
							xStart=rc.project(latlngs[0]).x;
							xStop=rc.project(latlngs[1]).x;
							yStart=rc.project(latlngs[0]).y;
							yStop=rc.project(latlngs[1]).y;
							
							
							
							 if ((xStop - xStart) != 0) {
								delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
								b = parseFloat(yStop) - parseFloat(xStop * delta);
								
								if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
							 
							 var stop=rc.unproject([xStop, yStop]);
							 var start=rc.unproject([xStart, yStart]);
							if (busRouteEdge==1)
							{
								busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'10'}).addTo(layerBounds);			
							}
							else
							{
								busRouteEdge.setLatLngs([start,stop]);
							}
					
							Xmid=(xStop+xStart)/2;
							Ymid=(yStop+yStart)/2;
								
							if (busRoutePath==1)
							{
								busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
							}
							else
							{
								busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
							}
							
							fix_busPath();
					
					
				 });
			}
			
			
			if (busReverse==1)
			{
				
				pt1=rc.project(latlngs[0]);
				pt2=rc.project(latlngs[1]);

				busReverse=L.marker(rc.unproject([ (pt1.x+pt2.x)/2,(pt1.y+pt2.y)/2]),{draggable:false,icon: bus_reverse}).addTo(map);
				busReverse.on('click', function (event) {
					 	hideRoute();
						
						var latlngst = busRoute.getLatLngs();
						var latlngs = [latlngst[1],latlngst[0]];
						busRoute.setLatLngs(latlngs);
						
						busStart.setLatLng(latlngs[0]);
						busStop.setLatLng(latlngs[1]);
					
							var b=0.0001;
							var delta=0.0001;
							var latlngs = busRoute.getLatLngs();

							
							xStart=rc.project(latlngs[0]).x;
							xStop=rc.project(latlngs[1]).x;
							yStart=rc.project(latlngs[0]).y;
							yStop=rc.project(latlngs[1]).y;
							
							
							
							 if ((xStop - xStart) != 0) {
								delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
								b = parseFloat(yStop) - parseFloat(xStop * delta);
								
								if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
							 
							 var stop=rc.unproject([xStop, yStop]);
							 var start=rc.unproject([xStart, yStart]);
							if (busRouteEdge==1)
							{
								busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'10'}).addTo(layerBounds);			
							}
							else
							{
								busRouteEdge.setLatLngs([start,stop]);
							}
					
							Xmid=(xStop+xStart)/2;
							Ymid=(yStop+yStart)/2;
								
							if (busRoutePath==1)
							{
								busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
							}
							else
							{
								busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
							}
							
							fix_busPath();
					
				 });
			}
			
			
			$(".busRoute").hide();
			
			var b=0.0001;
			var delta=0.0001;
			var latlngs = busRoute.getLatLngs();

			
			xStart=rc.project(latlngs[0]).x;
			xStop=rc.project(latlngs[1]).x;
			yStart=rc.project(latlngs[0]).y;
			yStop=rc.project(latlngs[1]).y;
			
			
			
			 if ((xStop - xStart) != 0) {
				delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
                b = parseFloat(yStop) - parseFloat(xStop * delta);
				
				
					if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
			 var stop=rc.unproject([xStop, yStop]);
			 var start=rc.unproject([xStart, yStart]);
			if (busRouteEdge==1)
			{
				busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'0'}).addTo(layerBounds);			
			}
			else
			{
				busRouteEdge.setLatLngs([start,stop]);
			}
			
			
			Xmid=(xStop+xStart)/2;
			Ymid=(yStop+yStart)/2;
				
			if (busRoutePath==1)
			{
				busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
			}
			else
			{
				busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
			}
			
			fix_busPath();
			 
}
	

function go()
{
	 //alert("Please wait until we are done re-mapping the new Chapter 3 Island");
	//	 return;
	
	/*
		if($('.adsbygoogle').css('display') == "none") {
			aderror=1;
		}
		
		if ($("rightside").val()==1)
			aderror=0;
	
		if (aderror==1)
		{
			alert("Please disable ad-block and refresh to be able to use our site properly");
			//return;
		}
	*/	
		
		
		if ($("#main_button").text()=="FIND BEST DROP")
		{	
	
		var target = rc.project(targetMarker.getLatLng());
			var latlngs = busRouteEdge.getLatLngs();
			var startB=rc.project(latlngs[0]);
			var stopB=rc.project(latlngs[1]);
			
			
			
			targetX=Math.round(500*(target.x-4096)/8192+250) ;
			targetY=Math.round(500*(target.y-4096)/8192+250);
			
			busStartX=Math.round(500*(startB.x-4096)/8192+250);
			busStartY=Math.round(500*(startB.y-4096)/8192+250);
			
			busStopX=Math.round(500*(stopB.x-4096)/8192+250);
			busStopY=Math.round(500*(stopB.y-4096)/8192+250);
			
		
		
		$.ajax(   // request url
			{
				url : 'ajax/preanalyze.php?targetX='+targetX+'&targetY='+targetY+'&busStartX='+busStartX+'&busStartY='+busStartY+'&busStopX='+busStopX+'&busStopY='+busStopY,
				timeout: 20000,
				beforeSend: function () { showWait(); }, 
				complete: function () { hideWait(); },
				success: function (data, status, xhr) {// success callback function
					try {
						
						//console.log(data);
						
						var startIndex=data.indexOf("<res>") + 5;
						if (startIndex==-1)
							startIndex=data.indexOf("<body>") + 6;
						
						var stopIndex=data.indexOf("</res>",startIndex);
						if (stopIndex==-1)
							stopIndex=data.indexOf("</body>",startIndex);
						
						var data=data.substring(startIndex,stopIndex );
						//console.log("test "+data1);
						
						//data = data.substring(data.indexOf("<body>") + 6);
						//data = data.substring(0,data.indexOf("<") );
						
						
						var d= data.split(',');
						if (d.length>4)
						{
							d[0]=d[0].replace("<html><head></head><body>","");
							d[0]=d[0].replace("</body></html>","");
							d[1]=d[1].replace("<html><head></head><body>","");
							d[1]=d[1].replace("</body></html>","");
							d[2]=d[2].replace("<html><head></head><body>","");
							d[2]=d[2].replace("</body></html>","");
							d[3]=d[3].replace("<html><head></head><body>","");
							d[3]=d[3].replace("</body></html>","");
							d[4]=d[4].replace("<html><head></head><body>","");
							d[4]=d[4].replace("</body></html>","");
							
							var jump= rc.unproject( [parseFloat(d[0])*8192,parseFloat(d[1])*8192] );
								console.log(jump);
							
							var deploy= rc.unproject( [parseFloat(d[2])*8192,parseFloat(d[3])*8192] );
							console.log(deploy);
						if (freefall==1)
							{
								freefall=L.polyline([jump,deploy ], {color: '#c3051c',weight:'3',className:'dropRoute',zIndexOffset:1000,dashArray:"20,10"}).addTo(layerBounds);			
							}
							else
							{
								freefall.setLatLngs([jump,deploy ]);
							}
						
							if (glide==1)
							{
								glide=L.polyline([deploy,targetMarker.getLatLng() ], {color: '#c3051c',weight:'3',className:'dropRoute',zIndexOffset:1000,dashArray:"20,10"}).addTo(layerBounds);			
							}
							else
							{
								glide.setLatLngs([deploy,targetMarker.getLatLng() ]);
							}
						
						
						
						if (jumpMarker==1)
							jumpMarker=L.marker(jump,{draggable:false,icon:red_circle,zIndexOffset:1000}).addTo(map);
						else
							jumpMarker.setLatLng(jump);
						
							
						if (deployMarkerS==1)
							deployMarkerS=L.marker(deploy,{draggable:false,icon:blue_circle,zIndexOffset:1000}).addTo(map);
						else
							deployMarkerS.setLatLng(deploy);
						
						if (deployMarker==1)
							deployMarker=L.marker(deploy,{draggable:false,icon:yellow_pointer,zIndexOffset:1000}).addTo(map);
						else
							deployMarker.setLatLng(deploy);
						
						
							
						if (d[4]>100)  
						{						
							deployMarker.bindPopup(""+Math.round(d[4])+" M").openPopup();
							$("#autodeploy").html("MANUAL GLIDER DEPLOYMENT");
						}
						else   
						{
							deployMarker.bindPopup(""+d[4]+" M").openPopup();
							$("#autodeploy").html("AUTOMATIC GLIDER DEPLOYMENT");
						}
						
						if (deployMarkerImg==1)
							deployMarkerImg=L.marker(deploy,{draggable:false,icon:parachute_pointer,zIndexOffset:1000}).addTo(map);
						else
							deployMarkerImg.setLatLng(deploy);
						
						
						
						$('.dropRoute').show();
						$('.yellow_pointer').show();
						$('.parachute_pointer').show();
						$('.blue_circle').show();
						$('.red_circle').show(); 
						
							
						
						}	
					}
					catch(err) {
						alert("Something went wrong... \n Please contact us with the following informaiton :  \n"+err.message+"  \n"+data);
						hideWait();
					}
					
					
					
					
				},
					error: function (jqXhr, textStatus, errorMessage) { // error callback 
						alert('Error: ' + errorMessage);
						hideWait();
					}
			
			});
		}
		else
		{	
	
			var target = rc.project(targetMarker.getLatLng());
			var timingPt = rc.project(timingMarker.getLatLng());

			
			
			
			targetX=Math.round(525*(target.x-4096)/8192+250);
			targetY=Math.round(525*(target.y-4096)/8192+250);
			timingX=Math.round(525*(timingPt.x-4096)/8192+250);
			timingY=Math.round(525*(timingPt.y-4096)/8192+250);

	
		$.ajax('ajax/timing.php?targetX='+targetX+'&targetY='+targetY+'&timingX='+timingX+'&timingY='+timingY,   // request url
			{
				beforeSend: function () { showWait(); }, 
				complete: function () { hideWait(); },
				success: function (data, status, xhr) {// success callback function
					
					var d= data.split(',');
					if (d.length==2)
					{
						if (d[1]>9)
							timingMarker.bindPopup("<b>"+Math.round(d[0])+":"+d[1]+"</b>").openPopup();
						else
							timingMarker.bindPopup("<b>"+Math.round(d[0])+":0"+d[1]+"</b>").openPopup();
						
					}
					
				},
					error: function (jqXhr, textStatus, errorMessage) { // error callback 
						alert('Error: ' + errorMessage);
					}
			
			});
		}	
}
	

function fix_busPath()
{
	
	if ($("#main_button").text()=="TIME TO DESTINATION")
		return;
	
	if ($(".bus_path").length)
	{
			for (i=0;i<360;i++)
				if ( $(".bus_path").hasClass('bus_path'+i) )
					$(".bus_path").removeClass('bus_path'+i);
				
			var latlngs = busRoute.getLatLngs();
			var dx=rc.project(latlngs[1]).x-rc.project(latlngs[0]).x;
			var dy=rc.project(latlngs[1]).y-rc.project(latlngs[0]).y;
			var angle=(Math.atan2(dy,dx) +3*Math.PI/2 ) ;
		
			angle=Math.round(180*(angle)/Math.PI);
			
			if (angle==360)
				angle=0;
			if (angle<0)
				angle+=360;
			if (angle>360)
				angle-=360;
			
			$(".bus_path").addClass('bus_path'+angle);
			$(".bus_path").show();
			
			if (busReverse==1)
			{
				
				pt1=rc.project(latlngs[0]);
				pt2=rc.project(latlngs[1]);

				busReverse=L.marker(rc.unproject([ (pt1.x+pt2.x)/2,(pt1.y+pt2.y)/2]),{draggable:false,icon: bus_reverse}).addTo(map);
				busReverse.on('click', function (event) {
					 	hideRoute();
						
						var latlngst = busRoute.getLatLngs();
						var latlngs = [latlngst[1],latlngst[0]];
						busRoute.setLatLngs(latlngs);
						
						busStart.setLatLng(latlngs[0]);
						busStop.setLatLng(latlngs[1]);
					
							var b=0.0001;
							var delta=0.0001;
							var latlngs = busRoute.getLatLngs();

							
							xStart=rc.project(latlngs[0]).x;
							xStop=rc.project(latlngs[1]).x;
							yStart=rc.project(latlngs[0]).y;
							yStop=rc.project(latlngs[1]).y;
							
							
							
							 if ((xStop - xStart) != 0) {
								delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
								b = parseFloat(yStop) - parseFloat(xStop * delta);
								
								if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
							 
							 var stop=rc.unproject([xStop, yStop]);
							 var start=rc.unproject([xStart, yStart]);
							if (busRouteEdge==1)
							{
								busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'10'}).addTo(layerBounds);			
							}
							else
							{
								busRouteEdge.setLatLngs([start,stop]);
							}
					
							Xmid=(xStop+xStart)/2;
							Ymid=(yStop+yStart)/2;
								
							if (busRoutePath==1)
							{
								busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
							}
							else
							{
								busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
							}
							
							fix_busPath();
					
				 });
			}
			else
			{
				pt1=rc.project(latlngs[0]);
				pt2=rc.project(latlngs[1]);
				busReverse.setLatLng(rc.unproject([ (pt1.x+pt2.x)/2,(pt1.y+pt2.y)/2]));
			}
		
			sharingcode=$("#sharingcode").val();;
			isSharing=$("#issharing").val();
								
								
								
			if (isSharing>0)
			{
			
				var startB=rc.project(latlngs[0]);
				var stopB=rc.project(latlngs[1]);
			
				 $.ajax('hooks/share_bus.php?code='+sharingcode+'&secret='+isSharing+'&userid='+$("#mapversion").val()+'&startbusx='+(parseFloat(startB.x)/8192)+'&stopbusx='+(parseFloat(stopB.x)/8192)+'&startbusy='+(parseFloat(startB.y)/8192)+'&stopbusy='+(parseFloat(stopB.y)/8192),   // request url
						{
							dataType: 'json',
							success: function (data, status, xhr) {// success callback function
								
								
							}
				});
			}
			
	}
	
}




var dialogShowing=0;
function loadingOver()
{

	if ($("#loadingId").val()==0)
	{
		dialogShowing=1;
		$( "#dialog" ).show();
		$( "#dialog" ).dialog({
			dialogClass: "no-close",
		});
		


			setTimeout(function () {
			   $( "#dialog" ).dialog( "close" );
			   if (aderror==0)
					$("#main_button").show();
				
				if ($("#settingSpots").val()==1)
					$("#main_button").hide();
				
				// $("#map").css({'height': $(window).height()*0.9});
				//$("#page").css({'height': $(window).height()*0.9});
				 map.invalidateSize(true);
			 }, 5000);
	}
	else
	{
		$("#main_button").show();
		 map.invalidateSize(true);
	}
	
	

}

function getDefaultLocation()
{
	if ( $( "#mapversion" ).length ) {
		
			
			
			$.ajax('hooks/default_location.php?userid='+$("#mapversion").val(),   // request url
						{
							dataType: 'json',
							success: function (data, status, xhr) {// success callback function
								
								var latlng=rc.unproject([data['x']*8192,data['y']*8192]);
								targetMarker.setLatLng(latlng);
							    targetMarkerS.setLatLng(latlng);
							}
				});
		}
	
	
}

function setDefaultLocation()
{
	if ( $( "#mapversion" ).length ) {
		
			var latlng=targetMarker.getLatLng();
			var pos=rc.project([latlng.lat,latlng.lng])
	
			
			$.ajax('hooks/default_location.php?userid='+$("#mapversion").val()+"&x="+pos.x/8192+"&y="+pos.y/8192,   // request url
						{
							dataType: 'json',
							success: function (data, status, xhr) {// success callback function
								

							}
				});
		}
	
	
}

function startShare()
{
	if ( $( "#mapversion" ).length ) {
		sharingcode=$("#sharingcode").val();
		if (sharingcode=="")
		{
			
			
			$.ajax('hooks/share_bus.php?userid='+$("#mapversion").val(),   // request url
						{
							dataType: 'json',
							success: function (data, status, xhr) {// success callback function
								
								sharingcode=data['code'];
								isSharing=data['secret'];
								
								$("#sharingcode").val(data['code']);
								$("#issharing").val(data['secret']);
								
								
								$("#getcode").html( "Share this code : <b>" +sharingcode+"</b>" );
								
								$("#entercode").hide();
								$("#shareor").hide();
								
								document.getElementById("hover_text").innerHTML = "CURENTLY SHARING BUS ROUTE WITH CODE <br><span style=\"font-size:24px;font-family: 'Ubuntu', sans-serif;font-weight:700;color:#34ff80; \">"+sharingcode+"</span>";
		
							}
				});
		}
	}
}

function validateShare()
{
	if ( $( "#mapversion" ).length ) {
		if ($('#code').val()!="")
		{
				$.ajax('hooks/share_bus.php?code='+$('#code').val()+'&userid='+$("#mapversion").val(),   // request url
						{
							dataType: 'json',
							success: function (data, status, xhr) {// success callback function
								
								
								
								if (data['code']==$('#code').val())
								{
									
									
									sharingcode=data['code'];
									
									$("#sharingcode").val(data['code']);
									$("#issharing").val(0);
									
									
									
									$("#getcode").html( "You are connected with code : <b>" +sharingcode+"</b>");
									$("#stopsharing").show();
									$("#stopsharing").html("Disconnect");
									$("#entercode").hide();
									$("#shareor").hide();
									
								if (  parseFloat( data['startbusx'] ) +  parseFloat( data['startbusy'] )+  parseFloat( data['stopbusx'] )+ parseFloat( data['stopbusy'] )>0.001)
								{
								
									startbusx_server=data['startbusx'];
									startbusy_server=data['startbusy'];
									stopbusx_server=data['stopbusx'];
									stopbusy_server=data['stopbusy'];
									
								
									data['startbusx']=parseFloat(data['startbusx'])*8192;
									data['startbusy']=parseFloat(data['startbusy'])*8192;
									data['stopbusx']=parseFloat(data['stopbusx'])*8192;
									data['stopbusy']=parseFloat(data['stopbusy'])*8192;
									
								
									
								
									 var stop=rc.unproject([data['stopbusx'], data['stopbusy']]);
									 var start=rc.unproject([data['startbusx'], data['startbusy']]);
									
									
									
									busStart.setLatLng(start);
									busStop.setLatLng(stop);
								
									busReverse.setLatLng(rc.unproject([ ( parseFloat(data['startbusx'])+ parseFloat(data['stopbusx']))/2,( parseFloat(data['startbusy'])+ parseFloat(data['stopbusy']))/2]));
									busRoute.setLatLngs([start,stop]);
					
									hideRoute();
									// var latlngs = busRoute.getLatLngs();
									//latlngs[0]=[event.latlng.lat, event.latlng.lng];
									//busRoute.setLatLngs(latlngs);
									
											var b=0.0001;
											var delta=0.0001;
											var latlngs = busRoute.getLatLngs();

											
											xStart=rc.project(latlngs[0]).x;
											xStop=rc.project(latlngs[1]).x;
											yStart=rc.project(latlngs[0]).y;
											yStop=rc.project(latlngs[1]).y;
											
											
											
											 if ((xStop - xStart) != 0) {
												delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
												b = parseFloat(yStop) - parseFloat(xStop * delta);
												
												if (xStart<xStop)
												{
													xStart=10;
													yStart=delta*xStart+b;
													
													xStop=8180;
													yStop=delta*xStop+b;

												}
												else
												{
													xStart=8180;
													yStart=delta*xStart+b;
													xStop=10;
													yStop=delta*xStop+b;
												}
												
												if (yStart<10)
													{
														yStart=10;
														xStart=(yStart-b)/delta;
													}
													
													if (yStart>8180)
													{
														yStart=8180;
														xStart=(yStart-b)/delta;
													}

													if (yStop<10)
													{
														yStop=10;
														xStop=(yStop-b)/delta;
													}
													
													if (yStop>8180)
													{
														yStop=8180;
														xStop=(yStop-b)/delta;
													}
											 }
											 else
											 {
												 if (yStart<yStop)
												 {
													yStart=10;
													yStop=8180;
												 }
												 else
												{
													yStart=8180;
													yStop=10;
												}
											 }
											 
											 var stop=rc.unproject([xStop, yStop]);
											 var start=rc.unproject([xStart, yStart]);
											if (busRouteEdge==1)
											{
												busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'0'}).addTo(layerBounds);			
											}
											else
											{
												busRouteEdge.setLatLngs([start,stop]);
											}
											Xmid=(xStop+xStart)/2;
											Ymid=(yStop+yStart)/2;
												
											if (busRoutePath==1)
											{
												busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
											}
											else
											{
												busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
											}
								
					
					
									fix_busPath();
								
		
			
					
								
								}
							
							
									setTimeout(function () {
									   updateShare()
										}, 1000);
										
									 $( "#sharedialog" ).dialog( "close" );
									document.getElementById("hover_text").innerHTML = "CURENTLY RECEIVING BUS ROUTE FROM CODE <br><span style=\"font-size:24px;font-family: 'Ubuntu', sans-serif;font-weight:700;color:#34ff80; \">"+sharingcode+"</span>";
				
								}		
							}						
						});
									
									
		}
	}
}



function stopSharing()
{
	isSharing=0;
	sharingcode="";
	
	$("#sharingcode").val("");
	$("#issharing").val(0);
	
	document.getElementById("hover_text").innerHTML =document.getElementById("icon7_text").value;
	
	$( "#sharedialog" ).dialog( "close" );
}

function updateShare()
{
	if ( $( "#mapversion" ).length ) {
		sharingcode=$("#sharingcode").val();
		if (sharingcode!="")
		{
		 $.ajax('hooks/share_bus.php?code='+sharingcode,   // request url
						{
							dataType: 'json',
							success: function (data, status, xhr) {// success callback function
								
								
								if (  parseFloat( data['startbusx'] ) +  parseFloat( data['startbusy'] )+  parseFloat( data['stopbusx'] )+ parseFloat( data['stopbusy'] )>0.001)
								{
									
									if (  Math.abs( parseFloat(startbusx_server)- parseFloat( data['startbusx'] ) ) +  Math.abs( parseFloat(startbusy_server)- parseFloat( data['startbusy'] ) )+Math.abs( parseFloat(stopbusx_server)- parseFloat( data['stopbusx'] ) )+Math.abs( parseFloat(stopbusy_server)- parseFloat( data['stopbusy'] ) )>0.001 )
									{
										
										
									startbusx_server=data['startbusx'];
									startbusy_server=data['startbusy'];
									stopbusx_server=data['stopbusx'];
									stopbusy_server=data['stopbusy'];
									
								
								
									data['startbusx']=parseFloat(data['startbusx'])*8192;
									data['startbusy']=parseFloat(data['startbusy'])*8192;
									data['stopbusx']=parseFloat(data['stopbusx'])*8192;
									data['stopbusy']=parseFloat(data['stopbusy'])*8192;
									
									
								
									 var stop=rc.unproject([parseFloat(data['stopbusx']), parseFloat(data['stopbusy'])]);
									 var start=rc.unproject([parseFloat(data['startbusx']), parseFloat(data['startbusy'])]);
									
									
									busStart.setLatLng(start);
									busStop.setLatLng(stop);
								
									busReverse.setLatLng(rc.unproject([ ( parseFloat(data['startbusx'])+ parseFloat(data['stopbusx']))/2,( parseFloat(data['startbusy'])+ parseFloat(data['stopbusy']))/2]));
									busRoute.setLatLngs([start,stop]);
									
									
								
									 hideRoute();
									// var latlngs = busRoute.getLatLngs();
									//latlngs[0]=[event.latlng.lat, event.latlng.lng];
									//busRoute.setLatLngs(latlngs);
									
											var b=0.0001;
											var delta=0.0001;
											var latlngs = busRoute.getLatLngs();

											
											xStart=rc.project(latlngs[0]).x;
											xStop=rc.project(latlngs[1]).x;
											yStart=rc.project(latlngs[0]).y;
											yStop=rc.project(latlngs[1]).y;
											
											
											
											 if ((xStop - xStart) != 0) {
												delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
												b = parseFloat(yStop) - parseFloat(xStop * delta);
												
												if (xStart<xStop)
												{
													xStart=10;
													yStart=delta*xStart+b;
													
													xStop=8180;
													yStop=delta*xStop+b;

												}
												else
												{
													xStart=8180;
													yStart=delta*xStart+b;
													xStop=10;
													yStop=delta*xStop+b;
												}
												
												if (yStart<10)
													{
														yStart=10;
														xStart=(yStart-b)/delta;
													}
													
													if (yStart>8180)
													{
														yStart=8180;
														xStart=(yStart-b)/delta;
													}

													if (yStop<10)
													{
														yStop=10;
														xStop=(yStop-b)/delta;
													}
													
													if (yStop>8180)
													{
														yStop=8180;
														xStop=(yStop-b)/delta;
													}
											 }
											 else
											 {
												 if (yStart<yStop)
												 {
													yStart=10;
													yStop=8180;
												 }
												 else
												{
													yStart=8180;
													yStop=10;
												}
											 }
											 
											 var stop=rc.unproject([xStop, yStop]);
											 var start=rc.unproject([xStart, yStart]);
											if (busRouteEdge==1)
											{
												busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'0'}).addTo(layerBounds);			
											}
											else
											{
												busRouteEdge.setLatLngs([start,stop]);
											}
											Xmid=(xStop+xStart)/2;
											Ymid=(yStop+yStart)/2;
												
											if (busRoutePath==1)
											{
												busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
											}
											else
											{
												busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
											}
								
								
							
							
							
							
							
							
										fix_busPath();
									}
		
									
									
								}
								setTimeout(function () {
									   updateShare()
									 }, 1000);
								
							}
				});
		}
	}
	
	
	
}


function showShare()
{
	
	
	if ( $( "#mapversion" ).length ) {
		
		sharingcode=$("#sharingcode").val();
		isSharing=$("#issharing").val();
		
		
		//$( "#sharedialog" ).css("height", $( "#map" ).css("height"));	   
		//$( "#sharedialog" ).css("width", $( "#map" ).css("width"));	   
		//$( "#waitdialog" ).css("top", $( "#page" ).css("margin-top"));	   
		
		
		$( "#sharedialog" ).dialog({
			dialogClass: "no-close",
			width: "30%",
		});
		
		
		$( "#sharedialog" ).show();	   
		  
		

		
				
		if (sharingcode=="")
		{
			$("#stopsharing").hide();
			$("#entercode").show();
			$("#shareor").show();
			$("#getcode").html( "Get a code");
			$("#code").val( "");
			
		}
		
		if (isSharing!=0)
		{
			$("#entercode").hide();
			$("#getcode").html( "Share this code : <b>" +sharingcode+"</b>");
			$("#stopsharing").show();
			$("#stopsharing").html("Stop Sharing");
		}
		else if (sharingcode!="")
		{
			$("#getcode").html( "You are connected with code : <b>" +sharingcode+"</b>");
			$("#stopsharing").show();
			$("#stopsharing").html("Disconnect");
			
		}
	}
	else
	{
		
		showLogin();
		/*
		$("#getcode").html( "Please <b>sign-in</b> in order to share your bus route.<br>It's free, makes things more reliable and we are working on bonus features.");
		$( "#sharedialog" ).dialog({
			dialogClass: "no-close",
			width: "40%",
		});
		$( "#sharedialog" ).show();	   
		
		$("#stopsharing").hide();
			$("#entercode").hide();
			$("#shareor").hide();
			$("#getcode").show( );
			$("#code").hide( );
			*/
		
	}
}





function hideShare()
{
	   
	  $( "#sharedialog" ).dialog( "close" );

}


function showWait()
{
	//$( "#waitdialog" ).dialog({
	//	dialogClass: "no-close"
	//});
	/* $('.ui-dialog').css({
				'width': $(window).width(),
				'height': $(window).height(),
				'left': '0px',
				'top':'0px'
		   });
		   */
		   
	$( "#waitdialog" ).css("height", $( "#map" ).css("height"));	   
	$( "#waitdialog" ).css("width", $( "#map" ).css("width"));	   
	//$( "#waitdialog" ).css("top", $( "#page" ).css("margin-top"));	   
	$( "#waitdialog" ).show();	   
		   
}

function hideWait()
{
	 // $( "#waitdialog" ).dialog( "close" );
	 $( "#waitdialog" ).hide();	
	
	
}

function init () { // eslint-disable-line no-unused-vars
  
	$("#main_button").click(function(e) {
		    e.stopPropagation();
			go();
		 
		});
	
  
  var img = [
    8192, // original width of image
    8192 // original height of image
  ]

  for (i=0;i<360;i++)
	  	$('head').append('<style>.bus_path'+i+':before{content: "";transform-origin:center center;position: absolute;width:100%;height: 100%;top: 0%;left: 0%;z-index: -1;background: url(img/bus_path.png) 0 0 repeat;-webkit-transform: rotate('+i+'deg);transform: rotate('+i+'deg);}</style>');
  
  
  

  
  // 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)
  // set max zoom Level (might be `x` if gdal2tiles was called with `-z 0-x` option)
  //map.setMaxZoom(rc.zoomLevel())
  // set the view in the middle of the image
  map.setView(rc.unproject([img[0] / 2, img[1] / 2]), 2)
  

  map.setView(rc.unproject([img[0] / 2, img[1] / 2]), map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false))


  
  

  // set marker at the image bound edges
  layerBounds = L.layerGroup([
  ])
  map.addLayer(layerBounds)

  
 sidebar = L.control.sidebar({ container: 'sidebar' });//.addTo(map);

          
  map.on('load', function (event) {
	   map.invalidateSize(true);
	   
   });

  
   map.on('zoomend', function (event) {
	   fix_busPath();
	   if ($("#settingSpots").val()==1)
			initSpots();
	   
   });
   map.on('zoomlevelschange', function (event) {
	   fix_busPath();
	   if ($("#settingSpots").val()==1)
			initSpots();
	   
   });
   map.on('zoomstart', function (event) {
	  $(".bus_path").hide();
	    if ($("#settingSpots").val()==1)
			initSpots();
   });
  
  map.on('resize', function (e) {
		
		
				map.setMinZoom( map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false) );
		});

  
  map.on('click', function (event) {
	  
	//try{$(".ezoic-floating-bottom").hide();  }catch(err){}
	  
	hideRoute();
	   
	  if ($("#settingSpots").val()==1)
	  {
		  clickSpots(event);
		  return;
	  }
	  
	  
	if ($("#selectedTool").val()==0){
		
		
		if (isMovingCircle===1)
		{
			isMovingCircle=0;
			return;
		}
		removeLikelihood();
		if (targetMarkerS==1)
			targetMarkerS=L.marker([event.latlng.lat, event.latlng.lng],{draggable:false,icon:white_circle}).addTo(map);
		else
			targetMarkerS.setLatLng([event.latlng.lat, event.latlng.lng]);
		
		if (targetMarker==1)
		{
			targetMarker=L.marker([event.latlng.lat, event.latlng.lng],{draggable:true,icon:white_pointer}).addTo(map);
			targetMarker.on('drag', function (event) {
				removeLikelihood();
				var latlng = targetMarker.getLatLng();
				targetMarkerS.setLatLng(latlng);
				hideRoute();
				$("#selectedTool").val(0);
				if (timingLine==1)
				{
					if (timingMarker!=1)
					timingLine=L.polyline([latlng,timingMarker.getLatLng() ], {color: '0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
				}
				else
				{
						var latlngs = timingLine.getLatLngs();
						latlngs[0]=latlng;
						timingLine.setLatLngs(latlngs);
				}
				 setDefaultLocation();
				
			});
			targetMarker.on('dragend', function (event) {
			//go();
			//console.log("yop");
			});
			
		 }
		else
			targetMarker.setLatLng([event.latlng.lat, event.latlng.lng]);

		 setDefaultLocation();
		//go();
		//console.log("yop");
	
	}
	
	if ($("#selectedTool").val()==2){
		
		if (isMovingCircle===1)
		{
			isMovingCircle=0;
			return;
		}
		removeLikelihood();
		if (timingMarkerS==1)
			timingMarkerS=L.marker([event.latlng.lat, event.latlng.lng],{draggable:false,icon:timing_circle}).addTo(map);
		else
			timingMarkerS.setLatLng([event.latlng.lat, event.latlng.lng]);
		
		if (timingMarker==1)
		{
			timingMarker=L.marker([event.latlng.lat, event.latlng.lng],{draggable:true,icon:timing_pointer}).addTo(map);
			timingMarker.on('drag', function (event) {
				removeLikelihood();
				var latlng = timingMarker.getLatLng();
				timingMarkerS.setLatLng(latlng);
				hideRoute();
				$("#selectedTool").val(2);
				
				if (timingLine==1)
				{
					timingLine=L.polyline([targetMarker.getLatLng(),[event.latlng.lat,event.latlng.lng] ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
				}
				else
				{
						var latlngs = timingLine.getLatLngs();
						latlngs[1]=[event.latlng.lat, event.latlng.lng];
						timingLine.setLatLngs(latlngs);
				}
				
				
			});
		 }
		else
			timingMarker.setLatLng([event.latlng.lat, event.latlng.lng]);
			if (timingLine==1)
			{
				timingLine=L.polyline([targetMarker.getLatLng(),[event.latlng.lat,event.latlng.lng] ], {color: '#0f89d1',dashArray: '5,10',weight:'2',className:'timingRoute'}).addTo(layerBounds);			
			}
			else
			{
					var latlngs = timingLine.getLatLngs();
					latlngs[1]=[event.latlng.lat, event.latlng.lng];
					timingLine.setLatLngs(latlngs);
			}
		
	
	}
	
  
  if ($("#selectedTool").val()==1){
		if (drawingBus==0)
		{
			if (busRoute==1)
			{
				busRoute=L.polyline([[event.latlng.lat,event.latlng.lng],[event.latlng.lat,event.latlng.lng] ], {color: 'red',weight:'2',className:'busRoute'}).addTo(layerBounds);			
			}
			else
			{
				busRoute.setLatLngs([[event.latlng.lat,event.latlng.lng],[event.latlng.lat,event.latlng.lng] ]);
				$(".busRoute").show();
			}
			drawingBus=1;
		}
		else
		{
			
			drawingBus=0;
			var latlngs = busRoute.getLatLngs();
			$("#selectedTool").val(0);
			
			if (busStart==1)
			{
				busStart=L.marker([latlngs[0].lat, latlngs[0].lng],{draggable:true,icon: bus_pointer}).addTo(map);
				 busStart.on('drag', function (event) {
					 	hideRoute();
					 var latlngs = busRoute.getLatLngs();
					latlngs[0]=[event.latlng.lat, event.latlng.lng];
					busRoute.setLatLngs(latlngs);
					
							var b=0.0001;
							var delta=0.0001;
							var latlngs = busRoute.getLatLngs();

							
							xStart=rc.project(latlngs[0]).x;
							xStop=rc.project(latlngs[1]).x;
							yStart=rc.project(latlngs[0]).y;
							yStop=rc.project(latlngs[1]).y;
							
							
							
							 if ((xStop - xStart) != 0) {
								delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
								b = parseFloat(yStop) - parseFloat(xStop * delta);
								
								if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
							 
							 var stop=rc.unproject([xStop, yStop]);
							 var start=rc.unproject([xStart, yStart]);
							if (busRouteEdge==1)
							{
								busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'0'}).addTo(layerBounds);			
							}
							else
							{
								busRouteEdge.setLatLngs([start,stop]);
							}
							Xmid=(xStop+xStart)/2;
							Ymid=(yStop+yStart)/2;
								
							if (busRoutePath==1)
							{
								busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
							}
							else
							{
								busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
							}
							
							fix_busPath();
					
				 });
			}
			else
				busStart.setLatLng([latlngs[0].lat, latlngs[0].lng]);
			
			if (busStop==1)
			{
				busStop=L.marker([latlngs[1].lat, latlngs[1].lng],{draggable:true,icon: bus_pointer}).addTo(map);
				 busStop.on('drag', function (event) {
					 	hideRoute();
					 var latlngs = busRoute.getLatLngs();
					latlngs[1]=[event.latlng.lat, event.latlng.lng];
					busRoute.setLatLngs(latlngs);
							var b=0.0001;
							var delta=0.0001;
							var latlngs = busRoute.getLatLngs();

							
							xStart=rc.project(latlngs[0]).x;
							xStop=rc.project(latlngs[1]).x;
							yStart=rc.project(latlngs[0]).y;
							yStop=rc.project(latlngs[1]).y;
							
							
							
							 if ((xStop - xStart) != 0) {
								delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
								b = parseFloat(yStop) - parseFloat(xStop * delta);
								
								if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
							 
							 var stop=rc.unproject([xStop, yStop]);
							 var start=rc.unproject([xStart, yStart]);
							if (busRouteEdge==1)
							{
								busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'10'}).addTo(layerBounds);			
							}
							else
							{
								busRouteEdge.setLatLngs([start,stop]);
							}
					
							Xmid=(xStop+xStart)/2;
							Ymid=(yStop+yStart)/2;
								
							if (busRoutePath==1)
							{
								busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
							}
							else
							{
								busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
							}
							
							fix_busPath();
					
					
				 });
			}
			else
				busStop.setLatLng([latlngs[1].lat, latlngs[1].lng]);
			
			$(".busRoute").hide();
			
			var b=0.0001;
			var delta=0.0001;
			var latlngs = busRoute.getLatLngs();

			
			xStart=rc.project(latlngs[0]).x;
			xStop=rc.project(latlngs[1]).x;
			yStart=rc.project(latlngs[0]).y;
			yStop=rc.project(latlngs[1]).y;
			
			
			
			 if ((xStop - xStart) != 0) {
				delta = parseFloat(yStop - yStart) / parseFloat(xStop - xStart);
                b = parseFloat(yStop) - parseFloat(xStop * delta);
				
				
					if (xStart<xStop)
								{
									xStart=10;
									yStart=delta*xStart+b;
									
									xStop=8180;
									yStop=delta*xStop+b;

								}
								else
								{
									xStart=8180;
									yStart=delta*xStart+b;
									xStop=10;
									yStop=delta*xStop+b;
								}
								
								if (yStart<10)
									{
										yStart=10;
										xStart=(yStart-b)/delta;
									}
									
									if (yStart>8180)
									{
										yStart=8180;
										xStart=(yStart-b)/delta;
									}

									if (yStop<10)
									{
										yStop=10;
										xStop=(yStop-b)/delta;
									}
									
									if (yStop>8180)
									{
										yStop=8180;
										xStop=(yStop-b)/delta;
									}
							 }
							 else
							 {
								 if (yStart<yStop)
								 {
									yStart=10;
									yStop=8180;
								 }
								 else
								{
									yStart=8180;
									yStop=10;
								}
							 }
			 var stop=rc.unproject([xStop, yStop]);
			 var start=rc.unproject([xStart, yStart]);
			if (busRouteEdge==1)
			{
				busRouteEdge=L.polyline([start,stop ], {color: 'red',weight:'0'}).addTo(layerBounds);			
			}
			else
			{
				busRouteEdge.setLatLngs([start,stop]);
			}
			
			
			Xmid=(xStop+xStart)/2;
			Ymid=(yStop+yStart)/2;
				
			if (busRoutePath==1)
			{
				busRoutePath=L.marker( rc.unproject([Xmid,Ymid]),{draggable:false,icon: bus_path,interactive:false}).addTo(map);		
			}
			else
			{
				busRoutePath.setLatLng(rc.unproject([Xmid,Ymid]));
			}
			
			fix_busPath();
			showBus();
			
			
			
			
		}
	}
	

  });
  

  
 
  
  
  map.on('mousemove', function (event) {
	
	if ($("#selectedTool").val()==1){
		if (drawingBus==1)
		{
			var latlngs = busRoute.getLatLngs();
			latlngs[1]=[event.latlng.lat, event.latlng.lng];
			busRoute.setLatLngs(latlngs);
		}
	}
  })
  
  
showNames();
  
// SideBar

  // the tile layer containing the image generated with gdal2tiles --leaflet ...
  L.tileLayer('./'+tiles_location+'/{z}/{x}/{y}.png?version=365642', {
    noWrap: true,
    attribution: '<a href="landingtutorial.com/home">landingtutorial.com</a>'
  }).addTo(map)
	
    
$('.leaflet-control-attribution').html('').hide();
   

  $('#upgrade-toggle').change(function() {
        showHideUpgrade();
      });
    
    $('#boat-toggle').change(function() {
        showHideBoat();
      });
    $('#heli-toggle').change(function() {
        showHideHeli();
      });
    
    $('#mushroom-toggle').change(function() {
        showHideMushroom();
      });
    
    $('#chug-toggle').change(function() {
        showHideChug();
      });
    
    $('#reboot-toggle').change(function() {
        showHideReboot();
      });
    
    $('#campfire-toggle').change(function() {
        showHideCampfire();
      });
    

	
	$("#icon2").attr("onclick",' hideBus();$("#selectedTool").val(1);');
	//$("#icon3").attr("onclick","chest_tool();");
	
	//$("#icon4").attr("onclick","showHideMarkers();");
	$("#icon4").hide();
	$("#icon5").attr("onclick","switch_tools();");
	
	$("#icon7").attr("onclick","showShare();");
	
	if ($("#settingSpots").val()==0)
		loadingOver();
	
	$(window).resize(function () {
		   $('.ui-dialog:not(#sharedialog)').css({
				'width': $(window).width(),
				'height': $(window).height(),
				'left': '0px',
				'top':'0px'
		   });
		   
			map.setMinZoom( map.getBoundsZoom(L.latLngBounds([85,-180],[-85,180]), false));
		   
		   
		   
	$( ".leaflet-control-zoom").html("");
	
	if ($( ".leaflet-control-zoom").html().indexOf("Marker") == -1)
	{
		$( ".leaflet-control-zoom").append("<a class=\"marker_btn\" style='margin-top:6px;' href=\"#\" title=\"Marker\" role=\"button\" aria-label=\"Marker\"><img style='text-indent: 0px  !important;width:30px;height:30px;' id=\"marker_img\" src=\"img/marker.png\" border=\"0\"/></a>");
			$(".marker_btn").click(function(e) {
					  e.stopPropagation();
					  showHideMarkers();
					   
					});
	}
/*
	if ($( ".leaflet-control-zoom").html().indexOf("Chest") == -1)
	{
		$( ".leaflet-control-zoom").append("<a class=\"chest_btn\" style='margin-top:6px;' href=\"#\" title=\"Chest\" role=\"button\" aria-label=\"Chest\"><img style='text-indent: 0px  !important;width:30px;height:30px;' id=\"chest_img\" src=\"img/chest_menu.png\" border=\"0\"/></a>");
			$(".chest_btn").click(function(e) {
					  e.stopPropagation();
					 chest_tool();
					   
					});
	}
	*/
	
	if ($( ".leaflet-control-zoom").html().indexOf("Edit") == -1)
	{
		$( ".leaflet-control-zoom").append("<a class=\"edit_btn\" style='margin-top:6px;' href=\"#\" title=\"Edit\" role=\"button\" aria-label=\"Edit\"><img style='text-indent: 0px  !important;width:30px;height:30px;' id=\"edit_img\" src=\"img/edit.png\" border=\"0\"/></a>");
			$(".edit_btn").click(function(e) {
					  e.stopPropagation();
					  hideBus();
					  $("#selectedTool").val(1);
					   
					});
	}

	
		 //  $("#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();
	
  
 $("#icon2").attr("onclick",' hideBus();$("#selectedTool").val(1);');
 
 $("#icon3").attr("onclick","window.location.replace(\"https://landingtutorial.com/dropmap.php\");");

	//$("#icon4").attr("onclick","showHideMarkers();");
	
	
	
	$("#icon5").attr("onclick","switch_tools();");
	initBus();
  	$("#storm_button").hide();
	

	// $("#map").css({'height': $(window).height()*0.9});
	// $("#left_banner").css({'height': $(window).height()*0.9});
	 //$("#page").css({'height': $(window).height()*0.9});
		
		
  
  
	if ($("#settingSpots").val()==1)
			initSpots();
		
	updateShare();
	
	getDefaultLocation();

  
   map.invalidateSize(true);
}

function adBlockFunction()
{
	
	
		aderror=1;
	
        // adblocker detected, show fallback
        $( "#ad_dialog" ).dialog({
		dialogClass: "no-close"
		});

 }
 
 
 function hover_apple(element) {
  element.setAttribute('src', 'img/apple_hover.png');
}

function unhover_apple(element) {
  element.setAttribute('src', 'img/apple.png');
}
 
 function hover_android(element) {
  element.setAttribute('src', 'img/android_hover.png');
}

function unhover_android(element) {
  element.setAttribute('src', 'img/android.png');
}

function hover_amazon(element) {
  element.setAttribute('src', 'img/amazon_hover.png');
}

function unhover_amazon(element) {
  element.setAttribute('src', 'img/amazon.png');
}

function hover_google(element) {
  element.setAttribute('src', 'img/google_hover.png');
}

function unhover_google(element) {
  element.setAttribute('src', 'img/google.png');
}
 
function hover_icon(element) {
	
	if (element.id=="icon7")
	{
		if (sharingcode!="")
		{
			if (isSharing>0)
				document.getElementById("hover_text").innerHTML = "CURENTLY SHARING BUS ROUTE WITH CODE <br><span style=\"font-size:24px;font-family: 'Ubuntu', sans-serif;font-weight:700;color:#34ff80; \">"+sharingcode+"</span>";
			else
				document.getElementById("hover_text").innerHTML = "CURENTLY RECEIVING BUS ROUTE FROM CODE <br><span style=\"font-size:24px;font-family: 'Ubuntu', sans-serif;font-weight:700;color:#34ff80; \">"+sharingcode+"</span>";
			
			
			
			
			
		}
		else
			document.getElementById("hover_text").innerHTML =document.getElementById(element.id+"_text").value;
	}
	else
	{
		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",
	//	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}); 
	  */
	$('#logindialog').iziModal('open');
}


function hideLogin()
{
	   
	 // $( "#logindialog" ).dialog( "close" );

$('#logindialog').iziModal('close');
}




function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
 
 
 
 