<?php
require('includes/global.php');
$ettvd->init();

if(isset($_POST['reloaddemos'])) {
   $ettvd->reload_demolist();
   send('demos.php');
}
if(isset($_POST['addqueue'])) {
   $replayer = intval($_POST['replayer']);
   $demo     = intval($_POST['demo']);
   $ettvd->addqueue($replayer, $demo);
   send("demos.php?playlist=$replayer#$demo");
}
if(isset($_POST['delqueue'])) {
   $ettvd->delqueue(intval($_POST['repid']));
   send('demos.php?playlist='.intval($_POST['repid']));
}
if(isset($_POST['repeatqueue'])) {
   $replayer = intval($_POST['repeatqueue']);
   if(isset($_POST['on'])) {
      $value = 1;
   } elseif(isset($_POST['off'])) {
      $value = 0;
   }
   $ettvd->repeatqueue($replayer, $value);
   send('demos.php?playlist='.intval($_POST['repeatqueue']));
}

$demos = format_demoarray($ettvd->fetch_demos());

if(isset($_POST['exportdemos'])) {
   $out  = ' ID  | ' . str_pad('Date', 25) . ' | ' . str_pad('Game', 48) . ' | Maps' . "\n";
   $out .= str_repeat('-', 90) . "\n";
   foreach($demos AS $demo) {
      $out .= str_pad($demo['id'], 4) . ' | ' . str_pad($demo['time'], 22) . '('.$demo['rec'].') | ' . str_pad($demo['name'], 48) . ' | ' . $demo['maps'] . "\n";
   }
   if(!$fp = @fopen('demolist.txt', 'w')) {
      error('Error opening demolist.txt, probably wrong permissions. Set chmod to 777');
   }
   @fputs($fp, $out);
   @fclose($fp);
   Header('Location: demolist.txt');
}

$tpl->assign('demos', $demos);

if($playlist = intval($_GET['playlist'])) {
   $tpl->assign('playlist', format_demoarray($ettvd->fetch_playlist($playlist)));
   if($ettvd->lastcode == 121) {
      $tpl->assign('off', true);
   } elseif($ettvd->lastcode == 120) {
      $tpl->assign('on', true);
   }
   $tpl->assign('playlistrep', $playlist);
}

if($player = intval($_GET['player'])) {
   $tpl->assign('player', $player);
}

$tpl->assign('body', $tpl->fetch('demolist.tpl'));
$tpl->assign('area', 'Demos');
require('finish.php');

?>