(function(factory) {

  function requireElement(el, fn) {
    function waiting() {
      setTimeout(function () {
        var $el = $(el);
        if ($el.length) {
          fn($, $el);
        } else {
          waiting();
        }
      }, 500);
    }

    waiting();
  }

  $(function() {
    requireElement('#xlib-template__activate-email-message', factory);
  });

})(function($, $template) {

  var cookie = CookieReaderWriter();
  var showActivateEmailMessage = cookie.get('show_activate_email_message');

  if (showActivateEmailMessage) {
    var templateHTML = $template.html();
    $(templateHTML).simpleModal({});
    cookie.del('show_activate_email_message');
  }

});



;(function() {
    var _slice = Array.prototype.slice;

    function BlockEditList(blockName, blockEl) {
        this.blockName = blockName;
        this.$bl = $(blockEl);
        this.visibleControllers = false;
    }
    BlockEditList.blockSelectHtml = null;
    BlockEditList.allSectionConfig = null;

    BlockEditList.prototype.$el = function() {
        return this.$bl.find('.' + [this.blockName].concat(_slice.call(arguments, 0)).join('__'));
    };

    BlockEditList.prototype.showAppendBlockItem = function() {
        if (this.$el('block-item-change', 'select-block').length === 0) {
            this.$el('block-item-change', 'w-select-block').html(BlockEditList.blockSelectHtml);
        } else {
            this.$el('block-item-change', 'select-block').val('default');
        }
        this.$el('block-item-change', 'btn-apply').text('Добавить');
        this.$el('w-add-new-block').hide();
        this.$el('block-item-change').show();
        return this;
    };

    BlockEditList.prototype.hideAppendBlockItem = function() {
        this.$el('w-add-new-block').show();
        this.$el('block-item-change').hide();
        return this;
    };

    BlockEditList.prototype.showControllers = function() {
        var $el = this.$el('x-change');
        $el.show();
        this.visibleControllers = true;
    };

    BlockEditList.prototype.hideControllers = function() {
        var $el = this.$el('x-change');
        $el.hide();
        this.visibleControllers = false;
    };

    BlockEditList.prototype.addNewBlock = function() {
        var $selectBlock = this.$el('block-item-change', 'select-block');

        if ($selectBlock.val() !== 'default') {
            this.appendBlock({
                blockId: $selectBlock.val(),
                text: $selectBlock.find(':selected').text()
            });
        }
        return this;
    };

    BlockEditList.prototype.appendBlock = function(config) {
        var $item = $('<li data-blockId="' + config.blockId + '">' +
            '<div>' + config.text + '</div>' +
            '<div class="block-edit-list__x-change">' +
            '<button class="block-edit-list__move-item-btn block-edit-list__move-item-btn_direction_up">вверх</button>&nbsp;' +
            '<button class="block-edit-list__move-item-btn block-edit-list__move-item-btn_direction_down">вниз</button>&nbsp;' +
            '<button class="block-edit-list__remove-item-btn">Удалить</button>&nbsp;' +
            '</div></li>')
            .appendTo( this.$el('list') );

        if (this.visibleControllers) {
            $item.find('.block-edit-list__x-change').show();
        }

        this.bindBlockEvents($item);
    };

    BlockEditList.prototype.getUrl = function(action) {
        return location.protocol + '//' + location.host +
                '/api/sidebars.php?action=' + action + '&section=' + this.sectionName +
                '&role=' + this.roleName +
                '&column=' + this.columnName;
    };

    BlockEditList.prototype.applyChanges = function() {
        this.blocks = this.$el('list').find('li').map(function() {
            return $(this).attr('data-blockid');
        });

        $.post(this.getUrl('post'), {data: this.blocks}, function() {}, 'json');

        return this;
    };

    BlockEditList.prototype.setUpBlocks = function(blocks) {
        if (blocks) {
            this.blocks = blocks;
        }

        this.$el('list').html('');
        _(this.blocks).each(function(key) {
            var title = BlockEditList.blockTitles[key];
            this.appendBlock({
                blockId: key,
                text: title
            });
        }.bind(this), {});

        return this;
    };

    BlockEditList.prototype.loadBlocks = function() {
        $.get(this.getUrl('get'), function(res) {
            this.setUpBlocks(res.result);
        }.bind(this), 'json');

        return this;
    };

    BlockEditList.prototype.bindBlockEvents = function($block) {
        var self = this;
        console.log('blockblockEvents', $block.find('.block-edit-list__move-item-btn_direction_down').length);
        $block.find('.block-edit-list__move-item-btn_direction_up').click(function(event) {
            event.preventDefault();
            moveBlock.call($block, 'up');
        });
        $block.find('.block-edit-list__move-item-btn_direction_down').click(function(event) {
            event.preventDefault();
            moveBlock.call($block, 'down');
        });
        $block.find('.block-edit-list__remove-item-btn').click(function(event) {
            event.preventDefault();
            $block.remove();
        });

        function moveBlock(direction) {
            var $item = $(this);
            var $subling = direction === 'up' ? $item.prev() : $item.next();
            var $container = $item.parent();
            if (direction === 'up') {
                $item.insertBefore($subling);
            } else {
                $item.insertAfter($subling);
            }
        }

        return this;
    };

    BlockEditList.prototype.bindEvents = function() {
        var self = this;
        this.$el('bnt-cancel').click(function(event) {
            event.preventDefault();
            self.setUpBlocks();
            self.hideControllers();
            self.$el('change-link').show();
        });
        this.$el('add-new-block').click(function(event) {
            event.preventDefault();
            self.showAppendBlockItem();
        });
        this.$el('block-item-change', 'btn-cancel').click(function(event) {
            event.preventDefault();
            self.hideAppendBlockItem();

        });
        this.$el('block-item-change', 'btn-apply').click(function(event) {
            event.preventDefault();
            self.addNewBlock()
                .hideAppendBlockItem();
        });
        this.$el('change-link').click(function(event) {
            event.preventDefault();
            self.showControllers();
            $(this).hide();
        });
        this.$el('bnt-apply-changes').click(function(event) {
            event.preventDefault();
            self.applyChanges();
            self.hideControllers();
            self.$el('change-link').show();
        });

        $('#sidebar-settings-form__section').change(function() {
            self.hideControllers();
            self.$el('change-link').show();
            self.sectionName = $(this).val();
            self.loadBlocks();
        });

        $('#sidebar-settings-form__roles').change(function() {
            self.hideControllers();
            self.$el('change-link').show();
            self.roleName = $(this).val();
            self.loadBlocks();
        });


        return this;
    };

    BlockEditList.loadSection = function(sectionName, roleName) {
        _([
            {
                element: '#block-edit-list__sidebar_position_left',
                columnName: 'left'
            },
            {
                element: '#block-edit-list__sidebar_position_right',
                columnName: 'right'
            }
        ]).each(function(sidebar) {
            var blockEditList = new BlockEditList("block-edit-list", sidebar.element);
            blockEditList.bindEvents();
            blockEditList.sectionName = sectionName;
            blockEditList.roleName = roleName;
            blockEditList.columnName = sidebar.columnName;
            blockEditList.loadBlocks();
        });


    };

    window.BlockEditList = BlockEditList;

})();



// переключение между разделами

$(function() {

  $('.chapter-nav').bind('xlib-bem:loaded', function() {
    var $nav = $(this);
    bindEvents($nav);
  });

  function bindEvents($nav) {
    var $content = $nav.find('.chapter-nav__content');

    $nav.find('.chapter-nav__header__item').click(function(ev) {
      ev.preventDefault();

      // select content
      var chapterName = $(this).attr('data-chapter_name');
      selectChapter(chapterName, $nav, $content);
    });
  }

  function selectChapter(chapterName, $nav, $content) {
    $nav.find('.chapter-nav__header__item')
      .removeClass('chapter-nav__header__item_active');

    $nav.find('.chapter-nav__header__item_' + chapterName)
      .addClass('chapter-nav__header__item_active');

    $content = $content || $nav.find('.chapter-nav__content');
    $content.find('.chapter-nav__content__item').hide();
    $content.find('.chapter-nav__content__item_' + chapterName).show();
  }

});


$(function() {
  window.activeChaptor = null;

  var $timeline = $('.timeline');

  function changeChapter(name) {
    $('.user-nav__notify-counter')
        .removeClass('user-nav__notify-counter_hover');

    if (window.activeChaptor === name) {
      $timeline
          .trigger('timeline:toggle', this);
      window.activeChaptor = null;
    } else if (window.activeChaptor !== null) {

      $timeline
          .trigger('timeline:show-chapter', name);
      $(this).toggleClass('user-nav__notify-counter_hover');
      window.activeChaptor = name;
    } else {

      $timeline
          .trigger('timeline:toggle', this)
          .trigger('timeline:show-chapter', name);

      $(this).toggleClass('user-nav__notify-counter_hover');
      window.activeChaptor = name;
    }
  }

  $('.user-nav__notify-counter_timeline').click(function(event) {
    event.preventDefault();
    event.stopPropagation();

    changeChapter.call(this, 'notifications');

  });

  $('.user-nav__notify-counter_chat').click(function(event) {
    event.preventDefault();
    event.stopPropagation();

    changeChapter.call(this, 'chat');

  });

});


;(function(factory) {

  $(function() {
    factory($);
  });

})(function($) {
  "use strict";

  function sendVerifyEmail(status, fn) {
    $.get('/a/r.php?action=verify_email&id=' + window.AUTH_USER_ID + (status ? '&status=1' : ''),
        {},
        function(res) {
          if (!res.status) {
            return alert('Ошибка запроса!');
          }

          (fn || function() {})(res);
        }, 'json');
  }

  function resendVerifyEmail() {
      $.get('/a/r.php?action=resend&ajax=1&id=' + window.AUTH_USER_ID,
          {},
          function(res) {
            if (!res.status) {
              return alert('Ошибка запроса!');
            }

            alert(res.message);
          },
          'json'
      );
    }

  var $eventElement = $('body');

  function getStartupModalState() {
    return window.VEFIRY_EMAIL_FORM__MODAL_STATUS;
  }

  function getUserData() {
    return window.VEFIRY_EMAIL_FORM__USER_DATA;
  }

  var bindModalPageEvents = {
    "proposal": function() {
      $('.modal').find('.header-nav__verify-email-form__submit-btn').click(function(ev) {
        ev.preventDefault();
        sendVerifyEmail(false, function(res) {
          alert(res.message);
          $('body').trigger('verify-email-form:goto-page', 'check-mailbox');
        });
      });
    },
    "check-mailbox": function() {
      $('.modal').find('.header-nav__verify-email-form__resend-email-btn').click(function(ev) {
        ev.preventDefault();
        resendVerifyEmail();
      });
    }
  };

  function showModal(state) {
    var template = $('#xlib-template__header-nav__verify-email-form_state_' + state).html();
    var $content = $(attachDataToTemplate(template, getUserData()));
    $content.simpleModal({
      beforeShow: bindModalPageEvents[state]
    });
  }

  $eventElement.bind('verify-email-form:show', function() {
    var state = getStartupModalState();
    showModal(state);
  });

  $eventElement.bind('verify-email-form:goto-page', function(ev, state) {
    showModal(state);
  });


  $eventElement.trigger('verify-email-form:init');
});



;(function($) {

  $(function() {
    var $verifyEmailNotify = $('.header-nav__verify-email-notify__close');
    $verifyEmailNotify.click(function(ev) {
      ev.preventDefault();
      _closest(this, 'header-nav__verify-email-notify').remove();
    });

    function sendVerifyEmail(status, fn) {
      var $text = $('.header-nav__verify-email-notify__text');
      $.get('/a/r.php?action=verify_email&id=' + window.AUTH_USER_ID + (status ? '&status=1' : ''),
          {},
          function(res) {
            if (!res.status) {
              return alert('Ошибка запроса!');
            }

            var sendStatus = res.send_status;
            if (sendStatus === 'verify_code_send') {
              $('.header-nav__verify-email-notify__controls').hide();
              $('.header-nav__verify-email-notify__resend-controls').show();
            } else if (sendStatus === 'verify_status_not_send') {
              $('.header-nav__verify-email-notify__controls').show();
              $('.header-nav__verify-email-notify__resend-controls').hide();
            } else if (sendStatus === 'verify_code_ok') {
              $('.header-nav__verify-email-notify__controls').hide();
              $('.header-nav__verify-email-notify__resend-controls').hide();
            }

            $text.text(res.message);
            (fn || function() {})();
          }, 'json');
    }

    var $applyBtn = $('.header-nav__verify-email-notify__apply-btn');
    $applyBtn.click(function(ev) {
      ev.preventDefault();
      sendVerifyEmail(false, function() {});
    });

    function resendVerifyEmail() {
      $.get('/a/r.php?action=resend&ajax=1&id=' + window.AUTH_USER_ID,
          {},
          function(res) {
            if (!res.status) {
              return alert('Ошибка запроса!');
            }

            alert(res.message);
          },
          'json'
      );
    }

    var $resendBtn = $('.header-nav__verify-email-notify__resend-btn');
    $resendBtn.click(function(ev) {
      ev.preventDefault();
      resendVerifyEmail();
    });

    /* if (window.AUTH_USER_ID) {
      sendVerifyEmail(true, function () {
        $('.header-nav__verify-email-notify').show();

      });
    } */
  });

})(jQuery);




$(function() {

    var coo = CookieReaderWriter();

    var $bar = $('.user-nav');
    var $doc = $(document);
    var $positionSaver = $('.position-saver');
    var $searchNav = $('.search-nav');
    var $background = $('.nav-bg');

    var $showMenu = $('.nav-show-menu');

    var showMenuVisible = true;

    var visible = coo.get('topMenuFixedDisabled') === 'false';
/*
    $(document).scroll(function() {
        if (visible) {
            documentScrollHandler();
        } else {
            if (showMenuVisible) {
                if ($doc.scrollTop() < $positionSaver[0].offsetTop) {
                    $showMenu.css({'display': 'none'});
                    showMenuVisible = false;
                }
            } else {
                if ($bar[0].offsetTop < $doc.scrollTop()) {
                    $showMenu.css({'display': 'block'});
                    showMenuVisible = true;
                }
            }
        }
    });*/

    function documentScrollHandler() {
        if ($bar[0].offsetTop < $doc.scrollTop()){
            showFixedPanel();
        }
        if ($doc.scrollTop() < $positionSaver[0].offsetTop){
            hideFixedPanel();
        }
    }

    function showFixedPanel() {
      $bar.css({
        'position': "fixed"
      });
      $searchNav.css({
        'margin-left': 76
      });
      $background.css({
        'top': 0
      });
    }
    function hideFixedPanel() {
      $bar.css({
        'position': "static"
      });
      $searchNav.css({
        'margin-left': 0
      });
      $background.css({
        'top': -74
      });
    }/*

    $('.nav-bg__close').click(function(ev) {
        ev.preventDefault();

        hideFixedPanel();

        $showMenu.css({'display': 'block'});
        showMenuVisible = true;

        coo.set('topMenuFixedDisabled', "true", 999999);
        visible = false;
    });

    $('.nav-bg__open').click(function(ev) {
        ev.preventDefault();

        coo.set('topMenuFixedDisabled', "false", 999999);
        documentScrollHandler();

        $showMenu.css({'display': 'none'});
        showMenuVisible = false;

        visible = true;
    });*/

    window.userNav = new BemBlock('.user-nav');

    $('body').click(function(ev) {
       $('.user-nav__item_type_dropdown_dd-panel_opened').trigger('click');
    });

    userNav.bind('dd-panel', 'click', function(ev) {
        ev.stopPropagation();
    });

    userNav.bind('item', {'type': 'dropdown'}, 'click', function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        var curr = this;

        $('.user-nav__item_type_dropdown_dd-panel_opened').each(function() {
            if (this === curr) return;
            $(this).trigger('click');
        });

        var $t = $(this);
        var originState = $t.hasClass('dd-opened') ? 'opened' : 'closed';
        var arrowDirect = originState === 'opened' ? 'down' : 'up';

        $t.toggleClass('dd-opened');
        $t.toggleClass('user-nav__item_type_dropdown_dd-panel_opened');
        BemBlock.findElemFrom(this, 'dd-panel').toggle();
        BemBlock.findElemFrom(this, 'dropdown')
            .css({
                'background-image': 'url(/images/icon_22345/icon_22345_12x_' + arrowDirect + '.svg)'
            });

        if (originState === 'opened') {
            $t.css({
               'background-color': '#fff'
            });
        } else {
            $t.css({
               'background-color': '#f6f6f6'
            });
        }
    });

    $('.search-nav')
      .bind('search-nav:hide', function() {
        $(this).hide();
      })
      .bind('search-nav:show', function() {
        $(this).show();
      });

    $('.search-panel input[type="text"]')
            .focus(function(ev) {
                if ($(this).val() === 'Поиск') {
                    $(this).val('')
                        .css({'color': '#464646'});
                }
            })
            .blur(function(ev) {
                if ($(this).val() === '') {
                    $(this).val('Поиск')
                        .css({'color': '#999'});
                }
            });

    $('.user-nav__item_type_dropdown').each(function() {
        var $t = $(this);
        $t.find('.user-nav__dd-panel')
                .css('min-width', $t.outerWidth() - 30);
    });

});




$(function() {


});



$(function() {
  $('.idea-form__info__detail-lnk').click(function(ev) {
    ev.preventDefault();

    var $info = _closest(this, 'idea-form__w-info')
      .find('.idea-form__info');

    if ($info.attr('data-opened')) {
      $(this).text('Подробнее');
      $info
        .css({'height': '126px'})
        .removeAttr('data-opened')
      ;
    } else {
      $(this).text('Скрыть');
      $info
        .css({'height': 'auto'})
        .attr('data-opened', '1')
      ;
    }
  });
});





window.ideaItem__approveBtn__bindEvents = function($item) {
  $item.find('.unset-winner-btn, .set-winner-btn').click(function(ev) {
    ev.preventDefault();
    ev.stopPropagation();

    var $t = $(this);
    var data = {};
    data.rating = {};
    data.rating[$t.attr('data-idea_id')] = $t.hasClass('unset-winner-btn') ? 10 : 20;
    // data.custom_reject_reason = {};
    // data.custom_reject_reason[$t.attr('data-idea_id')] = '';
    data.status = {};
    data.status[$t.attr('data-idea_id')] = $t.hasClass('set-winner-btn') ? 2 : 1;

    $('.ideas-container__over').show();
    $.post(
      '/moderators/process.php?task_id=' + $t.attr('data-task_id') + '&action=ideas',
      data,
      function() {
        window.reloadIdeas(function() {});
        $('.timeline__item_status_active .timeline__item__first-line').click().click()
      }
    );



  });

};



window.ideaItem__comments__bindEvents = (function() {


  return function ($ideaItem) {

    $ideaItem.find('.idea-item__submit-comment').click(function(ev) {
      ev.preventDefault();

      // closest imitation for jQuery1.4
      var $parent = _closest(this, 'idea-item__content');
      if ($parent.length === 0) {
        $parent = _closest(this, 'idea-item__details-card');
      }

      var idea_id = parseInt($(this).attr('data-idea_id'), 10);
      var $textarea =$(this).parent().find('textarea:eq(0)');

      $parent.find('.idea-item__comments__empty-message').remove();
      $( '<span class="idea-item__comments__waiting-message">Подождите...</span>' )
          .appendTo( $parent.find('.idea-item__comments') );

      $.post('/api/idea_comments.php', {
          action: 'add',
          idea_id: idea_id,
          content: $textarea.val()
      }, function(res) {
          if (!res.status) {
              var $errContainer = $parent.find('.idea-item__w-new-comment');
              var $errItem = $errContainer.find('.idea-item__comment-error');

              if ($errItem.length) {
                  $errItem.html(errMsg);
              } else {
                  $( '<div class="idea-item__comment-error">'+errMsg+'</div>' )
                      .appendTo($errContainer);
              }

              return ;

          }

          $parent.find('.idea-item__comments__empty-message').remove();
          $parent.find('.idea-item__comments__waiting-message').remove();
          var $commentCount = $parent.find('.idea-item__comment-count');
          var num = parseInt($commentCount.first().text(), 10);
          $commentCount.text(num + 1);
          $(renderComment(res.result))
              .appendTo( $parent.find('.idea-item__comments') );
          $textarea.val('');

      })


    });

    $ideaItem.find('.idea-item__update-comments').click(function(ev) {
      ev.preventDefault();

      // closest imitation for jQuery1.4
      var $parent = _closest(this, 'idea-item__details-card');

      var $discussion = $parent.find('.idea-item__w-discussion');
      var $comments   = $parent.find('.idea-item__comments');

      /*if ($discussion.is(':visible')) {
          $discussion.hide();
          return ;
      }*/

      var idea_id = parseInt($(this).attr('data-idea_id'), 10);

      $comments
          .html('<span class="idea-item__comments__waiting-message">Подождите, идет загрузка...</span>');
      $discussion.show();

      $.get('/api/idea_comments.php', {action: 'list', 'idea_id': idea_id}, function(res) {

          if (!res.status) {
              $discussion
                  .html(errMsg)
                  .show();
              return ;

          }

          if (res.result.length === 0) {
              $comments.html('<span class="idea-item__comments__empty-message">Комментариев к идее нет</span>');
              $discussion.show();
              return ;
          }

          $parent.find('.idea-item__comments__empty-message').remove();
          $parent.find('.idea-item__comments__waiting-message').remove();
          $comments
              .find('.idea-item__comment-item__line')
              .remove();
          appendComments($parent, res.result);

      }, 'json');

    });

    var commentTemplate = $('#xlib-template__idea-item__comment').html();

    function appendComments($parent, comments) {
      comments.forEach(function(item) {
              $(renderComment(item))
                  .appendTo( $parent.find('.idea-item__comments') )
          });
    }

    var dateFormat = window.ruDateFormat;

    function renderComment(data) {
      data.created_date = dateFormat(data.created_date);

      if (window.AUTH_USER_IS_CURATOR && window.AUTH_USER_ID !== +data.comment_author_id) {
        if (+data.comment_author_id === +data.idea_author_id) {
          data.user_alias = 'автор';
        }
      }

      return attachDataToTemplate(commentTemplate, data);
    }

  };



})();




window.ideaItem__domains__bindEvents = (function() {

  return function($ideaItem) {

    var domainZoneTemplate = $('#xlib-template__whois-panel__zone-list__item').html();
    var zoneListItemTemplate = $('#xlib-template__whois-panel__domain-list__item').html();

    $ideaItem.find('.w-whois-panel')
        .bind('idea-item:edit-start', function() {
            $(this).css('display', 'inline-block');
        })
        .bind('idea-item:edit-cancel', function() {
            if ($(this).find('.whois-panel__zone-list__item__text').length <= 1) {
                $(this).css('display', 'none');
            }
        })
    ;

    function checkDomain(fn) {
        var $parent = _closest(this, 'whois-panel');
        $parent.find('.whois-panel__status')
            .html('Подождите, идет проверка ...')
            .show()
        ;

        var errMsg = 'Ошибка запроса!';
        $.post('/api/idea_domain.php', {
                action: 'check_and_add',
                idea_id: parseInt(_closest(this, 'idea-item').attr('data-idea_id'), 10),
                domain: $parent.find('.whois-panel__input').val(),
                zones: [$parent.find('.whois-panel__domain-zone-select').val()]
            }, function(res) {
                if (!res.status)  {
                    $parent.find('.whois-panel__status')
                        .html(res.error || errMsg);
                    return ;
                }

                fn(res.result);
            }, 'json');
    }


    $ideaItem.find('.whois-panel__zone-list__item__button_add').click(function(ev) {
        ev.preventDefault();

        var $input = $(this).parent().find('.whois-panel__input');
        var domain = $input.val();
        if (domain.length < 2) {
            return ;
        }

        var $panel = _closest(this, 'whois-panel');
        checkDomain.call(this, function(domains) {
            addDomains($panel, domains);
            $input.val('');
        });
    });

    function addDomains($panel, domains, edit) {
        $panel.find('.whois-panel__status').html('').hide();

        var item = null;
        for(var domain in domains) {
            item = domains[domain];

            var $newItem = $(attachDataToTemplate(domainZoneTemplate, {
                domain: item.domain,
                domain_id: item.domain_id,
                status_text: item.is_unknown ? 'неизвестен' :
                            (item.is_free ? 'свободен' : 'занят'),
                status_color: item.is_unknown ? 'gray' :
                            (item.is_free ? 'green' : 'red'),
                close_style: edit ? 'style="display: none"' : ''
            }));
            zoneListItem__bindEvents($newItem);

            $newItem.insertBefore( $panel.find('.whois-panel__zone-list__item_add-zone') );

        }
    }

    $ideaItem.find('.whois-panel').each(function() {
        addDomains($(this), (window.DOMAINS || {})[parseInt($(this).attr('data-idea_id'), 10)], true);
    });


    $ideaItem.find('.whois-panel__add-domain-zone-input').keyup(function(ev) {
        ev.preventDefault();
        if (ev.keyCode == 13) {
            $ideaItem.find('.whois-panel__zone-list__item__button_add').click();
        }
    });

    function zoneListItem__bindEvents($item) {

        $item.find('.whois-panel__zone-list__item__button_remove').click(function(ev) {
            ev.preventDefault();

            var ideaId = parseInt(_closest(this, 'idea-item').attr('data-idea_id'), 10);
            if (!isNaN(ideaId)) {
                $.post('/api/idea_domain.php', {
                    action: 'remove_domain',
                    domain: $(this).parent().find('.whois-panel__zone-list__item__text').text(),
                    idea_id: ideaId
                });
            }
            $(this).parent().remove();
        });


    }
  };


})();



// редактирование идеи

window.ideaItem__edit__bindEvents = (function() {

  return function($ideaItem) {

    $ideaItem.find('.idea-item__edit__reject-reason__select').change(function(ev) {
      var $editForm = _closest(this, 'idea-item__edit');
      var $customRejectReason = $editForm.find('.idea-item__reject-reason__textarea');
      $customRejectReason.val('');
    });

    $ideaItem.find('.idea-item__edit__save').click(function(ev) {
      ev.preventDefault();
      ev.stopPropagation();

      var $t = $(this);
      var $editForm = _closest(this, 'idea-item__edit');
      var $select = $editForm.find('.idea-item__edit__status-select');
      var status = $select.find(':selected').attr('data-value');
      var statusCode = $select.val();

      var ideaId = $t.attr('data-idea_id');

      var data = {};

      data.status = {};
      data.status[ideaId] = statusCode;

      data.rating = {};
      data.rating[ideaId] = 0;

      data.reject_reason = {};
      data.custom_reject_reason = {};

      if (status === 'rejected') {
        var $rejectReason = $editForm.find('.idea-item__edit__reject-reason__select');
        var rejectReasonMessage = $rejectReason.find(':selected').val();
        data.reject_reason[ideaId] = rejectReasonMessage;
        data.custom_reject_reason[ideaId] = rejectReasonMessage;
        if (rejectReasonMessage.replace(/(^\s+|\s+$)/g, '') === '') {
          var $customRejectReason = $editForm.find('.idea-item__reject-reason__textarea');
          data.custom_reject_reason[ideaId] = $customRejectReason.val();
        }
      }

      if (status === 'active') {
        data.rating[ideaId] = $editForm.find('.idea-item__edit__rating-input').val();
      }


      $.post(
        '/moderators/process.php?task_id=' + $t.attr('data-task_id') + '&action=ideas',
        data,
        function() {
          if (window.ideaItem__edit__saveAndContinue) {
            window.ideaItem__edit__saveAndContinue = false;

            var $row = _closest($t[0], 'idea-row');
            window.reloadOneIdea($row, function() {
              var step = 1;
              window.ideaItem__nav__transition($row, step);
            });
          } else {
            window.reloadIdeas(function() {
            });
            $('.timeline__item_status_active .timeline__item__first-line').click().click();
          }
        }
      );
    });

    $ideaItem.find('.idea-item__edit__next-idea-link').click(function(ev) {
      ev.preventDefault();
      window.ideaItem__nav__transition(_closest(this, 'idea-row'), 1);
    });

    $ideaItem.find('.idea-item__edit__save-and-next').click(function(ev) {
      ev.preventDefault();
      window.ideaItem__edit__saveAndContinue = true;
      _closest(this, 'idea-item').find('.idea-item__edit__save').click();
    });


    $ideaItem.find('.idea-item__edit__change-rating').click(function(ev) {
      ev.preventDefault();

      var $rating = _closest(this, 'idea-item__edit__rating');
      var $ratingWInput = $rating.find('.idea-item__edit__w-rating-input');
      var $ratingInput = $rating.find('.idea-item__edit__rating-input');
      var $ratingValue = $rating.find('.idea-item__edit__rating-value');
      $ratingInput.val($ratingValue.text());
      $ratingWInput.show();
      $ratingValue.hide();
      $(this).hide();
    });

    function resetRating($itemEdit) {
      var $ratingWInput = $itemEdit.find('.idea-item__edit__w-rating-input');
      var $ratingInput = $itemEdit.find('.idea-item__edit__rating-input');
      var $ratingValue = $itemEdit.find('.idea-item__edit__rating-value');
      $ratingValue.text($ratingInput.val());
      $ratingWInput.hide();
      $ratingValue.show();
      $itemEdit.find('.idea-item__edit__change-rating').show();
    }

    $ideaItem.find('.idea-item__edit__status-select').change(function() {

      var $select = $(this);
      var $itemEdit = _closest(this, 'idea-item__edit');
      var ideaStatus = $select.find(':selected').attr('data-value');

      resetRating($itemEdit);

      switch (ideaStatus) {
        case IDEA_STATUSES.NOT_ACTIVE:
          $itemEdit.find('.idea-item__edit__reject-reason').hide();
          $itemEdit.find('.idea-item__edit__custom-reject-reason').hide();
          $itemEdit.find('.idea-item__edit__rating').hide();

          break;
        case IDEA_STATUSES.REJECTED:
          $itemEdit.find('.idea-item__edit__reject-reason').show();
          $itemEdit.find('.idea-item__edit__custom-reject-reason').show();
          $itemEdit.find('.idea-item__edit__rating').hide();

          break;
        case IDEA_STATUSES.ACCEPTED:
        case IDEA_STATUSES.ACTIVE:
          $itemEdit.find('.idea-item__edit__reject-reason').hide();
          $itemEdit.find('.idea-item__edit__custom-reject-reason').hide();
          $itemEdit.find('.idea-item__edit__rating').show();

          // если текущий статус идеи неактивирована и ее рейтинг равен нулю
          // то устанавливаем стандартный рейтинг для активированной идеи = 5

          var $ratingInput = $itemEdit.find('.idea-item__edit__rating-input');
          var $ratingValue = $itemEdit.find('.idea-item__edit__rating-value');

          if ($ratingValue.text() === '0') {
            $ratingValue.text(5);
            $ratingInput.val(5);
          } else {
          }

          break;
      }

    });

  };

})();


window.ideaItem__files__update = function(ideaId, files, $ctx) {
  var $list = $ctx || $('#idea-item-' + ideaId).find('.idea-item__files');
  if ($list.children().length > 0) return ;

  files.forEach(function(file, index) {
    var data = {
      number: index + 1,
      name: file.title

    };
    var fileItemTemplate = $('#xlib-template__idea-item__files__item').html();
    var $newItem = $(attachDataToTemplate(fileItemTemplate, data));
    $newItem.attr('data-file_id', file.file_id);
    $newItem.find('.idea-item__files__item__name').attr('href', '/' + file.link);
    fileItem__bindEvents($newItem);
    $newItem.appendTo($list);
  });
};

window.fileItem__bindEvents = function ($fileItem) {
  $fileItem.find('.idea-item__files__item__control-link_delete').click(function(ev) {
    ev.preventDefault();
    var $ideaItem = _closest(this, 'idea-item');
    var ideaId = parseInt($ideaItem.attr('data-idea_id'), 10);
    var taskId = parseInt($ideaItem.attr('data-task_id'), 10);
    var fileId = parseInt($fileItem.attr('data-file_id'), 10);

    $.post(
      '/authors/_idea.php?action=detach_file&' + (isNaN(ideaId) ? '' : ('idea_id=' + ideaId)) + '&task_id=' + taskId + '&file_id=' + fileId,
      {},
      function() {
        $fileItem.remove();
      },
      'json'
    )
  })
};

window.ideaItem__files__bindEvents = (function() {
  return function($ideaItem) {

    var fileItemTemplate = $('#xlib-template__idea-item__files__item').html();
    var $button = $ideaItem.find('.idea-item__files__upload-btn').click(function(ev) {
      ev.preventDefault();
      var $file = $(this).parent().find(':file');
      $file.click();
    });

    $ideaItem.find('.idea-item__files')
      .bind('idea-item:edit-start', function() {
        var $this = $(this);
        $this.parent().show();
        $this.find('.idea-item__files__item__controls').css('display', 'inline');
        $this.parent().find('.idea-item__files__upload').show();

      })

      .bind('idea-item:edit-cancel', function() {
        var $this = $(this);
        if ($this.find('.idea-item__files__item').length === 0) {
          $this.parent().hide();
        }
        $this.find('.idea-item__files__item__controls').css('display', 'none');
        $this.parent().find('.idea-item__files__upload').hide();
      });

    if (window.IdeaAttachFiles) {
      $.each(window.IdeaAttachFiles, window.ideaItem__files__update);

    }

    $ideaItem.find('.idea-item__files__upload :file').change(function(ev) {
      var $parent = _closest(this, 'idea-item__w-files');
      var $list = $parent.find('.idea-item__files');

      var data = {
        number: $list.find('.idea-item__files__item').length + 1,
        name: $(this).val()
      };

      var $newItem = $(attachDataToTemplate(fileItemTemplate, data));
      $newItem.find('.idea-item__files__item__preloader').show();
      $newItem.find('.idea-item__files__item__controls').hide();
      $button.css('disable', 'disable');
      fileItem__bindEvents($newItem);
      $newItem.appendTo($list);

      upload($(this), _closest(this, 'idea-item'), {
        complete: function(res) {
          $newItem.find('.idea-item__files__item__preloader').hide();
          $newItem.find('.idea-item__files__item__controls').css('display', 'inline');
          $button.css('disable', '');
          $newItem.attr('data-file_id', res.result.file_id);
          $newItem.find('.idea-item__files__item__name').attr('href', '/' + res.result.link);
        },
        error: function() {
          $newItem.find('.idea-item__files__item__preloader').text('Ошибка загрузки файла!');
        },
        progress: function(e) {
          if(e.lengthComputable) {
            $newItem.find('.idea-item__files__item__preloader-percents')
                .text((Math.ceil(e.loaded / e.total) * 100).toString() + '%');
          }
        }
      });

    });

    function upload($file, $ideaItem, handlers) {
      var dummy = function() {};
      handlers = $.extend({
        complete: dummy,
        error: dummy,
        progress: dummy
      }, handlers);

      var ideaId = parseInt($ideaItem.attr('data-idea_id'), 10);
      var taskId = parseInt($ideaItem.attr('data-task_id'), 10);

      var formData = new FormData();
      formData.append('new_attach', $file[0].files[0]);

      ajaxFileUpload(
        '/authors/_idea.php?' + (isNaN(ideaId) ? '' : ('idea_id=' + ideaId + '&')) + 'task_id=' + taskId,
        formData,
        handlers.complete,
        handlers.error,
        handlers.progress
      );
    }

    function ajaxFileUpload(url, formData, onSuccess, onError, onProgress) {
      var xhr = new XMLHttpRequest();
      xhr.onload = xhr.onerror = function() {
        if(this.status != 200 || JSON.parse(this.responseText).status != true) {
          onError(this);
          return;
        }
        onSuccess(JSON.parse(this.responseText));
      };


      xhr.upload.onprogress = onProgress;
      xhr.open("POST", url, true);
      xhr.send(formData);

    }
  };

})();







window.ideaItem__tags__bindEvents = (function() {
  return function($ideaItem) {
    bindTagItemEvents($ideaItem.find('.idea-item__tags__item'));

    function bindTagItemEvents($items) {
        $items
           .click(function(ev) {

               var $this = $(this);
               if ($this.hasClass('editable')) {
                   var attachAction = $this.hasClass('idea-item__tags__item_not_selected') ?
                            'attach' : 'remove_attach';

                   var $tags = _closest(this, 'idea-item__tags');
                   var ideaId = parseInt($tags.attr('data-idea_id'), 10);

                   function actionHandler() {
                       $this.toggleClass('idea-item__tags__item_selected');
                       $this.toggleClass('idea-item__tags__item_not_selected');
                   }

                   if (isNaN(ideaId)) {
                       actionHandler();
                   } else {
                       $.post('/api/tags.php?entity=idea&action=' + attachAction, {
                            idea_id: ideaId,
                           tag_id: parseInt($this.attr('data-tag_id'), 10)
                       }, function(res) {
                           if (!res) return ;
                           actionHandler();
                       });
                   }

               }

           });
    }


    $ideaItem.find('.idea-item__tags')
        .bind('idea-item:edit-start', function() {
            $(this).parent().show();
            $(this).find('.idea-item__tags__item').addClass('editable');
            $(this).find('.idea-item__tags__item_not_selected').show();
            $(this).find('.idea-item__tags__add').show();
        })
        .bind('idea-item:edit-cancel', function() {
            $(this).find('.idea-item__tags__item').removeClass('editable');
            $(this).find('.idea-item__tags__item_not_selected').hide();
            $(this).find('.idea-item__tags__add').hide();

            if ($(this).find('.idea-item__tags__item_selected').length === 0) {
                $(this).parent().hide();
            }

        })
    ;

    var tagItemTemplate = $('#xlib-template__idea-item__tags__item').html();
    $ideaItem.find('.idea-item__tags__add__button').click(function(ev) {
        ev.preventDefault();

        var $tags = _closest(this, 'idea-item__tags');
        var $input = $tags.find('.idea-item__tags__add__input');
        var newTag = $input.val();

        if (newTag.replace(/\s+/g, '').length === 0) {
            return;
        }

        var ideaId = parseInt($(this).attr('data-idea_id'), 10);

        function addTagHandler() {
            var html = attachDataToTemplate(tagItemTemplate, {
                tag: newTag
            });
            $input.val('');
            var $newTagItem = $(html);
            $newTagItem.insertBefore($tags.find('.idea-item__tags__add'));
            bindTagItemEvents($newTagItem);
        }

        if (isNaN(ideaId)) {
            addTagHandler();
        } else {
            $.post('/api/tags.php?entity=idea&action=add', {
                idea_id: ideaId,
                tag: newTag
            }, function(res) {
                if (!res || !res.status) return ;
                addTagHandler();
            });
        }

    });
    $ideaItem.find('.idea-item__tags__add__input').keypress(function(ev) {
        if (ev.keyCode === 13) {
            var $tags = _closest(this, 'idea-item__tags');
            $tags.find('.idea-item__tags__add__button').trigger('click');
        }
    });
  };


})();


    /**
     * show attached files
     */
    window.showAttachedFiles = function(appendToList) {

        $(this).find('.idea-item__w-files').each (function() {
            var $wFiles = $(this);
            try {
                var files = $wFiles.attr('data-file');
                files = JSON.parse(files);
                var ideaId = $wFiles.attr('data-idea_id');

                console.log(ideaId, files);
                appendToList = typeof appendToList === 'undefined' ? true : appendToList;
                if (appendToList) {
                    window.IdeaAttachFiles[ideaId] = files;
                } else {
                    console.log(ideaId, files);
                    window.ideaItem__files__update(ideaId, files, $(this).find('.idea-item__files'));
                }
            } catch(e) { console.log(e) }
        });
    };


    function ideaItem__bindEvents($item) {
        var classes = {
            dynamic: 'idea-item__reject-reason',
            dynamicEdit: 'idea-item__reject-reason__dynamic-edit',
            dynamicShow: 'idea-item__reject-reason__dynamic-show'
        };

        $item.find('.idea-item__reject-reason textarea')
            .resizableTextarea({ setUpHandlers: true, classes: classes });

        $item.find('.idea-item__remove-btn').click(function (ev) {
            ev.preventDefault();

            var $this = $(this);
            var $ideaItem = _closest(this, 'idea-item');
            if (confirm("Вы действительно хотите удалить идею?")) {
                var taskId = parseInt(_closest(this, 'idea-list').attr('data-task_id'), 10);
                var ideaId = parseInt($ideaItem.attr('data-idea_id'), 10);

                $ideaItem.find('.idea-item__details__overlay').show();
                $.post('/authors/_idea.php?task_id=' + taskId + '&idea_id=' + ideaId, {
                    action: 'remove_idea'
                }, function (res) {
                    if (!res || !res.status) {
                        alert('Произошла ошибка! Пожалуйста, обратитесь в службу поддержки для устранения неисправности (support@e-generator.ru).');
                        return;
                    }

                    // идея успешно удалена

                    $ideaItem.find('.idea-item__details__overlay').hide();
                    _closest($ideaItem[0], 'idea-row').remove();

                }, 'json');
            }
        });

        $item.find('.idea-item__relative-ideas__update-button').click(function(ev) {
            ev.preventDefault();

            var $parent = _closest(this, 'idea-item__relative-ideas');
            var $ideaItem = _closest(this, 'idea-item');
            var $text = $ideaItem.find('.idea-form__idea-text[name=idea]');
            var taskId = $parent.attr('data-taskid');
            var ideaId = parseInt( $parent.attr('data-ideaid'), 10);

            var message = {
                text: $text.val(),
                order: 'desc',
                limit: 50,
                idea_id: ideaId
                // task_id: taskId
            };

            $parent.find('.idea-item__relative-ideas__update-status')
                .text('Подождите, идет запрос ...')
                .show();

            $.get('/api/relative_ideas.php', message, function(res) {
                if (!res.status) {
                    $parent.find('.idea-item__relative-ideas__update-status')
                        .text('Произошла ошибка');
                }

                $parent.find('.idea-item__relative-ideas__update-status')
                    .text('')
                    .hide();

                var sumScore = res.result.matches.reduce(function(sum, m) {
                    return sum + parseFloat(m.score);
                }, 0);
                var averageScore = res.result.matches.length === 0 ? 0 :
                    sumScore / res.result.matches.length;

                $parent.find('.idea-item__relative-ideas__count').text(res.result.score);
                $parent.find('.idea-item__relative-ideas__percent')
                    .text(averageScore.toFixed(2));

            }, 'json');
        });

        $item.find('.idea-item__unburned-checkbox').change(function(ev) {
            ev.preventDefault();

            var $this = $(this);
            var $parent = _closest(this, 'idea-item');
            var $marker = $parent.find('.idea-item__info__unburned');
            var $taskId = parseInt($this.attr('task_number'), 10);
            var $ideaId = parseInt($this.attr('idea_number'), 10);
            var $unburned_value = 0;

            if ($this.is(':checked')) {
                $marker.css('display', 'inline-block');
                $unburned_value = 1;
            } else {
                $marker.css('display', 'none');
                $unburned_value = 0;
            }

            var data = {
                action: 'unburned_idea',
                idea_id: $ideaId,
                unburned_id: $ideaId,
                status: 'rejected',
                unburned_value: $unburned_value
            };

            $.ajax({
                type: 'GET',
                url: '/authors/_idea.php?task_id=' + $taskId,
                data: data,
                success: function(res) {
                    if (res === 'success') {
                        location.reload();
                        return;
                    }
                },
                error: function(jqXHR) {
                    try {
                        var json = JSON.parse(jqXHR.responseText);
                        errorHandler(json);
                    } catch (e) {
                        errorHandler();
                    }
                },
                dataType: 'text'
            });
        });

        // Добавление новой идеи
        $item.find('.idea-item__details-card__send-new-idea-button').click(function(ev) {
            ev.preventDefault();

            var $ideaItem = _closest(this, 'idea-item');
            var taskId = parseInt($ideaItem.attr('data-task_id'), 10);

            var tags = $ideaItem.find('.idea-item__tags > .idea-item__tags__item_selected')
                .map(function() {
                    return $(this).text().replace(/^\s+|\s+$/, '');
                }).toArray();

            var domains = $ideaItem.find('.whois-panel__zone-list > .whois-panel__zone-list__item')
                .map(function() {
                    return parseInt($(this).attr('data-domain_id'), 10);
                })
                .filter(function() {
                    return !isNaN(this);
                })
                .toArray();

            var files = $ideaItem.find('.idea-item__files__item')
                .map(function() {
                    return parseInt($(this).attr('data-file_id'), 10);
                })
                .filter(function() {
                    return !isNaN(this);
                })
                .toArray();

            var data = {
                idea: $ideaItem.find('.idea-form__textarea[name=idea]').val(),
                comment: $ideaItem.find('.idea-form__textarea[name=comment]').val(),
                tags: tags,
                domains: domains,
                files: files
            };

            $ideaItem.find('.idea-item__details__overlay').show();

            function errorHandler(json) {
              var message = (!json) ? null :
                  (json.error_layer === 'app' ? json.error : null);

              $ideaItem.find('.idea-item__details__overlay').hide();
              message = message || 'Ошибка запроса! Обратитесь в службу поддержки для устранения неисправности';
              alert(message);
            }

            $.ajax({
              type: 'POST',
              url: '/authors/_idea.php?task_id=' + taskId,
              data: data,
              success: function(res) {
                  if (!res || !res.status) {
                    errorHandler(res);
                    return ;
                  }

                  if (res.result.numOfAvailableIdeas <= 0) {
                      var new_idea_editor = document.getElementsByClassName('idea-item')[0];
                      new_idea_editor.innerHTML = "<h4>Вы исчерпали Ваш лимит, на подачу идей.</h4>";
                  }

                  fetchAndAddIdeaToList(res, $ideaItem, function() {
                    window.showAttachedFiles.call(this);

                    // hide overlay
                    $ideaItem.find('.idea-item__details__overlay').hide();

                    // success notify
                    ideaItem__bindEvents($(this));
                  });
                  clearIdeaForm($ideaItem);

                  IdeaFilter__incAllScores();
                  var ideaStatus = parseInt(res.result.status, 10);
                  if (ideaStatus === 3) {
                      IdeaFilter__incRejectedScores();
                  } else {
                      IdeaFilter__incNotActiveScores();
                  }
              },
              error: function(jqXHR) {
                try {
                    //debugger;
                  var json = JSON.parse(jqXHR.responseText);
                  errorHandler(json);
                } catch (e) {
                  errorHandler();
                }
              },
              dataType: 'json'
            });

        });

        $item.find('.idea-item__details-card__save-button').click(function(ev) {
            ev.preventDefault();

            var $ideaItem = _closest(this, 'idea-item');
            var status    = $ideaItem.attr('data-idea_status');
            switch (status) {
                case IDEA_STATUSES.NOT_ACTIVE:
                    // Если идея не активирована, то автор имеет право ее изменить.
                    saveButtonHandler.call(this);
                    break;
                case IDEA_STATUSES.ACTIVE:
                    // Если идея активирована, то автор имеет право ее изменить,
                    // НО при этом статус идеи перейдет в неактивированный о чем появится предупреждение.
                    $(this).parent().find('[type=button]').hide();
                    $ideaItem.find('.idea-item__details-card__save-active-warning').show();
                    break;
            }
        });

        $item.find('.idea-item__details-card__save-active-warning__yes').click(function(ev) {
            ev.preventDefault();

            var $ideaItem = _closest(this, 'idea-item');
            saveButtonHandler.call(
                $ideaItem.find('.idea-item__details-card__save-button')[0],
                function(res) {
                    $ideaItem.find('.idea-item__details-card__editor-buttons [type=button]').show();
                    $ideaItem.find('.idea-item__details-card__save-active-warning').hide();
                }
            );
        });

        $item.find('.idea-item__details-card__save-active-warning__no').click(function(ev) {
            ev.preventDefault();

            var $ideaItem = _closest(this, 'idea-item');
            $ideaItem.find('.idea-item__details-card__cancel-button').trigger('click');
            $ideaItem.find('.idea-item__details-card__editor-buttons [type=button]').show();
            $ideaItem.find('.idea-item__details-card__save-active-warning').hide();
        });

        $item.find('.idea-item__details-card__cancel-button').click(function(ev) {
            ev.preventDefault();

            var $ideaItem = _closest(this, 'idea-item');
            var $parent = $ideaItem.find('.idea-item__dynamic-container');
            $parent.find('.idea-item__dynamic_edit').each(function() {
                // closest imitation for jQuery1.4
                var $parent = _closest(this, 'idea-item__dynamic');

                $parent.find('.idea-item__dynamic_show').show();
                $(this).hide();
            });

            $parent.find('.idea-item__toggle-edit').hide();

            $parent.find('.idea-item__edit-mode').hide();

            var $container = _closest(this, 'idea-item__details-card__controller-container');
            $container.find('.idea-item__details-card__controller-buttons').show();
            $container.find('.idea-item__details-card__editor-buttons').hide();

            $ideaItem.find('.idea-item__tags, .w-whois-panel')
                .trigger('idea-item:edit-cancel');

            $ideaItem.find('.idea-item__files').trigger('idea-item:edit-cancel');


        });

        var classes = {
          dynamic: 'idea-item__dynamic',
          dynamicEdit: 'idea-item__dynamic_edit',
          dynamicShow: 'idea-item__dynamic_show'
        };

        $item.find('.idea-item__dynamic_edit textarea').resizableTextarea({ setUpHandlers: true, classes: classes });

        $item.find('.idea-item__edit-button').click(function(ev) {
            ev.preventDefault();
            var $ideaItem = _closest(this, 'idea-item');
            var $parent = $ideaItem.find('.idea-item__dynamic-container');

            $parent.find('.idea-item__dynamic_edit textarea').resizableTextarea({ showEditor: true, classes: classes });

            $parent.find('.idea-item__toggle-edit').show();
            $parent.find('.idea-item__edit-mode').show();

            var $container = _closest(this, 'idea-item__details-card__controller-container');
            $container.find('.idea-item__details-card__controller-buttons').hide();
            $container.find('.idea-item__details-card__editor-buttons').show();

            $ideaItem.find('.idea-item__tags, .w-whois-panel ')
                .trigger('idea-item:edit-start');

            $ideaItem.find('.idea-item__files').trigger('idea-item:edit-start');

        });

        var errMsg = 'Ошибка запроса! Пожалуйста, обратитесь в службу поддержки сайта для устранения неисправности (support@e-generator.ru)';

        $item.find('.idea-item__hide-new-idea').click(function(ev) {
            ev.preventDefault();

            $('.idea-row__new-item').hide();
            $('.new-idea-link').show();
        });

        $item.find('.idea-item__nav').click(function(ev) {
          ev.preventDefault();

          var $nav = $(this);
          var $row = _closest(this, 'idea-row');
          var step = $nav.hasClass('idea-item__nav_next') ? 1 : -1;
          window.ideaItem__nav__transition($row, step);
        });

      window.ideaItem__nav__transition = function($row, step) {
        var $list = $row.parent();
        var $items = $list.children('.idea-row');
        var rowIndex = $items.index($row);

        var newRowIndex = rowIndex + step;
        if (newRowIndex < 0 || newRowIndex >= $items.length) {
          return false;
        }

        $('.idea-list .idea-item__details:visible .idea-item__hide-details').click();

        var $nextRow = $list.find('.idea-row:eq(' + newRowIndex + ')');
        $nextRow.find('.idea-item__first-line').click();
        window.scrollTo(0, $(document).scrollTop() + step * parseInt($row.css('height'), 10));

        return true;
      };

        $item.find('.idea-item__hide-details').click(function(ev) {
            ev.preventDefault();

            // closest imitation for jQuery1.4
            var $parent = _closest(this, 'idea-item__content');
            $parent.find('.idea-item__details').hide();
            $parent.find('.idea-item__first-line').show();
        });

        $item.find('.idea-item__first-line').click(function(ev) {
            ev.preventDefault();

            $(this).removeClass('idea-item__first-line_unread');

            // closest imitation for jQuery1.4
            var $parent = _closest(this, 'idea-item__content');
            $parent.find('.idea-item__details').show();
            $parent.find('.idea-item__first-line').hide();

            $parent.find('.idea-item__update-comments').click();
        });


        ideaItem__approveBtn__bindEvents($item);
        ideaItem__comments__bindEvents($item);
        ideaItem__domains__bindEvents($item);
        ideaItem__files__bindEvents($item);
        ideaItem__tags__bindEvents($item);
        ideaItem__edit__bindEvents($item);
        ideaRatings__bindEvents();

    }  // ideaItem__bindEvents


    function IdeaFilter__incScore($cell) {
      $cell = $cell.find('.ideas-filter__item__count');
      $cell.text(parseInt($cell.text(), 10) + 1);
    }

    function IdeaFilter__incAllScores() {
        IdeaFilter__incScore($('.ideas-filter__item_status_all'));
    }

    function IdeaFilter__incNotActiveScores() {
        IdeaFilter__incScore($('.ideas-filter__item_status_notactive'));
    }

    function IdeaFilter__incRejectedScores() {
        IdeaFilter__incScore($('.ideas-filter__item_status_rejected'));
    }


    // добавление идеи в список идей
    function fetchAndAddIdeaToList(res, $ideaItem, fn) {
      var taskId = parseInt($ideaItem.attr('data-task_id'), 10);
      var resource = '/authors/_idea.php?task_id={task_id}&idea_id={idea_id}&mode=list_item .idea-row'
          .replace('{task_id}', taskId)
          .replace('{idea_id}', res.result.idea_id);

      $('<div></div>').load(resource, function(jqXHR) {
        var $newItem = $(this).children(':eq(0)');
        $newItem
          .css({display: 'none'})
          .prependTo($('.idea-list'))
          .slideDown(function() {
            $newItem.css('display', 'list-item');
          });
        fn.call($newItem);
      });
    }

    // очистка формы идеи
    function clearIdeaForm($ideaItem) {
        $ideaItem.find('.idea-form__w-textarea textarea').val('')
            .each(function() {
                var lh = $(this).css('line-height');
                $(this).css('height', '40px');
            });
        $ideaItem.find('.whois-panel__input whois-panel__add-domain-zone-input').val('');
        $ideaItem.find('.idea-item__tags__add__input').val('');
        $ideaItem.find('.idea-item__relative-ideas__count').html('?');
        $ideaItem.find('.idea-item__relative-ideas__percent').html('?');
        $ideaItem.find('.idea-item__tags .idea-item__tags__item')
            .filter(':not([data-tag_id])')
            .remove();

        $ideaItem.find('.whois-panel__zone-list > .whois-panel__zone-list__item[data-domain_id]').remove();

        $ideaItem.find('.idea-item__files > .idea-item__files__item').remove();
    }


    function saveButtonHandler(fn) {
        var $ideaItem = _closest(this, 'idea-item');
        var $parent = $ideaItem.find('.idea-item__dynamic-container');
        var taskId = parseInt(_closest(this, 'idea-list').attr('data-task_id'), 10);
        var ideaId = parseInt(_closest(this, 'idea-item').attr('data-idea_id'), 10);
        var ideaIdem = this;

        $ideaItem.find('.idea-item__details__overlay').show();

        $.post(
            '/authors/_idea.php?task_id=' + taskId + '&idea_id=' + ideaId,
            {
                idea: $ideaItem.find('[name=idea]').val(),
                comment: $ideaItem.find('[name=comment]').val()
            },
            function(res) {
                $ideaItem.find('.idea-item__details__overlay').hide();

                if (!res || !res.status) {
                    alert('Ошибка запроса! Обратитесь в службу поддержки для устранения неисправности');
                    return;
                }

                var ideaOriginText = $ideaItem.find('[name=idea]').val();
                var ideaPreparedText = ideaOriginText
                    .replace(/^\s+|\s+$/g, '')
                    .replace(/\n/g, '\n<br />');

                $ideaItem.find('.idea-item__first-line-text').text(ideaPreparedText);

                $parent.find('.idea-item__dynamic_edit').each(function() {
                    var $parent = _closest(this, 'idea-item__dynamic');

                    var $textarea = $(this).find('textarea');
                    $parent.find('.idea-item__dynamic_show')
                        .html($textarea.val()
                            .replace(/^\s+|\s+$/g, '')
                            .replace(/\n/g, '\n<br />')
                        )
                        .show();



                    $(this).hide();
                });

                $parent.find('.idea-item__toggle-edit').hide();

                $parent.find('.idea-item__edit-mode').hide();

                var $container = _closest(ideaIdem, 'idea-item__details-card__controller-container');
                $container.find('.idea-item__details-card__controller-buttons').show();
                $container.find('.idea-item__details-card__editor-buttons').hide();

                $ideaItem.find('.idea-item__tags, .w-whois-panel')
                    .trigger('idea-item:edit-cancel');

                $ideaItem.find('.idea-item__files').trigger('idea-item:edit-cancel');

                (fn || function() {}).call(ideaIdem, res);
            },
            'json'
        )
    }


$(function() {

    ideaItem__bindEvents($('body'));


      $('body').keydown(function(ev) {
        var ARROW_KEYS = {
          RIGHT: 39,
          LEFT: 37
        };

        if (ev.ctrlKey) {
          if ($(this).find('.idea-list').length &&
            (ev.keyCode === ARROW_KEYS.LEFT || ev.keyCode === ARROW_KEYS.RIGHT)) {
            window.ideaItem__nav__transition(
              _closest($('.idea-item__details:visible')[0], 'idea-row'),
              ev.keyCode === ARROW_KEYS.LEFT ? -1 : 1
            );
          }
        }

      });


});




$(function() {
    var r = $('#client_rating');
    r.change(function() {
      if ($(this).val() === '-') return ;
      var status = window.getCurStatus();
      var filter = window.IDEAS_Filters[status];
      var rating = $(this).val();
      filter.filter.rating = rating === 'a' ? '' : (+rating + 5);

      var filterStatus = window.getCurFilterStatus();
      $('.ideas-filter').trigger('ideas-filter:set-' + filterStatus)
    });

});




window.ideaRatings__bindEvents = function() {

    $('.make-rating').mouseout(function() {
      IdeaRatingStars.setUpOrigin($(this));
    });

    $('.make-rating .make-rating__item_active')

      .mouseover(function() {
        var $cur = $(this);
        IdeaRatingStars.setUntil($cur);
        IdeaRatingStars.clearFrom($cur.next());
      })

      .click(function(ev) {
        ev.preventDefault();
        ev.stopPropagation();

        var $t = $(this);
        var $p = $t.parent();

        var $ideaItem = _closest(this, 'idea-item');
        var status = $ideaItem.attr('data-idea_status');

        if (status === 'accepted') return false;

        var ideaId = parseInt($p.attr('data-idea_id'), 10);
        var rating = parseInt($t.attr('data-val'), 10);
        if (isNaN(rating)) return;

        var $rating = _closest(this, 'make-rating');

        if ($ideaItem.length === 0) {
          $ideaItem = _closest($rating[0], 'idea-item__details-card');
        }

        $ideaItem.find('.make-rating').each(function() {
          IdeaRatingStars.setUpOrigin($(this), rating);
        });

        $.post('/api/client_idea_rating.php?action=set', {
          'idea_id': ideaId,
          'rating': rating
        }, function(res) {
          if (!res.status) return ;
          $ideaItem.find('.idea-item__rating-val')
              .html(rating + 5);
          if ((rating + 5) === 10) {
            $ideaItem.find('.idea-item__approve-btn').css('display', 'inline-block');
          } else {
            $ideaItem.find('.idea-item__approve-btn').hide();
          }
        }.bind(this), 'json');
    });

};

$(function() {

  window.ideaRatings__bindEvents();

});

window.IdeaRatingStars = {};

window.IdeaRatingStars.setUpOrigin = function($rating, ratingVal) {
  if (typeof ratingVal !== 'undefined') {
    $rating.attr('data-origin_val', ratingVal);
  } else {
    ratingVal = parseInt($rating.attr('data-origin_val'), 10);
  }

  var $el = $rating.find('.make-rating__item')
      .removeClass('make-rating__item_marked');

  this.setUntil($el.eq(ratingVal));
};

window.IdeaRatingStars.setUntil = function(el) {
  while (el.length > 0) {
      el.addClass('make-rating__item_marked');
      el = el.prev();
  }
};

window.IdeaRatingStars.clearFrom = function(el) {
  while (el.length > 0) {
      el.removeClass('make-rating__item_marked');
      el = el.next();
  }
};




$(function() {
  $('.idea-form__search-btn').click(function(ev) {
    ev.preventDefault();

    var $input = $('.idea-form__search-input');

    var status = getCurStatus();
    var filter = window.IDEAS_Filters[status];
    filter.idea_id = $input.val();
    $('.ideas-container__over').show();
    $('.idea-form .w-ideas-container-outer')
      .load('/authors/_idea.php?' + $.param(filter) + ' .w-ideas-container', function() {
        $('.ideas-container__over').hide();
        ideaItem__bindEvents($('.idea-item'));
        ideasPagination__bindEvents();
        ideasPagination__setUp();
      });

  });

});


$(function() {


  window.IDEAS_Filters = {

  };

  function createBaseFilter(status, taskId) {
    var filter = {
      action: 'show_status_list',
      task_id: taskId,
      order_by: [{
        direction: 'ASC'
      }],
      limit: 25,
      offset: 0
    };

    filter.filter = {};

    if (status !== 'status-all') {
      filter.filter.status = status;
    }

    return filter;
  }

  var initIdeasFilters = function(taskId) {
      _.each(['status-all', 'not_active', 'active', 'rejected', 'unburned'], function(status) {
      window.IDEAS_Filters[status] = createBaseFilter(status, taskId);
    });
  };

  var $list = $('.idea-list');
  initIdeasFilters(parseInt($list.attr('data-task_id'), 10));

  function changeExportToExcelLink(status) {
    var $c = $('.w-ideas-filter__export-excel');
    if (status === 'status-all' && !window.AUTH_USER_IS_AUTHOR) {
      $c.css('display', 'none');
    } else {
      $c.find('.ideas-filter__link_export-excel')
        .attr('href', (function() {
          var url = window.AUTH_USER_IS_AUTHOR ?
            '/authors/_idea.php?task_id={task_id}&status={status}&version=excel' :
            '/moderators/ideas.php?task_id={task_id}&state={status}&version=excel';
          return url
            .replace('{status}', status === 'status-all' ? 'all' : status)
            .replace('{task_id}', window.CURRENT_TASK_ID);
        })());

      $c.css('display', 'inline-block');
    }
  }

  changeExportToExcelLink(getCurStatus());

  function getChangeFilterStatusHandler(status) {

    return (window.AUTH_USER_IS_AUTHOR) ?

      function() {
        var $list = $('.idea-list');
        if (status === 'status-all') {
            $list.find('.idea-row').show();
        } else {
            if (status === 'active') {
                $list.find('.idea-row_status_accepted').show();
                $list.find('.idea-row_status_active').show();
                $list.find('.idea-row:not(.idea-row_status_accepted):not(.idea-row_status_active)').hide();
            } else {
                $list.find('.idea-row_status_' + status).show();
                $list.find('.idea-row:not(.idea-row_status_' + status + ')').hide();
            }
        }
        changeExportToExcelLink(status);
      } :

      function() {
        var filter =  window.IDEAS_Filters[status];
        $('.ideas-container__over').show();
        $('.idea-form .w-ideas-container-outer')
          .load('/authors/_idea.php?' + $.param(filter) + ' .w-ideas-container', function() {
            $('.ideas-container__over').hide();
            ideaItem__bindEvents($('.idea-item'));
            ideasPagination__bindEvents();
            ideasPagination__setUp();
          });
        changeExportToExcelLink(status);
      };

  }

  $('.ideas-filter')
      .bind('ideas-filter:set-status_all', getChangeFilterStatusHandler('status-all'))
      .bind('ideas-filter:set-notactive', getChangeFilterStatusHandler('not_active'))
      .bind('ideas-filter:set-active', getChangeFilterStatusHandler('active'))
      .bind('ideas-filter:set-rejected', getChangeFilterStatusHandler('rejected'))
      .bind('ideas-filter:set-unburned', getChangeFilterStatusHandler('unburned'))
  ;

  routie({
      'status_notactive': function() {
          $('.ideas-filter__item_status_notactive').trigger('click');
      },
      'status_active': function() {
          $('.ideas-filter__item_status_active').trigger('click');
      },
      'status_rejected': function() {
          $('.ideas-filter__item_status_rejected').trigger('click');
      },
      'idea-:ideaId': function(ideaId) {
          $('#idea-item-' + ideaId).find('.idea-item__first-line').click();
      }
  });

});





window.getCurStatus = function () {
  var status = getCurFilterStatus();

  if (status === 'status_all') status = 'status-all';
  if (status === 'notactive') status = 'not_active';

  return status;
};

window.getCurFilterStatus = function () {
  var $filter = $('.ideas-filter');
  var $activeFilterItem = $filter.find('.ideas-filter__item_active');
  return $activeFilterItem.attr('data-status');
};

window.reloadOneIdea = function($row, success) {
  $row.find('.idea-row__over').show();
  var $item = $row.find('.idea-item');
  var uri = '/authors/_idea.php?task_id=' + $item.attr('data-task_id') +
    '&idea_id=' + $item.attr('data-idea_id') +
    '&mode=list_item';
  $row
    .load(uri + ' .idea-item', function() {
      success.call(this);
      $row.find('.idea-item__over').hide();
      ideaItem__bindEvents($row.find('.idea-item'));
    });
};
window.loadIdeas = function(filter, success) {
  $('.ideas-container__over').show();
  $('.idea-form .ideas-container')
    .load('/authors/_idea.php?' + $.param(filter) + ' .ideas-container>form', function() {
      success.call(this);
      $('.ideas-container__over').hide();

      var $items = $('.idea-item');
      window.showAttachedFiles.call($items, true);
      ideaItem__bindEvents($items);
    });
};

window.reloadIdeas = function(fn) {
  var status = getCurStatus();
  if (!status) return ;
  loadIdeas(window.IDEAS_Filters[status], fn);
};

$(function() {



  window.ideasPagination__bindEvents = function() {

    $('.idea-form__only-unread-btn').click(function(ev) {
      ev.preventDefault();

      console.log('click');

      $(this).toggleClass('sc-button-selected');
      var hideMethod = $(this).hasClass('sc-button-selected');

      $('.idea-list').find('.idea-item__first-line').each(function() {
        if (!$(this).hasClass('idea-item__first-line_unread')) {
          var $item = _closest(this, 'idea-item');
          if ($item) $item[hideMethod ? 'hide' : 'show'].call($item);
        }
      });
    });

    $('.ideas-load-more__anchor').click(function(ev) {
      ev.preventDefault();

      var status = getCurStatus();
      var $parent = _closest(this, 'ideas-load-more');
      $parent.find('.ideas-load-more__over').show();

      var filter =  window.IDEAS_Filters[status];
      filter.limit += 25;
      loadIdeas(filter, function() {
        $parent.find('.ideas-load-more__over').hide();
      });
    });

    $('.ideas-pagination__item').click(function(ev) {
      ev.preventDefault();

      var $item = $(this);
      var $date = $item.find('.ideas-pagination__date');
      var status = getCurStatus();
      var filter =  window.IDEAS_Filters[status];

      filter.date = $date.attr('data-date_add');
      filter.limit = 100;
      filter.offset = 0;

      var $parent = _closest(this, 'ideas-pagination');
      loadIdeas(filter, function() {
        $parent
          .find('.ideas-pagination__pages__item_active')
          .removeClass('ideas-pagination__pages__item_active');

        $parent
          .find('.ideas-pagination__date_active')
          .removeClass('ideas-pagination__date_active');

        $item.addClass('ideas-pagination__date_active');

        $item.find('.ideas-pagination__pages__item:first')
             .addClass('ideas-pagination__pages__item_active');
      });
    });

    $('.ideas-pagination__pages__item').click(function(ev) {
      ev.preventDefault();
      ev.stopPropagation();

      var $page = $(this);
      var pageVal = parseInt($page.text(), 10);

      var $item = _closest(this, 'ideas-pagination__item');
      var $date = $item.find('.ideas-pagination__date');

      if (isNaN(pageVal)) return ;

      pageVal -= 1;

      var status = getCurStatus();
      var filter =  window.IDEAS_Filters[status];

      filter.date = $date.attr('data-date_add');
      filter.limit = 100;
      filter.offset = 100 * pageVal;

      var $parent = _closest(this, 'ideas-pagination');
      loadIdeas(filter, function() {
        $parent
          .find('.ideas-pagination__pages__item_active')
          .removeClass('ideas-pagination__pages__item_active');

        $parent
          .find('.ideas-pagination__date_active')
          .removeClass('ideas-pagination__date_active');

        $item.addClass('ideas-pagination__date_active');
        $page.addClass('ideas-pagination__pages__item_active');
      });
    });
  };

  window.ideasPagination__setUp = function() {
    var status = getCurStatus();
    var filter = window.IDEAS_Filters[status];

    if (filter.date) {
      $('.ideas-pagination')

        .find('.ideas-pagination__date[data-date_add="' + filter.date + '"]')
        .parent()
        .addClass('ideas-pagination__date_active')

        .find('.ideas-pagination__pages__item[data-page="' + Math.ceil(filter.offset / 100) +  '"]')
        .addClass('ideas-pagination__pages__item_active')
      ;
    }
  };

  window.ideasPagination__bindEvents();

});



$(function() {
});



(function() {

  window.notificationMethodType = 'humane';

  function requireNotify(fn) {
    function waiting() {
      setTimeout(function () {
        if (window.Notify) {
          fn();
        } else {
          waiting();
        }
      }, 500);
    }

    waiting();
  }

  requireNotify(function() {
    if (!Notify.isSupported) {
        return;
    }

    if (Notification.permission === 'granted') {
      window.notificationMethodType = 'native';
      return ;
    }

    if (Notification.permission !== 'denied') {
      Notify.requestPermission(function () {
        window.notificationMethodType = 'native';
      });
    }
  });

  window.alert = function(text) {
    window.notify.error(text);
  };

  function nativeNotify(text, description, options) {

    var myNotification = new Notify('Е-генератор', _.extend({
      body: description || text,
      timeout: 5
    }, options));

    myNotification.show();
  }

  function humaneNotify(text, description, options) {
    if (description) {
      text = [text, description];
    }
    humane.timeout = 4500;
    humane.log(text, { addnCls: 'humane-flatty-' + options.eventType });
  }

  var method = {
    native: nativeNotify,
    humane: humaneNotify
  };

  var _notify = function(text, description, options) {
    var methodType = options.methodType || (Notify.isSupported ? 'native' : 'humane');
    return method[methodType].apply(null, arguments);
  };

  window.notify = {};
  ['info', 'success', 'error'].forEach(function(name) {
    window.notify[name] =  function(text, description, options) {
      options = options || {};
      options.methodType = window.notificationMethodType; // <--- жестко указываем тип натификации
      return _notify.call(this, text, description, $.extend(options, {eventType: name}));
    };
  });

})();


"use strict";

(function($) {

  $(function() {
    $('.timeline__details').bind('personal-messages:render', renderHandler);

    var newMessageTemplate = $('#xlib-template__personal-messages').html();

    var messageDateFormat = dateFormatCreator({
      onlyTime: true,
      seconds: true
    });

    var dateDelimTemplate = $('#xlib-template__timeline__item_chat-date').html();

    function renderHandler(ev, data) {
      var messages = data.messages;
      var $details = $(this);
      var $list = $details.find('.personal-messages__list');

      var html = [];
      messages.forEach(function(message) {
        var removeControls = parseInt(message.deleted, 10) === 1 ||
            window.AUTH_USER_ID !== parseInt(message.user_id, 10);
        message.remove_visible = removeControls ? 'display: none' : '';
        message.origin_created_date = message.timestamp;
        message.date_created = messageDateFormat(message.origin_created_date);

        if (parseInt(message.deleted, 10) === 1) {
          message.body = '<span style="font-size: 11px; font-weight: bold;">сообщение удалено</span>';
        }
      });

      messages = window.addDateDelims(messages);

      messages.forEach(function(message) {
        if (message.event_type === 'chat_date') {
          html.push(attachDataToTemplate(dateDelimTemplate, message));
        } else {
          html.push(attachDataToTemplate(
            newMessageTemplate,
            messageRequest(message)
          ));
        }
      });

      $list.html(html.join(''));

      bindEvents.call(this);
    }

    var room;

    function joinToRoom(threadId) {
      room = PMIO.join(threadId);
    }

    function newMessageHandler(ev, res) {
      console.log('newMessageHandler', res);
      res.remove_visible = 'display: none';
      renderMessage($(this).find('.personal-messages__list'), res);
    }



    function messageRequest(threadId, body, options) {
      options = options || {};
      if (typeof threadId === 'object') {
        options = threadId;
        threadId = options.thread_id;
        body = options.body;
      }
      return $.extend({
        body: body,
        user_alias: window.AUTH_USER_ALIAS,
        date_created: messageDateFormat(new Date),
        mid: '',
        thread_id: threadId,
        remove_visible: ''
      }, options);
    }

    function renderMessage($list, data) {
      var html = attachDataToTemplate(newMessageTemplate, data);
      var $newItem = $(html)
        .hide()
        .appendTo($list)
        .slideDown()
      ;

      $newItem.find('.personal-messages__control__delete').attr('data-mid', data.mid);
      $newItem.find('.personal-messages__control__delete').attr('data-thread_id', data.thread_id);
      personalMessages__item__bindEvents($newItem);

      return $newItem;
    }

    function personalMessages__item__bindEvents($item) {
      $item.find('.personal-messages__control__delete').click(function(ev) {
        ev.preventDefault();
        var threadId = $(this).attr('data-thread_id');
        var mid = $(this).attr('data-mid');
        $.post('/navapp.php?do=PM:Delete&action=thread&_json_response=1', { id: threadId, msgs: mid },
            function() {
              removeMessageHandler.call(this);
              room.remove({ thread_id: threadId, mid: mid });
            }.bind(this), 'json');
      });
    }

    function removeMessageHandler() {
      var $message = _closest(this, 'personal-messages__item');
      $message.find('.personal-messages__item__text')
        .html('<span style="font-size: 11px; font-weight: bold;">сообщение удалено</span>');
      $message.find('.personal-messages__control__delete').remove();
    }

    function bindEvents() {
      var classes = {
          dynamic: 'personal-messages__reply',
          dynamicEdit: 'personal-messages__dynamic-edit',
          dynamicShow: 'personal-messages__dynamic-show'
      };

      var $messages = $(this).find('.personal-messages')
        .bind('personal-messages:new-message', newMessageHandler)
        .bind('personal-messages:remove-message', function(ev, res) {
            var $item = $(this).find('#personal-messages__item_' + res.mid);
            removeMessageHandler.call($item);
          })
      ;

      var threadId = parseInt($messages.attr('data-thread_id'), 10);
      if (isNaN(threadId)) {
        console.log('unknown threadId');
      }
      joinToRoom(threadId);

      $(this).find('.personal-messages__reply textarea').resizableTextarea({ setUpHandlers: true, classes: classes });

      $(this).find('.personal-messages__reply__submit').click(function(ev) {
        ev.preventDefault();

        var $reply = _closest(this, 'personal-messages__reply');
        var $textarea = $reply.find('.personal-messages__reply__textarea');

        var $messages = _closest($reply[0], 'personal-messages');
        var $list = $messages.find('.personal-messages__list');


        var threadId = parseInt($messages.attr('data-thread_id'), 10);
        var messageBody = $textarea.val();

        $.post('/navapp.php?do=PM:Message', { msg: messageBody, thread: threadId, _json_response: true },
            handler.bind(this), 'json');
        $textarea.val('');

        function handler(res) {
          var messageReq = messageRequest(threadId, messageBody);
          var messageData = $.extend(messageReq, res.result);
          renderMessage($list, messageData);
          room.send(messageData);
        }
      });

      personalMessages__item__bindEvents($(this));
    }

  });

})(jQuery);


$(function () {
    $('.search-for-ideas-in-tasks__search-button').click(function (ev) {
        ev.preventDefault();

        var $input = $('.search-for-ideas-in-tasks__search-field');

        var input_text = $input.val();
        var encoded_search_text = encodeURIComponent(input_text);
        var task_id = parseInt($input.attr('data-task_id'), 10);
        var action_type = 'search-for-ideas-in-tasks';

        /* Всплывающее модальное окно. Используется при уведомлениях на сайте. Используется AS IS */
        var $details = $('.timeline__details');

        var detailsWidth = 785;
        $details.css({
            'width': detailsWidth
        });
        $details.parent().show();

        function createGlue($window, $modal, options) {
            return {
                size: {
                    height: function heightResize() {
                        var height = $window.height();

                        $modal.css({
                            height: height - parseInt($modal.css('top')) - options.margin.bottom

                        });
                    }
                },
                position: {
                    horizontal: {
                        center: function () {
                            var width = $window.width() - options.margin.right;
                            var modalWidth = parseInt($modal.css('width'));
                            $modal.css({
                                left: (width - modalWidth) / 2
                            });
                        }
                    }
                }

            };
        }

        var $window = $(window);
        var glue = createGlue($window, $details, {
            margin: {
                bottom: 20,
                right: 365
            }
        });

        function resizeDetails() {
            glue.size.height();
            glue.position.horizontal.center();
            $details.find('.timeline__details__w-content').nanoScroller();
        }

        $window.bind('resize', resizeDetails);
        resizeDetails();

        $('<div>Подождите...</div>')
            .css({'text-align': 'center', 'margin-top': '10px'})
            .appendTo($details.find('.timeline__details__content').html(''));
        $details.show();


        var resource = (function () {
            return '/authors/_idea.php?task_id={task_id}&action={action_type}&encoded_search_text={encoded_search_text} .idea-item__details-card'
                .replace('{task_id}', task_id)
                .replace('{action_type}', action_type)
                .replace('{encoded_search_text}', encoded_search_text);
        })();

        var $inner = $details.find('.timeline__details__content');

        var loadedHandler = function (responseText, textStatus, req) {
            if (textStatus == "error") {
                if (responseText.indexOf('idea')) {
                    if (responseText.indexOf('not found') >= 0) {
                        $inner.html('<div style="padding: 14px; text-align: center; color:red">Идея не найдена. Либо, возможно, ранее она была удалена</div>');
                    }
                }

                return;
            }

            if (responseText.length == 0) {
                $inner.html('<div style="padding: 14px; text-align: center; color:red">Идея не найдена. Либо, возможно, ранее она была удалена</div>');
            }

            $inner.find('.idea-item__details-card__controller-buttons').hide();
            var $ideaDetailsCard = $inner.find('.idea-item__details-card');
            if ($ideaDetailsCard.length) {
                window.showAttachedFiles.call($ideaDetailsCard, false);
                ideaItem__bindEvents($ideaDetailsCard);
            }
            $('.timeline__details .idea-item__update-comments').trigger('click');

            $(".timeline__details .nano").nanoScroller();
        };


        $inner.load(resource, loadedHandler);

        $('.timeline__details__close').click(function () {
            hideDetailPanel($details);
        });


    });
});


;(function(factory) {
  $(function() {
    factory($);
  });
})(function($) {
  "use strict";

  var $block = $('.settings-email');
  $('.settings-email__toggle-lnk').click(function(ev) {
    ev.preventDefault();
    var templateHtml = $('#xlib-template_settings-email').html();
    $(templateHtml).simpleModal({
      beforeShow: function() {
        var $modal = $('.modal');
        $modal.find('.settings-email__apply-btn').click(function(ev) {
          ev.preventDefault();
          var message = {
            new_email: $modal.find('#user_new_email').val()
          };
          $.post('/?do=Account:Reg&action=change_email&new_email=' +
              encodeURIComponent(message.new_email), {}, function(res) {
            if (!res) {
              return alert('Ошибка запроса!');
            }

            if (!res.status) {
              return alert(res.error || 'Ошибка запроса!');
            }

            window.notify.success(res.message);

            location.reload();
          }, 'json');
        });
      }
    });
  });
});



$(function() {

  var $timeline = $('.timeline');

  $('.timeline__filter .timeline__filter-btn').click(function(ev) {
    ev.preventDefault();
    var $filter = _closest(this, 'timeline__filter');
    $filter.find('.timeline__filter-btn').removeClass('timeline__filter-btn_status_active');

    $(this).addClass('timeline__filter-btn_status_active');

    var chaptorName = $(this).attr('data-chapter');
    $timeline.trigger('timeline:show-chapter', chaptorName);


    hideDetailPanel();

    $(".nano").nanoScroller();

    if (chaptorName === 'notifications') {
      $('.user-nav__notify-counter_timeline').addClass('user-nav__notify-counter_hover');
      $('.user-nav__notify-counter_chat').removeClass('user-nav__notify-counter_hover');
    } else if (chaptorName === 'chat') {
      $('.user-nav__notify-counter_timeline').removeClass('user-nav__notify-counter_hover');
      $('.user-nav__notify-counter_chat').addClass('user-nav__notify-counter_hover');
    }

    window.activeChaptor = chaptorName;
  });

  notificationScore__bindEvents();

  function changeNotificationScore(d) {
    var $score = $(this);
    if ($score.length === 0) return ;

    var $scoreVal = $score.find('.notification-score__value');
    var scoreVal = parseInt($scoreVal.text(), 10);
    if (isNaN(scoreVal)) scoreVal = 0;

    var newScoreVal = scoreVal + d;
    if (newScoreVal < 0) return;

    $scoreVal.text(newScoreVal);
    var $toggleElem = $score.find('.notification-score_on-empty_hide');
    if ($toggleElem.length) {
      if (newScoreVal === 0) {
        $toggleElem.hide();
      } else {
        $toggleElem.show();
      }
    }


  }

  function notificationScore__bindEvents() {
    $('.notification-score')
      .bind('notification-score:increment', function(ev, d) {
        changeNotificationScore.call(this, d || +1);
      })
      .bind('notification-score:decrement', function(ev, d) {
        changeNotificationScore.call(this, d || -1);
      });
  }

});


$(function() {
  $('.timeline__list__link_options').click(function(ev) {
      ev.preventDefault();

      $('.w-timeline__options').simpleModal({
          beforeShow: function() {
              $('body').click();

          },
          afterShow: afterShowModalHandler
      });

  });


  function afterShowModalHandler() {
      var $formContent = this;

      $formContent.find('[type=checkbox]').each(function() {
          var status = $(this).attr('id').substr('timeline__options__'.length);
          $(this).attr('checked', TimelineSettings[status] ? 'checked' : '');
      });



      $formContent.find('.timeline__options__apply-btn').click(function(ev) {
          ev.preventDefault();



          var $form = _closest(this, 'timeline__options__form');
          $.post('/api/timeline_settings.php?action=edit', $form.serializeArray(), function(res) {
              if (!res || !res.status) {
                  alert('Ошибка запроса! Пожалуйста, обратитесь в службу поддержки для устранения неисправности (support@e-generator.ru)');
                  $formContent.hideModal();
                  return ;
              }

              $formContent.find('[type=checkbox]').each(function() {
                  var status = $(this).attr('id').substr('timeline__options__'.length);
                  TimelineSettings[status] = $(this).is(':checked');
              });

              location.reload();
               // $formContent.hideModal();
          }, 'json');
      });

      $formContent.find('.timeline__options__cancel-btn').click(function(ev) {
          ev.preventDefault();

          $formContent.hideModal();
      });
  }
});



$(function() {
    var $card = $('.timeline');
    var $cardInner = $card.find('.timeline__inner');

    var $rightPanel = $('#right-panel');


    var cookie = CookieReaderWriter();

    $card.find('.timeline__read-all').click(function(ev) {
      ev.preventDefault();

      $.get('/api/timeline.php?action=read_timeline_for_user', {}, function() {
        location.reload();
      }, 'json');
    });

    $card.find('.timeline__short__close').click(function(ev) {
      ev.preventDefault();
      $('.timeline').trigger('timeline:toggle', this);

      if (window.activeChaptor) {
        var buttons = {
          'chat': '.user-nav__notify-counter_chat',
          'notifications': '.user-nav__notify-counter_timeline'
        };

        var btnSelector = buttons[window.activeChaptor];
        if (btnSelector) {
          $(btnSelector).toggleClass('user-nav__notify-counter_hover');
        }

        window.activeChaptor = null;
      }

    });

    var $currentTaskBtn = $card.find('.timeline__current-task').click(function(ev) {
      ev.preventDefault();
      $(this).toggleClass('sc-button-selected');

      cookie.set('timeline__current-task', + $(this).hasClass('sc-button-selected'));

      $card.trigger('timeline:show-chapter', 'notifications');
      $('.nano').nanoScroller();
    });

    if (cookie.get('timeline__current-task') == '1') {
      $currentTaskBtn.addClass('sc-button-selected');
    }

    function initCurrentTaskBtn() {
      if (window.CURRENT_TASK_ID) {
        $currentTaskBtn.show();
      }
    }

    function currentTaskMode() {
      return window.CURRENT_TASK_ID && $currentTaskBtn.hasClass('sc-button-selected');
    }

    initCurrentTaskBtn();

    function toggleResizeElements() {
//      return $('.idea-form__info, .idea-row__new-item, .w-ideas-filter, .ideas-container');
      return $('.not-exists-element');
    }

    function alignCard($t) {
        var width = parseInt($card.css('width'), 10);
        var tWidth = parseInt($t.css('width'), 10);
      $card.css('left', - (width - tWidth) / 2);
        // $card.css('left', $t.offset().left - (width - tWidth) / 2);
        //$card.css('top', $t.offset().top + $t.outerWidth() + 2);
    }

    $card.find('.timeline__list__link_hide').click(function(ev) {
      ev.preventDefault();
      $card.trigger('timeline:toggle');
    });

    var timelineStatus = 'hidden';
    $card.bind('timeline:toggle', function(ev, anchor) {
        var $rightPanel = $('.layout__right-panel');
        if (timelineStatus === 'visible') {
          hideDetailPanel();

          var $toggleResize = toggleResizeElements();
          $toggleResize.css('max-width', '1000px');

          // $card.hide();
          var width = parseInt($rightPanel.css('width'), 10);
          $rightPanel.animate({right: -(width + 20)}, 350);
          timelineStatus = 'hidden';
          return ;
        }

        $rightPanel.animate({right: 0}, 350, function() {
          $card.css({
              'visibility': 'hidden',
              'display': 'block'
          });

          $card.css('visibility', 'visible');
          resizeAlignRightCard();
          $(".nano").nanoScroller();
        });

        timelineStatus = 'visible';
    });

    $('.timeline__list__link_change-layout').click(function(ev) {
        ev.preventDefault();

        if ($card.hasClass('timeline_align_right')) {
            $(this).html('направо');

            $card.removeClass('timeline_align_right');
            $card.addClass('timeline_context-menu');
            $cardInner.removeClass('timeline__inner_align_right');

            $card.css('height', '');
            $card.css('top', '');
            $cardInner.css('height', '');

            $card.find('.timeline__list').css('height', '');

            $card.find('.timeline__list__controls')
                .css('position', '');

            $card.find('.timeline__item__details').hide();
            $card.find('.timeline__item__short').show();

            alignCard($('.user-nav__notify-counter:first'));

            return ;
        }

        $(this).text('свернуть');

        $card.addClass('timeline_align_right');
        $card.removeClass('timeline_context-menu');
        $cardInner.addClass('timeline__inner_align_right');
        $card.find('.timeline__list__controls')
            .css('position', 'absolute');

        // $card.find('.timeline__item__details').show();
        $card.find('.timeline__item__short').hide();

        resizeAlignRightCard();
    });

    $('.timeline__details__close').click(function(ev) {
      ev.preventDefault();
      $('.timeline__item_status_active > .timeline__item__first-line').trigger('click');
    });

    var $window = $(window);

    $window.resize(function() {
        if ($card.hasClass('timeline_align_right')) {
            resizeAlignRightCard();
        }
    });

    window.timelineListMargins = {
      right: 10,
      bottom: 43,
      top: 123
    };

    function resizeAlignRightCard() {
      var margins = window.timelineListMargins;
      var top = 74;
      var height = $window.height() - top - margins.bottom - margins.top;

      $card.css('top', top - 1);
      $card.css('height', $window.height() - top);
      $cardInner.css('height', height);
      // $card.find('.timeline__list').css('height', height - 33);

      var $details = $('.timeline__details');
      if ($details.is(':visible')) {
        var detailsWidth = $('.timeline').innerWidth() - $('.timeline__short').outerWidth() - 10;
        $details.css({
            'width': detailsWidth
        });
      }

      $card.find('.timeline__w-inner').css('padding-top', margins.top + 'px');
    }

    function targetEq(el, className) {
        return $(el).hasClass(className) || _closest(el, className).length;
    }

    $('body').click(function(ev) {
        if ($card.hasClass('timeline_align_right')) {
            return ;
        }

        if (targetEq(ev.target, 'user-nav__notify-counter') ||
            targetEq(ev.target, 'timeline')) return;

        if ($card.is(':visible')) {
            return $card.hide();
        }
    });

    var chatMessageTemplate = $('#xlib-template__timeline__item_chat-message').html();

    var templates = {
        idea_comment: $('#xlib-template__timeline__item_idea-comment').html(),
        forum_reply: $('#xlib-template__timeline__item_forum-reply').html(),
        new_personal_message: $('#xlib-template__timeline__item_pm').html(),
        change_idea_status: $('#xlib-template__timeline__item_change-idea-status').html(),
        new_idea: $('#xlib-template__timeline__item_new-idea').html(),
        chat_message: chatMessageTemplate,
        chat_date: $('#xlib-template__timeline__item_chat-date').html(),
        load_more: $('#xlib-template__timeline__item_load-more').html()
    };

    var bundleTemplate = $('#xlib-template__timeline__item_bundle').html();

    window.TimelinePluralDescriptions = {
      'new_idea': [
        'поданная идея',
        'поданные идеи',
        'поданных идей'
      ],
      'idea_comment': [
        'комментарий к идее',
        'комментария к идее',
        'комментариев к идее'
      ],
      'new_personal_message': [
        'личное сообщение',
        'личных сообщения',
        'личных сообщений'
      ],
      'forum_reply': [
        'сообщение на форуме',
        'сообщения на форуме',
        'сообщений на форуме'
      ],
      'chat_message': [
        'сообщение',
        'сообщения',
        'сообщений'
      ]
    };

    var defaultTimelinePluralDescriptions = [
      'новое уведомление',
      'новых уведомления',
      'новых уведомлений'
    ];

    function renderTimeline(container, events, inner, type) {
        type = type || 'notifications';
        var htmlItems = [];
        events.forEach(function(event) {
          try {
            if (event.event_type === 'bundle') {
              var $newBundle = $('<div class="timeline__bundle">');
              renderTimeline($newBundle, event.bundle, true);

              $newBundle.find('.timeline__item').css('margin-right', '0');

              var plural_descriptions = window.TimelinePluralDescriptions[event.bundle[0].event_type] ||
                  defaultTimelinePluralDescriptions;

              event.bundle_description = plural.apply(null, [event.bundle.length].concat(plural_descriptions));
              event.bundle_size = event.bundle.length;
              htmlItems.push(attachDataToTemplate(bundleTemplate, event));
              htmlItems.push($('<div>').html($newBundle).html());
            } else {
              if (!event._isProcessed) {
                event = processingEvent(event);
              }
              htmlItems.push(attachDataToTemplate(templates[event.event_type], event));
            }
          } catch (e) { console.error(e); }
        });

        $(container).html(htmlItems.join(''));

        if (!inner) {

          $(container)
            .addClass(type)
            .removeClass(type === 'notifications' ? 'chat' : 'notifications');

          if (type === 'notifications') {
            timelineItem__bindEvents($(container).find('.timeline__item'));
          } else if (type === 'chat') {
            chatMessage__bindEvents($(container).find('.timeline__item'));
          }
        }
    }



    $card.bind('timeline:add-notifications', function(ev, events) {
      try {
        var $newItems = addTimelineItems(events);
        timelineItem__bindEvents($newItems);
      } catch (e) {}

      $('.timeline__filter__notification-count').trigger('notification-score:increment', events.length);
      $('.user-nav__notify-counter__value').trigger('notification-score:increment', events.length);
    });

    $card.bind('timeline:add-notification', function(ev, evData) {
      try {
        var $newItem = addTimelineItem(evData);
        timelineItem__bindEvents($newItem);
      } catch (e) {}

      $('.timeline__filter__notification-count').trigger('notification-score:increment');
      $('.user-nav__notify-counter__value').trigger('notification-score:increment');
    });

    function addTimelineItems(events) {
      return $(_.map(events, function(ev) {
        return renderTimelineItem.call(this, ev);
      }).join('')).prependTo($('.timeline__list'));
    }

    function addTimelineItem(evData) {
      var html = renderTimelineItem(evData);
      if (!html) return '';
      return $(html).prependTo($('.timeline__list'));
    }

    function renderTimelineItem(evData) {
      evData.origin_created_date = evData.created_date;
      evData = processingEvent(evData);
      window.TimelineData = [evData].concat(window.TimelineData);
      if (!$('.timeline__list').hasClass('notifications')) return null;
      return attachDataToTemplate(templates[evData.event_type], evData)

    }

    function windowHasScrollBar() {
        var hContent = $("body").height(); // get the height of your content
        var hWindow = $(window).height();  // get the height of the visitor's browser window

        // if the height of your content is bigger than the height of the
        // browser window, we have a scroll bar
        return hContent > hWindow;
    }

    window.hideDetailPanel = function hideDetailPanel($details) {
      $details = $details || $('.timeline__details');

      $details.parent().hide();
      $details.hide();
    };


    function chatMessage__bindEvents($items) {
      var $filteredItems = $items
        .filter(':not([data-event-bind])')
        .filter(':not(.timeline__item_chat-date)');

      $filteredItems.attr('data-event-bind', 1);

      $filteredItems.find('.chat-message__remove').click(function(ev) {
        ev.preventDefault();

        var $t = $(this);
        var messageId = parseInt($t.attr('data-message_id'), 10);

        if (isNaN(messageId)) {
          alert('Ошибка удаления! Пожалуйста, обратитесь в службу поддержки для устранения неисправности (support@e-generator.ru)');
        }

        $.post('/api/chat_message.php?action=remove', { message_id: messageId }, function(res) {
          var $item = _closest($t[0], 'timeline__item');
          $item
            .find('.chat-message__message-text')
            .text('сообщение удалено')
            .css({
              'font-size': '11px',
              'font-weight': 'bold'
            });

          $t.remove();

        }, 'json');

      });
    }

    function timelineItem__bindEvents($items) {
      var $filteredItems = $items.filter(':not([data-event-bind])');

      $filteredItems.attr('data-event-bind', 1);

      $filteredItems.filter('.timeline__item_type_bundle').click(function(ev) {
        ev.preventDefault();

        var $item = $(this);
        var $bundle = $item.next();
        var bundleIsVisible = $bundle.is(':visible');
        var direction = bundleIsVisible ? 'down' : 'up';

        $bundle.toggle();

        $item.toggleClass('timeline__item_type_bundle_status_active');

        $item.find('.timeline__arrow').css('background-image', 'url(/images/icon_22345/icon_22345_12x_' + direction + '.svg)');

        $(".nano").nanoScroller();
      });

      $filteredItems
          .filter(':not(.timeline__item_type_bundle)')
          .find('.timeline__item__first-line').click(function(ev) {

        var $item = _closest(this, 'timeline__item');

        if ($item.hasClass('timeline__item_chat-date')) {
          ev.preventDefault();
          return ;
        }

        if ($item.hasClass('timeline__item_forum-reply')) {
          if ($(this).hasClass('timeline__item_read-status_unread')) {
            readTimelineItem($item);
          }
          return true;
        }

        ev.preventDefault();

        var isActive = $item.hasClass('timeline__item_status_active');

        var $details = $('.timeline__details');
        if (isActive) {
          hideDetailPanel($details);
        } else {
          var detailsWidth = 785;

          $details.css({
              'width': detailsWidth
          });

          $details.parent().show();

          function createGlue($window, $modal, options) {
            return {
              size: {
                height: function heightResize() {
                  var height = $window.height();

                  $modal.css({
                    height: height - parseInt($modal.css('top')) - options.margin.bottom

                  });
                }
              },
              position: {
                horizontal: {
                  center: function() {
                    var width = $window.width() - options.margin.right;
                    var modalWidth = parseInt($modal.css('width'));
                    $modal.css({
                      left: (width - modalWidth) / 2
                    });
                  }
                }
              }

            };
          }

          var $window = $(window);
          var glue = createGlue($window, $details, {
            margin: {
              bottom: 20,
              right: 365
            }
          });

          function resizeDetails() {
            glue.size.height();
            glue.position.horizontal.center();
            $details.find('.timeline__details__w-content').nanoScroller();
          }

          $window.bind('resize', resizeDetails);
          resizeDetails();


          $('<div>Подождите...</div>')
            .css({ 'text-align': 'center', 'margin-top': '10px' })
            .appendTo($details.find('.timeline__details__content').html(''));
          $details.show();

          var resource = (function () {
            var timelineId = parseInt($item.attr('data-timeline_id'), 10);
            var IndexedTimeline = _.indexBy(TimelineData, 'timeline_id');
            var timelineItem = IndexedTimeline[timelineId];

            if (timelineItem.event_type === 'new_idea' || timelineItem.event_type === 'idea_comment' ||
                  timelineItem.event_type === 'change_idea_status') {
              var context = timelineItem.idea_comment ? timelineItem.idea_comment : timelineItem.idea_task;
              return '/authors/_idea.php?task_id={task_id}&idea_id={idea_id} .idea-item__details-card'
                .replace('{task_id}', context.task_id)
                .replace('{idea_id}', timelineItem.idea_id);
            }

            if (timelineItem.event_type === 'new_personal_message') {
              return '/api/render_block.php?block_name=personal-messages&method_name=thread&params[mid]={mid}'
                 .replace('{mid}', timelineItem.pm.mid);
            }

          })();
          var $inner = $details.find('.timeline__details__content');

          readTimelineItem($item);

          var loadedHandler = function(responseText, textStatus, req) {
            if (textStatus == "error") {
              if (responseText.indexOf('idea')) {
                if (responseText.indexOf('not found') >= 0) {
                  $inner.html('<div style="padding: 14px; text-align: center">Идея не найдена. Возможно ранее она была удалена</div>');
                }
              }

              return ;
            }

            $inner.find('.idea-item__details-card__controller-buttons').hide();
            var $ideaDetailsCard = $inner.find('.idea-item__details-card');
            if ($ideaDetailsCard.length) {
              window.showAttachedFiles.call($ideaDetailsCard, false);
              ideaItem__bindEvents($ideaDetailsCard);
            }
            $('.timeline__details .idea-item__update-comments').trigger('click');

            $(".timeline__details .nano").nanoScroller();
          };

          $inner.load(resource, loadedHandler);
        }

        $item.parent().find('.timeline__item').removeClass('timeline__item_status_active');
        if (isActive) $item.removeClass('timeline__item_status_active');
        else          $item.addClass('timeline__item_status_active');



      });
    }

    function readTimelineItem($item) {
      var curStatus = $item.find('.timeline__item__first-line').hasClass('timeline__item_read-status_done') ?
          'done' : 'unread';

      if (curStatus === 'done') return;

      var timelineId = parseInt($item.attr('data-timeline_id'), 10);
      var isBroadcast = parseInt($item.attr('data-is_broadcast'), 10);
      $.post('/api/timeline.php', {
        action: 'read_timeline_item',
        timeline_id: timelineId,
        is_broadcast: isBroadcast
      }, function(res) {
        if (res && res.status) {
          _.each(window.TimelineData, function(item) {
            if (item.timeline_id == timelineId) {
              item.timeline_read_date = (new Date).toISOString();
              updateReadStatusClass(item);
            }
          });
        }

      }, 'json');

      $item.find('.timeline__item__first-line')
        .removeClass('timeline__item_read-status_unread')
        .addClass('timeline__item_read-status_done')
      ;
      $('.timeline__filter__notification-count').trigger('notification-score:decrement');
      $('.user-nav__notify-counter__value').trigger('notification-score:decrement');
    }

    function activeTimelineChapter() {
      return $card.attr('data-chapter');
    }

    function loadMore__bindEvents($item) {
      $item.find('a.timeline__item__load_more').click(function(ev) {
        ev.preventDefault();
      });

      $item.click(function(ev) {
        ev.preventDefault();
        var $this = $(this);
        if ($this.hasClass('loading')) return;
        $this.addClass('loading');
        load[activeTimelineChapter()].call(this, function done() {
          $this.removeClass('loading');
        });
      });

      var load = {
        notifications:  function (done) {
          loadItems.call(this, 'timelineLastDayOffset', '/api/timeline.php', function(res) {
            var events =  _.map(res.result.events, function(item) {
              item.origin_created_date = item.created_date;
              return item;
            });

            window.TimelineData = window.TimelineData.concat(events);
            window.timelineLastDayOffset = res.result.lastDayOffset;
            $('.timeline').trigger('timeline:show-chapter', 'notifications');
            $('.nano').nanoScroller();

            done(res);
          }, done);
        },

        chat: function (done) {
          loadItems.call(this, 'chatLastDayOffset', '/api/chat_message.php', function(res) {
            var messages = _.map(res.result.messages, function(item) {
              item.event_type =
                  item.timeline_event_type = 'chat_message';
              item.origin_created_date = item.created_date;
              return item;
            });

            window.ChatMessages = window.ChatMessages.concat(messages);
            window.chatLastDayOffset = res.result.lastDayOffset;
            $('.timeline').trigger('timeline:show-chapter', 'chat');
            $('.nano').nanoScroller();

            done(res);
          }, done);

        }
      };

      function loadItems(offsetKey, uri, fn, err) {
        if (window[offsetKey] === null) {
          return ;
        }

        var $this = $(this);

        $this.find('.timeline__item__load_more').hide();
        $this.find('.timeline__item__load_status').show();

        $.get(
          uri,
          {
            action: 'list',
            task_id: window.CURRENT_TASK_ID,
            lastDayOffset: window[offsetKey] + 1
          },
          function(res) {
            $this.find('.timeline__item__load_more').show();
            $this.find('.timeline__item__load_status').hide();

            if (!res || !res.status) {
              alert('Ошибка запроса! Пожалуйста, обратитесь в службу поддержки для устранения неисправности');
              err();
              return ;
            }

            fn(res);
          },
          'json'
        )
      }
    }

    var sending = false;

    $('.timeline__enter-simbol').click(function(ev) {
      ev.preventDefault();

      if (sending) return ;

      var $input = _closest(this, 'timeline__input');
      var $text = $input.find('.timeline__textarea');

      if ($text.val().replace(/^\s+|\s+$/, '').length === 0) {
        return ;
      }

      var $wList = $('.timeline__w-list');
      if ($wList.length) {
        $wList[0].scrollTop = 0;
      }

      sending = true;
      var message = {
          message_text: $text.val(),
          task_id: window.CURRENT_TASK_ID
      };

      $.post('/api/chat_message.php?action=add', message, function(res) {
        // try {
          $text.val('');
          addChatMessage(res.result);
          window.taskIORoom && taskIORoom.send(res.result);
        // } catch(e) {}
        sending = false;
      }, 'json');

    });



    $card.bind('chat-io:new-message', function(ev, data) {
      addChatMessage(data);
    });

    $('.timeline__input .timeline__textarea').keydown(function (e) {
      if (e.ctrlKey && e.keyCode == 13) {
        console.log('keydown', e);
        _closest(this, 'timeline__input').find('.timeline__enter-simbol').trigger('click');
      }
    });

    function addChatMessage(data) {
      data.event_type =
            data.timline_event_type = 'chat_message';
      data.origin_created_date = data.created_date;
        window.ChatMessages = [data].concat(window.ChatMessages);
        var processedData = processingEvent(_.clone(data));
        var $newItem = $(attachDataToTemplate(chatMessageTemplate, processedData))
          .css({display: 'none'})
          .prependTo($('.timeline__list '))
          .slideDown();
      // timelineItem__bindEvents($newItem);
      chatMessage__bindEvents($newItem);
    }

    function statusTitle(status) {
      var statuses = {
        0: '<span class="timeline__item__idea-status timeline__item__idea-status_notactive">неактивирована</span>',
        1: '<span class="timeline__item__idea-status timeline__item__idea-status_active">активирована</span>',
        2: '<span class="timeline__item__idea-status timeline__item__idea-status_approve">принята</span>',
        3: '<span class="timeline__item__idea-status timeline__item__idea-status_reject">отклонена</span>'
      };
      return statuses[parseInt(status, 10)];
    }

    window.pagination__statusTitle = statusTitle;

    var dateFormat = dateFormatCreator({ seconds: true, onlyTime: true });

    function strip(html) {
       var tmp = document.createElement("DIV");
       tmp.innerHTML = html;
       return tmp.textContent || tmp.innerText || "";
    }

    function updateReadStatusClass(event) {
      event.read_status = event.timeline_read_date ? 'timeline__item_read-status_done' :
          'timeline__item_read-status_unread';
    }

    window.processingEvent = function processingEvent(event) {
        if (event.event_type !== 'chat_date') {
            event.created_date = dateFormat(event.created_date);
        }

        if (event.event_type === 'chat_message') {
            var removeControls = event.remove_date ||
                window.AUTH_USER_ID !== parseInt(event.message_author_id, 10);
            event.remove_visible = removeControls ? 'display: none' : '';
            if (event.remove_date) {
              event.message_text = '<span style="font-size: 11px; font-weight: bold;">сообщение удалено</span>';
            }
        }
        updateReadStatusClass(event);

        if (event.event_type === 'forum_reply') {
            event.topic_id = event.reply_topic.topic_id;
            event.reply_id = event.reply_topic.reply_id;
            event.reply_topic_user_name = event.reply_topic.name;
            event.reply_topic__reply = strip(event.reply_topic.reply);
        }
        if (event.event_type === 'new_personal_message') {
            event.pm_subject = event.pm.subject;
            event.pm_body = event.pm.body;
            event.pm_created_date = dateFormat(event.pm_created_date);
        }
        if (event.event_type === 'change_idea_status') {
            event.idea_task_curator_id = event.idea_task.curator;
            event.idea_task__task_id = event.idea_task.task_id;
            var ideaStatuses = event.event_additional.split('|');
            event.old_status = statusTitle(ideaStatuses[0]);
            event.new_status = statusTitle(ideaStatuses[1]);
        }
        if (event.event_type === 'idea_comment') {
          event.ic_created_date = dateFormat(event.ic_created_date);

          // здесь event.author_user_id - автор комментария
          //       event.idea_comment.author_id - автор идеи
          if (window.AUTH_USER_IS_CURATOR && window.AUTH_USER_ID !== +event.author_user_id) {
            if (event.idea_comment && +event.author_user_id === +event.idea_comment.author_id) {
              event.sender_alias = 'автор';
              event.sender_id = 0;
            }
          } else {
            event.sender_alias = event.idea_comment ? event.idea_comment.sender_alias : '';
          }
          event.idea_id = event.idea_comment ? event.idea_comment.idea_id : '';

        }
        if (event.event_type === 'new_idea') {
            if (window.AUTH_USER_IS_CURATOR && window.AUTH_USER_ID !== +event.idea_task.author_id) {
              event.idea_task_author_id = 0;
            } else {
              event.idea_task_author_id = event.idea_task.author_id;
            }

            event.idea_task__task_id = event.idea_task.task_id;
            event.idea_task__idea_id = event.idea_task.idea_id;
            event.idea_task__idea_text = event.idea_task.idea_text;
        }

        event._isProcessed = true;
        return event;
    }

    function reduceTimelineData(timelineData) {
      var curEventType = null;
      var curEventBundle = [];

      var now = (new Date).getTime();
      var isOld = function(item) {
        if (item.event_type === 'chat_date') {
          return true
        } else {
          var itemTimestamp = (new Date(item.origin_created_date.replace(' ', 'T'))).getTime();
          return (now - itemTimestamp) > 3600000;
        }
      };

      var addCurBundle = function(item, reduced) {
        if (curEventBundle.length > 3) {
            reduced.push({
              event_type: 'bundle',
              bundle_type: curEventType,
              bundle: curEventBundle,
              created_date: curEventBundle[0].created_date,
              origin_created_date: curEventBundle[0].created_date
            });
          } else {
            reduced = reduced.concat(curEventBundle);
          }

          curEventBundle = [item];
          curEventType = item.event_type;

          return reduced;
      };

      var lastAction = null;
      var reduced =  _.reduce(timelineData, function(reduced, item) {
        if (curEventType === null) {
          curEventType = item.event_type;
        }

        if (!isOld(item)) {
          lastAction = 'push_item_to_timeline';
          reduced.push(item);
        } else if (curEventType === item.event_type && item.event_type !== 'chat_date' && curEventBundle.length < 30) {
          lastAction = 'push_item_to_bundle';
          curEventBundle.push(item);
        } else {
          lastAction = 'add_bundle';
          reduced = addCurBundle(item, reduced);
        }

        return reduced;
      }, []);

      if (lastAction === 'add_bundle') {
        reduced.push(curEventBundle[0]);
      } else if (lastAction === 'push_item_to_bundle') {
        reduced = addCurBundle({event_type: null}, reduced);
      }

      return reduced;
    } // end of reduceTimelineData ...

    if (window.ChatMessages) {
      window.ChatMessages = _.map(window.ChatMessages, function(item) {
        item.event_type =
            item.timeline_event_type = 'chat_message';
        item.origin_created_date = item.created_date;
        return item;
      });
    }

    if (window.TimelineData) {
      window.TimelineData =  _.map(window.TimelineData, function(item) {
        item.origin_created_date = item.created_date;
        return item;
      });
    }

    $('.timeline').bind('timeline:show-chapter', function(ev, chapterName) {
      var $timeline = $('.timeline');
      var $list = $timeline.find('.timeline__list');
      var $input = $timeline.find('.timeline__input');

      var $filter = $timeline.find('.timeline__filter');
      var $active = $filter.find('.timeline__filter-btn_chapter_' + chapterName);
      if (!$active.hasClass('timeline__filter-btn_status_active')) {
        $filter.find('.timeline__filter-btn').removeClass('timeline__filter-btn_status_active');
        $active.addClass('timeline__filter-btn_status_active');
      }

      $timeline.attr('data-chapter', chapterName);

      var now = (new Date()).toString();
      var loadMoreBtn = {
        created_date: now,
        origin_created_date: now,
        event_type: 'load_more',
        timeline_event_type: 'load_more'
      };
      var $toggleResize = toggleResizeElements();
      switch (chapterName) {
        case 'chat':
          $currentTaskBtn.hide();
          $card.find('.timeline__list__link_options').hide();
          $card.find('.timeline__read-all').hide();
          $input.show();
          $rightPanel.css('width', '565px');
          $toggleResize.css('max-width', '785px');
          timelineListMargins.top = 123;
          renderTimeline(
            $list,
            addDateDelims(window.ChatMessages || [])
              .concat(window.chatLastDayOffset === null ? [] : [loadMoreBtn]),
            false,
            chapterName
          );
          resizeAlignRightCard();
          break;
        case 'notifications':
          initCurrentTaskBtn();
          $card.find('.timeline__list__link_options').show();
          $card.find('.timeline__read-all').show();
          $input.hide();
          $rightPanel.css('width', '365px');
          $toggleResize.css('max-width', '1000px');
          timelineListMargins.top = 0;
          renderTimeline(
            $list,
            reduceTimelineData(addDateDelims(filterByTask(window.TimelineData || [])))
              .concat(window.timelineLastDayOffset === null ? [] : [loadMoreBtn]),
            false,
            chapterName
          );
          resizeAlignRightCard();
          break;
      }

      loadMore__bindEvents($card.find('.timeline__item__first-line_load'));
    });

    function filterByTask(timelineData) {
      if (!currentTaskMode()) {
        return timelineData;
      }

      return _.filter(timelineData, function(item) {
        var status;
        try {
          status = (item.timeline_event_type === 'idea_comment' && item.idea_comment.task_id == window.CURRENT_TASK_ID) ||
            (item.timeline_event_type === 'forum_reply' && item.reply_topic.task_id == window.CURRENT_TASK_ID) ||
            (item.timeline_event_type === 'change_idea_status' && item.idea_task.task_id == window.CURRENT_TASK_ID) ||
            (item.timeline_event_type === 'new_idea' && item.idea_task.task_id == window.CURRENT_TASK_ID);
        } catch (e) { status = false; }
        return status;
      });
    }

    window.filterByTask = filterByTask;

    var delimDateFormat;

    function addDateDelims(messages) {
      delimDateFormat = delimDateFormat || window.dateFormatCreator({onlyDate: true});
      return _.reduce(messages, function(reduced, item, index) {
        var date, prev, prevDate, oCreatedDate;
        if (item.event_type !== 'chat_date') {
          date = (new Date(item.origin_created_date.replace(' ', 'T'))).getDate();

          if (reduced.length === 0) {
            if (date !== (new Date()).getDate()) {
              reduced.push({
                event_type: 'chat_date',
                created_date: delimDateFormat(item.origin_created_date),
                origin_created_date: item.origin_created_date
              });
            }
          } else {
            prev = reduced[reduced.length - 1];
            prevDate = (new Date(prev.origin_created_date.replace(' ', 'T'))).getDate();
            oCreatedDate = item.origin_created_date;

            if (date !== prevDate) {
              reduced.push({
                event_type: 'chat_date',
                created_date: delimDateFormat(oCreatedDate),
                origin_created_date: oCreatedDate
              });
            }
          }
        }
        reduced.push(item);
        return reduced;
      }, []);
    }

    window.addDateDelims = addDateDelims;

    function sortByCreatedDateKeys(arr) {
      return _.sortBy(arr, function (item) {
        var time = item.created_date.replace(' ', 'T');
        return Date.now() - (new Date(time)).getTime();
      });
    }

    function mergeByTime(a, b) {
      return sortByCreatedDateKeys(a.concat(b));
    }

});

