<?php

require_once '../incfiles/core.php';
require_once '../incfiles/func.php';
require_once '../incfiles/auth.php';
require_once '../incfiles/user.php';

if (empty($user_id)) go(URL);


if (!empty($_GET['id']) && is_numeric($_GET['id'])) // Діалог
{

	$location = 'dialog';

	$id = abs(intval($_GET['id']));	
	if ($user_id == $id) go(URL.'/mail/');
	$result = mysql_query("SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1");
	if (mysql_num_rows($result) == true) $array_user = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '".$id."' LIMIT 1"));
	else go(URL);

	require_once 'handler/mail.php';
	$res = mysql_query("SELECT * FROM `mail_dialog` WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' AND `del` != '".$user_id."' LIMIT 1");
	if (mysql_num_rows($res) == false) go(URL.'/mail/');
	$arr_dialog = mysql_fetch_array($res);
	require_once 'handler/del_msg.php';

	$index = true;
	$title = lang('Диалог с','Діалог з').' '.$array_user['name'].' '.$array_user['surname'];
	require_once '../incfiles/head.php';

	
?>
<script type="text/javascript">
$('input:file').remove();
$(document).ready(function() {
    new AjaxUpload('upload', {
        action: "/mail/upload.php?id=<?echo$id;?>",
        name: "file",
		data: {ajax: "yes"},
        onSubmit: function(file, ext) {
            if(! (ext && /^(jpg|gif|png|jpeg)$/.test(ext))) {
                return false;
            }
 			$('#cache_photos').append('<img id="preview_loading" src="/design/img/preview_loading.gif" style="width:48px;height:48px;"/>');
        },
      onComplete: function(file, res) {
	  $('#preview_loading').remove();
            if(res)
                $("#cache_photos").append(res);
        }
    });
});

$(function(){
	$('#form').on('submit', function(e){
	$('#form_content').html('');
	Page.Loading('start');
    e.preventDefault();
    var $that = $(this),
        formData = new FormData($that.get(0));
    $.ajax({
      url: $that.attr('action'),
      type: $that.attr('method'),
      contentType: false,
      processData: false,
      data: formData,
      success: function(response){
		Page.Loading('stop');
        if(response){
 			Page.Go($that.attr('action'));
       }
     }
    });
  });
});
</script>

<?


	echo '<div class="title">
	<a href="'.URL.'/mail/" onclick="Page.Go(this.href); return false">'.lang('Диалоги','Діалоги').'</a>
	<a class="title_a_hover" href="'.URL.'/mail/?id='.$id.'" onclick="Title.Open(); return false">'.$array_user['name'].' '.$array_user['surname'].' <img src="'.URL.'/design/img/title_menu.png"/></a>
	</div>
	<div id="title_menu">
	<a href="'.URL.'/?id='.$id.'" onclick="Page.Go(this.href); return false">'.$array_user['name'].' '.$array_user['surname'].'</a>
	<a href="'.URL.'/mail/del.php?id='.$id.'" onclick="Page.Go(this.href); return false">'.lang('Удалить диалог','Видалити діалог').'</a>
	</div>';
	if ($array_user['ban'] == 1) echo err(lang('Страница пользователя заблокирована администрацией сайта.','Сторінка користувача заблокована адміністрацією сайту.'));
	if ($array_user['access_mail'] == 1) if (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `friends` WHERE `user_id` = '".$user_id."' AND `friend_id` = '".$id."' LIMIT 1"),0) == false) echo err($array_user['name'].' '.($array_user['sex']==1?lang('ограничил','обмежив'):lang('ограничила','обмежила')).' доступ '.lang('к своей почте','до своєї пошти').': '.lang('Только для друзей','Тільки для друзів'));
	echo '<div class="block2">
	<form id="form" method="post" action="'.URL.'/mail/?id='.$id.'">
	<textarea id="textarea" class="input textarea_mail_dialog" name="text" rows="4"></textarea>
	<p><div id="cache_photos">';
	if (!empty($arr_dialog['count_cache']))
	{
		$q = explode("||", substr($arr_dialog['cache_photos'], 1, -1));
		$count = count($q);
		for ($i = 0; $i < $count; $i++)
		{
			echo '<a id="'.$i.'" class="del_cache" href="'.URL.'/mail/upload.php?id='.$id.'&del='.$q[$i].'" onclick="FormContent.DelCache(this.id,this.href); return false"><img class="preview_icons" src="'.URL.'/files/mail/'.$arr_dialog['dir'].'/photos/icons/'.$q[$i].'"/></a>';
		}
	}	
	echo '</div></p>
	<input class="button2" type="submit" value="'.lang('Отправить','Надіслати').'"/>
	<a class="button3" href="'.URL.'/ajax/smiles.php" onclick="FormContent.Smiles(this.href); return false"><img src="'.URL.'/design/img/smile.png"/></a>';
	require_once '../ajax/include_stiker.php';
	echo'
	
	<span id="upload" class="button3 for_pc" style="cursor: pointer;" ><img src="'.URL.'/design/img/photo.png"/></span>
	<a class="for_mobile" href="'.URL.'/mail/upload.php?id='.$id.'"><img src="'.URL.'/design/img/photo.png"/></a>
	<span class="button3" id="user_pen" style="font-size:10px;color:#909090;display:none;"><img src="'.URL.'/design/img/user_pen.gif"/> '.$array_user['name'].' '.lang('пишет...','пише...').'</span>
	</form>
	</div>
	<div id="form_content"></div>
	'.($array_user['online']==0?'<div class="block" style="color:#777777;">'.$array_user['name'].' '.user_visit($array_user['sex'],$array_user['visit']).'</div>':'').'
	</form>
	<div id="refresh_dialog"><span>';
	$all = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `mail_msg` WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' AND `del` != '".$user_id."' or `for_id` = '".$id."' AND `from_id` = '".$user_id."' AND `del` != '".$user_id."'"),0);
	if ($all > 0)
	{
		$cp = ceil($all/10);
		$p = (isset($_GET['p']) and is_numeric($_GET['p']) and $_GET['p']>1 and $_GET['p']<=$cp) ? $_GET['p'] : 1;
		$start = $p*10-10;
		$res = mysql_query("SELECT * FROM `mail_msg` WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' AND `del` != '".$user_id."' or `for_id` = '".$id."' AND `from_id` = '".$user_id."' AND `del` != '".$user_id."' ORDER by `time` DESC LIMIT $start,10");
		while ($arr = mysql_fetch_array($res))
		{
			echo ($arr['np'] == 0?'<div class="block">':'<div class="block1">').''.user_name($arr['from_id'],0,0).'<div class="right"><a href="'.URL.'/mail/msg.php?id='.$arr['id'].'" onclick="Page.Go(this.href); return false;">'.vtime($arr['time']).'</a></div><ul>'.links(smiles(hastag($arr['text']))).'</ul>';
			if (!empty($arr['photos']))
			{
				echo '<p>';
				$q = explode("||", substr($arr['photos'], 1, -1));
				$count = count($q);
				for ($i = 0; $i < $count; $i++) 
					echo '<a href="'.URL.'/files/mail/'.$arr_dialog['dir'].'/photos/'.$q[$i].'" ><img class="'.($count>1?'preview_mini':'preview').'" src="'.URL.'/files/mail/'.$arr_dialog['dir'].'/photos/'.($count>1?'mini':'preview').'/'.$q[$i].'"/></a>';
				echo '</p>';
			}
			echo '</div>';
		}
		
		navi($p,$cp,'/mail/?id='.$id.'&');

	}
		
	if ($arr_dialog['count'] > 0)
	{	
		mysql_query("UPDATE `mail_dialog` SET `np` = 0, `count` = 0 WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."' LIMIT 1");
		mysql_query("UPDATE `mail_dialog` SET `np` = 0 WHERE `for_id` = '".$id."' AND `from_id` = '".$user_id."' LIMIT 1");
		mysql_query("UPDATE `mail_msg` SET `np` = 0 WHERE `for_id` = '".$user_id."' AND `from_id` = '".$id."'");

		$notifications_mail = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `mail_msg` WHERE `for_id` = '".$user_id."' AND `np` = 1"),0);
		if ($user['notifications_mail'] != $notifications_mail) mysql_query("UPDATE `users` SET `notifications_mail` = '".$notifications_mail."' WHERE `id` = '".$user_id."' LIMIT 1");
	}

	echo '</span></div>';

	
}
else // Діалоги
{



	require_once 'handler/del.php';
	
	$title = lang('Мои Сообщения','Мої Повідомлення');
	require_once '../incfiles/head.php';

	echo '<div class="title">'.lang('Диалоги','Діалоги').'</div>';

	$all = mysql_result(mysql_query("SELECT COUNT(`id`) FROM `mail_dialog` WHERE `for_id` = '".$user_id."' AND `del` != '".$user_id."'"),0);
	if ($all > 0)
	{
		$cp = ceil($all/10);
		$p = (isset($_GET['p']) and is_numeric($_GET['p']) and $_GET['p']>1 and $_GET['p']<=$cp) ? $_GET['p'] : 1;
		$start = $p*10-10;

		$res = mysql_query("SELECT * FROM `mail_dialog` WHERE `for_id` = '".$user_id."' AND `del` != '".$user_id."' ORDER by `time` DESC LIMIT $start,10");
		while ($arr = mysql_fetch_array($res))
		{
			echo '<a style="text-decoration:none;" href="'.URL.'/mail/?id='.$arr['from_id'].'" onclick="Page.Go(this.href); return false;">'.($arr['np']>0?'<div class="block1">':'<div class="block">').'<font color="#4C6B8F">'.user_name2($arr['from_id']).'</font><div class="right">'.vtime($arr['time']).'</div><ul style="color:#000000;">'.user_ava($arr['from'],16).' '.smiles(hastag(mb_strlen($arr['text'])>99?$arr['text'].'...':$arr['text']).'<div class="right">'.($arr['count']>0?'<span style="background:rgba(0,0,0,0.2);color:#FFFFFF;padding:3px 6px 3px 6px;border-radius:3px;">'.$arr['count'].'</span>':'')).'</div></ul></div></a>';
		}
	}

	navi($p,$cp,'/mail/?');
	
	
	
}

require_once '../incfiles/foot.php';

?>