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

        function parseId(id) {
            var idx = id.substring("a_light_".length, id.length);
            return idx.split("_");
        }

        params = $.extend({
            url: "/services/rest/",
            rtype: "json"
        }, params);

        return this.each(function() {
            var $_this = $(this);
            var item = $_this.parent().parent().next();
            var container = $('<div class="explain noshow"><h4>'+gettext("Why Did We Recommend This?")+'</h4></div>').appendTo(item);
            var loaded = false;
            var opened = false;
            var prm = {};

            var ids = parseId($_this.attr("id"));
            prm.content_type = ids[0];
            prm.obj_id = ids[1];
            prm.accessor_id = ids[2];

            $_this.data("ex_param", params);
            container.removeClass("noshow").hide();

            $_this.click(function () {
                var params = $_this.data("ex_param");
                if (opened) {
                    container.slideUp("fast", function () { opened = false; });
                } else {
                    container.slideDown("fast", function () {
                        // XXX: IE workaround - content must be "touched" otherwise
                        //      it will remain hidden
                        container.css("zoom", "1");
                    });

                    if (!loaded) {
                        var loader = $('<div class="simpleLoader"></div>').appendTo(container);

                        $.ajax({
                            url: params.url,
                            type: "GET",
                            dataType: "json",
                            data: { csrfmiddlewaretoken: CSRF_TOKEN,
                                      content_type: prm.content_type,
                                      object_id: prm.obj_id,
                                      rtype: params.rtype,
                                      method: "core.explainRecommendation"
                            },
                            success: function (response) {
                                loader.fadeOut("normal", function () { loader.remove(); });
                                if (response.content) {
                                    loaded = true;
                                    container.append($('<span>' + response.content + '</span>'));
                                    $_this[0].initVotingConsole(response.vote);
                                } else {
                                    alert (gettext("Something went wrong. Please try again later."));
                                    opened = false;
                                    container.slideUp("fast");
                                }
                            },
                            error: function () {
                                alert (gettext("Something went wrong. Please try again later."));
                                opened = false;
                                container.slideUp("fast");
                            }
                        });
                    }

                    opened = true;
                }
                return false;
            });

            this.initVotingConsole = function (vote) {
                var voting_console = $('<div class="votingConsole"></div>').prependTo(container);
                setTimeout(function () {
                    var voting_params = {
                        mid: prm.accessor_id,
                        vote_url: '/services/rest/',
                        method: "core.vote"
                    };
                    if (typeof vote != 'undefined') {
                        voting_params.vote = vote;
                    }
                    voting_console.votingConsole(voting_params);
                    $('.voteFor, .voteAgainst', voting_console).click(function () {
                        opened = false;
                        container.slideUp("fast");
                    });
                }, 50);
            };
        });
    };
})(jQuery);

