<?php

// Yahoo Yql Nextbus Primer Tutorial - RJM Programming - 2015

$smallestdist=-1.0;
$currdist=0.0;
$spareeverymapprefix = "youllneverfindthis";
$everymapprefix = "";
$thismapprefix = "";
$maxdistaway=5000;
$distaway="";

if (isset($_GET['maxdist'])) {
  $maxdistaway=$_GET['maxdist'];
}
if (isset($_POST['maxdist'])) {
  $maxdistaway=$_POST['maxdist'];
}

if (isset($_GET['latitude'])) {
  $everymapprefix="%20[" . $_GET['latitude'] . "," . $_GET['longitude'] . ",~You~],";
  $spareeverymapprefix = $everymapprefix;
}

function kph($iinh) {
  if ($iinh == null) return "0";
  return $iinh;
}

function htme($iinh) {
  if ($iinh == null) return "";
  $outh = "&#x2191;";
  $inh = $iinh;
  if ($iinh < 0) $inh = ($iinh + 360);
  for ($i=1; $i<=360; $i++) {
    if ($inh <= $i && $inh >= ($i - 1)) {
     return $inh . $outh;
    }
    if ($i == 22) $outh = "&#x2197;";
    if ($i == 67) $outh = "&#x2192;";
    if ($i == 112) $outh = "&#x2198;";
    if ($i == 157) $outh = "&#x2193;";
    if ($i == 202) $outh = "&#x2199;";
    if ($i == 247) $outh = "&#x2190;";
    if ($i == 292) $outh = "&#x2196;";
    if ($i == 337) $outh = "&#2191;";
  }
  return $inh; // . $outh;
}

function great_circle_distance($talis, $gnolis, $latis, $longis) {
  $ourdist=0.0;
  $rgnol=(($gnolis) * pi() / 180.0);
  $rtal=(($talis) * pi() / 180.0);
  $rlong=(($longis) * pi() / 180.0);
  $rlat=(($latis) * pi() / 180.0);
  
    
  $deltalong = abs(((($gnolis)-($longis)) * pi() / 180.0));

  
  $acof = (sin($rtal) * sin($rlat)) + (cos($rtal) * cos($rlat) * cos($deltalong)); // via http://en.wikipedia.org/wiki/Great-circle_distance ... thanks
  
  $ourdist = (round((acos($acof) * 6371000.0) + 0.00001) * 100) / 100;
  return $ourdist;
}

$selname = "";
$bigselname="";
if (isset($_POST['selname'])) $bigselname = str_replace(" ","%20",$_POST['selname']);
if (isset($_GET['selname'])) $bigselname = str_replace(" ","%20",$_GET['selname']);

if ($bigselname != "") {
  $bitsare=explode("~", $bigselname);
  $selname = $bitsare[0];
  if (sizeof($bitsare) > 1) $bigselname=$bitsare[1];
}

if ($selname != "") {


 		$pageContent = file_get_contents("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20nextbus.vehicles%20where%20route%3D'" . $selname . "'&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=",0,null,null);
 		$json_output = json_decode($pageContent); //  ,true);

        // Confirm that vehicles were returned before parsing
        $delim="";
        $prefix="";
        $suffix="";
        if (!is_null($json_output->query->results)) {
          $i = 0;
          if ($json_output->query->count == 1) {
            if (isset($_GET['latitude'])) {
             $currdist = great_circle_distance($_GET['latitude'], $_GET['longitude'], $json_output->query->results->vehicle->lat, $json_output->query->results->vehicle->lon);
             if ($smallestdist < 0.0 || $currdist < $smallestdist) $smallestdist = $currdist;
             if ($currdist <= $maxdistaway) {
                  $spareeverymapprefix = "youllNeverfindthis";
                  $thismapprefix = $everymapprefix;
                  $distaway = ", " . ($currdist / 1000.0) . " km away";
             } else {
                  $thismapprefix = "";
                  $distaway = ", Out of range";
             }
            } else {
             $thismapprefix = "";
             $distaway="";
            }
            echo "\n<table border=1 cellpadding=5><tr>";
            $xtitle = str_replace("'", "`", $json_output->query->results->vehicle->dirTag.", ".$json_output->query->results->vehicle->id.", ".htme($json_output->query->results->vehicle->heading).", ".$json_output->query->results->vehicle->leadingVehicleId. kph($json_output->query->results->vehicle->speedKmHr) . " kph, ".$json_output->query->results->vehicle->secsSinceReport. " secs ago".$distaway);
            $title = str_replace("'", "`", $json_output->query->results->vehicle->dirTag.", ".$json_output->query->results->vehicle->id.", ".($json_output->query->results->vehicle->heading).", ".$json_output->query->results->vehicle->leadingVehicleId. kph($json_output->query->results->vehicle->speedKmHr) . " kph, ".$json_output->query->results->vehicle->secsSinceReport. " secs ago".$distaway);
            echo "<td><p style='border: red 2px solid; padding: 2 2 2 2;'>" . $xtitle . "</p>";
            echo "\n<iframe height=500 title='" . $title . "' src='//www.rjmprogramming.com.au/PHP/Map/map.php?title=" . urldecode($title) . "&label=[%27Lat%27,&value=%27Lon%27,%20%27Name%27]&data=," . $thismapprefix . "%20[" . $json_output->query->results->vehicle->lat . "," . $json_output->query->results->vehicle->lon . ",~" . $selname . "~]'></iframe>";
            echo "\n</td>";
          } else {
            $title = str_replace("'", "`", str_replace("%20"," ",$bigselname));
            $delim = "\n<table border=1 cellpadding=5><tr><td style='border:9px yellow solid;; padding: 2 2 2 2;'>" . $title . "</p>\n<iframe height=500 title='" . $title . "' src='//www.rjmprogramming.com.au/PHP/Map/map.php?title=" . urldecode($title) . "&label=[%27Lat%27,&value=%27Lon%27,%20%27Name%27]&data=," . $everymapprefix . "%20[";
            $suffix = "]'></iframe></td>";
            for ($i=0; $i<$json_output->query->count; $i++) {
                if (isset($_GET['latitude'])) {
                 $currdist = great_circle_distance($_GET['latitude'], $_GET['longitude'], $json_output->query->results->vehicle[$i]->lat, $json_output->query->results->vehicle[$i]->lon);
                 if ($smallestdist < 0.0 || $currdist < $smallestdist) $smallestdist = $currdist;
                 if ($currdist <= $maxdistaway) {
                  $spareeverymapprefix = "Youllneverfindthis";
                  $thismapprefix = $everymapprefix;
                  $distaway = ", " . ($currdist / 1000.0) . " km away";
                 } else {
                  $thismapprefix = "";
                  $distaway = ", Out of range";
                 }
                } else {
                 $thismapprefix = "";
                 $distaway = "";
                }
                $xtitle = str_replace("'", "`", $json_output->query->results->vehicle[$i]->dirTag.", ".$json_output->query->results->vehicle[$i]->id.", ".htme($json_output->query->results->vehicle[$i]->heading).", ".$json_output->query->results->vehicle[$i]->leadingVehicleId.", ". kph($json_output->query->results->vehicle[$i]->speedKmHr) . " kph, ".$json_output->query->results->vehicle[$i]->secsSinceReport. " secs ago".$distaway);
                $title = str_replace("'", "`", $json_output->query->results->vehicle[$i]->dirTag.", ".$json_output->query->results->vehicle[$i]->id.", ".($json_output->query->results->vehicle[$i]->heading).", ".$json_output->query->results->vehicle[$i]->leadingVehicleId.", ". kph($json_output->query->results->vehicle[$i]->speedKmHr) . " kph, ".$json_output->query->results->vehicle[$i]->secsSinceReport. " secs ago".$distaway);
                $prefix .= ($delim . $json_output->query->results->vehicle[$i]->lat . "," . $json_output->query->results->vehicle[$i]->lon . ",~" . urldecode($title) . "~");
                $delim = "]%20,%20[";
                $suffix .= "<td><p style='border: red 2px solid; padding: 2 2 2 2;'>" . $xtitle . "</p>";
                $suffix .= "\n<iframe height=500 title='" . $title . "' src='//www.rjmprogramming.com.au/PHP/Map/map.php?title=" . urldecode($title) . "&label=[%27Lat%27,&value=%27Lon%27,%20%27Name%27]&data=," . $thismapprefix . "%20[" . $json_output->query->results->vehicle[$i]->lat . "," . $json_output->query->results->vehicle[$i]->lon . ",~" . $selname . "~]'></iframe>";
                $suffix .= "\n</td>";
                if (($i != 0) && ($i % 2) == 0) {
                 $suffix .= "\n</tr><tr>";
                }
            }
          }
          if ($smallestdist < 0.0) {
           echo "<html><head><meta charset='utf-8'></head><body>" . $prefix . $suffix . "</tr></table></body></html>";
          } else {
           echo "<html><head><meta charset='utf-8'><script type='text/javascript'> function ponl() { top.document.title='Nearest Nextbus is ' + '" . $smallestdist . " metres away" . "'; } </script></head><body onload=' ponl(); '>" . str_replace($spareeverymapprefix, "", $prefix) . $suffix . "</tr></table></body></html>";
          } 
        } else {
          echo "<html><head><meta charset='utf-8'></head><body><p>Nothing found at this time.</p></body></html>";
        }
} else if (isset($_POST['selname']) || isset($_GET['selname'])) {
       
 		$pageContent = file_get_contents("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20nextbus.routes&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=",0,null,null);
 		$json_output = json_decode($pageContent); //  ,true);
 		

        // Confirm that routes were returned before parsing
        $selstuff="";
        //$selstuff="<option value=''>Please select a route to show map of ...</option>";
        if (!is_null($json_output->query->results)) {
          $i = 0;
          if ($json_output->query->count == 1) {
            $selstuff .= "<option value='" . $json_output->query->results->route->tag . "'>" . $json_output->query->results->route->title . "</option>";
          } else {
            for ($i=0; $i<$json_output->query->count; $i++) {
             $selstuff .= "<option value='" . $json_output->query->results->route[$i]->tag."~".$json_output->query->results->route[$i]->title . "'>" . $json_output->query->results->route[$i]->title . "</option>";
            }
          }
          echo "<html><head><script type='text/javascript'> function onl() { parent.document.getElementById('selname').innerHTML=parent.document.getElementById('selname').innerHTML + \"" . $selstuff . "\"; } </script></head><body onload=' onl(); '></body></html>";
        }
}
?> 

