<?
session_start();

ini_set("display_errors", true);
error_reporting(E_ALL^E_NOTICE);



include_once $_SERVER['DOCUMENT_ROOT'].'/inc/report.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/styles.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/inc/footer.php';

include_once 'gender.inc';
//include_once 'verse.inc';

$rusr = array(12,164,52,49,103);

$UserId=$_SESSION['UserId'];

$uauth=in_array($UserId, $rusr);
if ($uauth) $_SESSION['PM_B_YeThee']=1;

//echo "<br>userid=$UserId uauth=$uauth";

$minplus=$_REQUEST['minplus'];
//echo "minplus=$minplus<br>";

$vol=$_REQUEST['vol'];
//echo "<br>vol=$vol";
if ($vol=='' or $vol=='1.0')
  {
    $vol=$_SESSION['PM_Volume'];
    if ($vol=='') $vol="0.3";
  }
$_SESSION['PM_Volume']=$vol;

//echo "<br>vol=$vol";

$play=$_REQUEST['play'];
if ($play!='1') $play=0;

$aupl='autoplay';
$go=$_REQUEST['go'];
if ($go=='')
  {
    $go=$_SESSION['PM_B_Go'];
    if ($go=='') $go=0;
  }
elseif ($go==2)
  {
    $go=0;
    $aupl='';
  }
$_SESSION['$PM_B_Go']=$go;

//if ($go==0)  $aupl='';

if ($uauth and $go==0 and $play==0) $aupl='';

//echo "<br>aupl=$aupl uauth=$uauth play=$play";

$yethee=$_SESSION['PM_B_YeThee'];

$lineNumber=$_REQUEST['refndx'];

$ref=$_REQUEST['ref'];
if ($ref!='')
  {
    $lineNumber=getline($ref);
    if ($lineNumber>=0) $_SESSION['PM_B_verse']=$ref;
  }
else $ref='';

$sbook=$_REQUEST['sbook'];
//echo "<br>sbook=$sbook";
if ($sbook>'')
  {
    $lineNumber=$lineNumber-1;
    do
      {
	$lineNumber=$lineNumber+1;
	$book=ShowQueryResultScalar("select book from Bible where line=$lineNumber");
	if ($book!=$sbook) break;
	$chapter=ShowQueryResultScalar("select chapter from Bible where line=$lineNumber");
	$verse=ShowQueryResultScalar("select verse from Bible where line=$lineNumber");
	$ref=$book.' '.$chapter.':'.$verse;
	$refm=$book.'_'.$chapter.'-'.$verse;
	$fil="../upload/Bible/audio/$book/".$genpre[$gendr].$refm.".wav";
      } while (file_exists($fil) and date("Ymd",filemtime($fil))>'20190404');
    if ($lineNumber==31102) $lineNumber=0;
  }

//echo "<br>line=$lineNumber";

if($lineNumber==='')
  {
    AlertCustom("Error","No Scripture Reference Number - showing John 3:16");
    $lineNumber=26136;
  }
//else
//  {
	$txt=ShowQueryResultScalar("select text from Bible where line=$lineNumber");
	TextClean($txt);
        if($yethee==1) $txt=YeThee($txt);
	$book=ShowQueryResultScalar("select book from Bible where line=$lineNumber");
	$chapter=ShowQueryResultScalar("select chapter from Bible where line=$lineNumber");
	$verse=ShowQueryResultScalar("select verse from Bible where line=$lineNumber");
	$ref=$book.' '.$chapter.':'.$verse;
	$refm=$book.'_'.$chapter.'-'.$verse;
	$fil="../upload/Bible/audio/$book/".$genpre[$gendr].$refm.".wav";
	if(!file_exists($fil) or date("Ymd",filemtime($fil))<'20190404') $needrcd="<font size=2>$ritaro</font>";
	else $needrcd='';
//echo "<br>fil=$fil filemtime=",date("Ymd",filemtime($fil));

	$com="<td><img onclick='javascript: popitup(\"Help.php?tabname=BibleTopic&refndx=".$lineNumber."&winnam=BibleTopic&fontsize=3&exte=1&txtsiz=15&clean=1\",50,375,550,500);' title='Discussion topics on ".str_replace(' ','_',$ref). "' src=../images/lightbulb.png height=28px></td>";

	$vrs="<td><img onclick='javascript: popitup(\"Help.php?tabname=BibleTopic&refndx=".$lineNumber."&winnam=BibleTopic&fontsize=3&exte=1&txtsiz=15&clean=1\",50,375,550,500);' title='Discussion topics on ".str_replace(' ','_',$ref). "' src=../images/lightbulb.png height=28px></td>";

        $chpimg="<td><img onclick='javascript: popitup(\"Help.php?tabname=BibleChapter&ref=$ref&winnam=BibleChapter&exte=1&clean=1\",75,175,575,700); ' title='$book chapter $chapter' src=../images/page.png width=38px></td>";

//  }

if($_FILES['audio_data'])
  {
	$input = $_FILES['audio_data']['tmp_name'];
	$output = $fil;
	move_uploaded_file($input, $output);
  }

include_once 'verse.inc';

$idx=BookIdx($book);
$bukl=strtolower($bks[$idx][1]);

$tsum="<td><img onclick='javascript: popitup(".'"'."Help.php?tabname=BibleBookHelp&buk=$bukl&winnam=BibleBookHelp&exte=1&clean=1".'"'.",75,225,575,700);' ".$_SESSION['PM_AltTitle'].'="Summary of '.$bukf.'" src=../images/info.gif height=26></td>';

if ($UserId>0) 	$lokico=' ../images/unlock.gif title="Log Out"';
else 		$lokico=' ../images/lock.gif title="Log In"';

$tlog='<td><img src='.$lokico.' height=25px onclick="javascript: logio();"></td>';

$lpre='<table border=0><tr><td><img src="../images/arrowL.jpg" width=22px title="Previous verse" onclick="GoToVrs(-1);">&nbsp;';
$lnxt='&nbsp;<img src="../images/arrowR.jpg" width=22px title="Next verse" onclick="GoToVrs(+1);"></td></tr></table>';

$tpla='<td><img onclick="javascript: SetGo();" title="Start or Stop audio for this verse forward" src=../images/movie.jpg width=28px></td>';

$tclos='<td><img onclick="javascript: window.close();" title="Close" src=../images/close.png width=30px></td>';

echo '

<!DOCTYPE html>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<meta id="meta" name="viewport" content="width=device-width; initial-scale=1.0" />

	<title>Live input record and playback</title>
  <style type="text/css">
    ul { list-style: none; }
    #recordingslist audio { display: block; margin-bottom: 10px; }
  </style>
</head>
<body bgcolor=#F0FFFF>
<center>

<table border=0 width=100%><tr><td>';
if ($play==0)
  {
     echo '
<table style="border-radius:10px" border=0 width=100% bgcolor=#FFA000><tr><td><table style="border-radius:10px" border=0 width=100% bgcolor=#FFFCCC><tr>',
$tclos,$tsum,'<td>',$genimg,'</td><td>',$vrsimg,'</td>',$com,$chpimg,$tpla,$tlog,'
</tr></table></td></tr></table>';
  }
else
  {
     $lpre='';
     $lnxt='';
  }
echo '
</td></tr><tr>
<td width=60% align=center>
',$lpre,'
  <font size=6><font color=green><b>',$ref,'</b></font></font>
',$lnxt,'
</td></tr></table>

<table border=0 style="border-radius:20px" width=90% bgcolor=#A00000><tr><td><table border=0 style="border-radius:17px" bgcolor=#FFFFEF cellpadding=10 width=100%><tr><td><font size=5><b>',
$txt
,'</b></font></td></tr></table></td></tr></table>

<p>

  <div id="recordingslist"></div>
';

if (!file_exists($fil)) echo '<h2>There is no recording available for this verse</h2>';
echo '<audio id="au" onended=NextVerse(',$go,'); controls ',$aupl,' src="',$fil,'"></audio><br>';

if ($play==0 and $uauth) echo '
  <button onclick="Lookfor(\'',$book,'\');">seek</button>
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
',$needrcd,'
  <button onclick="startRecording(this);">record</button>
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <button onclick="stopRecording(this);" disabled>stop</button>
</center>
<p>

  <h2><hr>Log:</h2>
  <dir><pre id="log"></pre></dir>
';
echo '
  <script language=javascript>

    var vol="',$vol,'";
    if (document.getElementById("au"))
      {
	    aid=document.getElementById("au");
    	aid.volume=vol;
	var li = document.createElement("p");
	li.appendChild(au);
	recordingslist.appendChild(li);
      }

function GoToVrs(minplus)
{
//alert("GoToVrs minplus="+minplus);
   updvol();
   linnum=',$lineNumber,'+ minplus;
//alert("gotovrs linnum="+linnum+" vol="+vol);
   location.href="BibleAudio.php?refndx="+linnum+"&vol="+vol;
}
</script>

';
if ($play==0 and $uauth) echo '
<script>
  function __log(e, data) {
//    log.innerHTML += "\n" + e + " " + (data || "");
    log.innerHTML = e + "<br>" + log.innerHTML + " " + (data || "")+"<br>\n";

  }

  var audio_context;
  var recorder;

  function startUserMedia(stream) {
    var input = audio_context.createMediaStreamSource(stream);
    __log("Media stream created.");

    // Uncomment if you want the audio to feedback directly
    //input.connect(audio_context.destination);
//    __log("Input connected to audio context destination.");

    recorder = new Recorder(input);
    __log("<hr>Recorder initialised.");
  }

  function startRecording(button) {
    recorder && recorder.record();
    button.disabled = true;
    button.nextElementSibling.disabled = false;
    __log("<font color=green>Recording...</font>");
  }

  function stopRecording(button) {
    recorder && recorder.stop();
    button.disabled = true;
    button.previousElementSibling.disabled = false;
    __log("<font color=red>Stopped recording.</font>");

    // create WAV download link using audio data blob
    createDownloadLink();

    recorder.clear();
  }

  function createDownloadLink() {
    recorder && recorder.exportWAV(function(blob) {
      var url = URL.createObjectURL(blob);
      au.src = url;
//begin not example
		var xhr=new XMLHttpRequest();
		xhr.onload=function(e) {
  	    		console.log("Server returned: ",e.target.responseText);
		};
		var fd=new FormData();
		fd.append("audio_data",blob, "filename");
  aid=document.getElementById("au");
  vol=aid.volume;
		xhr.open("POST","BibleAudio.php?refndx=',$lineNumber,'&vol="+vol,false);
		xhr.send(fd);
		if (xhr.status === 200) {
 		     __log("<font color=blue>Saved to server.</font>");
		}
//end not example
    });
  }

  window.onload = function init() {
    try {
      // webkit shim
      window.AudioContext = window.AudioContext || window.webkitAudioContext;
//      navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia;
	  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

      window.URL = window.URL || window.webkitURL;

      audio_context = new AudioContext;
      __log("Audio context set up.");
      __log("navigator.getUserMedia " + (navigator.getUserMedia ? "available." : "not present!"));
    } catch (e) {
      alert("No web audio support in this browser!");
    }

    navigator.getUserMedia({audio: true}, startUserMedia, function(e) {
      __log("No live audio input: " + e);
    });
  };
  </script>

  <script src="../../inc/Recorderjs-master/dist/recorder.js"></script>

';
echo '
</body>
</html>
<script language=javascript>
function updvol()
{
  if (document.getElementById("au"))
    {
	  aid=document.getElementById("au");
	  vol=aid.volume;
    }
}

function Lookfor(book)
{
  updvol();
  act="BibleAudio.php?refndx=',$lineNumber,'&minplus=',$minplus,'&sbook="+book+"&go=',$go,'&vol="+vol;
//alert("act="+act);
  location.href=act;
}

function SetGo()
{
  updvol();
  if ("',$go,'"==0) go=1;
  else if ("',$go,'"==1) go=2;
  else go=0;
  act="BibleAudio.php?refndx=',$lineNumber,'&go="+go+"&minplus=1&vol="+vol;
  location.href=act;
}

function NextVerse(go)
{
  updvol();
  if (go==1) {
     act="BibleAudio.php?refndx=',$lineNumber+1,'&go=1&minplus=1&vol="+vol;
     location.href=act;
  }
  else if ("',$play,'"==1) {
	updvol();
	window.parent.SSnext();
	window.close();
  }
}

function ReLoadPage(parm)
{
  act="BibleAudio.php?refndx=',$lineNumber,'&minplus=',$minplus,'&vol="+vol+parm;
  location.href=act;
}

function logio()
{
//alert("In logio");
  popitup("Login.php?winnam=UserLogin",100,375,375,450);
//  ReLoadPage();
}

</script>

';

function getline($ref)
{
   $refprt=RefParts($ref);
   $sql="select line from Bible where book='$refprt[1]' and chapter='$refprt[2]' and verse in ($refprt[3])";
   $lineNumber=ShowQueryResultScalar($sql);
   return $lineNumber;
}

?>
