/* globals define, app, ajaxify, bootbox, socket, templates, utils */

require([
    'translator'
], function (translator) {

    var elements = {
        BUTTON : '.ns-spoiler-control a',
        CONTENT: '.ns-spoiler-content',
        MAIN   : '.ns-spoiler',
        POST   : '[component="post"]'
    }, classes   = {
        OPEN_EYE : 'fa-eye',
        CLOSE_EYE: 'fa-eye-slash'
    };

    $(window).on('action:topic.loading', function (e) {
        addTopicListener();
    });

    function addTopicListener() {
        $('[component="topic"]').on("click", elements.BUTTON, function () {
            toggle($(this));
        });
    }

    function toggle($button) {
        var $spoiler = $button.parents(elements.MAIN),
            $content = $spoiler.find(elements.CONTENT),
            open     = $spoiler.attr('data-open') === 'true',
            postId   = parseInt($spoiler.parents('[data-pid]').attr('data-pid')),
            index    = parseInt($spoiler.attr('data-index')),
            icon     = $button.find('i');

        $spoiler.attr('data-open', !open);

        if (!open) {
            icon.removeClass(classes.OPEN_EYE).addClass(classes.CLOSE_EYE);
        } else {
            icon.removeClass(classes.CLOSE_EYE).addClass(classes.OPEN_EYE);
        }

        // Check if content is empty
        if ($content.html().length === 0) {
            socket.emit(
                'plugins.ns-spoiler.getSpoilerContent',
                {index: index, postId: postId},
                function (error, content) {
                    if (error) {
                        return console.error('Error has occurred, error: %s', error.message);
                    }
                    $content.html(content);
                }
            );
        }

    }
});

@@ -413,21 +413,19 @@
 ion:
-topic.loading
+ajaxify.end
 ', f
@@ -433,17 +433,16 @@
 nction (
-e
 ) %7B%0A    
@@ -448,29 +448,24 @@
      add
-Topic
 Listener
 ();%0A    
@@ -456,16 +456,17 @@
 Listener
+s
 ();%0A    
@@ -490,21 +490,16 @@
  add
-Topic
 Listener
 () %7B
@@ -494,16 +494,17 @@
 Listener
+s
 () %7B%0A   
@@ -514,43 +514,8 @@
   $(
-'%5Bcomponent=%22topic%22%5D').on(%22click%22, 
 elem
@@ -525,16 +525,28 @@
 s.BUTTON
+).on(%22click%22
 , functi
@@ -988,24 +988,170 @@
 find('i');%0A%0A
+        if (!postId %7C%7C !index) %7B%0A            return console.warn('%5Bns-spoiler%5D data-index or data-pid missing from spoiler element!');%0A        %7D%0A%0A
         $spo

different approach