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

$(document).ready(function () {
    'use strict';

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

        var elements = {
            MAIN   : '.ns-spoiler',
            BUTTON : '.ns-spoiler-control a',
            CONTENT: '.ns-spoiler-content'
        }, 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 getSpoiler($child) {
            return $child.parents(elements.MAIN);
        }

        function toggle($button) {
            var $spoiler = getSpoiler($button);
            var open = $spoiler.attr('data-open') === 'true';
            var 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);
            }
        }
    });
});

@@ -715,32 +715,156 @@
  %7D);%0A        %7D%0A%0A
+        function getPostId($child) %7B%0A            return parseInt($child.parents('%5Bdata-pid%5D').attr('data-pid'));%0A        %7D%0A%0A
         function
@@ -1027,17 +1027,17 @@
 $button)
-;
+,
 %0A       
@@ -1045,17 +1045,81 @@
     
-var
+    $content = $spoiler.find(elements.CONTENT),%0A               
  open 
+    
 = $s
@@ -1157,31 +1157,148 @@
 rue'
-;%0A            var
+,%0A                postId   = getPostId($button),%0A                index    = parseInt($spoiler.attr('data-index')),%0A               
  icon 
+    
 = $b
@@ -1579,24 +1579,567 @@
           %7D%0A
+%0A            // Check if content is empty%0A            if ($content.text().length == 0) %7B%0A                socket.emit(%0A                    'plugins.ns-spoiler.getSpoilerContent',%0A                    %7Bindex: index, postId: postId%7D,%0A                    function (error, content) %7B%0A                        if (error) %7B%0A                            return console.error('Error has occurred, error: %25s', error.message);%0A                        %7D%0A                        $content.html(content);%0A                    %7D%0A                );%0A            %7D%0A%0A
         %7D%0A  

add socket connection from client