try {
  if(IALoid) {
$(document).ready(function(){
	$('.mail-load-block').css('display', "block");
  $('#button-mail').attr('type','button');
  var timer;

$('#message-textarea').on('keyup',function(e){
    var elm=$(this);
    var time=(new Date()).getTime();
    var delay=1000;
 
    elm.attr({'keyup':time});
    elm.off('keypress');
    elm.on('keydown',function(e){$(this).attr({'keyup':time});});
    elm.on('keypress',function(e){$(this).attr({'keyup':time});});
 
    setTimeout(function(){
        oldtime=parseFloat(elm.attr('keyup'));
        if(oldtime<=(new Date()).getTime()-delay & oldtime>0 & elm.attr('keyup')!='' & typeof elm.attr('keyup')!=='undefined'){
            IALoid.typing = false;
            elm.removeAttr('keyup');
        }
    },delay);
});
  $('#message-textarea').on('keyup', function(){IALoid.typing = true;});
  Intervals.push(setInterval(function () {
        if(IALoid.typing == true) {
          $.ajax({
               'url' : '/mail?act=typing',
               'type' : 'GET',
               'data' : {'id': IALoid.id, 't': 0},
               'beforeSend' : function(){
               },
               'success' : function(data){
               }
            });
        }
  }, 2000));
  Intervals.push(setInterval(function () {
    $.ajax({
               'url' : '/mail?act=typing',
               'type' : 'GET',
               'data' : {'id': IALoid.id, 't': 1},
               'beforeSend' : function(){
               },
               'success' : function(data){
                  data = parseInt(data);
                  if(parseInt(((new Date()).getTime()) / 1000) < data + 3) {
                    $('#message-typing').css('display','inline');
                  } else {
                     $('#message-typing').css('display','none');
                  }
               }
            });
  }, 1000));
});
Intervals.push(setInterval(function(){
message_load_data();
}, 1500));
$(window).scroll(function(){
   if (IALoid.scroll_start < IALoid.posts_count && ! IALoid.load && on_screen('.mail-load'))
    {     
       message_load_scrolling();
    }
});


function message_load_scrolling()
{
    if ( IALoid.scroll_start < IALoid.posts_count && ! IALoid.load )
    {
        $.ajax({
           'url' : '?act=posts_scrolling',
           'data' : {'start' : IALoid.scroll_start, 'id' : IALoid.id},
           'beforeSend' : function()
           {
               IALoid.load = true;
           },
           'success' : function(data)
           {
               IALoid.load = false;
               var j = $.parseJSON(data);
               var count = j.data.length;
               if ($('.mail').children(':last').attr('class') == '_line')
                  $('.mail ._line:last').remove();
               for(var i = 0; i < count; i++)
               {
                   var q = j.data[i];
                   var last = $('.mail .list:last');
                   var n = (q.id_user != IALoid.last_user);
                   IALoid.scroll_start++;
                   $('.mail').append((n ? '<div class="_line"></div>' : '') + '<div data-user="' 
+ q.id_user + '" class="list mail-message' + (q.new != 0 ? ' mail-message-new' : '' ) + '"> ' + (n ? '<div class="post-l mail-message-l"><a href="/id' +
q.id_user + '"><img src="' + q.ava + '" style="border-radius: 50%;width: 45px;height: 45px;"></a></div>' : '' ) + ' <div class="post-c mail-message-r"><span class="_fl-r _time _gray">' + q.time + '</span> ' + (n ? '<div dell><a href="/id'+q.id_user+'"><b>' + q.login +'</b></a></div>' : '' ) + '<span style="vertical-align:sub">' + q.message + 
'</span></div></div>');
                   IALoid.last_user = q.id_user;
                }
               if (IALoid.scroll_start >= IALoid.posts_count)
              		$('.mail-load').html('Все сообщения загружены');

            }
        });
    }
}

function message_load_data()
{
  if($LP.mailContactMessagesCount == 0) {
    $LP.mailContactMessages = $.ajax({
    'url': '?act=posts',
    'data': {'id': IALoid.id, 'start': IALoid.start,'active': Linesoc.activeWindow},
    'beforeSend': function(){$LP.mailContactMessagesCount++;},
    'success' : function(data){
        $LP.mailContactMessagesCount = 0;
        //$('#data').html(data);
        var j = $.parseJSON(data);
        if(Linesoc.activeWindow) {
        if (j.read == "0")
        {
           $('div[data-user="' + IALoid.user + '"]').removeClass('mail-message-new');
        }
        $('div[data-user != "' + IALoid.user + '"]').removeClass('mail-message-new');
        }
        var count = j.data.length;
        if (count > 0)
           IALoid.start = j.data[0].id;
        for(var i = 0; i < count; i++)
        {
            
            var q = j.data[i];
            IALoid.scroll_start++;
            IALoid.posts_count++;
            var first = $('.mail .list:first');
            if (q.id_user == first.attr('data-user'))
            {
               first.find('div[dell]').remove();
            }
            $('.mail').prepend('<div data-user="' 
+ q.id_user + '" class="list mail-message mail-message-new"><div dell class="post-l mail-message-l"><a href="/id' +
q.id_user + '"><img src="' + q.ava + 
'" style="border-radius: 50%;width: 45px;height: 45px;"></a></div> <div class="post-c mail-message-r"><span class="_fl-r _time _gray">' + q.time + '</span> <div dell><a href="/id'+q.id_user+'"><span class="_name">' 
+ q.login +'</span></a></div><span style="vertical-align:sub">' + q.message + 
'</span></div></div>' + ( q.id_user != first.attr('data-user') ? '<div class="_line"></div>' : '' ));
        }
    }
    });
  }
}
function message_create_post()
{
   if (!IALoid.load)
   {
      var msg = $('#message-textarea').val();
      $.ajax({
         'url' : '/mail?act=new_post',
         'type' : 'POST',
         'data' : {'id': IALoid.id, 'message': msg},
         'beforeSend' : function(){
            IALoid.load = true;
         },
         'success' : function(data){
         IALoid.load = false;
            
            var j = $.parseJSON(data);
            if(j.error != 0) {
            	Linesoc.addNote(j.error_string, 1);
            	//console.log(data);
            } else {
            	$('#message-textarea').val(null);
            	message_load_data();
            	Linesoc.delNote();
            }
         }

      });
   }
}}
} catch(e) {}
/*
var $MAIL = {
  on: true,
  last_message: '',
  scroll_load: false,
  thisLoad: false,
  par: function(user,message,set){
    var first = $('.mail .list:first');
    if(set && (first.attr('data-user') == user.id)){ first.find('span[class="_name"]').remove();first.find('div[class="post-l mail-message-l"]').remove(); }
    var p = "<div"+(message.id ? " data-id=\""+message.id+"\"" : '' )+" id=\"s0\" class=\""+(user.delete ? "js-mail-delete " : '' )+"list mail-message"+(USER.id == user.id ? " mail-message-out" : '')+( set || (!set && message.read) ? " mail-message-new" : '' )+"\" data-user=\""+user.id+"\">\
        <div class=\"mail-message-box\">\
        "+(set || (!set && user.hide) ? "<div class=\"post-l mail-message-l\">\
          <a href=\""+user.link+"\"><img src=\""+user.avatar+"\" style=\"border-radius: 50%;width: 45px;height: 45px;\"></a>\
          </div>\
          " : '')+"\
        <div class=\"post-c mail-message-r\">\
          <span class=\"_fl-r _time _gray\">"+(message.time ? message.time : 'отправка')+"</span>\
          "+(set || (!set && user.hide) ? "<div><span class=\"_name\"><a href=\""+user.link+"\">"+user.name+"</a></span></div>" : '')+"\
          <span style=\"vertical-align: sub;\">"+message.text+"</span>\
        </div>\
        </div>\
      </div>";         
    return p;
  },
  sending: [],
  send: function() {      
      var msg = $('#message-textarea').val().trim();
      var event = event || window.event;; 
      var data = {id: contactData.id,message: msg};
      if(msg.length>0){$MAIL.sending.push(data);$MAIL.s(0);$(".mail").prepend($MAIL.par({id: USER.id,delete: 1,name: USER.name,avatar: USER.avatar,link: USER.Page},{text: msg},true));}
      $('#message-textarea').val('');
      UI.formFocus($("textarea[data-focus='1']"));
      event.preventDefault ? event.preventDefault() : (event.returnValue=false);
      return false;
  },
  long: null,
  s: function(k) {
      try {
      $.ajax({
         'url' : '/mail?act=new_post',
         'type' : 'POST',
         'data' : $MAIL.sending[k],
         'beforeSend': function(){},
         'success': function(data){     
            var j = $.parseJSON(data);

            ($MAIL.sending).splice(0,1);
            if(j.error == 0) {
              $('._time',$('#s0')).text(j.timeCreate);
            } else {
              $('._time',$('#s0')).html('<span style="color: #9e2222;">ошибка</span>');
              console.log(j.error_string);
            }
            $('#s0').removeAttr('id');
            if($MAIL.length>0){$MAIL.s(0);}
         }

      });
    } catch(e){}
  },
  loadNew: function() {
    //if($LP.mailContactMessagesCount == 0) {
   // try {
    $LP.mailContactMessages = $.ajax({
    'url': '?act=posts',
    'data': {'id': IALoid.id, 'start': IALoid.start,'active': Linesoc.activeWindow},
    'beforeSend': function(){$LP.mailContactMessagesCount++;},
    'success' : function(data){
        $LP.mailContactMessagesCount = 0;
        //try {
                  var j = $.parseJSON(data);
        //if(Linesoc.activeWindow) {
        if (j.read == "0")
        {
           $('div[data-user="' + IALoid.user + '"]').removeClass('mail-message-new');
        }
        $('div[data-user != "' + IALoid.user + '"]').removeClass('mail-message-new');
       // }

        var count = j.data.length;
        if (count > 0){
          IALoid.start = j.data[0].id;
          var lol = 0;
          for(var i = 0; i < count; i++) { 
              if(lol != j.data[i].id) {
              var q = j.data[i];
              var n = (q.id_user != IALoid.last_user);
              $(".js-mail-delete").remove();
              $('.mail').prepend($MAIL.par({id:q.id_user,name:q.login,avatar:q.ava,link:'/id'+q.id_user,hide:n},{text:q.message,read:(q.new!=0),time:q.time},true));
              lol = q.id;
              }
          }
        }
       // $MAIL.loadNew();
       // } catch(e) {$MAIL.loadNew();}

    }, 
    error: function(e) {
     // $MAIL.loadNew();
      //$LP.mailContactMessagesCount = 0;
      return false;
    }});
    //} catch(e){$MAIL.loadNew();}
    //}
  },
  messageLoader: function() {
    if (!$MAIL.scroll_load && !$MAIL.thisLoad){
        $.ajax({
           'url' : '?act=posts_scrolling',
           'data' : {'start' : IALoid.scroll_start, 'id' : IALoid.id},
           'beforeSend' : function(){$('.mail-load').val('Идет загрузка..');$MAIL.thisLoad = true;},
           'success' : function(data){
               var j = $.parseJSON(data);
               var count = j.data.length;
               for(var i = 0; i < count; i++)
               {
                   
                   var q = j.data[i];
                   var last = $('.mail .list:last');
                   var n = (q.id_user != IALoid.last_user);
                   $('.mail').append($MAIL.par({id:q.id_user,name:q.login,avatar:q.ava,link:'/id'+q.id_user,hide:n},{text:q.message,read:(q.new != 0),time:q.time}));
                   IALoid.last_user = q.id_user;
                   IALoid.scroll_start = q.id;
                   if(q.last_message){$MAIL.scroll_load = true;$('.mail-load-block').html('<div class="_line"></div><div class="_center _l-padd _gray _font-s">Загружены последние сообщения</div>');}else{$('.mail-load').val('Загрузить еще сообщения');}
                   
                }
                $MAIL.thisLoad = false;
            }
        });
    }
  },
  __initialization: function() {
    $MAIL.on = true;
    $("#button-mail").on('click',function(){$MAIL.send()});
    $("#message-textarea").on('keypress',function(){if(event.keyCode==10||(event.ctrlKey&&event.keyCode==13)){$MAIL.send();}});
    $MAIL.loadNew();
    $(window).scroll(function(){if(on_screen('.mail-load')){$MAIL.messageLoader();}});

  }
};

$(document).ready(function(){});
    Intervals.push(setInterval(function(){$MAIL.loadNew()}, 1500));
/*
$('#message-textarea').on('keyup',function(e){
    var elm=$(this);
    var time=(new Date()).getTime();
    var delay=1000;
 
    elm.attr({'keyup':time});
    elm.off('keypress');
    elm.on('keydown',function(e){$(this).attr({'keyup':time});});
    elm.on('keypress',function(e){$(this).attr({'keyup':time});});
 
    setTimeout(function(){
        oldtime=parseFloat(elm.attr('keyup'));
        if(oldtime<=(new Date()).getTime()-delay & oldtime>0 & elm.attr('keyup')!='' & typeof elm.attr('keyup')!=='undefined'){
            IALoid.typing = false;
            elm.removeAttr('keyup');
        }
    },delay);
});
  $('#message-textarea').on('keyup', function(){IALoid.typing = true;});
  Intervals.push(setInterval(function () {
        if(IALoid.typing == true) {
          $.ajax({
               'url' : '/mail?act=typing',
               'type' : 'GET',
               'data' : {'id': IALoid.id, 't': 0},
               'beforeSend' : function(){
               },
               'success' : function(data){
               }
            });
        }
  }, 2000));
  Intervals.push(setInterval(function () {
    $.ajax({
               'url' : '/mail?act=typing',
               'type' : 'GET',
               'data' : {'id': IALoid.id, 't': 1},
               'beforeSend' : function(){
               },
               'success' : function(data){
                  data = parseInt(data);
                  if(parseInt(((new Date()).getTime()) / 1000) < data + 3) {
                    $('#message-typing').css('display','inline');
                  } else {
                     $('#message-typing').css('display','none');
                  }
               }
            });
  }, 1000));
*/