<?
    
include './system/common.php';
    
include './system/functions.php';
   
include './system/antimat.php';     
         
include './system/user.php';
    
if(!$user) { header('location: /'); exit; }

$title = ($_GET['clan'] == true) ? 'Клановый чат':'Общий чат';

include './system/h.php';  

echo '<div class=\'title\'>'.$title.'</div>
<div class=\'line\'></div>';

if($user['save'] == 0) {

  echo '<div class=\'content\'><font color=\'#909090\'>Для общения в чате вам нужно сохранить своего персонажа</font></div>';

}
else
{

  echo '<div class=\'menu\'>';

  
 

  if($user['level'] < 15) {

    echo '<li><font color=\'#909090\'>Писать в чат можно с <img src=\'/images/icon/level.png\' alt=\'\'/> 15 уровня</font></li>';

  }
  else
  {


$text = _string($_POST['msg']);
  $to = _string(_num($_GET['to']));

  if($to) {

      $_to = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$to.'"');
      $_to = mysql_fetch_array($_to);
  
  if(!$_to OR $_to['id'] == $user['id']) {
  
    header('location: /chat/'.($_GET['clan'] == true ? 'clan/':''));
    
  exit;
  
  }
  
  }

  if($text && $user['level'] > 2) {
  
    $antiflood = mysql_fetch_array(mysql_query('SELECT * FROM `chat` WHERE `clan` = \''.($_GET['clan'] == true ? $clan['id']:0).'\' AND `user` = \''.$user['id'].'\' ORDER BY `time` DESC LIMIT 1'));
  
    if(time() - $antiflood['time'] < 5) $errors[] = 'Ошибка, писать можно 1 раз в 5 секунд';

    if($errors) {
    
      echo '<div class=\'content\' align=\'center\'>';
      
      foreach($errors as $error) {
        
        echo $error.'<br/>';
        
      }
    
      echo '</div>
      <div class=\'line\'></div>';
    
    }
    else
    {

      if($_to) {
      
        $text = str_replace($_to['login'].', ', '', $text);
      
      }
      
        $text = eregi_replace( "[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "Игрок кинул кубик на ", $text);
        
        $text = str_replace(array('ru',
                                 'aux.su',
                                 'com',
                                  'рф',
                                  'tk',
                                  'su',
                                  'mpesh',
                                'mobi',
                                  'bt-mobi',
                                  'rand',
                                 'www',
                                'http'), 'Упс,ошибочка вышла', $text);

      
        mysql_query('INSERT INTO `chat` (`clan`,
                                         `user`,
                                           `to`,
                                         `text`,
                                         `time`) VALUES ("'.($_GET['clan'] == true ? $clan['id']:0).'",
                                                         "'.$user['id'].'", 
                                                          "'.$_to['id'].'",
                                                               "'.$text.'",
                                                              "'.time().'")');
        mysql_query("UPDATE `users` SET `orator`=`orator`+'1' WHERE `id`='".$user['id']."'");
      
      header('location: /chat/'.($_GET['clan'] == true ? 'clan/':''));
  
    }
  
  }
?>

<div class="content" align = "center">
  <form name="message" action='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>?to=<?=$to?>' method='post'>
 <script language="JavaScript" type="text/javascript">

                function tag(text1, text2) {

                if ((document.selection)) {

                document.message.msg.focus();

                document.message.document.selection.createRange().text = text1+document.message.document.selection.createRange().text+text2;

                } else if(document.forms['message'].elements['msg'].selectionStart!=undefined) {

                var element = document.forms['message'].elements['msg'];

                var str = element.value;

                var start = element.selectionStart;

                var length = element.selectionEnd - element.selectionStart;

                element.value = str.substr(0, start) + text1 + str.substr(start, length) + text2 + str.substr(start + length);

				document.forms['message'].elements['msg'].focus();

                } else document.message.msg.value += text1+text2;

				document.forms['message'].elements['msg'].focus();}</script>    
				
<a href="javascript:tag(':))', '')"><img src="/images/smiles/mini_lol.gif" alt="*" /></a>
<a href="javascript:tag(':-/', '')"><img src="/images/smiles/mini_hm.gif" alt="*" /></a>
<a href="javascript:tag('8-)', '')"><img src="/images/smiles/mini_krut.gif" alt="*" /></a>
<a href="javascript:tag(':ob ', '')"><img src="/images/smiles/mini_good.gif" alt="*" /></a>
<a href="javascript:tag(':bravo', '')"><img src="/images/smiles/mini_bravo.gif" alt="*" /></a>
<a href="javascript:tag(':]', '')"><img src="/images/smiles/mini_dovolen.gif" alt="*" /></a>
<a href="javascript:tag(':)', '')"><img src="/images/smiles/mini_ulibka.gif" alt="*" /></a>
<a href="javascript:tag(':-Р', '')"><img src="/images/smiles/mini_yazyk.gif" alt="*" /></a><br>
<a href="javascript:tag('O:-)', '')"><img src="/images/smiles/mini_angel.gif" alt="*" /></a>
<a href="javascript:tag(']:-)', '')"><img src="/images/smiles/mini_diablo.gif" alt="*" /></a>
<a href="javascript:tag(':-D', '')"><img src="/images/smiles/mini_spin.gif" alt="*" /></a>
<a href="javascript:tag(':'(', '')"><img src="/images/smiles/mini_cry.gif" alt="*" /></a>
<a href="javascript:tag('6-(', '')"><img src="/images/smiles/mini_fingal.gif" alt="*" /></a>
<a href="javascript:tag(':heart', '')"><img src="/images/smiles/mini_heart.gif" alt="*" /></a>
<a href="javascript:tag(':-о', '')"><img src="/images/smiles/mini_chok.gif" alt="*" /></a>
<a href="javascript:tag(';)', '')"><img src="/images/smiles/mini_podmigivanie.gif" alt="*" /></a>
<a href="javascript:tag(':бе', '')"><img src="/images/smiles/ao.gif" alt="*" /></a>
<a href="javascript:tag(':bugaga)', '')"><img src="/images/smiles/bugaga.gif" alt="*" /></a>
</center>

<br/>

 Введите сообщени:<br/>
  <textarea name="msg" style="width: 90%;"><?=($to ? $_to['login'].', ':'')?></textarea><br/>
	
    <input type='submit' value='Отправить'/> <a href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>'> <a href="?">Обновить</a></form></a>
</div>


<?

}

?>

 

<?

    $max = 15;
  $count = mysql_result(mysql_query('SELECT COUNT(*) FROM `chat` WHERE `clan` = "'.($_GET['clan'] == true ? $clan['id']:0).'"'),0);
  $pages = ceil($count/$max);
   $page = _string(_num($_GET['page']));

    if($page > $pages) {
    
   $page = $pages;
    
    }
  
    if($page < 1) {
    
   $page = 1;
    
    }
    
  $start = $page * $max - $max;

if($count > 0) {



$msg = _string(_num($_GET['msg']));

       if($msg) {

    $i_msg = mysql_query('SELECT * FROM `chat` WHERE `id` = "'.$msg.'"');
    $i_msg = mysql_fetch_array($i_msg);

    if(!$i_msg) {
    
      header('location: /chat/'.($_GET['clan'] == true ? 'clan/':'').'?page='.$page);
      exit;
    
    }

    if($_GET['clan'] == true && $clan_memb['rank'] == 4 OR $user['access'] > 0) {
        
      mysql_query('DELETE FROM `chat` WHERE `clan` = "'.($_GET['clan'] == true ? $clan['id']:0).'" AND`id` = "'.$i_msg['id'].'"');

    }

    header('location: /chat/'.($_GET['clan'] == true ? 'clan/':'').'?page='.$page);

  }



$q = mysql_query('SELECT * FROM `chat` WHERE `clan` = "'.($_GET['clan'] == true ? $clan['id']:0).'" ORDER BY `id` DESC LIMIT '.$start.', '.$max.'');
  while($row = mysql_fetch_array($q)) {
echo '<div class="content">';
  if($row['to'] == $user['id'] && $row['read'] == 0) {
  
    mysql_query('UPDATE `chat` SET `read` = "1" WHERE `id` = "'.$row['id'].'"');
  
  }

  $sender = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['user'].'"');
  $sender = mysql_fetch_array($sender);
?>

<?

    if($sender['access'] == 2) {

?>
<img src="/adm.png">

<?

    }

?>
<?

    if($sender['access'] == 1) {

?>

<img width='16' height='16' src='/mod.png' alt='*'/>

<?

    }

?>
<img src='/images/icon/race/<?=$sender['r'].($sender['online'] > (time() - 300) ? '':'-off')?>.png' alt='*'/>

<a href='/user/<?=$sender['id']?>/'><b><?=$sender['login']?></b></a><?

  if($sender['id'] != $user['id']) {

?> <a href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>?to=<?=$sender['id']?>'>(&#187;)</a><?

  }

?> <font color="#8B8B83"><?=date('H:i:s', $row['time'])?></font><br/><?

    if($row['to']) {

      $__to = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['to'].'"');
      $__to = mysql_fetch_array($__to);

if($__to['id'] == $user['id']) {

?>

<font color='#90c090'>

<?

    }

?>

<?=$__to['login']?>,

<?

if($__to['id'] == $user['id']) {

?>

</font>

<?

    }
    
    }

    if($sender['access'] == 1) {

?>

<font color='#f09060'>

<?

    }

?>

<?

    if($sender['access'] == 2) {

?>

<font color='CornflowerBlue'>

<?

    }

?>

<?

    if($sender['access'] == 3) {

?>

<font color='green'>

<?

    }

?>

<?=smiles($row['text'])?> 

<?

    if($sender['access'] > 0) {

?>

</font>

<?

    }

  if($user['access'] > 0) {


?>

<a href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>?msg=<?=$row['id']?>'>[Удалить SMS]</a>

<?

  }
  
?>


<?
echo '<hr/></div>';

  }

  }
  else
  {
  
?>

<font color='#909090'>Сообщений нет</font>

<?
  
  }

?>

</li>

<?

  if($clan) {
  
     $_chat = mysql_query('SELECT COUNT(*) FROM `chat` WHERE `clan` = "0" AND `to` = "'.$user['id'].'" AND `read` = "0"');
     $_chat = mysql_result($_chat,0);

$_clan_chat = mysql_query('SELECT COUNT(*) FROM `chat` WHERE `clan` = "'.$clan['id'].'" AND `to` = "'.$user['id'].'" AND `read` = "0"');
$_clan_chat = mysql_result($_clan_chat,0);

?>

  <li><small><img src='/images/icon/chat.png' alt='*'/> <?=($_GET['clan'] == true ? '<a href=\'/chat/\'>Общий</a>':'<font color=\'#606060\'>Общий</font>')?> <?=($_chat > 0 ? '<font color=\'#30c030\'>(+)</font>':'')?> | <?=($_GET['clan'] == true ? '<font color=\'#606060\'>Клан</font>':'<a href=\'/chat/clan/\'>Клан</a>')?> <?=($_clan_chat > 0 ? '<font color=\'#dgreen\'>(+)</font>':'')?> | <a href=/torg_chat.php>Торговый</a>

<?

  }

?>

<li>

<?=pages('/chat/'.($_GET['clan'] == true ? 'clan/':'').'?');?>


</li>

<?

  if($_GET['read_all'] == true) {

    mysql_query('UPDATE `chat` SET `read` = "1" WHERE '.($_GET['clan'] == true ? '`clan` = "'.$clan['id'].'" AND':'').' `to` = "'.$user['id'].'"');
    
    header('location: /chat/'.($_GET['clan'] == true ? 'clan/':''));
  
  }

?>

<li><a href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>?read_all=true'><img src='/images/icon/arrow.png' alt='*'/> Отметить все сообщения как прочитанные</a></li>
<li class='no_b'><a href='/admins.php/'><img src='/images/icon/league.png' alt='*'/> Администрация</a></li>
<li class='no_b'><a href='/moderators/'><img src='/images/icon/league.png' alt='*'/> Модераторы</a></li>
</div>

<?
echo '</div>';
$self = 'Общий Чат';
$inFight = mysql_num_rows(mysql_query("SELECT `id`,`self` FROM `users` 
                                    WHERE `self`='".($self)."' and 
                                    `online`>'".(time()-300)."'"));

?>
<div class ='line'/></div>
<div class ='content'/>
<center/>
В чате <?=$inFight;?> титанов
</center>
</div>
<?


}

include './system/f.php';

?>