/*global jQuery */
(function($) {
    $.fn.editorConsole = function (params) {
        params = $.extend({

        }, params);

        return this.each(function() {
            var $_this = $(this);

            var accessor_id = $_this.attr("accessor");
            var from_path = $_this.attr("path");
            var ids = $_this.attr("id").split('_');
            var content_type = ids[1];
            var oid = ids[2];

            var expander = $("#a_edit_" + content_type + "_" + oid);
            var opened = false;

            $_this.removeClass("noshow").hide();

            expander.bind("click", function () {
                if (opened) {
                    $_this.slideUp();
                    opened = false;
                } else {
                    $_this[0].loadContent();
                    opened = true;
                }
                return false;
            });

            this.loadContent = function () {

                $_this.addClass("loading").empty().slideDown();

                $.ajax({
                    url: "/services/rest/",
                    type: "POST",
                    dataType: "json",
                    data: { method: "core.getEditorConsole",
                            accessor_id: accessor_id,
                            from_path: from_path,
                            csrfmiddlewaretoken: CSRF_TOKEN,
                            rtype: "json"
                    },
                    error: function () {
                        alert (gettext("Something went wrong. Please, try again later."));
                        $_this.removeClass("loading").slideUp();
                        opened = false;
                    },
                    success: function (response) {
                        if (!response.content) {
                            alert (gettext("Something went wrong. Please, try again later."));
                            $_this.removeClass("loading").slideUp();
                            opened = false;
                        } else {
                            $(response.content).appendTo($_this);
                            $_this.removeClass("loading");
                        }
                    }
                });
            };
        });
    };
})(jQuery);
