Source: unit_groups.js

(
/**
* Contains the functionalities related to the unit groups page.
*
* @module unit_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 unitGroups = null;
var emptyUnitGroup = null;
var units = null;
var types = null;
var currentUnitGroup = null;
var currentUnitGroupId = null;
var unitsCopy = null;

/**
* Adds all the unit type options (basic studies, advanced studies etc.) to
* the current unit group type and adds a listener which updates
* the type of the current unit group when the option is changed.
* @memberof module:unit_groups
*/
function setUnitGroupType() {
    if ( $('#unitGroupType').has('option').length > 0 ) {
        return;
    }
    else {
        for (var i = 0; i < types.length; i++){
            var option = $("<option>").attr("value", types[i].unit_type_id);
            option.text(types[i].unit_type_name);
            $('#unitGroupType').append(option);
        }
        $("#unitGroupType").change(function (v) {
            var selectedStudyType = parseInt(v.target.value);
            currentUnitGroup.unit_type_id = selectedStudyType;
        });

    }
}

/**
* Sets the qualifier to the selected unit.
* @memberof module:unit_groups
* @param {object} unit - The selected unit.
* @returns A function that sets the qualifier to the selected unit.
*/
function makeUpdateUnit(unit){
    return function () {
        unit.qualifier = $(this).val();
    };
}

/**
* Creates a label and an input field for the wanted unit and adds the created
* fields to shown units.
* @memberof module:unit_groups
* @param {object} unit - The unit for which information is shown.
*/
function addUnitToUnitGroupInfo(unit) {
    var unitDiv = $("<div>").addClass("col-sm-12 form-horizontal");
    unitDiv.attr("align", "left").css("clear", "both");

    var unitLabel = $("<label>").addClass("control-label col-sm-9");
    unitLabel.text(unit.name).css("text-align", "left");

    var unitQuantity = $("<input>").addClass("form-control quantity-input");
    unitQuantity.attr("type", "text").attr("placeholder", "Anna työlle koodi");
    unitQuantity.val(unit.qualifier); //TODO(Anu) Check if this works...

    unitQuantity.change(makeUpdateUnit(unit));

    var unitQuantityDiv = $("<div>").addClass("col-sm-3");
    unitQuantityDiv.css("clear", "right").css("padding", "0px");

    unitQuantityDiv.append(unitQuantity);
    unitDiv.append(unitQuantityDiv);
    unitDiv.append(unitLabel);
    $("#units").append(unitDiv);

    $("#unitWarning").hide();
}

/**
* Gets all units associated to the wanted unit group and displays them in the
* edit fields. If no units are found, shows a notification.
* @memberof module:unit_groups
* @param {object} unitGroup - The unit group for which information is to be
* shown.
*/
function updateUnits (unitGroup) {
    $("#units").empty();
    $("#units").show();
    if (unitGroup.units.length === 0) {
        $("#unitWarning").show();
    }
    else {
        //$("#unitWarning").hide();
        for (var i = 0; i < unitGroup.units.length; i++) {
            addUnitToUnitGroupInfo(unitGroup.units[i]);
        }
    }
}

/**
* Sets the information of the current unit group to the corresponding fields.
* @memberof module:unit_groups
*/
function setCurrentSelection(){
    var ug = currentUnitGroup;
    if(ug.id !== -1){
        $("#unitGroupName").val(ug.name);
        $('#unitGroupType').val(currentUnitGroup.unit_type_id.toString());
    }
    updateUnits(ug);
}

/**
* Makes a new object by cloning the empty unit group received from the database.
* @memberof module:unit_groups
*/
function setNewUnitGroup() {
    currentUnitGroup = kepler.clone(emptyUnitGroup);
    currentUnitGroupId = currentUnitGroup.id;
    currentUnitGroup.unit_type_id = $('#unitGroupType').val();
    setCurrentSelection();
}


/**
* Copies all of the units in units list and sets the hidden attribute
* to true for the units that are already related to the current unit group.
* @memberof module:unit_groups
*/
function setUnitCopy() {
    if(currentUnitGroup === null) return;
    if(currentUnitGroup.units.length === 0) {
        for(var i in unitsCopy){
            unitsCopy[i].hidden = false;
        }
    }
    else {
        for (var k = 0; k < unitsCopy.length; k++) {
            unitsCopy[k].hidden = false;
            for (var j = 0; j < currentUnitGroup.units.length; j++) {
                if(unitsCopy[k].id === currentUnitGroup.units[j].id) {
                    unitsCopy[k].hidden = true;
                    break;
                }
            }
        }
    }
}

/**
* Displays the information of the current unit group in the corresponding
* fields.
* @memberof module:unit_groups
*/
function fillEditFields(){
    $("#noSelectedUnitGroup").hide();
    $("#editFields").show();
    $("#unitGroupName").val("");
    $("#unitGroupName").attr("placeholder",
        kepler.translate('content.unit_group_give_identifier') + ".");
    setCurrentSelection();
    setUnitCopy();
}


/**
* Fill the unit groupt list with only the units that match the given string.
* @memberof module:unit_groups
* @param {string} inputText - The string that has to be found in the
*                             name of every displayed unit group.
*/
function updateUnitGroupList(inputText){
    $("#unitGroupList").empty();
    var filter = inputText.toLowerCase();
    for (var i = 0; i < unitGroups.length; i++) {
        var unitGroup = unitGroups[i];
        var displayName = unitGroup.name;
        var displayLower = displayName.toLowerCase();

        if (displayLower.indexOf(filter) != -1) {
            var option = $("<option>");
            option.val(unitGroup.id);
            option.text(displayName);

            $("#unitGroupList").append(option);
        }
    }
}

/**
* Checks units to see if their names include the given string.
* If the string is found, adds the unit to the list of units.
* If the string is empty, displays all units.
* @memberof module:unit_groups
* @param {string} inputText - The string that is searched from the unit name.
*/
function updateUnitList(inputText){
    $("#unitList").empty();
    var filter = inputText.toLowerCase();
    for (var i = 0; i < unitsCopy.length; i++) {
        var unit = unitsCopy[i];
        if(unit.hidden) continue;
        var displayName = unit.name;
        var displayLower = displayName.toLowerCase();
        if (displayLower.indexOf(filter) != -1) {
            var option = $("<option>");
            option.val(unit.id);
            option.text(displayName);
            $("#unitList").append(option);
        }
    }
}

/**
* Displays the information of the current unit and empties the unit qualifier
* edit field.
* @memberof module:unit_groups
*/
function updateUnitInfo() {
    if (currentUnit === null){
        $("#noUnitSelection").show();
        $("#unitInfo").hide();
    }
    else {
        $("#unitName").text(currentUnit.name);
        if (currentUnit.description === null){
            $("#unitDescr").text(
              kepler.translate('content.unit_group_no_descr'));
        }
        else {
            $("#unitDescr").text(currentUnit.description);
        }
        $("#maxUserGroupSize").text(currentUnit.max_user_group_size);
        $("#unitQualifier").val("");
    }
}

/**
* Sets the current unit null and empties the search field of the modal.
* Displays all units, that are not yet related to the unit group,
* and their information in the modal.
* @memberof module:unit_groups
*/
function initModal() {
    currentUnit = null;
    currentUnitId = null;
    $("#unitSearchField").val("");
    if(currentUnitGroup !== null) {
        setUnitCopy();
        updateUnitList("");
        updateUnitInfo();
    }
}

/**
* Sets hidden to true for the current selected unit in a local copy of
* the units variable.
* @memberof module:unit_groups
*/
function hideUnit() {
    unitsCopy[currentUnit.index].hidden = true;
}


/**
* Empties the edit fields and reloads the unit group list.
* @memberof module:unit_groups
*/
function resetView() {
    $("#unitGroupName").val("").removeAttr("placeholder");
    $("#unitGroupList").empty();
    $("#units").empty();
    $("#units").hide();
    //$("#btnAddUnit").hide();
    unitGroupList.load();
    $("#noSelectedUnitGroup").show();
    $("#editFields").hide();
}

/**
* 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:unit_groups
*/
function doc_ready(){
    $("#navUnitGroups").addClass("active");

    unitGroupList =
        kepler.createLoadElement("#unitGroupList", function (element) {
            call = kepler.getUnitGroups(function(data) {
                var unitGroupList = $("#unitGroupList");
                unitGroups = data.unit_groups;
                emptyUnitGroup = data.empty_unit_group;
                units = data.units;
                types = data.unit_types;
                unitsCopy = kepler.clone(units);

                for (var i = 0; i < unitGroups.length; i++) {
                    var unitGroup = unitGroups[i];
                    var opt = $('<option>');
                    opt.val(unitGroup.id).text(unitGroup.name);
                    element.append(opt);
                }

                if(currentUnitGroup === null && currentUnitGroupId !== null) {
                    for (var k = 0; k < unitGroups.length; k++){
                        if (unitGroups[k].id === currentUnitGroupId) {
                            currentUnitGroup = unitGroups[k];
                            fillEditFields();
                            break;
                        }
                    }
                }
                if(currentUnitGroup !== null) {
                    $('#unitGroupList option[value="' + currentUnitGroupId +
                    '"]').prop("selected", true);
                }
                setUnitGroupType();
        });
        return call;
    });
    unitGroupList.load();

    $("#searchField").on("input", function(v){
        var inputText = v.target.value;
        updateUnitGroupList(inputText);
    });

    /**
    * Makes a clone of the selected unit group and sets its information to the
    * edit fields.
    *
    * @function
    * @name unitGroupList change
    * @inner
    * @memberof module:unit_groups
    */
    $("#unitGroupList").change(function (v) {
        if (currentUnitGroupId !== v.target.value && v.target.value !== "") {
            for (var i = 0; i < unitGroups.length; i++) {
                if (unitGroups[i].id === parseInt(v.target.value)){
                    currentUnitGroup = kepler.clone(unitGroups[i]);
                    currentUnitGroupId = unitGroups[i].id;
                }
            }
            fillEditFields();
        }
    });

    /**
    * If current unit group id is null, makes a call to create a new unit group
    * with the given parameters. Otherwise makes a call to save changes to the
    * current unit group. If important fields are empty, shows a notification
    * without making a call. Updates the view after the call has been completed.
    *
    * @function
    * @name btnSaveChanges click
    * @inner
    * @memberof module:unit_groups
    */
    $("#btnSaveChanges").click(function() {
        if(currentUnitGroupId === null) {
            alert(kepler.translate('content.unit_group_select_or_new') + "!");
            //TODO (Anu) Don't use an alert!
        }
        else if (currentUnitGroup.id !== -1) {
            var params = {
                "name_fi": $("#unitGroupName").val(),
                "unit_group_id": currentUnitGroup.id,
                "unit_type_id": currentUnitGroup.unit_type_id,
                "units": currentUnitGroup.units,
            };
            console.log(params); //TODO (Anu) Remove when not needed.
            kepler.editUnitGroup(
                params,
                function(data) {
                    kepler.showResult(data.result, "#notification");
                    currentUnitGroup = null;
                    resetView();
                }
            );
        }
        else {
            if($("#unitGroupName").val() === ""){
                alert(kepler.translate('label.give_name') + "!");
                //TODO (Anu) Don't use an alert!
                return;
            } else {
                var params = {
                    "name_fi": $("#unitGroupName").val(),
                    "unit_type_id": currentUnitGroup.unit_type_id,
                    "units": currentUnitGroup.units,
                };
                console.log("Tehdään uutta kurssia. Parametrit ovat:");
                console.log(params);
                //TODO (Anu) Remove console.log when not needed.

                kepler.addUnitGroup(
                    params,
                    function(data) {
                        kepler.showResult(data.result, "#notification");
                        currentUnitGroupId = data.result.unit_group_id;
                        currentUnitGroup = null;
                        resetView();
                    }
                );
            }
        }
    });

    /**
    * If the current unit group id is not null, removes it from the database.
    *
    * @function
    * @name btnDeleteUnitGroup click
    * @inner
    * @memberof module:unit_groups
    */
    $("#btnDeleteUnitGroup").click(function() {
        if(currentUnitGroupId === null) {
            alert(kepler.translate('content.unit_group_no_selection') + ".");
            // TODO Don't use an alert
        }
        else {
            $("#modalButtonYes").off();
            /**
            * Makes a call to remove the current unit group from the database.
            *
            * @function
            * @name modalButtonYes click
            * @inner
            * @memberof module:unit_groups
            */
            $("#modalButtonYes").click(function () {
                if (currentUnitGroup.id === -1) {
                    currentUnitGroup = null;
                    currentUnitGroupId = null;
                    resetView();
                }
                else {
                    kepler.deleteUnitGroup(
                        { "unit_group_id": currentUnitGroupId },
                        function(data) {
                            kepler.showResult(data.result, "#notification");
                            currentUnitGroup = null;
                            currentUnitGroupId = null;
                            resetView();
                        }
                    );
                }
            });

            $("#modalLabel").text(currentUnitGroup.name);
            $("#modalCancel").modal('show');
        }
    });

    /**
    * Sets the current unit group to null and updates the contents of the edit
    * fields.
    *
    * @function
    * @name btnAddNewUnitGroup click
    * @inner
    * @memberof module:unit_groups
    */
    $("#btnAddNewUnitGroup").click(function() {
        currentUnitGroup = null;
        currentUnitGroupId = null;
        $("option:selected").prop("selected", false);
        setNewUnitGroup();
        fillEditFields();
    });

    $("#btnAddUnit").click(function() {
        $("#modalUnit").modal('show');
        initModal();
    });

    $("#unitSearchField").on("input", function(v){
        var inputText = v.target.value;
        updateUnitList(inputText);
    });

    /**
    * Displays the information of the selected unit.
    *
    * @function
    * @name unitList change
    * @inner
    * @memberof module:unit_groups
    */
    $("#unitList").change(function (v) {
        $("#noUnitSelection").hide();
        $("#unitInfo").show();
        if (currentUnitId !== v.target.value && v.target.value !== "") {
            var selectedId = parseInt(v.target.value);
            for (var i = 0; i < units.length; i++) {
                if (units[i].id === selectedId){
                    currentUnit = units[i];
                    currentUnitId = units[i].id;
                    currentUnit.index = i;
                    break;
                }
            }
            updateUnitInfo();
        }
    });

    /**
    * Adds the selected unit to the current unit group's unit list and updates
    * the view.
    *
    * @function
    * @name modalButtonAdd click
    * @inner
    * @memberof module:unit_groups
    */
    $("#modalButtonAdd").click(function() {
        currentUnit.qualifier = $("#unitQualifier").val();
        currentUnitGroup.units.push(currentUnit);
        $("#modalUnit").modal('hide');
        addUnitToUnitGroupInfo(currentUnit);
        hideUnit();
    });

    $("#modalButtonCancel").click(function() {
        $("#modalUnit").modal('hide');
    });
}

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