(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.FriendSelectorDialog = function(app, saveCallback) {
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var selectedIds = {};
        var newSelections = {};

        function events() {
            $('#btn-save-friends').click(saveFriendInvitations);
        }

        function loadFriends() {
            $('#friend-selector-list').empty();

            // TODO: page this as users scroll - show selected friends from parent screen at top
            rest.getFriends({ id: context.JK.currentUserId })
                .done(function(friends) {
                    var template = $('#template-friend-selection').html();
                    $.each(friends, function(index, val) {
                        var id = val.id;
                        var isSelected = selectedIds[id];

                        var html = context.JK.fillTemplate(template, {
                            userId: id,
                            css_class: isSelected ? 'selected' : '',
                            userName: val.name,
                            avatar_url: context.JK.resolveAvatarUrl(val.photo_url),
                            status: "",
                            status_img_url: "",
                            check_mark_display: isSelected ? "block" : "none",
                            status_img_display: "none"
                        });

                        $('#friend-selector-list').append(html);

                        // disable row click if it was chosen on parent screen
                        if (!isSelected) {
                            $('#friend-selector-list tr[user-id="' + id + '"]').click(function() {
                                updateSelectionList(id, val.name, $(this), $(this).find('img[user-id="' + id + '"]'));
                            });
                        }
                    });
                })
                .error(app.ajaxError);
        }

        function updateSelectionList(id, name, tr, img) {
            if (!tr.hasClass('selected')) {
                tr.addClass('selected');
                img.show();
                newSelections[id] = { userId: id, userName: name };
            }
            else {
                tr.removeClass('selected');
                img.hide();
                delete newSelections[id];
            }
        }

        function saveFriendInvitations(evt) {
            evt.stopPropagation();
            saveCallback(newSelections);
        }

        function showDialog(ids) {
            selectedIds = ids;
            newSelections = {};
            loadFriends();
            // HACK TO OVERRIDE PADDING SET SOMEWHERE ELSE
            $('.choosefriends-overlay').css({"padding":"8px"});
        }

        this.initialize = function() {
            events();
        };

        this.showDialog = showDialog;
        return this;
    };

 })(window,jQuery);