<?
### Версия ПО (ДМ) 1.0.0.0 ( (c)2018 MISOFT Продукт защищен регистрацией патента и авторских прав! www.misoft.studio )
######################################################################################################################

if ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) {
    define( 'ROOT_DIR', $_SERVER['DOCUMENT_ROOT'] );
    session_start();
    header( 'Content-type: text/html; charset=windows-1251' );
    include_once ROOT_DIR . '/engine/config.php';
    include_once ROOT_DIR . '/engine/function.php';
    include_once ROOT_DIR . '/engine/classes/bbcode.class.php';
} else {
    if ( !defined( 'MISOFT' ) ) { exit(); }
}

if ( !isset( $_SESSION['iduser'] ) ) {
    echo '<div style="margin-left: -10px;" class="alert alert-info alert-dismissible fade in" role="alert">
		<button type="button" class="close" data-dismiss="alert" aria-label="Close">
			<span aria-hidden="true">&times;</span>
		</button>
		<h5 class="alert-heading"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Внимание!</h5>
		<p style="font-size: 14px;">Вы не авторизированы. Доступ к этой странице разрешен только авторизованным пользователям. <br>Пожалуйста, воспользуйтесь формой авторизации.</p>
		<p style="font-size: 14px;" class="m-b-0">Для перехода в форму авторизации нажмите <a class="a_link" href="/login" >login</a>.</p>
	  </div>';
} else {

  #Обновление даты чтения чата
  mysql_query( "UPDATE user SET chat_view = '".time()."' WHERE id = '" .  $_SESSION['iduser'] . "' " );
  $check_read = mysql_query( "SELECT * FROM chat_mess  ORDER BY data ASC LIMIT 1000" );
  
    ?>
	  <script type="text/javascript">
		var tmChatOnline;
		
		$(document).ready(function() {
		  
		  $('#forum_msg').focus();
		  
		  if (navigator.userAgent.indexOf("Firefox") > 0) {
		    $('.wrap_read_chat').animate({scrollTop:10000000000001}, 0);
		  } else {
		    $('.wrap_read_chat').scrollTop(1000000000000);
		  } 
		  
		  tmChatOnline = setInterval(function(){
		        refreshOnline();
		    }, 3000);
		});
		
		function refreshOnline() {
	        $.post('ajax.php?func=refreshonline', {
	        }, function(data) {
		        $('#chat-online-user').html(data);
	        });
        }
        
		var setIid;
		var adm_chat_status_json;
		setIid = setInterval('msgread()', 1000);
		
		function msgread() {
		  $.post('modules/chat/ajax_read.php', {
			
		  }, function(data) {
			if (data.ok == 1) {
			  $('body').append('<audio autoplay="" class="qplay"><source src="theme/sound/msg.mp3" ></audio>');
			  for(var i = 0; i <= data.chat.length - 1; i++) {
				if( data.chat[i].adm == 1 ) { 
				  adm_chat_status_json = '<div onclick="chat.Dell_mess('+data.chat[i].id+'); return false;" class="mess_text_chat_dell2" title="Удалить сообщение"><i class="fa fa-times" aria-hidden="true"></i></div>'; 
				} else { 
				  adm_chat_status_json = ''; 
				}
				$('.wrap_read_chat').append('<div class="wrap_in_chat" id="mess_d'+data.chat[i].id+'"><div class="pred-mail-chat-ava"><img src="/temp/avatar/'+data.chat[i].avatar+'" width="34" height="34" class="img-circle" alt="" /></div><div class="in_mess_text_chat"><div class="wrap_in_chat_name">'+data.chat[i].username+''+adm_chat_status_json+'</div><div class="in_mess_text_chat_padd">'+data.chat[i].text+'<div class="time_mess_msg">'+data.chat[i].data+'</div></div></div></div>');
			  }
			$('.wrap_read_chat').scrollTop(1000000000000);
			}
		  }, "json");
		  $('.qplay').remove();
		}
		
		function descchange(elem) {
		  if (elem.value.length > 1000) {
		    elem.value = elem.value.substr(0,1000);
		  }
		  $('#allmsgchat').html(1000-elem.value.length);
	    }
	    tm = setInterval(function() {
		  if (location.pathname.indexOf('posts') !== -1) {
		    if ($('#forum_msg').val() != '') {
		      descchange(document.getElementById('forum_msg'));
		    }
		  } else {
		    clearInterval(tm);
		  }
		
	    }, 100);
	 
	    $(document).ready(function(){    
		  $('.bb-b-forum').tipTip({defaultPosition:'right'});
		  $('.bb-i-forum').tipTip({defaultPosition:'right'});
		  $('.bb-u-forum').tipTip({defaultPosition:'right'});
		  $('.bb-s-forum').tipTip({defaultPosition:'right'});
		  $('.bb-sub-forum').tipTip({defaultPosition:'right'});
		  $('.bb-sup-forum').tipTip({defaultPosition:'right'});
		  $('.bb_quotet').tipTip({defaultPosition:'right'});
		  $('.bb_youtube').tipTip({defaultPosition:'right'});
		  $('.bb_link').tipTip({defaultPosition:'right'});
		  
		  $('.color-red').tipTip({defaultPosition:'right'});
		  $('.color-blue').tipTip({defaultPosition:'right'});
		  $('.mess_text_chat_dell').tipTip({defaultPosition:'right'});
		  $('.mess_text_chat_dell2').tipTip({defaultPosition:'right'});
	    });
		
		function delbanserg(e) {
		  $.post('ajax.php?func=chatdel', {
			id: e
		  }, function(data) {
		 	if (data == 1) {
			  location.href = '/chat';
			} else {
			  $('body').Qnotify({text:data, sound:'error'});	
			}
		  });
		return false;
        }
      </script>
	  
	  <div class="content_bar content_bar_fix_chain">
	    <article class="postBox">
		  <div class="wrap_read_chat_top_text"><i class="fa fa-commenting" aria-hidden="true"></i> ОНЛАЙН ЧАТ</div>
		  <div class="wrap_read_chat_top"></div>
		  <div class="wrap_read_chat">
		    <?
			  if ( !mysql_num_rows( $check_read ) > 0 ) {
				echo 'Нет ни одного сообщения! Вы можете быть первым, напишите что нибудь!'; 
			  }
			  
			  while ( $get_mess_row = mysql_fetch_array( $check_read ) ) {
				$info_from_id = mysql_fetch_array( mysql_query( "SELECT username, avatar, id FROM user WHERE id = '" . $get_mess_row['from_id'] . "' LIMIT 1" ) );
				
				#формируем дату сообщения
				if ( date( 'd.m.Y', $get_mess_row['data'] ) == date( 'd.m.Y', time() ) ) {
				  $mess_time = 'сегодня в ' . date( 'H:i', $get_mess_row['data'] );
				} else
				if ( date( 'd.m.Y', $get_mess_row['data'] ) == date( 'd.m.Y', time() - 86400 ) ) {
				  $mess_time = 'вчера в ' . date( 'H:i', $get_mess_row['data'] );
				} else {
				  $mess_time = ( int ) date( 'd', $get_mess_row['data'] ) . ' ' . $month[( int ) date( 'm', $get_mess_row['data'] ) - 1] . ' ' . date( 'Y', $get_mess_row['data'] )  . ' в ' . date( 'H:i', $get_mess_row['data'] );
				}
				
				if( $config_user['account'] == 5 OR $config_user['account'] == 2 ) { 
				  $adm_chat_status_json1 = '<div onclick="chat.Dell_mess('.$get_mess_row['id'].'); return false;" class="mess_text_chat_dell2" title="Удалить сообщение"><i class="fa fa-times" aria-hidden="true"></i></div>';
				  $adm_chat_status_json2 = '<div onclick="chat.Dell_mess('.$get_mess_row['id'].'); return false;" class="mess_text_chat_dell" title="Удалить сообщение"><i class="fa fa-times" aria-hidden="true"></i></div>';
				} else {
				  $adm_chat_status_json1 = '';	
				  $adm_chat_status_json2 = '<div onclick="chat.Dell_mess('.$get_mess_row['id'].'); return false;" class="mess_text_chat_dell" title="Удалить сообщение"><i class="fa fa-times" aria-hidden="true"></i></div>';	
				}
				
			    if($info_from_id['id'] != $_SESSION['iduser']) {
				  ?>
					<div class="wrap_in_chat" id="mess_d<?=$get_mess_row['id']?>">
					  <div class="in_mess_text_chat">
						<div class="wrap_in_chat_name">
						  <?=$info_from_id['username']?>
						  <?=$adm_chat_status_json1?>
						</div>
						<div class="in_mess_text_chat_padd">
						  <?=$get_mess_row['text']?>
						  <div class="time_mess_msg"><?=$mess_time?></div>
						</div>
					  </div>
					  <div class="pred-mail-chat-ava">
						<img src="/temp/avatar/<?=$info_from_id['avatar']?>" width="34" height="34" class="img-circle" alt="" />
					  </div>
					</div>
				  <?
			    } else {
				  ?>
					<div class="wrap_in_chat" id="mess_d<?=$get_mess_row['id']?>">
					  <div class="in_mess_text_chat_user">
					    <?=$adm_chat_status_json2?>
						<?=$get_mess_row['text']?>
						<div class="time_mess_msg"><?=$mess_time?></div>
					  </div>
					  
					</div>
				  <?	
			    }
			  }
			?>
		  </div>
		  
		  <div class="chat-online-user">
		    <div class="chat-online-title">Кто в чате</div>
			<div class="chat-online-scroll">
			<div id="chat-online-user" >
			 
			<?
			  #Онлайн 
			  $checkOnlineChatUser = mysql_query( " SELECT id FROM chat_online WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
			  if ( mysql_num_rows( $checkOnlineChatUser ) < 1 ) {
				$timeOnlyChat = (time())+60;
				mysql_query( "INSERT INTO chat_online SET iduser = '" . $_SESSION['iduser'] . "', time = '" . $timeOnlyChat . "'" );
			  }
			 
			  $userOnlineChat = mysql_query( "SELECT iduser FROM chat_online" );
			  if ( mysql_num_rows( $userOnlineChat ) > 0 ) {
				while ( $userOnlineChatRow = mysql_fetch_array( $userOnlineChat ) ) {
					$userNameChat = mysql_fetch_array( mysql_query( "SELECT id, username, avatar, account FROM user WHERE id = '" . $userOnlineChatRow['iduser'] . "' LIMIT 1" ) );
					
					switch( $userNameChat['account'] ) {
					  case 0:
						$chatOnlineClass = 'chat_online_user';
						$nameStatus = 'Пользователь';
					  break;
					  case 2:
						$chatOnlineClass = 'chat_online_moder';
						$nameStatus = 'Модератор';
					  break;
					  case 5:
						$chatOnlineClass = 'chat_online_admin';
						$nameStatus = 'Администратор';
					  break;
					}
					
					$userBan = mysql_query( "SELECT iduser FROM chat_ban WHERE iduser = '" . $userNameChat['id'] . "' LIMIT 10" );
					if ( mysql_num_rows( $userBan ) > 0 ) {
					  $chatOnlineClass = 'chat_online_banfon';
					  if ( $config_user['account'] == 5 ) {
						$chat_ban = '<i title="Разбанить в чате" onclick="delbanserg(' . $userNameChat['id'] . '); return false;" class="fa fa-ban color-red" aria-hidden="true"></i>';
					  } else {
						$chat_ban = '';
					  }
					} else {
					  $chatOnlineClass = '';
					  if ( $config_user['account'] == 5 ) {
						$chat_ban = '<i title="Забанить в чате" onclick="chat.Ban(' . $userNameChat['id'] . '); return false;" class="fa fa-ban color-red" aria-hidden="true"></i>';
					  } else {
						$chat_ban = '';
					  }
					}
					
					?>
					<div class="chat-online-block <?=$chatOnlineClass?>">
					  <a target="_blank" href="/id<?=$userNameChat['id']?>">
					    <img src="/temp/avatar/<?=$userNameChat['avatar']?>" width="24" height="24" class="img-circle" alt="" />
					  </a>
					  <div class="ch_online_name" onclick="toChat(this.innerHTML);"><?=$userNameChat['username']?></div>
					  <div class="ch_online_ban"><?=$chat_ban?></div>
					</div>
				  <?
				}
			  }
			
			  $checkBan_form = mysql_query( "SELECT * FROM chat_ban WHERE iduser = '" . $_SESSION['iduser'] . "' LIMIT 1" );
			  
			?>
			
		    </div>
		    </div>
			<div class="online-scroll-shadow"></div>
		  </div>
		  
		  <div class="chat-group-post">
		    <? if ( mysql_num_rows( $checkBan_form ) < 1 ) { ?>
			  <div class="bbcode-panel-chat-post ">
			    <span onclick="qbb('[b]','[/b]','forum_msg')" id="bb_b" title="Полужирный текст" class="bb-b-forum"><i class="fa fa-bold" aria-hidden="true"></i></span>
			    <span onclick="qbb('[i]','[/i]','forum_msg')" id="bb_i" title="Наклонный текст" class="bb-i-forum"><i class="fa fa-italic" aria-hidden="true"></i></span>
			    <span onclick="qbb('[u]','[/u]','forum_msg')" id="bb_u" title="Подчеркнутый текст" class="bb-u-forum"><i class="fa fa-underline" aria-hidden="true"></i></span>
			    <span onclick="qbb('[s]','[/s]','forum_msg')" id="bb_s" title="Зачеркнутый текст" class="bb-s-forum"><i class="fa fa-strikethrough" aria-hidden="true"></i></span>
			    <span onclick="qbb('[sub]','[/sub]','forum_msg')" id="bb_sub" title="Нижний индекс" class="bb-sub-forum"><i class="fa fa-subscript" aria-hidden="true"></i></span>
			    <span onclick="qbb('[sup]','[/sup]','forum_msg')" id="bb_sup" title="Верхний индекс" class="bb-sup-forum"><i class="fa fa-superscript" aria-hidden="true"></i></span>
			    <span onclick="qbb('[quotet]','[/quotet]','forum_msg')" class="bb_quotet" id="quotet" title="Цитировать текст"><i class="fa fa-quote-left" aria-hidden="true"></i></span>
			    <span onclick="forum.ShowSmiles();" class="bb_quotet" id="" title="Выбрать смайлы"><i class="fa fa-smile-o" aria-hidden="true"></i><div class="wrap_smiles_forum_post" ></div></span>
			    <span onclick="qbb('[video]','[/video]','forum_msg')" class="bb_youtube" id="video" title="Вставить видео (поддерживаются видео с таких сервисов как – youtube, vk, facebook, rutube, mail.ru и другие.  Просто вставьте ссылку на видео, в теги video)."><i class="fa fa-youtube-play" aria-hidden="true"></i></span>
			    <span onclick="qbb('[images]','[/images]','forum_msg')" class="bb_youtube" id="images_forum_post" title="Вставить изображение (поддерживаются форматы jpg/png/bmp/gif)."><i class="fa fa-picture-o" aria-hidden="true"></i></span>
			    <div id="allmsgchat" class="allmsgchat" >1000</div>
		      </div>
		      <textarea class="form-control forum-textarea-style" style="height: 84px; width: 557px;" id="forum_msg" onkeyup="descchange(this);"></textarea><br>
		      <a href="#" onclick="chat.Send($('#forum_msg').val()); return false;" class="btn_box_big" id="btn_new_forum_msg">Отправить сообщение</a>
		      <? if( $config_user['account'] == 5 OR $config_user['account'] == 2 ) { ?>
			    <a href="#" onclick="chat.Ban_list(); return false;" class="btn_box_big_red" id="btn_new_forum_msg" style="height: 21px;">Список заблокированных</a>
			  <? } ?>
		      <a href="#" onclick="chat.Rules(); return false;" class="btn_box_big_yloveu" id="btn_new_forum_msg" style="height: 21px;">Правила</a>
		    <? } else { 
			  $checkBan_form_row = mysql_fetch_array( $checkBan_form );
			  ?>
			  <div class="alert alert-danger" role="alert" style="width: 558px; margin: -5px 0 0 -4px;">
			    <i class="fa fa-ban" aria-hidden="true"></i> Внимание! Вы заблокированы в чате до: <?=date( 'd.m.Y H:i', $checkBan_form_row['timeban'] );?><br/>
				<div class="chat_ban_blockquote">
				  <?=$checkBan_form_row['coment']?>
				</div>
				Пожалуйста ознакомьтесь с <a href="#" class="a_box" onclick="chat.Rules(); return false;">правилами</a> чата!
			  </div>
			<? } ?>
		  </div>
	      <br/>
	    </article>
	  </div>   
	  
    <?
}
?>




