<?php

// TMS Rewritten - Early 2010
// By Joseph Robert Gillotti

defined('in_tms'or exit;

// HTML output management

class Layout  {

    // Hold themes
    var
        $themes array(),
        $current_theme 0,
        $ob true;

    // Stuff dealing with the nav and files to use
    var
        $nav array(),
        $css array('main.css'),
        $js array('layout.js''common.js''jquery-1.4.2.min.js''jquery.lazyload.mini.js');


    /*
     * Start us off by determining the themes and nav
     */
    function __construct() {

        /*
         * Construct navigation
         */
        $this->nav array(
            array('act' => 'home''name' => 'Home'),
            array('act' => 'tos''name' => 'Rules'),
            array('act' => 'maps''name' => 'Maps'),
            array('act' => 'members''name' => 'Members'),
            array('act' => 'resources''name' => 'Resources'),
            array('act' => 'prefabs''name' => 'Prefabs'),
            array('act' => 'forum''name' => 'Forum'),
            array('act' => 'tools''name' => 'Tools'),
            array('act' => 'tutorials''name' => 'Tutorials'),
            array('act' => 'contact''name' => 'Contact'),
        );
    }

    /*
     * Determine themes. Call this after the user class has been started
     */
    function determineTheme() {

        global $ui$sp;

        // Get available themes
        $this->themes glob($sp['local_theme'].'theme_*.css');

        // Get a user's preference if we have the user class loaded
        if (is_object($ui))
        {
            // Which one? Default to first if invalid
            $this->current_theme array_key_exists($ui->userTheme(), $this->themes) ? $ui->userTheme() : 0;
        }

        // Or default to first
        else {
            $this->current_theme 0;
        }

        // Path to it etc
        $this->css[] = basename($this->themes[$this->current_theme]);


    }


    /*
     *  Main layout header
     */
    public function head($title '') {

        // Need paths
        global $sp$web_url$entry_point$entry_point_sm$fluid_layout_actions;

        // Need SQL and USER classes
        global $sql$ui;

        header('Content-type: text/html; charset=utf-8');

        // Buffering to make us faster, smaller, and sexier?
        if ($this->ob)
            ob_start('ob_gzhandler');

        // Start sending it out
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';

    // Send out CSS deps
    foreach ($this->css as $f)
    echo '
    <link href="'.$sp['web_theme'].$f.'?v='.filemtime($sp['local_theme'].$f).'" rel="stylesheet" type="text/css" />';

    // And JS
    foreach ($this->js as $f)
    echo '
    <script type="text/javascript" src="'.$sp['web_theme'].$f.'?v='.filemtime($sp['local_theme'].$f).'"></script>';

    echo '
    <title>TMS Revamp ',$title ' &raquo; '.$title '','</title>
    <style type="text/css">
        #wrapper {
            width: ',@$_SESSION['site_width'] == 'fluid' || in_array(SITE_ACTION$fluid_layout_actions) ? '95%' '770px',';
        }
    </style>
    <script type="text/javascript">
        user_sessid = \''.session_id().'\';
        width = \'',@$_SESSION['site_width'] == 'fluid' || in_array(SITE_ACTION$fluid_layout_actions) ? 'fluid' 'fixed','\';
    </script>
</head>';

//flush();

echo'
<body id="tms">
    <div id="wrapper">
        <div id="head">
            <div id="logo"><a href="'.$web_url.'" title="Soldat Mapping Showcase"></a></div>
            <ul id="nav">';

        // Send out nav
        foreach ($this->nav as $n)
            echo '
                <li><a href="'.$entry_point.'?action='.$n['act'].'" title="'.$n['name'].'">'.$n['name'].'</a></li>';

        echo '
            </ul>
        </div>

        <div id="user_panel">
            <div id="user_greeting">
                Hello,
                    ',$ui->loggedIn() ? '<a href="'.$entry_point.'?action=view_profile&amp;u='.$ui->userID().'">'.stringprep($ui->userName()).'</a>' 'Guest','
                </div>
            <div id="layout_collapse">
            ';

            // If we're forced fluid, show arrows grayed out
            if (in_array(SITE_ACTION$fluid_layout_actions)) {
                echo '&laquo; &middot; &raquo;';
            }
            // Otherwise let you choose
            else {
                echo '
                <a href="'.$entry_point.'?action=change_layout&amp;sa=width&amp;w=fixed" onclick="set_width(\'fixed\'); return false;" title="Fixed width">&laquo;</a>
                &middot;
                <a href="'.$entry_point.'?action=change_layout&amp;sa=width&amp;w=fixed" onclick="set_width(\'fluid\'); return false;" title="Fluid width">&raquo;</a>';
            }

            echo '
            </div>';

            // User panel
            if ($ui->loggedIn())
            echo '
            <div style="overflow: hidden;">
                <div id="ave"><img src="'.$entry_point.'?action=view_avatar&amp;u='.$ui->userID().'" alt="'.stringprep($ui->userName()).'" /></div>
                <ul id="user_actions">
                    <li><a href="'.$entry_point.'?action=map_upload">Map Upload</a></li>
                    <li><a href="'.$entry_point.'?action=pm">PM</a></li>
                    <li><a href="'.$entry_point.'?action=profile">Settings</a></li>
                    <li><a href="'.$entry_point.'?action=logout">Logout</a></li>
                </ul>
            </div>';
            else
            echo '
            <form id="top_login" action="'.$entry_point.'?action=login" method="post" onclick="return top_login(this);">
                <div style="overflow: hidden;">
                    <input type="hidden" name="do_login" value="yes" />
                    <div>
                        <label for="top_login_user">Username:</label>
                        <input type="text" id="top_login_user" name="username" class="txt" />
                        <label for="top_login_pass">Password:</label>
                        <input type="password" id="top_login_pass" name="password" class="txt" />
                        <input type="submit" value="Login" />
                    </div>
                    <input type="checkbox" id="top_login_rem" name="remember" value="yes" />
                    <label for="top_login_rem">Remember me</label>
                    <div id="top_login_meta">
                        <a href="'.$entry_point.'?action=register">Register Account</a> |
                        <a href="'.$entry_point.'?action=pass_recover">Recover Password</a>
                    </div>
                </div>
            </form>
            ';

        echo '
        </div>
        <script type="text/javascript">
            $(function(){
                $("img").lazyload({effect: "fadeIn"});
            });
        </script>
        <div id="content_out">
            <div id="content">
                <h1><span>'.$title.'</span></h1>
                <div id="content_inner">
        ';

    }

    /*
     *  Main layout footer
     */
    public function foot() {

        // Gain access to hits and stuff
        global $ui$sql$entry_point$time_start;

echo '

                </div>
            </div>
        </div>
        <div id="side">
            <div class="widge poll" id="poll">
                <h2><span>Poll</span><span class="fake_link border" onclick="toggle_show(\'poll_content\', this);">',$this->checkHidden('poll_content') ? '+' '-','</span></h2>
                <div id="poll_content"',$this->checkHidden('poll_content') ? '' ' style="display: none;"','>
                ';

                    /*
                     *
                     * Poll
                     *
                     */

                    // Get latest poll
                    $get_poll $sql->query("
                        select
                            `poll_id`,
                            `total_votes`,
                            `locked`,
                            `question`
                        from
                            `poll_questions`
                        order by `poll_id` desc
                        limit 1
                    ");

                    $poll_info $sql->fetch_assoc($get_poll);
                    $sql->free($get_poll);

                    // Get options
                    $poll_options array();

                    $get_options $sql->query("
                        select
                            `option_id`,
                            `votes`,
                            `option`
                        from
                            `poll_options`
                        where
                            `poll_id` = '{$poll_info['poll_id']}'
                        order by `option` desc
                    ");

                    // Stuff it
                    while ($info $sql->fetch_row($get_options))
                        $poll_options[$info[0]] = array($info[1], stringprep($info[2]));

                    $sql->free($get_options);

                    // Am I logged in? Have I voted?
                    if ($ui->loggedIn()) {

                        // Get my vote
                        $get_me $sql->query("select `option_id` from `poll_votes` where `poll_id` = '{$poll_info['poll_id']}' and `user_id` = '".$ui->userID()."' limit 1");

                        if ($sql->num($get_me) == 1) {
                            list($my_vote_id) = $sql->fetch_row($get_me);
                            $voted true;
                        }
                        else {
                            $voted false;
                        }

                        $sql->free($get_me);
                    }

                    // Send out question
                    echo '
                    <p class="poll_question">'.stringprep($poll_info['question']).'</p>';

                    // Start form if needed
                    if ($ui->loggedIn() && $voted == false)
                        echo '
                    <form action="'.$entry_point.'?action=poll_vote" method="post">
                        <div>
                            <input type="hidden" id="pid" name="pid" value="'.$poll_info['poll_id'].'" />
                        </div>
                        ';

                    // Start options list
                    echo '
                    <ul class="poll_options">
                    ';


                    // If I am not logged in, just show options
                    if (!$ui->loggedIn()) {
                        foreach ($poll_options as $option)
                        echo '
                        <li class="border">'.$option[1].'</li>
                        ';
                    }

                    // if I am logged in and haven't voted
                    elseif($ui->loggedIn() && $voted == false) {
                        foreach ($poll_options as $option_id => $option)
                        echo '
                        <li class="border"><input onchange="this.form.submit();" type="radio" id="poll_op_'.$option_id.'" name="oid" value="'.$option_id.'" /><label for="poll_op_'.$option_id.'" class="poll_option_op">'.$option[1].'</label></li>
                        ';
                    }

                    // if I am logged in and have voted. (and can hence see results)
                    elseif($ui->loggedIn() && $voted == true) {
                        foreach ($poll_options as $option) {
                            $this_percent $option[0] == round(($option[0] / $poll_info['total_votes']) * 100);
                            echo '
                            <li class="border',$option_id == $my_vote_id ' my_vote' '','">
                                <div class="alt poll_option_bar" style="width: '.$this_percent.'%;">
                                    <div class="poll_option">
                                        <span class="poll_option_op">'.$option[1].'</span>  <span class="poll_option_sub">'.$this_percent.'% - '.$option[0].' votes</span>
                                    </div>
                                </div>
                            </li>
                            ';
                        }
                    }

                    // Finish option list
                    echo '
                    </ul>';

                    // Finish form if there was one
                    if ($ui->loggedIn() && $voted == false)
                        echo '</form>';

                    // Link to prior polls
                    echo '
                    <p id="poll_view_all"><a href="'.$entry_point.'?action=poll_history">View old polls</a></p>
                    ';

                echo '
                </div>
            </div>
            <div class="widge" id="shoutbox">
                <h2><span>Shoutbox</span><span class="fake_link border" onclick="toggle_show(\'shoutbox_content\', this);">',$this->checkHidden('shoutbox_content') ? '+' '-','</span></h2>
                <div id="shoutbox_content"',$this->checkHidden('shoutbox_content') ? '' ' style="display: none;"','>';

                    /*
                     *
                     * Shoutbox
                     *
                     */

                    // Get shouts
                    $get_shouts $sql->query("select sb.`date`, sb.`user`, sb.`msg`, u.`username` from `shoutbox` as sb join `members` as u on u.`id` = sb.`user` order by sb.`id` desc limit 10");

                    // Hold them here
                    $shouts array();

                    // Stuff it
                    while ($shout $sql->fetch_row($get_shouts)) {
                        $shouts[] = array(
                            'date' => $shout[0],
                            'name' => stringprep($shout[3], true),
                            'uid' => $shout[1],
                            'msg' => stringprep($shout[2], truetrue2)
                        );
                    }

                    // Free
                    $sql->free($get_shouts);

                    echo '<p style="padding: 0px; margin: 5px; text-align: center; font-size: 10px;">
                        Last:
                        '.(date('m/d/y') == date('m/d/y'$shouts[0]['date']) ? 'Today' date('m/d/y'$shouts[0]['date'])).date(' @ h:i A'$shouts[0]['date']).'
                    </p>';

                    // Give them
                    $alt false;
                    foreach ($shouts as $shout) {
                        echo '<p title="Posted: '.date('m/d/y @ h:i A'$shout['date']).'" class="p',$alt ' alt' '','"><span><a href="'.$entry_point.'?action=view_profile&amp;u='.$shout['uid'].'">'.$shout['name'].'</a> says:</span> '.$shout['msg'].'</p>';
                        $alt = !$alt;
                    }

                    echo '
                    <h2 class="sect"><span>Shout</span></h2>';

                    // Reply?
                    if ($ui->loggedIn())
                    echo '
                        <form action="'.$entry_point.'?action=shout" method="post" onclick="return shout_submit(this);">
                            <div id="sb_form_contents">
                                <label for="sb_main_msg">Message: </label>
                                <textarea name="sb_main_msg" id="sb_main_msg" cols="4" rows="4"></textarea>
                                <input type="hidden" name="'.$ui->verifKey().'" value="'.$ui->verifVal().'" />
                                <input type="hidden" id="sb_do_shout" name="sb_do_shout" value="yes" />
                                <div><input type="submit" value="Shout!" /></div>
                            </div>
                        </form>
                    ';
                    else
                        echo '<p>Login to shout</p>';
            echo '
                </div>
            </div>
            ';


            /*
             * Latest downloaded maps
             */
            echo '
            <div class="widge" id="last_downloaded_maps">
                <h2><span>Maps just downloaded</span><span class="fake_link border" onclick="toggle_show(\'last_downloaded_maps_content\', this);">',$this->checkHidden('last_downloaded_maps_content') ? '+' '-','</span></h2>
                <div id="last_downloaded_maps_content"',$this->checkHidden('last_downloaded_maps_content') ? '' ' style="display: none;"','>
                    <ul>
                    ';

                    // Get them
                    $get_latest_downloaded_maps $sql->query("
                        select
                            m.`title`,
                            l.`map`,
                            d.`file`,
                            l.`when`
                        from
                            `map_download_log` as l
                            join `maps` as m on m.`id` = l.`map`
                            join `map_downloads` as d on d.`mapid` = l.`map`
                        where
                            m.`missing` = '0'
                        order by
                            l.`when`
                        desc
                        limit 15
                    ");

                    // Show them
                    while ($info $sql->fetch_row($get_latest_downloaded_maps))
                        echo '<li title="On '.date('m/d/Y @ h:i A'$info[3]).'"><a href="'.$entry_point.'?map='.$info[1].'">'.stringprep($info[0]).'</a> <span class="sm_note">('.number_format($info[2]).' total)</span></li>';

                    // Free ram
                    $sql->free($get_latest_downloaded_maps);

                    // Get total downloads
                    list($total_downloads) = $sql->fetch_row($sql->query("select sum(`file`) from `map_downloads`"));
                    $sql->freelast();

                    echo '
                    </ul>
                    <p class="border">Total downloads: '.number_format($total_downloads).'</p>
                </div>
            </div>
            ';


            /*
             * Theme chooser
             */

            echo '
            <div class="widge">
                <h2><span>Theme</span><span class="fake_link border" onclick="toggle_show(\'theme_changer_content\', this);">',$this->checkHidden('theme_changer_content') ? '+' '-','</span></h2>
                <div id="theme_changer_content"',$this->checkHidden('theme_changer_content') ? '' ' style="display: none;"','>
                    <form id="theme_changer" action="'.$entry_point.'?action=change_layout&amp;sa=theme" method="post">
                        <div><select id="theme" name="theme" onchange="this.form.submit();">
                        ';
                        foreach($this->themes as $k => $v)
                        {
                            preg_match('/theme_(.+)\.css$/i'$v$m);
                            echo '
                            <option',$this->current_theme == $k ' selected="selected"' '',' value="'.$k.'">'.stringprep($m[1], true).'</option>
                            ';
                        }

                        echo '
                        </select></div>
                    </form>
                </div>
            </div>';

            /*
             * Finish layout
             */

            echo '
        </div>
    </div>
    <div id="foot">
        &copy; 2007 &mdash; 2010 JRG Productions. All Rights Reserved. <a href="'.$entry_point.'?action=credits">Credits</a><br />
        '.number_format($ui->hits['today']).' hits today; '.number_format($ui->hits['overall']).' hits since 1/10/2008.
        <br />Page generated in '.round(microtime(true) - $time_start3).' seconds.
    </div>
</body>
</html>
<!-- Reading my html makes you stonger -->
';

    // Send out hopefully compressed html tinily
    if ($this->ob)
        ob_end_flush();

    }

    /*
     *  Minimal layout head
     */
    public function mHead() {

    }

    /*
     *  Minimal layout foot
     */
    public function mFoot() {

    }

    /*
     * Error Messages..
     */

    // Include main layout with error message
    public function errorMsg($msg$title '') {
        $this->head($title $title 'Error');
        echo '<p class="error">'.$msg.'</p>';
        $this->foot();
        exit;
    }

    // Use minimal layout for error message
    public function errorMsgMinimal($msg$title '') {

    }

    /*
     * Notifs
     */
    public function notifMsg($msg$title '') {
        $this->head($title $title 'Notification');
        echo '<p class="notif">'.$msg.'</p>';
        $this->foot();
        exit;
    }

    /*
     * Add a required css or javascript file
     */
    public function add_dep($type$file) {
        if ($type == 'css')
            $this->css[] = $file;
        elseif ($type == 'js')
            $this->js[] = $file;
        else
            return false;
        return true;
    }

    /*
     * See if a sidebar item is set to be hidden
     */
    public function checkHidden($area) {
        return !isset($_COOKIE['pref_'.$area]) || $_COOKIE['pref_'.$area] == 1;
    }

}