var trackstack_last_date = 0;
var trackstack_user_id = -1;
var trackstack_last_send = true;
var trackstack_cache = {'notify': '', 'message': ''};
var trackstack_notyplay = false;
var trackstack_notyplay_first = false;

ion.sound({
  sounds: [
    {
      name: "incom_massage"
    },
  ],
  volume: 1,
  path: "modules/ds/audio/",
  preload: true,
  loop: false,
  multiplay: false,
});

function cot_trackstack_update() {
  if(trackstack_last_send) {
    trackstack_last_send = false;

    var IS_ACTIVE_DIALOG_CHECKMSG = new Array();
    if(IS_ACTIVE_DIALOG > 0) {
      $('.conversation-message.out.unread[data-mid]').each(function() {
        IS_ACTIVE_DIALOG_CHECKMSG.push($(this).attr('data-mid'));
      });
    }

    var onlineWidgetIds = new Array();
    if($('[data-is-online][data-user-id]').length > 0) {
      $('[data-is-online][data-user-id]').each(function() {
        onlineWidgetIds.push($(this).attr('data-user-id'));
      });
    }

    $.get('api?method=track_stack&lastdate=' + trackstack_last_date
        + '&IS_ORDER_PAGE=' + IS_ORDER_PAGE
        + '&IS_ACTIVE_DIALOG=' + IS_ACTIVE_DIALOG
        + '&IS_ACTIVE_DIALOG_CHECKMSG=' + IS_ACTIVE_DIALOG_CHECKMSG.join(',')
        + '&ONLINE_WIDGET_IDS=' + onlineWidgetIds
    , function(data) {
      //console.log(data);
      if(data.status == 'success') {
        trackstack_notyplay = false;

        trackstack_user_id = data.user_id;
        trackstack_last_date = data.lastdate;

        var _arr;

        _arr = data.push.onlinewidget;
        if(_arr.length > 0) {
          for(i=0; i < _arr.length; i++) {
            $('[data-is-online][data-user-id="' + _arr[i]['uid'] + '"]').each(function() {
              $(this).attr('data-is-online', _arr[i]['online']).html('<i class="icon ico-' + (_arr[i]['online'] == 1 ? 'online' : ($(this).attr('data-darktheme') == 'true' ? 'offlineDark' : 'offline')) + '"></i>' + ($(this).attr('data-with-text') == 'true' ? (_arr[i]['online'] == 1 ? ' Онлайн' : ' Оффлайн' + (_arr[i]['last'] != '' ? ' (' + _arr[i]['last'] + ')' : '')) : ''));
            });
          }
        }

        if(IS_ORDER_PAGE > 0 && data.push.cntnew.order > 0) {
          _arr = data.push.order;

          if(_arr['tracks'].length > 0) {
            for(i=0; i < _arr['tracks'].length; i++) {
              if(_arr['tracks'][i]['mkt_id'] > 0 && $('#track-id-' + _arr['tracks'][i]['mkt_id']).length > 0) {
                $('#track-id-' + _arr['tracks'][i]['mkt_id']).replaceWith(_arr['tracks'][i]['html']);
              } else {
                $('#tracks-wrapper').append(_arr['tracks'][i]['html']);
              }
              trackstack_notyplay = true;
            }
          }
          if(_arr['hist'].length > 0) {
            for(i=0; i < _arr['hist'].length; i++) {
              if(_arr['hist'][i]['mkt_id'] > 0 && $('.track-order-state-history div[data-trackstatehist="' + _arr['hist'][i]['mkt_id'] + '"]').length > 0) {
                 $('.track-order-state-history div[data-trackstatehist="' + _arr['hist'][i]['mkt_id'] + '"]').replaceWith(_arr['hist'][i]['html']);
              } else {
                $('.track-order-state-history').append(_arr['hist'][i]['html']);
              }
              trackstack_notyplay = true;
            }
          }
          if(typeof newContentProcess == "function") newContentProcess(document);
        }

        if(data.push.cnt.notify > 0) {
          $('.js-notice-other').attr('data-active', data.push.cnt.notify).find('.massage_counter').html((data.push.cnt.notify > 10 ? '+' : data.push.cnt.notify)).show();
          if(data.push.cnt.notify > 10) {
            $('.js-notice-other .massage_counter').addClass('message_counter_warning');
          } else {
            $('.js-notice-other .massage_counter').removeClass('message_counter_warning');
          }
          $('.notify-number-block').html(data.push.cnt.notify).show();
          $('#foxNotifBox_none .empty-notice-data').hide();

          if(data.push.cntnew.notify > 0) {
            _arr = data.push.notify;
            for(i=0; i < _arr.length; i++) {
              $('#foxNotifBox_none').prepend(_arr[i]);
              //trackstack_notyplay = true;
            }
          }
        } else {
          $('.js-notice-other').attr('data-active', '0').find('.massage_counter').hide().removeClass('message_counter_warning');
          $('.notify-number-block').hide();
          $('#foxNotifBox_none').html(trackstack_cache['notify']);
        }

        if(IS_ACTIVE_DIALOG > 0) {
          _arr = data.push.message;

          if(_arr['msgs'].length > 0) {
            var msgresults = $('#msgresults'),
                msgresults_list = msgresults.find('.gig-reviews-list');
            if(msgresults.hasClass('islastpage')) {
              for(i=0; i < _arr['msgs'].length; i++) {
                  msgresults_list.append(_arr['msgs'][i]);
              }
              msgresults.stop().animate({
                  'scrollTop': msgresults.prop('scrollHeight')+1000
                }, 500, 'swing', function () {
              });
            } else {
              var newcntmsg = 0,
                  newcntmsgblock = $('div[data-newdialogmsg]').eq(0);
              newcntmsg = (newcntmsgblock.attr('data-newdialogmsg')-0) + _arr['msgs'].length;
              newcntmsgblock.attr('data-newdialogmsg', newcntmsg);
              newcntmsgblock.html((newcntmsg > 0 ? '<a href="' + newcntmsgblock.attr('data-lastmsgurl') + '">Есть новые сообщения (' + newcntmsg + ')</a>' : ''));
            }
            trackstack_notyplay = true;
          }
          if(_arr['chk_msg'].length > 0) {
            for(i=0; i < _arr['chk_msg'].length; i++) {
              $('.conversation-message.out.unread[data-mid="' + _arr['chk_msg'][i] + '"]').removeClass('unread');//.find('a[data-deletemsg]').remove();
            }
          }
        }

        var dslistchat = $('#dslistchat');
        if(dslistchat.length > 0) {
          dslistchat.find('.bold').removeClass('bold');
          dslistchat.find('.dialog-preview__new-count').remove();

          if(data.push.message.dialogs.length > 0) {
            _arr = data.push.message.dialogs;

            var tmpchatlink,
                forsupportpage = (dslistchat.attr('data-supportpage') == 'true');

            for(i=0; i < _arr.length; i++) {
              if((forsupportpage && _arr[i]['forsupportpage']) || (!forsupportpage && !_arr[i]['forsupportpage'])) {
                tmpchatlink = dslistchat.find('[data-dslistchat="' + _arr[i]['dialog'] + '"]');
                if(tmpchatlink.length > 0) {
                  tmpchatlink.remove();
                }
                dslistchat.prepend(_arr[i]['html']);
                //trackstack_notyplay = true;
              }
            }

          }
        }

        if(data.push.cnt.message > 0) {
          $('.js-notice-inbox').attr('data-active', data.push.cnt.message).find('.massage_counter').html((data.push.cnt.message > 10 ? '+' : data.push.cnt.message)).show();
          if(data.push.cnt.message > 10) {
            $('.js-notice-inbox .massage_counter').addClass('message_counter_warning');
          } else {
            $('.js-notice-inbox .massage_counter').removeClass('message_counter_warning');
          }
          $('#foxMessageBox_none').html('');
          $('.message-number-block').html(data.push.cnt.message).show();

          _arr = data.push.message.notify;
          for(i=0; i < _arr.length; i++) {
            $('#foxMessageBox_none').prepend(_arr[i]);
            //trackstack_notyplay = true;
          }
        } else {
          $('.js-notice-inbox').attr('data-active', '0').find('.massage_counter').hide();
          $('.message-number-block').hide();
          $('#foxMessageBox_none').html(trackstack_cache['message']);
        }
        trackstack_last_send = true;

        if(trackstack_notyplay && trackstack_notyplay_first) {
          ion.sound.play("incom_massage");
        } else if(!trackstack_notyplay_first) {
          trackstack_notyplay_first = true;
        }
      }
    }, 'json');
  }

  setTimeout(function() {
    if(trackstack_user_id != 0)
      cot_trackstack_update();
  }, 5000);
}

$(function() {
  trackstack_cache['notify'] = $('#foxNotifBox_none').html();
  trackstack_cache['message'] = $('#foxMessageBox_none').html();
  cot_trackstack_update();
});