<?php
/*
   The Index software may be freely distributed.
   See license.txt for details.
*/
define('RANDOMSITE', ROOT . 'list/random.lst');

function ReadRandom()
{
    global $randomsite;
    if (file_exists(RANDOMSITE))
        include(RANDOMSITE);
    else
        NewRandom();
}

function WriteRandom()
{
    global $randomsite;
    $f = fopen(RANDOMSITE, "w");
    fwrite($f, "<?php\n");
    fwrite($f, "\$randomsite = array (\n"); // Notes array
    fwrite($f, "    'date' => ");
    fwrite($f, $randomsite['date']);
    fwrite($f, ",\n");
    fwrite($f, "    'key' => '");
    fwrite($f, $randomsite['key']);
    fwrite($f, "'\n");
    fwrite($f, ");\n");
    fwrite($f, "?>\n");
    fclose($f);
}

function NewRandom()
{
    global $randomsite;
    global $combilist;
    srand((int)time());
    $num = rand(1, count($combilist));
    reset($combilist);
    for ($i = 0; $i < $num; $i++)
    {
        list($key,) = each($combilist);
    }
    $randomsite['key'] = $key;
    $randomsite['date'] = strtotime("+1 day", (int)(time() / (24 * 60 * 60)) * (24 * 60 * 60));
    WriteRandom();
}

function TimeLeft()
{
    global $randomsite;

    $time = $randomsite['date'];
    $secsleft = $time - time();
    $h = (int)($secsleft / (60 * 60));
    $secsleft -= $h * (60 * 60);
    $m = (int)($secsleft / 60);
    $secsleft -= $m * 60;
    $s = $secsleft;
    $timeleft = ($h ? "$h hours, " : "")
                . ($m || $h ? "$m minutes and " : "")
                . ($s || $m || $h ? "$s seconds" : "");
    return $timeleft;
}

// MAIN
function randomsite()
{
    global $randomsite;
    global $combilist;
    ReadList();
    ReadRandom();
    $key = $randomsite['key'];
    $date = $randomsite['date'];
    if (time() > $date)
    {
        NewRandom();
        $key = $randomsite['key'];
        $date = $randomsite['date'];
    }
    $value = $combilist[$key];

    ?>

    <table border="0" width="170" bgcolor="#ffcccc">
    <tr><td><b>Random Site of the Day</b>
    <p>
    This site will be Random Site of the Day for another 
    <?php print TimeLeft() ?>.
    </p>
    </td></tr>
    <tr><td>
    <?php
    start_itemlist();
    start_item();
    blockitem($key, $value);
    end_item();
    end_itemlist();
    ?>
    </td></tr></table>

    <?php
}
?>