<?php
if (!defined('webid')) {
    exit();
}
if (!(isset($_SESSION["username"]) && isset($_SESSION["password"]))) {
    header("Location: /");
	exit();
}
?>
<script type="text/javascript" src="theme/js/bbcode.js"></script>
<script type="text/javascript" src="theme/js/autoresize.jquery.js"></script>
<script type="text/javascript">
$('a.mlbt1, a.mlbt2, a.mlbt3, a.mlbt4, img.mimg, img.avatar, #userid').tipTip();
$('#newmail').tipTip({defaultPosition : 'top'});
$('#mailtext').autoResize({limit:200});
$(document).ready(function(){
    $('#mailtext').Qbb();
})
</script>
<?php
if ($_GET['m'] == 'noread') {
    $pagetitle = '<span style="font-weight:normal; color:#212121; font-size:10px; text-shadow:none">(<font color="#800000">Непрочитанные</font>)</span>';
} elseif ($_GET['m'] == 'in') {
    $pagetitle = '<span style="font-weight:normal; color:#212121; font-size:10px; text-shadow:none">(<font color="#800000">Мне пишут</font>)</span>';
} elseif ($_GET['m'] == 'out') {
    $pagetitle = '<span style="font-weight:normal; color:#212121; font-size:10px; text-shadow:none">(<font color="#800000">Я пишу</font>)</span>';
} elseif ($_GET['read']) {
    $pagetitle = '<span style="font-weight:normal; color:#212121; font-size:10px; text-shadow:none">(<font color="#800000">Чтение письма</font>)</span>';
} elseif ($_GET['m'] == 'new') {
    $pagetitle = '<span style="font-weight:normal; color:#212121; font-size:10px; text-shadow:none">(<font color="#800000">Новое письмо</font>)</span>';
} else {
    $pagetitle = '';
}
?>
<h3 style="border-bottom: 1px dotted #cccccc; color: #1c62b9; text-shadow: 0 1px 0 #fafafa;">Внутренняя почта <?=$pagetitle?></h3>
Всегда хорошо держать связь с другими участниками проекта. Пожалуйста, помните, что в сообщениях запрещён СПАМ, нецензурная лексика и оскорбления. Так же запрещено использовать почту в рекламных целях. По <a href="tos" class="link">правилам</a> проекта, Администрация имеет право просматривать сообщения и наказывать нарушителей.
<center><a href="/mail/new" id="newmail" class="big_btn" title="Новое сообщение"><img src="theme/img/mail/new_mail.png" width="24" height="24" border="0" /></a></center>
<center><div class="mlcon_btn"><a href="/mail" class="mlbt1" title="Вся почта"></a><a href="/mail/noread" class="mlbt2" title="Непрочитанные"></a><a href="/mail/out" class="mlbt3" title="Я пишу"></a><a href="/mail/in" class="mlbt4" title="Мне пишут"></a></div></center>
    <?php
    if (!$_GET['m'] and !$_GET['read']) {
        
        $kolvo = 10;
        $all = mysql_num_rows(mysql_query("SELECT id FROM seo_mails WHERE fromid = '" . $_SESSION['iduser'] . "' or toid = '" . $_SESSION['iduser'] . "' order by id desc"));
        $allpage = ceil($all/$kolvo);
        $this_page = (isset($_GET['pg'])) ? intval($_GET['pg']) : 1 ;
        if ($this_page < 1) $this_page = 1;
        if ($this_page > $allpage) $this_page = $allpage;
        $start = $this_page * $kolvo - $kolvo;
        if ($start == -10) { $start = 1; }
        
        include_once 'functiones.php';
    
    echo "<table width='100%' style='margin-bottom: 5px;'><tr><td nowrap='nowrap'>";
    $nextp = $this_page + 1;
    $lastp = $this_page - 1;
    if ($this_page > 1) { echo "<a href='/mail/pg=$lastp' class=\"link\"><span class='text14'>"; } else { echo "<span class='textgray'>"; } echo "&larr;&nbsp;Предыдущие</span>";
    if ($this_page == 1) { echo "</a>"; } echo "</td><td width='90%' align='center'>". navigation($allpage,'/mail/pg=',1,1)."</td><td nowrap='nowrap'>";
    if ($this_page == $allpage) { echo "<span class='textgray'>"; } else { echo "<a href='/mail/pg=$nextp' class=\"link\"><span class='text14'>"; } echo "Следующие&nbsp;&rarr;</span>"; 
    if ($this_page == $allpage) { echo "</a>"; } echo "</td></tr></table>";
    ?>
    <table class="otab" width="100%" border="0" cellpadding="0" cellspacing="1">
    <thead>
        <th width="30" style="padding: 5px; background: #ebebeb; text-align: center;"></th>
        <th width="80" style="padding: 5px; background: #ebebeb; text-align: center;">Дата и время</th>
        <th style="padding: 5px; background: #ebebeb; text-align: center;">Тема</th>
    </thead>
    <?php
        $get_id_from = mysql_query( "SELECT id, subject, toid, fromid, timemessage, `read` FROM seo_mails WHERE fromid = '" . $_SESSION['iduser'] . "' or toid = '" . $_SESSION['iduser'] . "' order by timemessage desc limit $start,$kolvo" );
        while ($get_id_from_row = mysql_fetch_array($get_id_from)) {
            $get_us_from = mysql_fetch_array(mysql_query( "SELECT username, avatar FROM tb_users WHERE id = '" . $get_id_from_row['fromid'] . "'" ));
            $get_us_from2 = mysql_fetch_array(mysql_query( "SELECT username FROM tb_users WHERE id = '" . $get_id_from_row['toid'] . "'" ));
            if ($get_id_from_row['read'] == 0) {
                $bold = 'link_b';
            } else {
                $bold = 'link';
            }
            
            if ($get_id_from_row['fromid'] != $_SESSION['iduser'] and $get_id_from_row['read'] != 0) {
                $mimg = 'theme/img/mail/mail_out.png';
            } else
            if ($get_id_from_row['fromid'] == $_SESSION['iduser'] and $get_id_from_row['read'] != 0) {
                $mimg = 'theme/img/mail/mail_in.png';
            } else {
                $mimg = 'theme/img/mail/no_read.png';
            }
            
            if ($get_id_from_row['fromid'] != $_SESSION['iduser'] and $get_id_from_row['fromid'] != $_SESSION['username']) {
                $minf = $get_us_from['username'] . ' -> ' . $get_us_from2['username'];
            } else
            if ($get_id_from_row['toid'] != $_SESSION['iduser'] and $get_id_from_row['fromid'] == $_SESSION['username']) {
                $minf = $get_us_from2['username'] . ' -> ' . $get_us_from['username'];
            } else {
                $minf = $get_us_from['username'] . ' -> ' . $get_us_from2['username'];
            }
            
            if ($get_id_from_row['fromid'] == 0) {
                $minf = 'Служебное сообщение -> ' . $get_us_from2['username'];
            }
            ?>
            <tr>
            <td class="lt" align="center"><img src="<?=$mimg?>" width="24" height="24" class="mimg" title="<?=$minf?>" /></td>
            <td class="rt" valign="center" align="center"><?=date('d.m.Y', $get_id_from_row['timemessage'])?><br /><?=date('H:i', $get_id_from_row['timemessage'])?></td>
            <td class="lt"><a href="/mail/read=<?=$get_id_from_row['id']?>" class="<?=$bold?>"><?=substr($get_id_from_row['subject'], 0, 50)?></a></td>
            </tr>
            <?php
        }
    }
    //----------Непрочитанные----------
    if ($_REQUEST['m'] == 'noread') {
        $kolvo = 10;
        $all = mysql_num_rows(mysql_query("SELECT id FROM seo_mails WHERE toid = '" . $_SESSION['iduser'] . "' and `read` = 0 order by id desc"));
        $allpage = ceil($all/$kolvo);
        $this_page = (isset($_GET['pg'])) ? intval($_GET['pg']) : 1 ;
        if ($this_page < 1) $this_page = 1;
        if ($this_page > $allpage) $this_page = $allpage;
        $start = $this_page * $kolvo - $kolvo;
        if ($start == -10) { $start = 1; }
        
        include_once 'functiones.php';
    
    echo "<table width='100%' style='margin-bottom: 5px;'><tr><td nowrap='nowrap'>";
    $nextp = $this_page + 1;
    $lastp = $this_page - 1;
    if ($this_page > 1) { echo "<a href='/mail/noread/pg=$lastp' class=\"link\"><span class='text14'>"; } else { echo "<span class='textgray'>"; } echo "&larr;&nbsp;Предыдущие</span>";
    if ($this_page == 1) { echo "</a>"; } echo "</td><td width='90%' align='center'>". navigation($allpage,'/mail/noread/pg=',1,1)."</td><td nowrap='nowrap'>";
    if ($this_page == $allpage) { echo "<span class='textgray'>"; } else { echo "<a href='/mail/noread/pg=$nextp' class=\"link\"><span class='text14'>"; } echo "Следующие&nbsp;&rarr;</span>"; 
    if ($this_page == $allpage) { echo "</a>"; } echo "</td></tr></table>";
    ?>
    <table class="otab" width="100%" border="0" cellpadding="0" cellspacing="1">
    <thead>
        <th width="30" style="padding: 5px; background: #ebebeb; text-align: center;"></th>
        <th width="80" style="padding: 5px; background: #ebebeb; text-align: center;">Дата и время</th>
        <th style="padding: 5px; background: #ebebeb; text-align: center;">Тема</th>
    </thead>
    <?php
        $get_id_from = mysql_query( "SELECT id, subject, toid, fromid, timemessage, `read` FROM seo_mails WHERE toid = '" . $_SESSION['iduser'] . "' and `read` = 0 order by timemessage desc limit $start,$kolvo" );
        while ($get_id_from_row = mysql_fetch_array($get_id_from)) {
            $get_us_from = mysql_fetch_array(mysql_query( "SELECT username, avatar FROM tb_users WHERE id = '" . $get_id_from_row['fromid'] . "'" ));
            if ($get_id_from_row['read'] == 0) {
                $bold = 'link_b';
            } else {
                $bold = 'link';
            }
            
            if ($get_id_from_row['fromid'] != $_SESSION['iduser']) {
                $mimg = 'theme/img/mail/no_read.png';
            } else {
                $mimg = 'theme/img/mail/no_read.png';
            }
            ?>
            <tr>
            <td class="lt" align="center"><img src="<?=$mimg?>" width="24" height="24" class="mimg" title="<?=$get_us_from['username']?>" /></td>
            <td class="rt" valign="center" align="center"><?=date('d.m.Y', $get_id_from_row['timemessage'])?><br /><?=date('H:i', $get_id_from_row['timemessage'])?></td>
            <td class="lt"><a href="/mail/read=<?=$get_id_from_row['id']?>" class="<?=$bold?>"><?=substr($get_id_from_row['subject'], 0, 50)?></a></td>
            </tr>
            <?php
        }
    }
    //----------Я пишу----------
    if ($_REQUEST['m'] == 'out') {
        $kolvo = 10;
        $all = mysql_num_rows(mysql_query("SELECT id FROM seo_mails WHERE fromid = '" . $_SESSION['iduser'] . "' order by id desc"));
        $allpage = ceil($all/$kolvo);
        $this_page = (isset($_GET['pg'])) ? intval($_GET['pg']) : 1 ;
        if ($this_page < 1) $this_page = 1;
        if ($this_page > $allpage) $this_page = $allpage;
        $start = $this_page * $kolvo - $kolvo;
        if ($start == -10) { $start = 1; }
        
        include_once 'functiones.php';
    
    echo "<table width='100%' style='margin-bottom: 5px;'><tr><td nowrap='nowrap'>";
    $nextp = $this_page + 1;
    $lastp = $this_page - 1;
    if ($this_page > 1) { echo "<a href='/mail/out/pg=$lastp' class=\"link\"><span class='text14'>"; } else { echo "<span class='textgray'>"; } echo "&larr;&nbsp;Предыдущие</span>";
    if ($this_page == 1) { echo "</a>"; } echo "</td><td width='90%' align='center'>". navigation($allpage,'/mail/out/pg=',1,1)."</td><td nowrap='nowrap'>";
    if ($this_page == $allpage) { echo "<span class='textgray'>"; } else { echo "<a href='/mail/out/pg=$nextp' class=\"link\"><span class='text14'>"; } echo "Следующие&nbsp;&rarr;</span>"; 
    if ($this_page == $allpage) { echo "</a>"; } echo "</td></tr></table>";
    ?>
    <table class="otab" width="100%" border="0" cellpadding="0" cellspacing="1">
    <thead>
        <th width="30" style="padding: 5px; background: #ebebeb; text-align: center;"></th>
        <th width="80" style="padding: 5px; background: #ebebeb; text-align: center;">Дата и время</th>
        <th style="padding: 5px; background: #ebebeb; text-align: center;">Тема</th>
    </thead>
    <?php
        $get_id_from = mysql_query( "SELECT id, subject, toid, fromid, timemessage, `read` FROM seo_mails WHERE fromid = '" . $_SESSION['iduser'] . "' order by timemessage desc limit $start,$kolvo" );
        while ($get_id_from_row = mysql_fetch_array($get_id_from)) {
            $get_us_from = mysql_fetch_array(mysql_query( "SELECT username, avatar FROM tb_users WHERE id = '" . $get_id_from_row['toid'] . "'" ));
            if ($get_id_from_row['read'] == 0) {
                $bold = 'link_b';
            } else {
                $bold = 'link';
            }
            if ($get_id_from_row['fromid'] != $_SESSION['iduser']) {
                $mimg = 'theme/img/mail/mail_out.png';
            } else {
                $mimg = 'theme/img/mail/mail_in.png';
            }
            ?>
            <tr>
            <td class="lt" align="center"><img src="<?=$mimg?>" width="24" height="24" class="mimg" title="<?=$get_us_from['username']?>" /></td>
            <td class="rt" valign="center" align="center"><?=date('d.m.Y', $get_id_from_row['timemessage'])?><br /><?=date('H:i', $get_id_from_row['timemessage'])?></td>
            <td class="lt"><a href="/mail/read=<?=$get_id_from_row['id']?>" class="<?=$bold?>"><?=substr($get_id_from_row['subject'], 0, 50)?></a></td>
            </tr>
            <?php
        }
    }
    //----------Мне пишут----------
    if ($_REQUEST['m'] == 'in') {
        $kolvo = 1;
        $all = mysql_num_rows(mysql_query("SELECT id FROM seo_mails WHERE toid = '" . $_SESSION['iduser'] . "' order by id desc"));
        $allpage = ceil($all/$kolvo);
        $this_page = (isset($_GET['pg'])) ? intval($_GET['pg']) : 1 ;
        if ($this_page < 1) $this_page = 1;
        if ($this_page > $allpage) $this_page = $allpage;
        $start = $this_page * $kolvo - $kolvo;
        if ($start == -1) { $start = 1; }
        
        include_once 'functiones.php';
    
    echo "<table width='100%' style='margin-bottom: 5px;'><tr><td nowrap='nowrap'>";
    $nextp = $this_page + 1;
    $lastp = $this_page - 1;
    if ($this_page > 1) { echo "<a href='/mail/in/pg=$lastp' class=\"link\"><span class='text14'>"; } else { echo "<span class='textgray'>"; } echo "&larr;&nbsp;Предыдущие</span>";
    if ($this_page == 1) { echo "</a>"; } echo "</td><td width='90%' align='center'>". navigation($allpage,'/mail/in/pg=',1,1)."</td><td nowrap='nowrap'>";
    if ($this_page == $allpage) { echo "<span class='textgray'>"; } else { echo "<a href='/mail/in/pg=$nextp' class=\"link\"><span class='text14'>"; } echo "Следующие&nbsp;&rarr;</span>"; 
    if ($this_page == $allpage) { echo "</a>"; } echo "</td></tr></table>";
    ?>
    <table class="otab" width="100%" border="0" cellpadding="0" cellspacing="1">
    <thead>
        <th width="30" style="padding: 5px; background: #ebebeb; text-align: center;"></th>
        <th width="80" style="padding: 5px; background: #ebebeb; text-align: center;">Дата и время</th>
        <th style="padding: 5px; background: #ebebeb; text-align: center;">Тема</th>
    </thead>
    <?php
        $get_id_from = mysql_query( "SELECT id, subject, toid, fromid, timemessage, `read` FROM seo_mails WHERE toid = '" . $_SESSION['iduser'] . "' order by timemessage desc limit $start,$kolvo" );
        while ($get_id_from_row = mysql_fetch_array($get_id_from)) {
            $get_us_from = mysql_fetch_array(mysql_query( "SELECT username, avatar FROM tb_users WHERE id = '" . $get_id_from_row['fromid'] . "'" ));
            if ($get_id_from_row['read'] == 0) {
                $bold = 'link_b';
            } else {
                $bold = 'link';
            }
            
            if ($get_id_from_row['fromid'] != $_SESSION['iduser']) {
                $mimg = 'theme/img/mail/mail_out.png';
            } else {
                $mimg = 'theme/img/mail/mail_in.png';
            }
            ?>
            <tr>
            <td class="lt" align="center"><img src="<?=$mimg?>" width="24" height="24" class="mimg" title="<?=$get_us_from['username']?>" /></td>
            <td class="rt" valign="center" align="center"><?=date('d.m.Y', $get_id_from_row['timemessage'])?><br /><?=date('H:i', $get_id_from_row['timemessage'])?></td>
            <td class="lt"><a href="/mail/read=<?=$get_id_from_row['id']?>" class="<?=$bold?>"><?=substr($get_id_from_row['subject'], 0, 50)?></a></td>
            </tr>
            <?php
        }
    }
    ?>
    </table>
    <?php
    //----------Чтение писем----------
    if ($_GET['read']) {
        $get_mail = mysql_fetch_array( mysql_query( "SELECT id, text, subject, fromid, toid, timemessage FROM seo_mails WHERE id = '" . intval($_GET['read']) . "'" ) );
        if ($get_mail['toid'] != $_SESSION['iduser'] and $get_mail['fromid'] != $_SESSION['iduser'] and $get_mail['id'] != '') {
            echo '<center><span style="color:#800000; padding:10px; font-weight:bold">Вы не можете читать чужие письма</span></center>';
        } else
        if ($get_mail['id'] == '') {
            echo '<center><span style="color:#800000; padding:10px; font-weight:bold">Письмо не существует</span></center>';
        } else {
            if ($get_mail['toid'] == $_SESSION['iduser']) {
                mysql_query( "UPDATE seo_mails SET `read` = 1 WHERE id = '" . intval($_GET['read']) . "'" );
            }
            $get_user = mysql_fetch_array( mysql_query( "SELECT id, username, avatar FROM tb_users WHERE id = '" . $get_mail['fromid'] . "'" ) );
            $get_user2 = mysql_fetch_array( mysql_query( "SELECT id, username, avatar FROM tb_users WHERE id = '" . $get_mail['toid'] . "'" ) );
            $_SESSION['mailuserid'] = $get_user['id'];
            
            if ($get_mail['fromid'] == 0) {
                $get_user['avatar'] = 'no.png';
                $get_user['username'] = 'Служебное сообщение';
            }
            ?>
            <script type="text/javascript">
            function hideserfaddblock(bname) {
                if (document.getElementById(bname).style.display == 'none') {
                    document.getElementById(bname).style.display = '';
                } else {
                    document.getElementById(bname).style.display = 'none';
                }
                return false;
            }
            
            function sendmsg(userid, subject) {
                $.post('ajax.php?func=reply',{
                    usid : userid,
                    ussubject : subject,
                    text : $('#mailtext').val()
                }, function(data) {
                    if (data == 1) {
                        $('.otab').remove();
                        $('#msg').html('<div style="padding:3px">Идет отправка сообщения...</div><div align="center"><img src="theme/images/mailsendanimation.gif" width="232" height="11" /></div>');
                        setTimeout(function(){
                            window.location.hash = '#:mail';
                        //$('#msg').html('<font color="#8D950B">Сообщение успешно отправлено</font>');
                        }, 1500);
                    } else {
                        $('#msg').html('<font color="#800000">'+data+'</font>');
                    }
                });
                return false;
            }
            </script>
            <div id="msg"></div>
            <table class="otab" width="100%" border="0" cellpadding="0" cellspacing="1">
                <thead>
                <th width="60" style="padding: 5px; background: #ebebeb; text-align: center;"><img src="avp/<?=$get_user['avatar']?>" width="60" height="60" class="avatar" title="<?=$get_user['username']?> -> <?=$get_user2['username']?>" /></th>
                <th style="padding: 5px; background: #ebebeb; text-align: left;"><span style="color: #1c62b9;">Тема</span><br /><?=$get_mail['subject']?></th>
            </thead>
            <tr>
                <td colspan="2" style="padding: 5px;">
                <?
                $get_mail['text'] = preg_replace("~(\r\n|\n|\r)~", '<br />', $get_mail['text']);
                $array = explode(" ", $get_mail['text']);
                for ($i = 0, $array_num = count($array); $i < $array_num; $i++) {
                    $word_split = wordwrap($array[$i], 70, "<br />", true);
                    echo $word_split . ' ';
                }
                ?>
                </td>
            </tr>
            <?php
            if ($get_mail['fromid'] == $_SESSION['iduser'] or $get_mail['fromid'] == 0) {
                ?>
                </table>
                <?php
            } else {
            ?>
            <tr>
                <td colspan="2" style="padding: 5px; background: #ebebeb; text-align: right;"><a href="#" onclick="hideserfaddblock('smsg')" class="big_btn">Ответить</a></td>
            </tr>
            <tr style="display: none;" id="smsg">
                <td colspan="2" style="padding: 5px; background: #EDEDED;" align="center"><textarea id="mailtext"></textarea><br /><a href="#" class="big_btn" onclick="sendmsg(<?=$get_user['id']?>, '<?=$get_mail['subject']?>')">Отправить</a></td>
            </tr>
            </table>
        <?
        }
    }
}
//----------Новое письмо----------
if ($_GET['m'] == 'new') {
    if ($referer == 0) {
        $mref = 'нет';
    } else {
        $mref = 'ID-' . $referer;
    }
    
    $zus = mysql_fetch_array( mysql_query( "SELECT id, username FROM tb_users WHERE id = '" . intval($_GET['id']) . "'" ) );
    if ($zus['id'] == '') {
        $zid = '';
        $zuser = '';
    } else {
        $zid = $zus['id'];
        $zuser = '&nbsp;-&nbsp;' . $zus['username'];
    }
    ?>
    <script type="text/javascript">
    function descchange(elem) {
        if (elem.value.length > 1000) {
            elem.value = elem.value.substr(0,1000);
        }
        $('#countsms').html('Осталось '+(1000-elem.value.length)+' символов');
    }
    $(document).ready(function(){
        $('#userid').keyup(function(){
            $.post('ajax.php?func=checkid',{
                id : $('#userid').val()
            }, function(data){
                    $('.mstatus').html('&nbsp;-&nbsp;<font color="#1c62b9">'+data+'</font>');
            });
            return false;
        });
        
        $('#sendmail').click(function(){
            $.post('ajax.php?func=newmail',{
                id : $('#userid').val(),
                subject : $('#subject').val(),
                text : $('#mailtext').val()
            }, function(data){
                if (data == 1){
                    $('.otab').remove();
                    $('#msg').html('<div style="padding:3px">Идет отправка сообщения...</div><div align="center"><img src="theme/images/mailsendanimation.gif" width="232" height="11" /></div>');
                    setTimeout(function(){
                        window.location.hash = ':mail';
                        //$('#msg').html('<font color="#8D950B">Сообщение успешно отправлено</font>');
                }, 1500);
                }else{
                    $('#msg').html(data);
                }
            });
            return false;
        });
    })
    </script>
    <div id="msg"></div>
    <table class="otab" width="100%" border="0" cellpadding="0" cellspacing="1">
    <tr>
        <th width="100" style="padding: 5px; background: #ebebeb;">Получатель (ID):</th>
        <th style="padding: 5px; background: #ebebeb;" align="left"><input type="text" value="<?=$zid?>" id="userid" class="val" title="Администратор <font color='#FFCD01'>ID-1</font><br />Ваш реферер <font color='#CFE61F'><?=$mref?></font>" /><span class="mstatus"><?=$zuser?></span></th>
    </tr>
    <tr>
    <th style="padding: 5px; background: #ebebeb;">Тема письма:</th>
    <th style="padding: 5px; background: #ebebeb;"><input type="text" id="subject" class="val" style="width: 97%;" /></th>
    </tr>
    <tr><td class="rt" colspan="2" id="countsms" style="text-align: center; padding: 5px;">Осталось 1000 символов</td></tr>
    <tr><th colspan="2" align="center" style="padding: 5px; background: #ebebeb;"><textarea id="mailtext" onkeyup="descchange(this);"></textarea><br /><a href="#" class="big_btn" id="sendmail">Отправить</a></th></tr>
    </table>
    <?php
}
?>
