<?php
$tab_style = 'block';
$tab_style_height = '';
if (isset($_SESSION['open_chat'])) {
  if($_SESSION['open_chat'] == 0) {
    $tab_style = 'none';
    $tab_style_height = 'min-height:auto;';
  }
}
?>
<?php if (Wo_IsMobile() == false) { ?>
<div class="chat-all-container">
	<div class="chat-tab"></div>
	<div class="chat-container full" style="<?php echo $tab_style_height; ?>">
		<div class="online-toggle pointer" onclick="Wo_OpenChatUsersTab();">
			<?php echo $wo['lang']['online_chat'];?>
		</div>
		<div class="chat-status">
			<span class="pointer" style="margin-right: 5px;" onclick="Wo_CreateGChat(event)">
				<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"><path fill="currentColor" d="M13,13C11,13 7,14 7,16V18H19V16C19,14 15,13 13,13M19.62,13.16C20.45,13.88 21,14.82 21,16V18H24V16C24,14.46 21.63,13.5 19.62,13.16M13,11A3,3 0 0,0 16,8A3,3 0 0,0 13,5A3,3 0 0,0 10,8A3,3 0 0,0 13,11M18,11A3,3 0 0,0 21,8A3,3 0 0,0 18,5C17.68,5 17.37,5.05 17.08,5.14C17.65,5.95 18,6.94 18,8C18,9.06 17.65,10.04 17.08,10.85C17.37,10.95 17.68,11 18,11M8,10H5V7H3V10H0V12H3V15H5V12H8V10Z" /></svg>
			</span>
			<div class="dropdown" style="display: inline;">
				<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><path fill="currentColor" d="M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z" /></svg>
				<ul class="dropdown-menu dropdown-menu-right" role="menu" style="min-width: 80px; font-size: 12px;">
					<li><a href="#" onclick="Wo_UpdateStatus('online',event);"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg> <?php echo $wo['lang']['online'];?></a></li>
					<li><a href="#" onclick="Wo_UpdateStatus('offline',event);"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye-off"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg> <?php echo $wo['lang']['offline'];?></a></li>
				</ul>
			</div>
		</div>
		
		<div class="search">
			<input type="text" class="form-control search-users-chat" placeholder="<?php echo $wo['lang']['search_for_users'];?>" onkeyup="Wo_ChatSearchUsers(this.value);">
		</div>
		
		<div class="online-content-toggler" style="display:<?php echo $tab_style; ?>">
			<div class="chat-opacity <?php echo ($wo['user']['status'] == 1) ? 'active': '';?>">
				<div class="text-center">
					<h5 class="empty_state">
						<span>
							<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye-off"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line></svg>
							<?php echo $wo['lang']['you_are_currently_offline'];?>
						</span>
					</h5>
				</div>
			</div>
			
			<ul class="nav nav-tabs wo_chat_tabs">
				<li class="active">
					<a data-toggle="tab" data-target="#users-chat" href="#" data-toggle="tooltip" data-placement="bottom" title="<?php echo $wo['lang']['users'];?>">
						<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M12,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z" /></svg>
						<span class="count-online-users"><?php echo Wo_CountOnlineUsers();?></span>
					</a>
				</li>
						
				<li>
					<a data-toggle="tab" data-target="#groups-chat" href="#" data-toggle="tooltip" data-placement="bottom" title="<?php echo $wo['lang']['groups'];?>">
						<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M12,6A3,3 0 0,0 9,9A3,3 0 0,0 12,12A3,3 0 0,0 15,9A3,3 0 0,0 12,6M6,8.17A2.5,2.5 0 0,0 3.5,10.67A2.5,2.5 0 0,0 6,13.17C6.88,13.17 7.65,12.71 8.09,12.03C7.42,11.18 7,10.15 7,9C7,8.8 7,8.6 7.04,8.4C6.72,8.25 6.37,8.17 6,8.17M18,8.17C17.63,8.17 17.28,8.25 16.96,8.4C17,8.6 17,8.8 17,9C17,10.15 16.58,11.18 15.91,12.03C16.35,12.71 17.12,13.17 18,13.17A2.5,2.5 0 0,0 20.5,10.67A2.5,2.5 0 0,0 18,8.17M12,14C10,14 6,15 6,17V19H18V17C18,15 14,14 12,14M4.67,14.97C3,15.26 1,16.04 1,17.33V19H4V17C4,16.22 4.29,15.53 4.67,14.97M19.33,14.97C19.71,15.53 20,16.22 20,17V19H23V17.33C23,16.04 21,15.26 19.33,14.97Z" /></svg>
					</a>
				</li>				
			</ul>
			<div class="tab-content">
				<div id="users-chat" class="tab-pane fade in active">
					<div class="online-users">
						<?php 
							$OnlineUsers = Wo_GetChatUsers('online');
							if (count($OnlineUsers) == 0) {
								echo '';
							} else {  
								foreach ($OnlineUsers as $wo['chatList']) {
									echo Wo_LoadPage('chat/online-user');
								}
							} 
						?>
					</div>
					<div class="offline-users">
						<?php 
							$Offlineusers = Wo_GetChatUsers('offline');
							if (count($Offlineusers) == 0) {
								echo '';
							} else {
								foreach ($Offlineusers as $wo['chatList']) {
									echo Wo_LoadPage('chat/offline-user');
								}
							}
						?>
					</div>
					<div class="clear"></div>
				</div>
				<div id="groups-chat" class="tab-pane fade groups chat_groups">
					<?php $chat_groups = Wo_GetChatGroups(); ?>
					<?php if (count($chat_groups)): ?>
						<?php 
							if (count($chat_groups) == 0) {
								echo '<span class="no-online-users center-text">' . $wo['lang']['no_groups_found'] . '</span>';
							} 
							else {
								foreach ($chat_groups as $wo['group']) {
									echo Wo_LoadPage('chat/group-list');
                
								}
							}
						?>
					<?php endif; ?>
				</div>
			</div>
		</div>
		
		<!--Activities -->
		<div class="chat_acts">
            <?php $activities = Wo_GetActivities();?>
            <ul class="list-group activity-container sun_side_activities">
                <li class="text-muted sidebar-title-back" contenteditable="false">
					<?php echo $wo['lang']['whats_happening']; ?>
					<?php if (count($activities) > 0) { ?>
						<p class="<?php echo Wo_RightToLeft('pull-right');?> mb0">
							<span onclick="Wo_GetMoreActivities();" title="<?php echo $wo['lang']['load_more_activities'];?>" class="<?php echo Wo_RightToLeft('pull-right');?> refresh"><i class="fa fa-repeat progress-icon" data-icon="repeat"></i></span>
						</p>
					<?php } ?>
                </li>
                <li class="activities-wrapper" id="activities-wrapper">
                    <?php
                        if (count($activities) == 0) {
                            echo '<h2><div class="no-activities text-center">' . $wo['lang']['no_activities'] . '</div><h2>';
                        } else {
                            foreach ($activities as $wo['activity']) {
                                echo Wo_LoadPage('chat/activities-list');
                            }
                        }
					?>
                </li>
				<div class="no-activities center-text"></div>
            </ul>
        </div>
		
	</div>
</div>
<div class="modal fade" id="create_group_chat" role="dialog">
	<div class="modal-dialog modal-sm">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></span></button>
				<h4 class="modal-title">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
					<?php echo $wo['lang']['create_new_group']; ?>
				</h4>
			</div>
			<form id="insert-caht-parts" class="wo_create_chat_group">
				<div class="modal-body">
					<div id="insert-caht-alert"></div>
					<div class="form-group input-group">
						<span class="input-group-addon pointer" onclick="$('#group_chat_avatar').trigger('click');">
							<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-camera"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"></path><circle cx="12" cy="13" r="4"></circle></svg>
						</span>
						<input type="text" class="form-control" name="group_name" placeholder="<?php echo $wo['lang']['name']; ?>">
					</div>
					<div class="w100">
						<div class="group_chat_avatar"></div>
						<div class="clear"></div>
					</div>
					<div class="form-group input-group">
						<span class="input-group-addon" id="group_chat_mbrs">0</span>
						<input type="text" class="form-control" placeholder="<?php echo $wo['lang']['add_parts']; ?>" onkeydown="Wo_GetGChatParticipants(this.value)">
					</div>
					<div class="form-group">
						<div class="group_chat_mbr_list"></div>
					</div>
				</div>
				<div class="modal-footer">
					<div class="ball-pulse"><div></div><div></div><div></div></div>
					<button id="delete-all-post" type="submit" class="btn btn-main">
						<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-plus"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
						<?php echo $wo['lang']['create']; ?>
					</button>
				</div>
				<input type="hidden" name="parts" id="chat_group_users">
				<input type="reset" id="reset" class="hidden">
				<input type="file" name="avatar" class="hidden" id="group_chat_avatar" onchange="$('.group_chat_avatar').html('<img src=\'' + window.URL.createObjectURL(this.files[0]) + '\' alt=\'Picture\'>');" accept="image/jpeg,image/png,image/gif">
			</form>
		</div>
	</div>
</div>
<div class="modal fade" id="manage_group_chat" role="dialog">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></span></button>
				<h4 class="modal-title">
					<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
					<?php echo $wo['lang']['group_members']; ?>
					(<span id="group_chat_mbrs">0</span>)
					<div class="clear"></div>
				</h4>
			</div>
			<form id="insert-caht-parts">
				<div id="insert-caht-alert"></div>
				<div class="modal-body"></div>
				<input type="hidden" name="parts" id="chat_group_users">
			</form>
		</div>
	</div>
</div>

<div class="modal fade sun_modal" id="edit_group_chat" role="dialog">
	<div class="modal-dialog modal-sm">
		<div class="modal-content">
			<form id="edit_chat_group_form" class="wo_edit_chat_group">
				<div class="modal-body">
					<div class="edit_grp_info_modal">
						<div class="group_chat_avatar__container" onclick="$('#edit_group_chat_avatar_').trigger('click');">
							<span><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9Z" /></svg></span>
						</div>
						<input type="text" class="form-control" name="group_name" placeholder="<?php echo $wo['lang']['name']; ?>" id="edit_group_name">
						<div class="clear"></div>
					</div>
					<div id="edit_chat_group_alert"></div>
				</div>
				<div class="modal-footer">
					<div class="ball-pulse"><div></div><div></div><div></div></div>
					<button id="delete-all-post" type="submit" class="btn btn-main"><?php echo $wo['lang']['update']; ?></button>
				</div>
				<input type="hidden" id="edit_group_id" class="hidden" name="group_id">
				<input type="file" name="avatar" class="hidden" id="edit_group_chat_avatar_" onchange="change_avatar(this);" accept="image/jpeg,image/png,image/gif">
			</form>
		</div>
	</div>
</div>

<script type="text/javascript">
function Wo_ShowMessageOptions(id) {
    $('.deleteMessage').hide();
    $('#messageId_' + id).find('.deleteMessage').show();
}
	function change_avatar(self) {
		$('.group_chat_avatar__container').css('background-image', "url('"+window.URL.createObjectURL(self.files[0])+"')");
	}
function Wo_GetGChatParticipants(name){
    if (!name) {
        return false;
    }
    $.ajax({
        url: Wo_Ajax_Requests_File(),
        type: 'GET',
        dataType: 'json',
        data: {f: 'chat',s:'get_parts',name:name},
    })
    .done(function(data) {
        if (data.status == 200) {
            $('.group_chat_mbr_list').html(data.html);
        }
        else{
          $('.group_chat_mbr_list').html('<p class="no_participant"><?php echo $wo['lang']['no_result']; ?></p>');
        }
    })
    .fail(function() {
        console.log("error");
    })   
}

function Wo_CreateGChat(e){
    e.preventDefault();
    $('#create_group_chat').modal('show');
}
function Wo_EditGChat(e,group_id){
    e.preventDefault();
    $.get(Wo_Ajax_Requests_File(), {f:'chat', s:'get_group_info',group_id:group_id}, function(data) {
    	if (data.status == 200) {
    		//$('#edit_group_chat_avatar').attr('src', data.group.avatar);
    		$('.group_chat_avatar__container').css('background-image', "url('"+data.group.avatar+"')");
    		$('#edit_group_name').val(data.group.group_name);
    		$('#edit_group_id').val(data.group.group_id);
    		$('#edit_group_chat').modal('show');
    	}
    });
}


function socketSide(){
  <?php if ($wo['config']['node_socket_flow'] == "1") { ?>
    console.log("user status change registered")
    socket.on("user_status_change", (data)=>{
      var online_users_container = $('.online-users');
      var offline_users_container = $('.offline-users');
      if (data.online_users.length == 0) {
        online_users_container.html('');
      } else {
          online_users_container.html(data.online_users);
      }
      if (data.offline_users.length == 0) {
        offline_users_container.html('');
      } else {
        offline_users_container.html(data.offline_users);
      }
    })
    // console.log("Typing registered")
    socket.on("typing",(data)=>{
    var inputs = $("input.chat-user-id");
    if (inputs.length > 0) {
        for(var i = 0; i < inputs.length; i++){
          let id = $(inputs[i]).val()
          if (current_width < 700) {
          return false;
          }
          if ($('.search-users-chat').val().length > 0) {
            return false;
          }
          if ($('body').attr('sending-' + id) == 'true') {
              return false;
          }
          var chat_container = $('.chat-tab').find('.chat_main_' + id);
          var offline_users_container = $('.offline-users');
          var user_id = chat_container.find('.chat-user-id').val();
          var message_id = chat_container.find('.chat-messages-wrapper').find('.messages-wrapper:last').attr('data-message-id');
          var chat_user_tab = chat_container.find('.chat-wrapper').find('.chat-status');
          var online_users_container = $('.online-users');
          var last_id = chat_container.find('.messages-text:last').attr('data-message-id');
          var is_empty_seen = 1;
          var chat_groups = $(".chat_groups");
          var last_group = ($(".groups-list").length > 0) ? $(".groups-list").last().attr('data-chat-group') : 0;

          if (!$('#messageId_'+message_id).find('.message-seen').is(':empty')) {
              is_empty_seen = 0;
          }
          if (typeof user_id === 'undefined') {
            user_id = 0;
          }
          if (typeof message_id === 'undefined') {
            message_id = 0;
          }
          if (typeof last_id === 'undefined') {
            last_id = 0;
          }
          var count_span = $('.count-online-users');

          if ( data.sender_id === +user_id && data.is_typing == 200) {
                chat_container.find('#messageId_'+message_id).find('.message-typing').html('<img class="user-avatar-left" src="' + data.img + '" alt="Profile Picture"><div id="loading"> <img class="typing" src="' + data.typing + '"></div>').fadeIn(300);

                setTimeout(function(){
               chat_container.find('.chat-messages-wrapper').scrollTop(chat_container.find('.chat-messages-wrapper')[0].scrollHeight);
            }, 100);
                
          } else {
              chat_container.find('#messageId_'+message_id).find('.message-typing').empty();
          } 
        }
      }
    })
    // console.log("Seen registered")
    // socket.on("lastseen", (data) => {
         
    // var inputs = $("input.chat-user-id");
    // if (inputs.length > 0) {
    //     for(var i = 0; i < inputs.length; i++){
    //       let id = $(inputs[i]).val()
    //       if (current_width < 700) {
    //         return false;
    //       }
    //       if ($('.search-users-chat').val().length > 0) {
    //         return false;
    //       }
    //       if ($('body').attr('sending-' + id) == 'true') {
    //           return false;
    //       }
    //       var chat_container = $('.chat-tab').find('.chat_main_' + id);
    //       var offline_users_container = $('.offline-users');
    //       var user_id = chat_container.find('.chat-user-id').val();
    //       var message_id = chat_container.find('.chat-messages-wrapper').find('.messages-wrapper:last').attr('data-message-id');
    //       var chat_user_tab = chat_container.find('.chat-wrapper').find('.chat-status');
    //       var online_users_container = $('.online-users');
    //       var last_id = chat_container.find('.messages-text:last').attr('data-message-id');
    //       var is_empty_seen = 1;
    //       var chat_groups = $(".chat_groups");
    //       var last_group = ($(".groups-list").length > 0) ? $(".groups-list").last().attr('data-chat-group') : 0;

    //       if (!$('#messageId_'+message_id).find('.message-seen').is(':empty')) {
    //           is_empty_seen = 0;
    //       }
    //       if (typeof user_id === 'undefined') {
    //         user_id = 0;
    //       }
    //       if (typeof message_id === 'undefined') {
    //         message_id = 0;
    //       }
    //       if (typeof last_id === 'undefined') {
    //         last_id = 0;
    //       }
    //       var count_span = $('.count-online-users');

    //       if (is_empty_seen == 1 && data.can_seen == 1) {
    //           chat_container.find('#messageId_'+message_id).find('.message-seen').hide().html('<i class="fa fa-check"></i> <?php echo $wo["lang"]["seen"];?> (<span class="ajax-time" title="' + data.time + '">' + data.seen + '</span>)').fadeIn(300);
    //           setTimeout(function(){
    //            chat_container.find('.chat-messages-wrapper').scrollTop(chat_container.find('.chat-messages-wrapper')[0].scrollHeight);
    //         }, 100);
    //       }
    //     }
    //   }
    // })
  <?php } ?>
}
$(()=>{
  socketSide()
})

function Wo_ChatSide(id) {
  <?php if ($wo['config']['node_socket_flow'] == "0") { ?>
    if (current_width < 700) {
        return false;
    }
    if ($('.search-users-chat').val().length > 0) {
       return false;
    }
    if ($('body').attr('sending-' + id) == 'true') {
        return false;
    }
    var chat_container = $('.chat-tab').find('.chat_main_' + id);
    var offline_users_container = $('.offline-users');
    var user_id = chat_container.find('.chat-user-id').val();
    var message_id = chat_container.find('.chat-messages-wrapper').find('.messages-wrapper:last').attr('data-message-id');
    var chat_user_tab = chat_container.find('.chat-wrapper').find('.chat-status');
    var online_users_container = $('.online-users');
    var last_id = chat_container.find('.messages-text:last').attr('data-message-id');
    var is_empty_seen = 1;
    var chat_groups = $(".chat_groups");
    var last_group = ($(".groups-list").length > 0) ? $(".groups-list").last().attr('data-chat-group') : 0;
    if (!$('.messages-text:last').find('.message-seen').is(':empty')) {
        is_empty_seen = 0;
    }
    if (typeof user_id === 'undefined') {
       user_id = 0;
    }
    if (typeof message_id === 'undefined') {
       message_id = 0;
    }
    if (typeof last_id === 'undefined') {
       last_id = 0;
    }
    var count_span = $('.count-online-users');
    $.get(Wo_Ajax_Requests_File(), {f:'chat', s:'chat_side', user_id:user_id, message_id:message_id, last_id:last_id,last_group:last_group}, function(data) {
    	if (data.reactions) {
	      	for (var i = data.reactions.length - 1; i >= 0; i--) {
	      		$('.post-reactions-icons-m-'+data.reactions[i].id).html(data.reactions[i].reactions);
	      		
	      	}
	      }
        if (data.status == 200  && data.chat_groups.length > 0) {
          chat_groups.html(data.chat_groups);
        }
        if (data.status == 200) {
            count_span.html(data.count_chat);
        }
        if (data.update_group_status.length > 0) {
         if ('<?php echo $wo['page']; ?>' != 'messages') {
          for (var i = 0; i < data.update_group_status.length; i++) {
            if ($(".chat_group_"+data.update_group_status[i]).length == 0) {
              $("[data-chat-group='"+ data.update_group_status[i] +"']").find('.group-lastseen').html('<i class="fa fa-circle main" style="font-size:10px;"></i>');
            }
          }
         }
         else if ('<?php echo $wo['page']; ?>' == 'messages') {}{
          for (var i = 0; i < data.update_group_status.length; i++) {
            if ($(".chat_group_"+data.update_group_status[i]).length == 0 && $("#messages-group-id").val() != data.update_group_status[i]) {
              $("#messages-group-"+ data.update_group_status[i]).find('.group-lastseen').html('<i class="fa fa-circle main" style="font-size:10px;"></i>');
            }
          }
         }
        }
        if (data.online_users.length == 0) {
            online_users_container.html('');
        } else {
            online_users_container.html(data.online_users);
        }
        if (data.offline_users.length == 0) {
            offline_users_container.html('');
        } else {
            offline_users_container.html(data.offline_users);
        }
        if (data.chat_user_tab == 200) {
            chat_user_tab.html('active');
        } else {
            chat_user_tab.removeClass('active');
        }
        if (data.messages == 200) {
        	if (data.chat_color) {
        	 $('.chat_' + user_id).find('.online-toggle').attr('style', 'background: '+data.chat_color+' !important;');
        	}
            chat_container.find('.chat-messages-wrapper').find("div[class*='message-seen']").empty();
            chat_container.find('.chat-messages-wrapper').find("div[class*='message-typing']").empty();
            chat_container.find('.chat-messages-wrapper').append(data.messages_html);
            setTimeout(function(){
               chat_container.find('.chat-messages-wrapper').scrollTop(chat_container.find('.chat-messages-wrapper')[0].scrollHeight);
            }, 100);
            if (data.sender != user_id) {
               document.getElementById('message-sound').play();
            }
            if (!$('#sendMessage').is(':focus')) {
                document.title = 'New Message | ' + document_title;
            }
        }
        if (is_empty_seen == 1 && data.can_seen == 1) {
            chat_container.find('.messages-text:last').find('.message-seen').hide().html('<i class="fa fa-check"></i> <?php echo $wo["lang"]["seen"];?> (<span class="ajax-time" title="' + data.time + '">' + data.seen + '</span>)').fadeIn(300);
            setTimeout(function(){
               chat_container.find('.chat-messages-wrapper').scrollTop(chat_container.find('.chat-messages-wrapper')[0].scrollHeight);
            }, 100);
        }
        if (data.is_typing == 200) {
            chat_container.find('.messages-text:last').find('.message-typing').html('<img class="user-avatar-left" src="' + data.img + '" alt="Profile Picture"><div id="loading"> <img class="typing" src="' + data.typing + '"></div>').fadeIn(300);

            setTimeout(function(){
               chat_container.find('.chat-messages-wrapper').scrollTop(chat_container.find('.chat-messages-wrapper')[0].scrollHeight);
            }, 100);
            
        } else {
            chat_container.find('.messages-text:last').find('.message-typing').empty();
        } 
        if (data.chat_color) {
	        //$(".chat_" + user_id).find('.online-toggle, .outgoing').css('background', data.chat_color);
            $(".chat_" + user_id).find('.outgoing p').css('color', '#fff');
            $(".chat_" + user_id).find('#color').val(data.chat_color);
            $(".chat_" + user_id).find('.select-color').css('color', data.chat_color);
            $(".chat_" + user_id).find('.outgoing .message-text, .outgoing .message-media, .outgoing.message').css('background', data.chat_color);
             $(".chat_" + user_id).find('.outgoing .message-text').css('color', '#fff');
             $(".chat_" + user_id).find('.select-color path').css('fill', data.chat_color);
             $(".chat_" + user_id).find('#color').val(data.chat_color);
             $(".text-sender-container .red-list").css('background', data.chat_color);
             $(".text-sender-container .btn-file").css('background', data.chat_color);
             $(".text-sender-container .btn-file").css('border-color', data.chat_color);
             $(".chat_" + user_id).find('.record-chat-audio').find('[fill]').attr('fill', data.chat_color);
        }
    });
  <?php } ?>
}

var chat_part_array = [];

$(function() {
    <?php
    if (isset($_SESSION['chat_id'])) {
        if (strpos($_SESSION['chat_id'], ',') !== false) {
            $explode = @explode(',', $_SESSION['chat_id']);
            foreach ($explode as $key => $value) {
            ?>
            setTimeout(function () {
                Wo_OpenChatTab(<?php echo $value;?>);
            }, 2000);
            <?php
            }
        } else {
            ?>
            setTimeout(function () {
                Wo_OpenChatTab(<?php echo $_SESSION['chat_id'];?>);
            }, 2000);
            <?php
        }
    }
    ?>
    setTimeout(function () {
       Timeout();
    }, 7000);
    <?php if (isset($_SESSION['group_id']) && is_numeric($_SESSION['group_id']) && $_SESSION['group_id'] > 0): ?>
      Wo_OpenChatTab(0,"<?php echo $_SESSION['group_id'];?>");
    <?php endif; ?>

    $(document).on('click', '.group_chat_mbr_part', function(event) {
        event.preventDefault();
        var self_id    = $(this).attr('id');
        if ($.inArray(self_id, chat_part_array) == -1) {
            chat_part_array.push(self_id);
            $("#group_chat_mbrs").text(chat_part_array.length);
            
            $(this).fadeOut(100,function(){
                $("#chat_group_users").val(chat_part_array.join());
                $(this).remove();
            })
        }
        else{
          $(this).addClass('disabled').removeAttr('title');
        }
    });

    $('#insert-caht-parts').ajaxForm({
      url: Wo_Ajax_Requests_File() + '?f=chat&s=create_group',
      type:'POST',
      dataType:'json',

      beforeSend: function() {
        Wo_progressIconLoader($('#insert-caht-parts').find('button'));
		$('#insert-caht-parts').find('.modal-footer .ball-pulse').fadeIn(100);
      },
      success: function(data) {
        if (data['status'] == 200) {
            $("#create_group_chat").modal('hide');
            Wo_OpenChatTab(0,data.group_id);
            $("#insert-caht-parts").find('#reset').trigger('click');
            $(".group_chat_mbr_list").empty();
            $(".group_chat_avatar").empty();
            chat_part_array = [];
            socket.emit("sync_groups")
        }
        else if (data.status == 500){
            $("#insert-caht-alert").html('<div class="alert alert-danger">' + data['message'] + '</div>');
        } 
        $('#insert-caht-parts').find('.modal-footer .ball-pulse').fadeOut(100);
    }});

    
    $('#edit_chat_group_form').ajaxForm({
	  url: Wo_Ajax_Requests_File() + '?f=chat&s=edit_group',
	  type:'POST',
	  dataType:'json',
	  beforeSend: function() {
	    Wo_progressIconLoader($('#edit_chat_group_form').find('button'));
		$('#edit_chat_group_form').find('.modal-footer .ball-pulse').fadeIn(100);
	  },
	  success: function(data) {
	    if (data['status'] == 200) {
	        $("#edit_group_chat").modal('hide');
	        location.reload();
	    }
	    else{
	        $("#edit_chat_group_alert").html('<div class="alert alert-danger">' + data['message'] + '</div>');
	    } 
	    $('#edit_chat_group_form').find('.modal-footer .ball-pulse').fadeOut(100);
	}});
});

function Timeout() {
    var inputs = $("input.chat-user-id");
    if (inputs.length > 0) {
        for(var i = 0; i < inputs.length; i++){
            Wo_ChatSide($(inputs[i]).val());
        }
    } else {
        Wo_ChatSide(0);
    }
    setTimeout(function () {
       Timeout();
    }, 7000);
}

function Wo_ChatSearchUsers(search_query) {
    var input = $($('.search-users-chat'));
    var offline_users_container = $('.online-users');
    if (input.val() == "") {
        Wo_ChatSide(0);
    }
    $.post(Wo_Ajax_Requests_File() + '?f=chat&s=search_for_recipients', {
        search_query: search_query
    }, function(data) {
        if (data.status == 200) {
            if (data.html.length == 0) {
                offline_users_container.html('<span class="no-online-users center-text"><?php echo $wo["lang"]["no_users_found"];?></span>');
            } else {
                offline_users_container.html(data.html);
            }
            $('.chat-container').scrollTop($('.chat-container')[0].scrollHeight);
        }
    });
}

function Wo_UpdateStatus(status,event) {
    event.preventDefault();
    if (status == 'offline') {
    	socket.emit('on_user_loggedoff', {from_id: _getCookie("user_id")});
    }
    if (status == 'online') {
    	socket.emit('on_user_loggedin', {from_id: _getCookie("user_id")});
    }
    var status_container = $('.online-content-toggler');
    var offline_status = status_container.find('.chat-opacity');
    $.post(Wo_Ajax_Requests_File() + '?f=chat&s=update_chat_status', {
        status: status
    }, function(data) {
        if (data.status == 0) {
            offline_status.removeClass('active').fadeOut(200);
        } else {
            offline_status.addClass('active').fadeIn(200);
        }
    });
}

function Wo_RegisterTyping(id) {
    recipient_id = $('.chat_main_' + id).find('#user-id').val();
    if (typeof recipient_id === 'undefined') {
       return false;
    }
  <?php if ($wo['config']['node_socket_flow'] == "0") { ?>
    $.get(Wo_Ajax_Requests_File(), {
        f: 'chat',
        s: 'recipient_is_typing',
        recipient_id: recipient_id
    });
  <?php } ?>

  <?php if ($wo['config']['node_socket_flow'] == "1") { ?>
    socket.emit("typing", { recipient_id: recipient_id, user_id: _getCookie("user_id") })
  <?php } ?>
}

function Wo_DeleteTyping(id) {
  <?php if ($wo['config']['node_socket_flow'] == "1") { ?>
    socket.emit("typing_done", {recipient_id: id, user_id: _getCookie("user_id")})
  <?php } ?>
  <?php if ($wo['config']['node_socket_flow'] == "0") { ?>
    chat_container = $('.chat_main_' + id);
    recipient_id = chat_container.find('#user-id').val();
    if (typeof recipient_id === 'undefined') {
       return false;
    }
    $.get(Wo_Ajax_Requests_File(), {
        f: 'chat',
        s: 'remove_typing',
        recipient_id: recipient_id
    });
  <?php } ?>
}

function Wo_CloseChat(id, type) {
  var tab_type = {};
  if (!type) {
    Wo_CleanRecordNodes();
    Wo_StopLocalStream();
    <?php if ($wo['config']['message_typing'] == 1) { ?>
        Wo_DeleteTyping(id);
    <?php } ?>

    $('.chat_main_' + id).fadeOut(200, function () {
        $(this).remove();
    });

    $(document.body).removeAttr('data-chat-recipient');
    tab_type = {f: 'chat',s: 'close_chat',id:id};
  }
  else if(type == 'group'){
    $('.chat_main_0').fadeOut(200, function () {
        $(this).remove();
    });
    tab_type = {f: 'chat',s: 'close_group',id:id};
  }
  else if (type == 'page') {
  	$('.chat_main_0').fadeOut(200, function () {
        $(this).remove();
    });
    tab_type = {f: 'chat',s: 'close_page',id:id};
  }
  <?php if ($wo['config']['node_socket_flow'] == "1") { ?>
    if(type === "group"){
      socket.emit("close_chat", {recipient_id: id, user_id: _getCookie("user_id"), group: true})
    }
    else{
      socket.emit("close_chat", {recipient_id: id, user_id: _getCookie("user_id")})
    }
  <?php } ?>

  <?php //if ($wo['config']['node_socket_flow'] == "0") { ?>
    $.get(Wo_Ajax_Requests_File(),tab_type);
  <?php //} ?>
}
function Wo_DeleteChatMessage(message_id) {
  $.get(Wo_Ajax_Requests_File(), {
    f:'messages',
    s:'delete_message',
    message_id: message_id
  }, function (data) {
    if(data.status == 200) {
      $('#messageId_' + message_id).slideUp(200, function () {
        $(this).remove();
      });
    }
  });
}
 
function Wo_ShareChatFile(id) {

    <?php if ($wo['config']['node_socket_flow'] == "0") { ?>
    document.title = document_title;
    $("form.chat-sending-form-" + id + " #sendMessage").focus();
    $("form.chat-sending-form-" + id).submit();
  <?php } ?>
  <?php if ($wo['config']['node_socket_flow'] == "1") { ?>
    var main_hash_id = $('.main_session').val();
    var chat_messages_wrapper = $('.chat-messages-wrapper-'+id);

    $('form.chat-sending-form-'+id).ajaxSubmit({
        url: Wo_Ajax_Requests_File() + '?f=chat&s=send_message&hash=' + main_hash_id,
        beforeSend: function() {
            if (chat_messages_wrapper.find('.chat-user-desc').length == 1) {
                chat_messages_wrapper.find('.chat-user-desc').hide();
            }
            var text_message = escapeHTML($('.chat-sending-form-'+id+' #sendMessage').val());
            $('.chat-sending-form-'+id).attr('disabled', true);
            var color = $('.chat-sending-form-'+id+' #color').val();
            <?php  if (!empty($wo['chat']['color'])) { ?>
             var html_message = '<div class="sended_message"><div class="messages-wrapper pull-right messages-text" id="messageId_" data-message-id=""><div class="message outgoing pull-right"><p class="message-text" style="background: ' + color + ';color: #fff" dir="auto">' + text_message + '</p><div class="clear"></div><div class="message-media"></div></div><div class="clear"></div><div class="message-seen text-right message-details"></div><div class="clear"></div><div class="message-typing message-details"></div></div><div class="clear"></div></div>';
            <?php } else { ?>
              var html_message = '<div class="sended_message"><div class="messages-wrapper pull-right messages-text" id="messageId_" data-message-id=""><div class="message outgoing pull-right"><p class="message-text" dir="auto">' + text_message + '</p><div class="clear"></div><div class="message-media"></div></div><div class="clear"></div><div class="message-seen text-right message-details"></div><div class="clear"></div><div class="message-typing message-details"></div></div><div class="clear"></div></div>';
            <?php } ?>
            if (!text_message && $('form.chat-sending-form-'+id).find('input.message-record').val() == '' && $('form.chat-sending-form-'+id).find('#chatSticker').val() == '') {
              $('form.chat-sending-form-'+id).find('#sendMessasgeFile').val('');
              return false;
            }
            $('body').attr('sending-'+id, true);
            if (text_message && $('form.chat-sending-form-'+id+' #sendMessasgeFile').val() == '') {
              if (chat_messages_wrapper.length == 0) {
                chat_messages_wrapper.html(html_message);
              } else {
                chat_messages_wrapper.append(html_message);
              }
            }
            setTimeout(function() {
                  chat_messages_wrapper.scrollTop(chat_messages_wrapper[0].scrollHeight);
            }, 100);
            $('form.chat-sending-form-'+id).clearForm();
        },
        uploadProgress: function () {
		  $('form.chat-sending-form-'+id).find('.ball-pulse').fadeIn(100);
        },
        success: function(data) {
            if (data.status == 200) {
                chat_messages_wrapper.find("div[class*='message-seen']").empty();
                chat_messages_wrapper.find("div[class*='message-typing']").empty();
                if( data.stickers == true ){
                  chat_messages_wrapper.append(data.html); 
                }else{
                  chat_messages_wrapper.append(data.html); 
                }
                var dom = $($.parseHTML(data.html));
                var mediaId = dom.find(".message").attr("onclick").substr("Wo_ShowMessageOptions(".length, dom.find(".message").attr("onclick").indexOf(')')-"Wo_ShowMessageOptions(".length);
                
                $('form.chat-sending-form-'+id).find('input.message-record').val('');   
                $('form.chat-sending-form-'+id).find('input.media-name').val('');
                $("#chatSticker").val('');
                $("#chat-gifs").removeClass('open');
                if (data.invalid_file == 1) {
                  $("#invalid_file").modal('show');
                  Wo_Delay(function(){
                    $("#invalid_file").modal('hide');
                  },3000);
				          $('form.chat-sending-form-'+id).find('.ball-pulse').fadeOut(100);
                }
                if(data.invalid_file == 2){
                  $("#file_not_supported").modal('show');
                  Wo_Delay(function(){
                    $("#file_not_supported").modal('hide');
                  },3000);
                }

                if (![1,2].includes(data.invalid_file)) {
                  socket.emit("private_message", {
                      to_id: id, 
                      from_id: _getCookie("user_id"),
                      username: '<?php echo $wo['user']['username']; ?>',
                      mediaId: mediaId,
                      isSticker: false
                  })
                }
                
                $('body').attr('sending-'+id, false);
                if (data.file == true) {
                  $('form.chat-sending-form-'+id).find('.ball-pulse').fadeOut(100);
                }
                
            }
            else if(data.status == 500 && data.invalid_file == 1){
              $("#invalid_file").modal('show');
              Wo_Delay(function(){
                $("#invalid_file").modal('hide');
              },3000);
              $('form.chat-sending-form-'+id).find('.ball-pulse').fadeOut(100);
            }
            else if(data.status == 500 && data.invalid_file == 2){
              $("#file_not_supported").modal('show');
              Wo_Delay(function(){
                $("#file_not_supported").modal('hide');
              },3000);
              $('form.chat-sending-form-'+id).find('.ball-pulse').fadeOut(100);
            }
            else if(data.status == 500 && data.invalid_file == 3){
              $("#pro_upload_file").modal('show');
              Wo_Delay(function(){
                $("#pro_upload_file").modal('hide');
              },3000);
              $('form.chat-sending-form-'+id).find('.ball-pulse').fadeOut(100);
            }
            setTimeout(function() {
              chat_messages_wrapper.scrollTop(chat_messages_wrapper[0].scrollHeight);
            }, 700);
        }
    });
   <?php } ?>
}

function Wo_AddEmoToChat(code, id) {
    inputTag = $('.chat-sending-form-'+ id +' textarea');
    inputVal = inputTag.val();
    //$('.emo-container').hide();
    if (typeof(inputTag.attr('placeholder')) != "undefined") {
        inputPlaceholder = inputTag.attr('placeholder');
        if (inputPlaceholder == inputVal) {
            inputTag.val('');
            inputVal = inputTag.val();
        }
    }
    if (inputVal.length == 0) {
        inputTag.val(code + ' ');
    } else {
        inputTag.val(inputVal + ' ' + code);
    }
    inputTag.keyup().focus();
}

function Wo_AddEmoToGroup(code, id,type = '') {
	inputTag = $('.group-chat-sending-'+ id +' textarea');
	if (type == 'page') {
		inputTag = $('.page-chat-sending-'+ id +' textarea');
	}
    
    inputVal = inputTag.val();
    $('.emo-container').hide();
    if (typeof(inputTag.attr('placeholder')) != "undefined") {
        inputPlaceholder = inputTag.attr('placeholder');
        if (inputPlaceholder == inputVal) {
            inputTag.val('');
            inputVal = inputTag.val();
        }
    }
    if (inputVal.length == 0) {
        inputTag.val(code + ' ');
    } else {
        inputTag.val(inputVal + ' ' + code);
    }
    inputTag.keyup().focus();
}

function Wo_SubmitChatForm(e, id) {
    document.title = document_title;
    <?php if ($wo['config']['message_typing'] == 1) { ?>
    var typing_chat_con = $('.chat_main_' + id);
    if (typing_chat_con.find('#sendMessage').val().length > 1) {
        if (typeof (typing_chat_con.attr('data-typing')) == "undefined" || typing_chat_con.attr('data-typing') == 'false') {
            typing_chat_con.attr('data-typing', 'true');
            Wo_RegisterTyping(id);
        } 
    }
    else if (typing_chat_con.find('#sendMessage').val().length == 1) {
        if (typeof (typing_chat_con.attr('data-typing')) != "undefined") {
           if (typing_chat_con.attr('data-typing') == 'true') {
               typing_chat_con.attr('data-typing', 'false');
               //typing_chat_con.removeAttr('data-typing');
               Wo_DeleteTyping(id);
            }
           }
        }
    <?php } ?>
    chat_tab_container = $('.chat_main_' + id);
    if (e.keyCode == 13 && e.shiftKey == 0) {
        Wo_DeleteTyping(id);
        e.preventDefault();
        Wo_RegisterTabMessage(id);
        typing_chat_con.find('.messages-text:last').find('.message-seen').empty();
        $('form.chat-sending-form-' + id).submit()
    } else {
      if(e.keyCode && ![17, 18, 9].includes(e.keyCode)){
        Wo_Typing(e, id)
      }
    }
}

function Wo_Typing(e, recipient_id){
  <?php if ($wo['config']['node_socket_flow'] == "1") { ?>
    socket.emit("typing", { recipient_id: recipient_id, user_id: _getCookie("user_id") })
  <?php } ?>
}

function Wo_SearchGChatParticipants(name,group_id){
  if (!name || !group_id) { return false;}
  $.ajax({
      url: Wo_Ajax_Requests_File(),
      type: 'GET',
      dataType: 'json',
      data: {f: 'chat',s:'search_parts',name:name,group_id:group_id},
  })
  .done(function(data) {
      if (data.status == 200) {
          $('.group_chat_mbr_list_' + group_id).html(data.html);
      }
      else{
        $('.group_chat_mbr_list_' + group_id).html('<p class="search-filter-center-text"><?php echo $wo['lang']['no_result']; ?></p>');
      }
  })
  .fail(function() {
      console.log("error");
  }) 
}

function Wo_AddGChatPart(group_id, user_id){
  if (!user_id || !group_id) { return false;}
  $.ajax({
    url: Wo_Ajax_Requests_File(),
    type: 'GET',
    dataType: 'json',
    data: {f: 'chat',s:'add_gchat_user',user_id:user_id,group_id:group_id},
  })
  .done(function(data) {
    if (data.status == 200 && data.code == 1) {
      $("[data-group-chat-part='"+user_id+"']").find('span.status').html('<i class="fa fa-times main"></i>');
    }
    else if(data.status == 200 && data.code == 0){
      $("[data-group-chat-part='"+user_id+"']").find('span.status').html('<i class="fa fa-plus-square-o main"></i');
    }
    else{
      return false;
    }
  })
  .fail(function() {
    console.log("error");
  })
}
</script>
<?php } ?>