<?php
// ephem_astronomy.php
// Supervising great pyephem module in python3.3
// RJM Programming
// October, 2018

date_default_timezone_set('UTC');

$bodies=["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto","Moon","Sun",
 "Phobos",
 "Deimos",
 "Io",
 "Europa",
 "Ganymede",
 "Callisto",
 "Mimas",
 "Enceladus",
 "Tethys",
 "Dione",
 "Rhea",
 "Titan",
 "Hyperion",
 "Iapetus",
 "Ariel",
 "Umbriel",
 "Titania",
 "Oberon",
 "Miranda"];

$more="";

$bodyopts="";
for ($i=0; $i<sizeof($bodies); $i++) {
  $bodyopts.="<option value=" . $bodies[$i] . ">" . $bodies[$i] . "</option>";
}

$sb="";
if (isset($_GET['observer'])) {
    if (urldecode($_GET['observer']) != "") {
      $sb="\n #epoch { display: none; } \n";
    }
}


$htmlis="<!doctype html>
<html>
<head>
<title>Astronomy Helper via Python PyEphem Module</title>
<meta name='viewport' content='width=device-width, initial-scale=1, minimum-scale=0.1, maximum-scale=8, user-scalable=yes' />
<style>
  td { vertical-align: top; } " . $sb . "
</style>
<script type='text/javascript'>
 var firstgo=true;
 var startPos=null;
 function observerask() {
  if (firstgo) {
  if (document.URL.toLowerCase().indexOf('https:') == -1) {
    location.href='https:' + document.URL.substring(document.URL.indexOf('/')).split('#')[0].split('?')[0] + '?cobs=y';
  }
  try {
  navigator.geolocation.getCurrentPosition(function(position) {
    if (firstgo) {
      startPos = position;
   document.getElementById('taobserver').value=\"iam = ephem.Observer()\" + String.fromCharCode(10) + \"iam.lon = '\" + ('' + startPos.coords.longitude + '.').split('.')[0] + \":\" + eval(eval('0.' + eval(('' + startPos.coords.longitude + '.0').split('.')[1])) * 60.0) + \"' # [LongitudeDegrees]:[DecimalMinutes]\" + String.fromCharCode(10) + \"iam.lat = '\" + ('' + startPos.coords.latitude + '.').split('.')[0] + \":\" + eval(eval('0.' + eval(('' + startPos.coords.latitude + '.0').split('.')[1])) * 60.0) + \"' # [LatitudeDegrees]:[DecimalMinutes]\" + String.fromCharCode(10) + \"iam.elevation = 0.0   # Metres\" + String.fromCharCode(10) + \"iam.date = '" . date('Y/m/d H:i', time()) . "'  # Y/m/d H:i (GMT)\" + String.fromCharCode(10) + \"iam.temp = 25.0  # Celsius degrees\" + String.fromCharCode(10) + \"iam.epoch = '2000'  # Nearest 50 year epoch under date\" + String.fromCharCode(10) + \"iam.pressure = 1010  # Millibars\";
      firstgo=false;
    } else if (startPos == null) {
   document.getElementById('taobserver').value=\"iam = ephem.Observer()\" + String.fromCharCode(10) + \"iam.lon = '-111:32.1'\" + String.fromCharCode(10) + \"iam.lat = '35:05.8'\" + String.fromCharCode(10) + \"iam.elevation = 0.0\" + String.fromCharCode(10) + \"iam.date = '" . date('Y/m/d H:i', time()) . "'\" + String.fromCharCode(10) + \"iam.temp = 25.0\" + String.fromCharCode(10) + \"iam.epoch = '2000'\" + String.fromCharCode(10) + \"iam.pressure = 1010\";
    } else {
   document.getElementById('taobserver').value=\"iam = ephem.Observer()\" + String.fromCharCode(10) + \"iam.lon = '-111:32.1'\" + String.fromCharCode(10) + \"iam.lat = '35:05.8'\" + String.fromCharCode(10) + \"iam.elevation = 0.0\" + String.fromCharCode(10) + \"iam.date = '" . date('Y/m/d H:i', time()) . "'\" + String.fromCharCode(10) + \"iam.temp = 25.0\" + String.fromCharCode(10) + \"iam.epoch = '2000'\" + String.fromCharCode(10) + \"iam.pressure = 1010\";
    }
  });
  } catch(ee) {
   document.getElementById('taobserver').value=\"iam = ephem.Observer()\" + String.fromCharCode(10) + \"iam.lon = '-111:32.1'\" + String.fromCharCode(10) + \"iam.lat = '35:05.8'\" + String.fromCharCode(10) + \"iam.elevation = 0.0\" + String.fromCharCode(10) + \"iam.date = '" . date('Y/m/d H:i', time()) . "'\" + String.fromCharCode(10) + \"iam.temp = 25.0\" + String.fromCharCode(10) + \"iam.epoch = '2000'\" + String.fromCharCode(10) + \"iam.pressure = 1010\";
  }
  } else if (startPos == null) {
   document.getElementById('taobserver').value=\"iam = ephem.Observer()\" + String.fromCharCode(10) + \"iam.lon = '-111:32.1'\" + String.fromCharCode(10) + \"iam.lat = '35:05.8'\" + String.fromCharCode(10) + \"iam.elevation = 0.0\" + String.fromCharCode(10) + \"iam.date = '" . date('Y/m/d H:i', time()) . "'\" + String.fromCharCode(10) + \"iam.temp = 25.0\" + String.fromCharCode(10) + \"iam.epoch = '2000'\" + String.fromCharCode(10) + \"iam.pressure = 1010\";
    } else {
   document.getElementById('taobserver').value=\"iam = ephem.Observer()\" + String.fromCharCode(10) + \"iam.lon = '-111:32.1'\" + String.fromCharCode(10) + \"iam.lat = '35:05.8'\" + String.fromCharCode(10) + \"iam.elevation = 0.0\" + String.fromCharCode(10) + \"iam.date = '" . date('Y/m/d H:i', time()) . "'\" + String.fromCharCode(10) + \"iam.temp = 25.0\" + String.fromCharCode(10) + \"iam.epoch = '2000'\" + String.fromCharCode(10) + \"iam.pressure = 1010\";
    } 
   document.getElementById('ra').innerHTML='Altitude';
   document.getElementById('dec').innerHTML='Azimuth';
   document.getElementById('ag').innerHTML='Horizontal coordinate system';
   document.getElementById('divobserver').style.display='block';
 }
 
 function testdo() {
      if(window.DeviceOrientationEvent) {
        window.addEventListener('deviceorientation', function(event) {
              if (document.getElementById('dodiv').innerHTML == '') {
                var alpha = event.alpha;
                var beta = event.beta;
                var gamma = event.gamma;
               
                if (alpha!=null || beta!=null || gamma!=null) {
                  document.getElementById('dodiv').innerHTML = 'alpha: ' + alpha + '<br/>beta: ' + beta + '<br />gamma: ' + gamma;
                  document.getElementById('docompass').style.display='block';
                }
              }
              }, false);
      }
 }
</script>
</head>
<body style='background-color:pink;' onload=\" if (document.URL.indexOf('?cobs=') != -1) { document.getElementById('bobs').click();  } if (window.DeviceOrientationEvent) { if (1 == 1) { testdo(); } else { document.getElementById('docompass').style.display='block'; }  } \">
<h1>Astronomy Helper via Python <a target=_blank title='PyEphem ... thanks' href='//rhodesmill.org/pyephem/'>PyEphem</a> module</h1>
<h3>RJM Programming <a onclick=\"location.href=document.URL.split('#')[0].split('?')[0];\" title=\"Rerun\">-</a> October, 2018</h3>
<table style='background-color:yellow;' border=50>
<tr><th>Celestial Body</th><th><span id=ag>Astrometric geocentric</span> <br><span id=ra>Right Ascension</span> ... for now or ...<br><input style='width:300px;' id=epoch title=\"Optional date definition such as '1986/2/9', epoch='1950'\" placeholder=\"Optional date definition such as '1986/2/9', epoch='1950'\" value=''></input></th><th><span id=dec>Declination</span> ... for now or ...<br><input id=bobs type=button onclick=observerask(); value=Observer></input><div style=display:none; id=divobserver><br><textarea id=taobserver cols=80 rows=8 value=></textarea></div></th></tr>
<tr><td><select size=" . (1 + sizeof($bodies)) . " onchange=\"if (this.value == '') { document.getElementById('epoch').value=(' ').trim(); } else { location.href=document.URL.split('#')[0].split('?')[0] + '?body=' + encodeURIComponent(this.value) + '&epoch=' + encodeURIComponent(document.getElementById('epoch').value) + '&observer=' + encodeURIComponent(document.getElementById('taobserver').value); }\"><option id=myopt value=>Please select a Celestial Body below ...</option>" . $bodyopts . "</select></td><td id=ra></td><td id=dec></td></tr>
</table>
<div id='dodiv' style='display: none;'></div>
</body>
</html>";

if (isset($_GET['body'])) {
  if (urldecode($_GET['body']) != "") {
      if (file_exists('py_ephem.xxx')) {
        unlink('py_ephem.xxx');
      }
      if (file_exists('../Python/thisone.py')) {
        unlink('../Python/thisone.py');
      }
      if (isset($_GET['epoch']) || isset($_GET['observer'])) {
       if (urldecode($_GET['observer']) != "") {
         $more="<br><iframe id=docompass style='width:100%;height:500px;display:none;' src='//www.rjmprogramming.com.au/HTMLCSS/yaw_etc.html' title='Yaw etcetera'></iframe>";
         file_put_contents("../Python/thisone.py", "import ephem\n" . urldecode($_GET['observer']) . "\n");
         $htmlis=str_replace("</textarea>", urldecode($_GET['observer']) . "</textarea>", $htmlis);
         exec("cat .." . '/' . "Python" . '/' . "Jupiter.py | grep -v '==' | grep -v 'import ephem' | sed '" . '/' . ".dec" . '/' . "s" . '/' . "" . '/' . ".az" . '/' . "g' | sed '" . '/' . ".ra" . '/' . "s" . '/' . "" . '/' . ".alt" . '/' . "g'  | sed '" . '/' . "Jupiter" . '/' . "s" . '/' . "" . '/' . "" . urldecode($_GET['body']) . "" . '/' . "g' | sed \"" . '/' . "compute()" . '/' . "s" . '/' . "" . '/' . "compute(iam)" . '/' . "g\" | tr '!' '/' >>  .." . '/' . "Python" . '/' . "thisone.py");
         $htmlis=str_replace(">Right Ascension<", ">Altitude<", $htmlis);
         $htmlis=str_replace(">Declination<", ">Azimuth<", $htmlis);
         $htmlis=str_replace(">Astrometric geocentric<", ">Horizontal coordinate system<", $htmlis);
         $htmlis=str_replace(":none;", ":block;", $htmlis);
         $htmlis=str_replace(">Please select a Celestial Body below ...<", ">Celestial Bodies ...<", $htmlis);
       } else if (urldecode($_GET['epoch']) != "") {
         exec("cat .." . '/' . "Python" . '/' . "Jupiter.py | sed '" . '/' . "Jupiter" . '/' . "s" . '/' . "" . '/' . "" . urldecode($_GET['body']) . "" . '/' . "g' | sed \"" . '/' . "compute()" . '/' . "s" . '/' . "" . '/' . "compute(" . str_replace('/','!',urldecode($_GET['epoch'])) . ")" . '/' . "g\" | tr '!' '/' >>  .." . '/' . "Python" . '/' . "thisone.py");
         $htmlis=str_replace(" value=''", " value=\"" . urldecode($_GET['epoch']) . "\"", $htmlis);
       } else {
        exec("cat .." . '/' . "Python" . '/' . "Jupiter.py | sed '" . '/' . "Jupiter" . '/' . "s" . '/' . "" . '/' . "" . urldecode($_GET['body']) . "" . '/' . "g' >>  .." . '/' . "Python" . '/' . "thisone.py");
       }
      } else {
       exec("cat .." . '/' . "Python" . '/' . "Jupiter.py | sed '" . '/' . "Jupiter" . '/' . "s" . '/' . "" . '/' . "" . urldecode($_GET['body']) . "" . '/' . "g' >>  .." . '/' . "Python" . '/' . "thisone.py");
      }
      exec("" . '/' . "usr" . '/' . "local" . '/' . "bin" . '/' . "python3.3 .." . '/' . "Python" . '/' . "thisone.py > py_ephem.xxx");
      $ar_dec="";
      if (file_exists('py_ephem.xxx')) {
        $ar_dec=file_get_contents('py_ephem.xxx');
        unlink('py_ephem.xxx');
        $htmlis=str_replace(">" . urldecode($_GET['body']) . "<", " selected>" . urldecode($_GET['body']) . "<", $htmlis);
        $htmlis=str_replace("<td id=ra></td>", "<td id=ra>&nbsp;&nbsp;&nbsp;" . explode(" ",$ar_dec)[0] . "</td>", $htmlis);
        $htmlis=str_replace("<td id=dec></td>", "<td id=dec>&nbsp;&nbsp;&nbsp;" . explode(" ",$ar_dec)[1] . $more . "</td>", $htmlis);
      }
  }
}

echo $htmlis;
?>