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

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

include './system/h.php';  

//$titans_in_chat = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `online` > '".(time() - 300)."' and `self`='".(/chat.php)."'"));
//$titans_in_chat = mysql_num_rows(mysql_query(SELECT * FROM `users` WHERE `online` > '".(time() - 300)."' and `self`='".(/chat.php)."'));
$self_chat='/chat.php';
$titans_in_chat = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `online` > '".(time() - 300)."' and `self`='$self_chat'"));
//echo '<div class=\'title\'><a href="?vievAll" style="text-decoration:none;display:block;">В чате  сейчас '.$titans_in_chat.' <img src="/images/icon/race/0.png"> <img src="/images/icon/race/1.png"> титанов</a></div>';
if(isset($_GET['vievAll'])){
$tk=mysql_query("SELECT * FROM `users` WHERE `online` > '".(time() - 300)."' and `self`='$self_chat'");
?>
<div class='title'>Титаны в чате</div>
<div class='content'>
<?
while ($titanc=mysql_fetch_array($tk))
{
if($titanc['access']=='0'){
 ?>
<img src='/images/icon/race/<?=$titanc['r'].($titanc['online'] > (time() - 300) ? '':'-off')?>.png' alt='*'/> <a href='/user/<?=$titanc['id']?>/'><?=$titanc['login']?></a> <img src='/images/icon/level.png' alt='*'/> <?=$titanc['level']?> ур<br/>
<?
}elseif($titanc['access']=='1'){

 ?>
<img src='/images/icon/race/<?=$titanc['r'].($titanc['online'] > (time() - 300) ? '':'-off')?>.png' alt='*'/> <a href='/user/<?=$titanc['id']?>/'><font color="#f09060"><?=$titanc['login']?></font></a> <img src='/images/icon/level.png' alt='*'/> <?=$titanc['level']?> ур<br/>
<?
}elseif($titanc['access']=='2'){

 ?>
<img src='/images/icon/race/<?=$titanc['r'].($titanc['online'] > (time() - 300) ? '':'-off')?>.png' alt='*'/> <a href='/user/<?=$titanc['id']?>/'><font color="#90c0c0"><?=$titanc['login']?></font></a> <img src='/images/icon/level.png' alt='*'/> <?=$titanc['level']?> ур<br/>
<?

}
}
?>
</div>
<div class='list'>
<li><a href='/chat/'><img src='/images/icon/chat.png'> Вернуться в чат</a></li>
</div>
<?
include './system/f.php';
exit;  

}

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

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

}
else
{

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


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

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

  }
  else
  {

$text = _string($_POST['text']);
  $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'] < 0) $errors[] = 'Ошибка';

    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);
           $arrReplace = array('.ru',
                                 '.net',
                                 '.com',
                                  '.рф',
                                  '.tk',
                                  '.su',
                                  '.us',
                                '.mobi',
                                  '.ua',
                                 
                                 '.ru',
                                
                                'http');

$size = count($arrReplace);
  while($size--)
{
if(substr_count($text, $arrReplace[$size]))
{
mysql_query("INSERT INTO `mail` SET `from`='2',`to`='1',`text`=' Пользователь ".$user['login']." | ID: ".$user['id']." нарушает правила игры! Сообщение: ".$text."',`time`='".time()."'");
mysql_query("INSERT INTO `ban` SET `user`='".$user['id']."',`time`='36000',`text`='Реклама сторонних ресурсов!',`who`='Система', `ip`='".$user['ip']."'");
break;
}
}
$text = str_replace($arrReplace, '*', $text);
$typemsg=_string($_POST['typemsg']);
      if($user['access']=='2' && $typemsg=='sys'){
  
  mysql_query('INSERT INTO `chat` (`clan`,
                                         `user`,
                                           `to`,
                                         `text`,
                                         `time`) VALUES ("'.($_GET['clan'] == true ? $clan['id']:0).'",
                                                         "0", 
                                                          "'.$_to['id'].'",
                                                               "'.$text.'",
                                                              "'.time().'")');


}else{
        mysql_query('INSERT INTO `chat` (`clan`,
                                         `user`,
                                           `to`,
                                         `text`,
                                         `time`) VALUES ("'.($_GET['clan'] == true ? $clan['id']:0).'",
                                                         "'.$user['id'].'", 
                                                          "'.$_to['id'].'",
                                                               "'.$text.'",
                                                              "'.time().'")');
}
      
      header('location: /chat/'.($_GET['clan'] == true ? 'clan/':''));
  
    }
  
  }
?>
<script 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>


  
  
  </div>
            <script type='text/javascript'>
        /*<![CDATA[*/
        function sml(id, html) {
            var e = document.getElementById(id);
            if (e != null) {
                e.value += ' ' + html + ' ';
                e.focus();
            }
        }
        /*]]>*/
        </script><div class='block_zero'><form method='post'><div><input type='hidden' name='s' value='88721373'/><table style='width:100%;padding:0px'><tr><td style='width:100%'>
  
  <input id='sml' type='text' class='text large' name='text' maxlength='250' value=''>
  <input type='submit' class='cosmos' name='send_message' value=''/></td>
  <td><input class='smilebtn' type='submit' name='show_smiles' value=''></td></tr></table>
  <div class='float-left'><span class='btn'><span class='end'>
  <input class='label' type='submit' name='send_message' value='Отправить'>Отправить</span></span></div>
  <div style='margin-top:2px;'></div>
  <a style='padding:0px 0px 0px 5px' class='grey ' href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>'>Обновить</a><div style='clear:both;'></div>
  <div class='dot-line'></div>
  
  
  
  
  
  
  
<?
if(isset($_GET['showSmiles'])){
?>

  <li>
<div class="bl cntr mr0a" style="width:60%">

 </div>
</li>
<?
}

}

?>

  <li>

<?

    $max = 20;
  $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)) {
if($row['user']=='0'){

?>

<img src='/images/icon/race/bot.png'><font color='red'> Система: </font><?
 if($row['to']) {
      $__to = mysql_query('SELECT * FROM `users` WHERE `id` = "'.$row['to'].'"');
      $__to = mysql_fetch_array($__to);
if($__to['id'] != $user['id']) {
?>
<span  class='dgreen'>
<?
    }
?>
<?=$__to['login']?>, 
<?
if($__to['id'] != $user['id']) {
?>
</span>
<?
    }
    }
?>



<span class='dred'><?=smiles($row['text'])?> </span> <?
  if($user['access'] > 0) {


?>

<a href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>?msg=<?=$row['id']?>'>[x]</a>

<?

  }
echo '<br/>';

}else{
  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);

?>

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

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

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

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

  }

?>:<?

    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='yellow'> </font> <font color='#90c0c0'> 

<?

    }

?>


<?=smiles($row['text'])?><font size='1'><font color='#909090'><b> [<?=_times(time() - $row['time'])?>]</b></font></font>

<?

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

?>

</font>

<?

    }

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


?>

<a href='/chat/<?=($_GET['clan'] == true ? 'clan/':'')?>?msg=<?=$row['id']?>'>[x]</a>

<?

  }
  
?>

<br/>

<?

  }
}
  }
  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);

?>

<div class='dot-line'></div><div class='block_zero medium'>
<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=\'#30c030\'>(+)</font>':'')?></small>
</div>
<div class='dot-line'></div>
<?

  }

?>

<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='/moderators/'><img src='/images/icon/arrow.png' alt='*'/> Модераторы</a></li>
<li class='no_b'><a href='/smiles.php'><img src='/images/icon/arrow.png' alt='*'/> Смайлики</a></li>
</div>


<?

}

include './system/f.php';

?>