<?php include("php/session.php"); ?>
<?php include("header.php"); 
$user		= $_SESSION['user_id'];
$timezone 	= $_SESSION['timezone'];
$imei =  $_SESSION['imei'];
$user_agent     = $_SERVER['HTTP_USER_AGENT'];
$device = $_REQUEST['device'];
//$date = new DateTime('now', $timezone);
//echo date("m/d/Y h:i:s a", time());;
$query ="select latitude,longitude from pushnotification where user_id = $user and imei = $imei ";
//echo $query;
$res = mysql_query($query) or die($query. mysql_error());
        if(mysql_num_rows($res)>0){
	$row=mysql_fetch_array($res);
	 
	$deviceLat = $row['latitude'];
        $deviceLng = $row['longitude'];
      //  echo $deviceLat.' '.$deviceLng;
        
        }
       // die();
if($user != 1){
	$query ="select *,tlp.lati, tlp.longi, CONVERT_TZ(tlp.add_date,'+00:00','".$timezone."') as add_date, Now() as current, TIME_TO_SEC(TIMEDIFF( NOW( ) , tlp.add_date)) as beforeTime from assests_master am left join tbl_last_point tlp on tlp.device_id=am.device_id  where am.status=1 AND am.del_date is null AND find_in_set(am.id, (SELECT assets_ids FROM user_assets_map where user_id = $user)) and tlp.device_id='".$_REQUEST['device']."' and am.device_id='".$_REQUEST['device']."'"; 
}else{
	$query ="select *,tlp.lati, tlp.longi, CONVERT_TZ(tlp.add_date,'+00:00','".$timezone."') as add_date, Now() as current, TIME_TO_SEC(TIMEDIFF( NOW( ) , tlp.add_date)) as beforeTime from assests_master am left join tbl_last_point tlp on tlp.device_id=am.device_id  where am.status=1 AND am.del_date is null AND tlp.device_id='".$_REQUEST['device']."' and am.device_id='".$_REQUEST['device']."'"; 
}

$res = mysql_query($query) or die($query. mysql_error());

if(mysql_num_rows($res)>0){
	$row=mysql_fetch_array($res);
	$device_id = $row['device_id'];
        
	$lat = $row['lati'];
        $lng = $row['longi'];
        
}else{
	echo '<div data-role="content"><div class="ui-body ui-body-d"><div data-role="fieldcontain"><a data-icon="back" data-rel="back"  href="#" data-role="button" data-theme="e" data-inline="false">Device Not Found '.$lang['back'].'</a></div></div></div>';
	include("footer.php");
		die;
}


?>
<style type="text/css">
	.tbl { border-collapse: collapse; }
	.tbl td { padding:3px; border: solid gold 1px; }
        .tbl tr {padding:3px; border: solid gold 1px;}
</style>
		<div data-role="content"><!-- style='padding:0px;'-->
				<div class="ui-body ui-body-d">
					<div data-role="fieldcontain">
<?php if(mysql_num_rows($res)<1) { echo "<center>Device Not Found</center>";} else{
?>  
<form method = "post" >                                           
<table class="tbl" style='max-width:100%' width="100%" align="center">
        <tr>
            <label><center>Estimated Time of Arrival For Asset <b><?php echo $row['assets_name']; ?></b> on <?php echo date("d-m-Y h:i:s a", time()); ?> </center></label>
        </tr>  
	<tr>
		<td width="50%"><?php echo "Mobile Current Location:" ?></td>
		<td width="50%" id="mobile_address"><?php echo ""; ?></td>
	</tr>
	<tr>
		<td><?php echo "Asset Current Location:"; ?></td>
		<?php $address = explode(",",$row['address']);
				if($address[0]>6){
					$address=$address[0];
				}else{
					$address=$address[0]." ".$address[1];
				}

		?>
		
		<td><?php echo $row['address']; ?></td>
	</tr>
	<tr>
		<td><?php echo "Total Distance:"; ?></td>
                <td id="distance"><?php echo "KM"; ?></td>
	</tr>
        <tr>
                <td><?php echo "ETA:"; ?></td>
                <td id="estimated_time"><?php echo ""; ?></td>
        </tr>
</table>
</form>    
<?php }
 
?>                             
<script type='text/javascript'>  
       var map = null;
                var mapOptionsmap;
                var markersmap = [];
                var lat = new Array();
                var lng = new Array();
                var html = new Array();
                var ib;
                var loop = 0, j, x;
                //var directionsDisplay = [];
                var map;
                var path = new google.maps.MVCArray;
                var poly;
                var polyMarkers = [];
                var newPoly = false;
                var polyLat = [];
                var polyLng = [];
                var deviceCombo = "<?php echo $dCombo; ?>";
                var abounds;
                var markers = [];
                var points = [];
                var mobile_lat;
                var mobile_lng;
<?php if ($lat != "" && $lng != "") { ?>
                    lat.push(<?php echo $lat; ?>);
                    lng.push(<?php echo $lng; ?>);
                    html.push('<?php echo $html_address; ?>');
<?php } ?>
   $(document).ready(function () {
         initialize();
   });
 function initialize() {
                    var Latlng = new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $lng; ?>);
                    directionsService = new google.maps.DirectionsService();
                    var mapOptions = {
                        zoom: 4,
                        center: new google.maps.LatLng(<?php echo $lat; ?>, <?php echo $lng; ?>),
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };
                    var mbounds = new google.maps.LatLngBounds();
                    var bounds = new google.maps.LatLngBounds();
                    map = new google.maps.Map(document.getElementById('map_canvas_area'),
                            mapOptions);
                    GetLocationInfo(Latlng);        
                    var asset_location_marker = new google.maps.Marker({
                                position: Latlng,
                                map: map,
                                icon: "images/asset.png",
                                title: "Current Location"
                            }); 
                           
                              
                 //   if (navigator.geolocation) {
                         
                    //    navigator.geolocation.getCurrentPosition(function (p) {
                            mobile_lat = <?php echo $deviceLat; ?>;
                            mobile_lng = <?php echo $deviceLng; ?>;
                          console.log(mobile_lat + 'hi');
                            var LocationLatLng = new google.maps.LatLng( mobile_lat, mobile_lng);
                            var mobile_location_marker = new google.maps.Marker({
                                position: LocationLatLng,
                                map: map,
                                icon: "images/current_location_marker.png",
                                title: "Current Location"
                            });
                            getAddressFromLatLang(mobile_lat, mobile_lng);
                            GetLocationInfo(LocationLatLng);  
                            //console.log("mobile location:"+LocationLatLng);
                            map.setCenter(LocationLatLng);
                            mbounds.extend(LocationLatLng);
                            map.fitBounds(mbounds);
                            //console.log(mobile_lat+" "+mobile_lng);
                            if(mobile_lat != "" && mobile_lng != ""){
                                $.post('getdrivingdist.php', {lat: '<?php echo $lat; ?>', lng:'<?php echo $lng; ?>', mobile_lat:mobile_lat, mobile_lng:mobile_lng},function( data ) {
                                  if(data.nxt_bstp_distance != null && data.nxt_eta_time != null){
                                        document.getElementById("distance").innerHTML = data.nxt_bstp_distance;
                                        document.getElementById("estimated_time").innerHTML = data.nxt_eta_time;
                                    }
                                }, "json");
                            }
                      // });

                  //  } else {
                  //      alert('Geo Location feature is not supported in this browser.');
                  //  }
                    
                    var point = new google.maps.LatLng(<?php echo $lat; ?>,<?php echo $lng; ?>);
                    var myOptions = {
                        //content: $("#imgR").html()
                        boxStyle: {
                            textAlign: "center"
                            , fontSize: "8pt"
                            , width: "18px"
                        }
                        , disableAutoPan: true
                        , pixelOffset: new google.maps.Size(-7, 0)
                        , enableEventPropagation: true
                        , position: point
                        , closeBoxURL: ""
                        , isHidden: false
                        , pane: "mapPane"
                    };
                    ib = new InfoBox(myOptions);
                    ib.open(map);
                    geocoder = new google.maps.Geocoder();
                    map.setCenter(Latlng);
                    bounds.extend(Latlng);
                    map.fitBounds(bounds);
                    
                }  
                 function getAddressFromLatLang(lat,lng){
                    //console.log("Entering getAddressFromLatLang()");
                    var geocoder = new google.maps.Geocoder();
                      var latLng1 = new google.maps.LatLng(lat, lng);
                      geocoder.geocode( { 'latLng': latLng1}, function(results, status) {
                      //console.log("After getting address");
                      //console.log(results);
                      if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                          //console.log(results[1]);
                          var mobile_location = results[1].formatted_address;  
                          //$("#mobile_address").val(mobile_location);
                          document.getElementById("mobile_address").innerHTML = mobile_location;
                        }
                      }else{
                        alert("Geocode was not successful for the following reason: " + status);
                      }
                      });
                    //console.log("Entering getAddressFromLatLang()");
                  }
                   function GetLocationInfo(latlng)
                    {
                      if (latlng != null)
                      {
                        points.push(latlng);
                        //console.log("pointlen:"+points.length);
                        }
                        if(points.length > 1){
                            GetDirections();
                        }
                    }
                     function GetDirections()
                    {
                      var directions = new google.maps.DirectionsService();
                      var directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers : true});
                      directionsDisplay.setMap(map);
                      // build array of waypoints (excluding start and end)
                      var waypts = [];
                      var end = points.length-1;
                      var dest = points[points.length-1];
                      //if (document.getElementById("roundTrip<?php echo time(); ?>").checked) {
                        end = points.length;
                        dest = points[0];
                      //}
                      for (var i=1; i<end; i++) {
                        waypts.push({location:points[i]});
                      }

                      var travelMode = google.maps.DirectionsTravelMode.DRIVING;

                      var optimiseRoute = true;
                      var request = {
                        origin: points[0],
                        destination: dest,
                        waypoints: waypts,
                        travelMode: travelMode,
                        optimizeWaypoints: optimiseRoute
                      };
                      directions.route(request, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                          directionsDisplay.setDirections(result);

                          // calculate total distance and duration
                          var distance = 0;
                          var time = 0;
                          var theRoute = result.routes[0];
                          for (var i=0; i<theRoute.legs.length; i++) {
                            var theLeg = theRoute.legs[i];
                            distance += theLeg.distance.value;
                            time += theLeg.duration.value;
                          }
                        }
                        else {
                          var statusText = getDirectionStatusText(status);
                        }
                      });
                    }
                   
</script>    
 <div class="ui-bar-c ui-corner-all ui-shadow" style="padding:0.8em;">
     <div id="map_canvas_area" style="width: 100%; height: 300px; position:relative;"></div>
    
 </div>
<?php

echo '<a data-icon="back" data-rel="back"  href="#" data-role="button" data-theme="e" data-inline="false">Back</a></div></div></div>';
include("footer.php");  ?>
