Source: user_groups.js

(
/**
* Contains the functionalities related to the user groups page.
*
* @module user_groups
* @author Joonas Konki
* @author Anu Koskela
* @author Mikko Kuhno
* @author Henrik Paananen
* @author Atte Räty
* @license BSD 3-clause, see LICENSE for more details.
* @copyright 2015 Kepler project authors
*/
function(){

var userGroups = null;
var currentUser = null;
var foundUser = null;
var newGroupMemberIDs = [];

/**
* Empties the groupList area. Fetches the latest user group information from
* the database. If the user has only the default group, shows a notification
* that there are no user groups. Otherwise displays the user groups of the
* current user.
* @memberof module:user_groups
*/
function reloadGroups() {
    var groupList = $("#groupList");
    groupList.empty();

    kepler.getUserGroups(function (data) {
        userGroups = data.groups;
        if(userGroups.length < 2){
            $("#noGroupsNotification").show();
        } else {
            $("#noGroupsNotification").hide();
            initGroupList(userGroups);
            initNewGroup(userGroups);
        }
    });
}

/**
* Creates a click event to a button.
* Returns a function that shows a modal with correct information
* and removes a user group. If a group is removed, the view is updated.
* @memberof module:user_groups
* @param {string} groupId - The ID of the group to be removed.
* @param {string} groupName - The name of the group to be removed.
* @returns A function that shows a modal with correct information.
*/
function makeRemoveGroup(groupId, groupName) {
    return function () {
        $("#modalButtonYes").off();
        /**
        * Makes a call to remove the selected user group. Reloads the view.
        * @function
        * @name modalButtonYes click
        * @memberof module:user_groups
        * @inner
        */
        $("#modalButtonYes").click(function () {
            kepler.deleteUserGroup(
                { 'group_id': groupId },
                function (data) {
                    kepler.showResult(data.result, "#notification");
                    if (data.result.success) {
                        reloadGroups();
                    }
                }
            );
        });
        $("#modalLabel").text(groupName);
        $("#modalCancel").modal('show');
    };
}

/**
* If there are groups to be shown, empties the group list area and displays the
* information of all the current user's groups (except the default group).
* @memberof module:user_groups
* @param {Object} groups - A list object of the user groups of the current user.
*/
function initGroupList(groups) {
    var groupList = $("#groupList");
    groupList.empty();
    groupList.show();

    for (var i = 0; i < groups.length; i++) {
        var group = groups[i];
        if (group.is_personal) {
            //Every user has one personal group as a default.
            //Set the variable currentUser for future use.
            currentUser = group.members[0];
        }
        else {
            var groupLi = $('<li>').addClass('group').attr('id',"li" + i);

            var groupRow = $('<div>');
            groupRow.addClass("list-group-item list-group-item-info");

            var bSpan = $("<span>").addClass("badge");
            bSpan.text(group.members.length).css("display", "inline-block");

            groupRow.append(bSpan);
            groupRow.attr("id", "header" + i).attr("data-toggle", "collapse");
            groupRow.attr("data-target", "#row" + i).css("cursor","pointer");

            var gSpan = $("<span>");
            gSpan.addClass("glyphicon glyphicon-chevron-down");
            gSpan.css("float","left").css("cursor","pointer");

            groupRow.append(gSpan);

            var groupNameDiv = $("<div>").text(group.name);
            groupNameDiv.css("display", "inline-block");
            groupNameDiv.css("min-width", "12em");
            groupNameDiv.css("margin-left", "1em");
            groupRow.append(groupNameDiv);
            groupLi.append(groupRow);

            //This part is toggled by clicking the groupRow (div) element.
            var groupCollapse = $('<ul>').addClass('collapse list-group');
            groupCollapse.attr('id',"row" + i);

            for (var j = 0; j < group.members.length; j++){
                var member = group.members[j];
                var memberName = member.fullname;
                var memberItem = $("<li>").addClass("list-group-item");
                memberItem.append($("<span>").text(memberName));

                if (member.is_owner) {
                  var ownerTag = $("<span>").addClass('owner-tag');
                  ownerTag.text(kepler.translate('content.user_groups.owner'));
                  memberItem.append(ownerTag);
                }

                groupCollapse.append(memberItem);
            }

            var groupRemoveButton = $("<button>").addClass("btn btn-default");
            groupRemoveButton.text(kepler.translate('button.delete_group'));
            groupRemoveButton.click(makeRemoveGroup(group.id, group.name));
            var buttonDiv = $("<div>").attr("align", "right");
            buttonDiv.append(groupRemoveButton);
            groupCollapse.append(buttonDiv);
            groupLi.append(groupCollapse);
            groupList.append(groupLi);
        }
    }
}

/**
* Initialises the area for creating a new user group.
* Sets the current user automatically as a member of the new user group.
* @memberof module:user_groups
* @param {object} groups - A list of the user groups of the current user.
*/
function initNewGroup(groups){
    $("#newMembers").empty();
    $("#newGroupName").val("");
    if (currentUser === null) {
        for (var i = 0; i < groups.length; i++){
            var group = groups[i];
            if (group.is_personal) {
                currentUser = group.members[0];
            }
        }
    }
    var userName = "";
    if(currentUser.call_name !== null){
        userName += currentUser.call_name;
    }
    else
        userName += currentUser.first_names;
    userName += " " + currentUser.last_name;
    $("#newMembers").append($("<li>").text(userName));

    newGroupMemberIDs.push(currentUser.id);
}

/**
* Shows the found user's name and a button that can be used to add the person
* to the new group. If no users can be found, displays a notification and hides
* the button.
* @memberof module:user_groups
* @param {string} searchText - The string that must be matched.
*/
function displaySearchResult(searchText) {
    var params = {
        "search_string": searchText,
    };
    kepler.searchUser(params, function (data) {
        $("#searchResultDiv").show();
        if (data.user === null) {
            $("#btnAddToGroup").hide();
            $("#searchResult").text(kepler.translate('label.noMatches'));
            foundUser = null;
        }
        else {
            $("#btnAddToGroup").show();
            foundUser = data.user;
            if (foundUser.call_name !== null)
                $("#searchResult").text(foundUser.call_name + " " +
                foundUser.last_name);
            else
                $("#searchResult").text(foundUser.first_names + " " +
                foundUser.last_name);
        }
    });
}

/**
* Returns a function that removes a person from the group.
* @memberof module:user_groups
* @param groupId - The ID of the group where the person is to be removed from.
* If the person is to be removed from an unregistered new group, set to null.
* @param userId - The ID of the user to be removed.
* @param element - The element (typically a list element) to be removed.
* @returns A function that removes a person from the group.
*/
function makeRemovePerson(groupId, userId, element) {
    return function () {
        if (groupId === null) { //Remove person from a new group.
            newGroupMemberIDs = jQuery.grep(newGroupMemberIDs, function(value) {
                return value != userId;
            });
            element.remove();
        }
        else { //Remove person from a selected group.
            //TODO (Anu)
        }
    };
}

/**
* Adds the found user to a new group and sets the global variable for the found
* user to null. If the user has already been added to the new group, displays a
* notification.
* @memberof module:user_groups
*/
function addToGroup() {
    for (var i = 0; i < newGroupMemberIDs.length; i++) {
        if (foundUser.id === newGroupMemberIDs[i]) {
            alert(kepler.translate("content.user_groups_old_member") + "!");
            //TODO (Anu) Don't use an alert!
            return;
        }
    }
    var memberDiv = $("<li>").val(foundUser.id);

    if (foundUser.call_name !== null)
        memberDiv.text(foundUser.call_name + " " + foundUser.last_name + " ");
    else
        memberDiv.text(foundUser.first_names + " " + foundUser.last_name + " ");

    var deleteBtn = $("<button>");
    deleteBtn.addClass("btn btn-default btn-sm");
    deleteBtn.text(kepler.translate('button.delete_from_group'));
    deleteBtn.click(makeRemovePerson(null, foundUser.id, memberDiv));
    memberDiv.append(deleteBtn);

    $("#newMembers").append(memberDiv);

    newGroupMemberIDs.push(foundUser.id);

    $('#searchField').val("");
    $("#searchResult").text("");
    $("#searchResultDiv").hide();
    foundUser = null;
}

/**
* If all the necessary information has been given, saves the new user group and
* reloads the user group list.
* @memberof module:user_groups
*/
function saveNewGroup() {
    var groupName = $("#newGroupName").val();
    var errorText = "";
    if ((groupName !== "") && (newGroupMemberIDs.length > 1)) {
        var params = {
            'member_id_list': newGroupMemberIDs,
            'name': groupName,
        };
        console.log(params);
        kepler.addUserGroup(params, function(data){
            kepler.showResult(data.result, "#notification");
            reloadGroups();
            //TODO Kuhno Fix this collapse and cancel collapse
            /*
            $('#newgroup').collapse({
                toggle: false
            });
            */
        });
        //TODO (Anu) initialize the new group area.
        return;
    }
    else {
        if (groupName === ""){
            errorText += kepler.translate('content.user_groups_box_group_name')+
            ". ";
        }
        if (newGroupMemberIDs.length === 1){
            errorText += kepler.translate('content.user_groups_add_members') +
             ".";
        }
        alert(errorText);
    }
}

/**
* This is executed after the HTML page has been loaded.
* This is a common procedure of all of the client-side modules to
* initialise the page content.
* @memberof module:user_groups
*/
function doc_ready() {
    //Highlight the corresponding navigation area.
    $("#navUserGroups").addClass("active");

    kepler.getUserGroups(function (data) {
        //As a default every user has a personal group,
        //which has only one member (the current user).
        if(data.groups.length < 2){
            $("#noGroupsNotification").show();
        }
        else {
            initGroupList(data.groups);
        }
        initNewGroup(data.groups);
    });

    $("#searchButton").click(function (){
        var searchText = $("#searchField").val();
        if (searchText !== "") {
            displaySearchResult(searchText);
        }
    });

    $('#searchField').bind("enterKey",function(e){
        var searchText = $("#searchField").val();
        if (searchText !== "") {
            displaySearchResult(searchText);
        }
    });

    $('#searchField').keyup(function(e){
        if(e.keyCode == 13) { //TODO (Anu) Find a better way to do this!
            $(this).trigger("enterKey");
        }
    });

    $("#btnAddToGroup").click(function (){
        addToGroup();
    });

    $("#btnSaveNewGroup").click(function () {
        saveNewGroup();
    });
}

$(document).ready(doc_ready);
}());