<?php
	$wxmap_key = "fce2b9d1230c36c259555020aaf4d1a1";
?>

<div class="row">
	<div class="col-md-12">
		<div class="block">
			<div class="block-title">
				<h3><i class="fa fa-map"></i> Live Flights Map </h3>
			</div>
			<div class="mapcenter" align="center">
				<div id="icrewsystems_acars_map" style="width: 95%; height: 500px"></div>
			</div>

			<br>
		</div>
	</div>
</div>



<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.0.6/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.0.6/dist/MarkerCluster.Default.css" />
<script src="<?php echo SITE_URL?>/lib/js/base_map.js"></script>
<script src="https://rawgit.com/mapshakers/leaflet-icon-pulse/master/src/L.Icon.Pulse.js"></script>
<script src="https://unpkg.com/leaflet.markercluster@1.0.6/dist/leaflet.markercluster.js"></script>
<script src="https://iosphere.github.io/Leaflet.hotline/dist/leaflet.hotline.js"></script>
<script src="https://unpkg.com/@joergdietrich/leaflet.terminator"></script>
<script src="<?php echo SITE_URL; ?>/lib/skins/iCrew/ICSMap/graticule.js"></script>

<style>
   .leaflet-pulsing-icon {
   border-radius: 100%;
   box-shadow: 1px 1px 8px 0 rgba(0,0,0,0.75);
   }
   .leaflet-pulsing-icon:after {
   content: "";
   border-radius: 100%;
   height: 300%;
   width: 300%;
   position: absolute;
   margin: -100% 0 0 -100%;
   }
   @keyframes pulsate {
   0% {
   transform: scale(0.1, 0.1);
   opacity: 0;
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   }
   50% {
   opacity: 1;
   -ms-filter: none;
   filter: none;
   }
   100% {
   transform: scale(1.2, 1.2);
   opacity: 0;
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   }
   }
</style>

<script type="text/javascript">
   // Creating a new map element.
    let bounds = [];

    let selPoints = [],
        selMarkers = [];
    let selDepMarker, selArrMarker, selPointsLayer;

    let flightMarkers = [];
    let headingIcons = {};

    let info_window = null;
    let run_once = false;


   const map = createMap({
   	render_elem: 'icrewsystems_acars_map',
   	provider: '<?php echo Config::Get("MAP_TYPE"); ?>',
		center: [<?php echo Config::Get("MAP_CENTER_LAT"); ?>, <?php echo Config::Get("MAP_CENTER_LNG"); ?>],
   	refreshTime: 2000,
    autorefresh: true,
		zoom: <?php echo Config::Get('MAP_ZOOM_LEVEL'); ?>
   });

   	function get_api_request(yourUrl){
   		var Httpreq = new XMLHttpRequest();
   		Httpreq.open("GET",yourUrl,false);
   		Httpreq.send(null);
   		return Httpreq.responseText;
   	}

   	const getHeadingIcon = (heading) => {
        if (!(heading in headingIcons)) {
            headingIcons[heading] = L.icon({
                iconUrl: url + "/lib/images/inair/" + heading + ".png",
                iconSize: [20, 20]
            });
        }

        return headingIcons[heading];
    };



   	var cities = L.layerGroup();
	var daynight = L.terminator().addTo(map);
	var graticule = L.latlngGraticule({
		showLabel: true,
		opacity: 1,
		weight: 0.8,
		color: '#aaa',
		font: '12px Calibri',
		zoomInterval: [
			{start: 2, end: 3, interval: 30},
            {start: 4, end: 4, interval: 10},
			{start: 5, end: 7, interval: 5},
			{start: 8, end: 10, interval: 1}
        ]
	}).addTo(map);

	var grayscale  = L.tileLayer("https://cartodb-basemaps-{s}.global.ssl.fastly.net/{variant}/{z}/{x}/{y}.png", {
		tileSize: 512,
		zoomOffset: -1
	}),

	Temp = L.tileLayer('https://tile.openweathermap.org/map/temp_new/{z}/{x}/{y}.png?appid=<?php echo $wxmap_key; ?>', {
        maxZoom: 18,
		id: 'temp'
    }),

    Precipitation = L.tileLayer('https://tile.openweathermap.org/map/precipitation_new/{z}/{x}/{y}.png?appid=<?php echo $wxmap_key; ?>', {
		maxZoom: 18,
	}),

	Wind = L.tileLayer('https://tile.openweathermap.org/map/wind_new/{z}/{x}/{y}.png?appid=<?php echo $wxmap_key; ?>', {
		maxZoom: 18,
	}),

	Pressure = L.tileLayer('https://tile.openweathermap.org/map/pressure_new/{z}/{x}/{y}.png?appid=<?php echo $wxmap_key; ?>', {
		maxZoom: 18,
	}),

	Clouds = L.tileLayer('https://tile.openweathermap.org/map/clouds_new/{z}/{x}/{y}.png?appid=<?php echo $wxmap_key; ?>', {
		maxZoom: 18,
	});



    var baseLayers = {
		"Clouds": Clouds,
        "Pressure": Pressure,
        "Wind": Wind,
        "Precipitation": Precipitation,
        "Temparature": Temp,
        "No Layer": grayscale,
    };

	var overlays = {
		"Day / Night Overlay": daynight,
        "LAT / LNG Graticules Overlay": graticule
    };

    L.control.layers(baseLayers, overlays).addTo(map);

   //Initializing Cluster Group
   var markersLayer = new L.LayerGroup();
   var markers = L.markerClusterGroup();
   map.addLayer(markersLayer);

   var apiURL = "<?php echo SITE_URL; ?>/action.php/ACARS/data";
   var current_location = "<?php echo SITE_URL; ?>/action.php/schedules/current_location_api";
   var flights = JSON.parse(get_api_request(apiURL));
   var current_location = JSON.parse(get_api_request(current_location));

   //map.setView(new L.LatLng(current_location.lat, current_location.lng), 4);

   	var pulsingIcon_currentlocation = L.icon.pulse({
   		iconSize: [12,12],
              fillColor: 'red',
              color: 'red',
              animate: true,
              heartbeat: 1
   	});


   	var current_location_pulsing_marker = L.marker([current_location.lat, current_location.lng],{icon: pulsingIcon_currentlocation}).bindTooltip("You are at " + current_location.name).addTo(map);

	if(flights.length > 0) {
		activeflights  = flights.length;
	} else {
		activeflights  = "0";
	}

    var reset = L.control({position: 'topright'});
   reset.onAdd = function (map) {

      var div = L.DomUtil.create('div', 'info legend');
          div.innerHTML = '<a id="update_flights" class="btn btn-primary btn-alt">Refresh</a>';
      return div;
   };
   reset.addTo(map);

	$("#update_flights").click(function() {
		clearMap();
		clearSelMarkers();
		liveRefresh();
		$.bootstrapGrowl("<h4>iCrew <strong>Notifications </strong> </h4> Updating live flights.... ", {
			ele: 'body', // which element to append to
			type: 'success', // (null, 'info', 'danger', 'success')
			offset: {from: 'top', amount: 20}, // 'top', or 'bottom'
			align: 'right', // ('left', 'right', or 'center')
			width: 250, // (integer, or 'auto')
			delay: 1000, // Time while the message will be displayed. It's not equivalent to the *demo* timeOut!
			allow_dismiss: true, // If true then will display a cross to close the popup.
			stackup_spacing: 10 // spacing between consecutively stacked growls.
		});

	});

	var legend = L.control({position: 'bottomright'});
   legend.onAdd = function (map) {

      var div = L.DomUtil.create('div', 'info legend');
          div.innerHTML = '<span class="label label-primary"><?php echo SITE_NAME; ?> Airline Map</span> ';
      return div;
   };
   legend.addTo(map);



   var flightcount = L.control({position: 'bottomleft'});
   flightcount.onAdd = function (map) {

      var div = L.DomUtil.create('div', 'info legend');
          div.innerHTML = '<span class="badge badge-muted">There are ' + activeflights  + ' active flights</span>';
      return div;
   };
   flightcount.addTo(map);
	/**
     * Clear all of the markers and selected points
     */
    const clearSelMarkers = () => {
        if (selDepMarker) {
            selDepMarker.remove();
            selDepMarker = null;
        }

        if (selArrMarker) {
            selArrMarker.remove();
            selArrMarker = null;
        }

        if (selPointsLayer) {
            selPointsLayer.remove();
            selPointsLayer = null;
        }

        for (let i in selMarkers) {
            selMarkers[i].remove();
        }

        selPoints = [];
    };




    /**
     * Draw the points/route for a flight
     * @param {*} features
     */
    const flightClick = (flight) => {

        clearSelMarkers();

        const depCoords = L.latLng(flight.deplat, flight.deplng);
        selDepMarker = L.marker(depCoords, {
            // icon: MapFeatures.icons.departure,
        }).addTo(map);

        const arrCoords = L.latLng(flight.arrlat, flight.arrlng);
        selArrMarker = L.marker(arrCoords, {
            // icon: MapFeatures.icons.arrival,
        }).addTo(map);

        selPoints.push(depCoords);

        $.each(flight.route_details, function(i, nav) {
            const loc = L.latLng(nav.lat, nav.lng);
            const icon = (nav.type === 3) ? MapFeatures.icons.vor : MapFeatures.icons.fix;
            selPoints.push(loc);

            const marker = L.marker(loc, {
                    icon: icon,
                    title: nav.title,
                })
                .bindPopup(tmpl("navpoint_bubble", { nav: nav }))
                .addTo(map);

            selMarkers.push(marker);
        });

        selPoints.push(arrCoords);

        selPointsLayer = L.geodesic([selPoints], {
            weight: 2,
            opacity: 1.0,
            color: '#000',
            steps: 10
        }).addTo(map);




	legend.addTo(map);


        map.fitBounds(selPointsLayer.getBounds());
    };

    /**
     *
     * @param {*} data
     */
    const populateMap = (data) => {

        clearMap();

        $("#pilotlist").html("");

        if (data.length == 0) {
            return false;
        }

        let lat, lng;
        let details, row, pilotlink;

        bounds = [];

        $.each(data, function(i, flight) {
            if (flight == null || flight.lat == null || flight.lng == null ||
                flight.lat == "" || flight.lng == "") {
                return;
            }

            flight.lat = Number(flight.lat);
            flight.lng = Number(flight.lng);

            lat = flight.lat;
            lng = flight.lng;

            if (i % 2 == 0)
                flight.trclass = "even";
            else
                flight.trclass = "odd";

            // Pull ze templates!
            const map_row = tmpl("acars_map_row", { flight: flight });
            const detailed_bubble = tmpl("acars_map_bubble", { flight: flight });

            $('#pilotlist').append(map_row);

            const pos = L.latLng(lat, lng);
            const marker = L.marker(pos, {
                    icon: getHeadingIcon(flight.heading)
                })
                .on('click', (e) => {
                    flightClick(flight);
                })
                .bindPopup(detailed_bubble)
                .addTo(map);

            flightMarkers.push(marker);
            bounds.push(pos);
        });

        // If they selected autozoom, only do the zoom first time
        if (run_once == false) {
            map.fitBounds(bounds);
            run_once = true;
        }
    }

    /**
     * Clear all markers and layers
     */
    const clearMap = () => {
        // clear markers
        for (let i in flightMarkers) {
            flightMarkers[i].remove();
        }
    };

    /**
     *
     */
    const liveRefresh = () => {
        $.ajax({
            type: "GET",
            url: url + "/action.php/acars/data",
            dataType: "json",
            cache: false,
            success: function(data) {
                populateMap(data);
            }
        });



    };

    /**
     * Render
     *
     */
    liveRefresh();

	setInterval(function() { liveRefresh(); }, 60000);






</script>
<!--<table border = "0" width="100%" class="acarsmap">-->
<!--<thead>-->
<!--	<tr>-->
<!--		<td><b>Pilot</b></td>-->
<!--		<td><b>Flight Number</b></td>-->
<!--		<td><b>Departure</b></td>-->
<!--		<td><b>Arrival</b></td>-->
<!--		<td><b>Status</b></td>-->
<!--		<td><b>Altitude</b></td>-->
<!--		<td><b>Speed</b></td>-->
<!--		<td><b>Distance/Time Remain</b></td>-->
<!--	</tr>-->
<!--</thead>-->
<!--<tbody id="pilotlist"></tbody>-->
<!--</table>-->

<script type="text/html" id="acars_map_row">
<tr class="<%=flight.trclass%>">
<td><a href="<?php echo url('/profile/view');?>/<%=flight.pilotid%>"><%=flight.pilotid%> - <%=flight.pilotname%></a></td>
<td><%=flight.flightnum%></td>
<td><%=flight.depicao%></td>
<td><%=flight.arricao%></td>
<td><%=flight.phasedetail%></td>
<td><%=flight.alt%></td>
<td><%=flight.gs%></td>
<td><%=flight.distremaining%> <?php echo Config::Get('UNITS');?> / <%=flight.timeremaining%></td>
</tr>
</script>


<script type="text/html" id="acars_map_bubble">
<div class="block">

<span style="" align="">
	<center>
	<h1 class="label label-primary">
	<%=flight.flightnum%></strong> (<%=flight.depicao%> to <%=flight.arricao%>)

	</h1>
<br><br>
<strong>Pilot In Command</strong>:
<a class="text-primary" target="_blank" href="<?php echo url('/profile/view');?>/<%=flight.pilotid%>">
<%=flight.pilotid%>	<%=flight.pilotname%>
</a><br />

<strong>Status: </strong><%=flight.phasedetail%><br />
<strong>Dist/Time Remain: </strong><%=flight.distremaining%> <?php echo Config::Get('UNITS');?> / <%=flight.timeremaining%><br />
<strong>Altitude: </strong> <%=flight.alt%> ft<br />
<strong>GS: </strong> <%=flight.gs%> Kts<br />


</center>
</span>

</div>
</script>




<script type="text/html" id="navpoint_bubble">
<span style="font-size: 10px; text-align:left; width: 100%" align="left">
<strong>Name: </strong><%=nav.title%> (<%=nav.name%>)<br />
<strong>Type: </strong>
<?php	/* Show the type of point */ ?>
<% if(nav.type == 2) { %> NDB <% } %>
<% if(nav.type == 3) { %> VOR <% } %>
<% if(nav.type == 4) { %> DME <% } %>
<% if(nav.type == 5) { %> FIX <% } %>
<% if(nav.type == 6) { %> TRACK <% } %>
<br />
<?php	/* Only show frequency if it's not a 0*/ ?>
<% if(nav.freq != 0) { %>
<strong>Frequency: </strong><%=nav.freq%>
<% } %>
</span>
</script>
