Source: reservations.js

(
/**
* Contains the functionalities related to the reservations page.
*
* @module reservations
* @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 reservations = null;
var currentTime;
var cal = null;
var savedTSColor;
var savedTitle;
var eventReservation = null;
var reservationId = null;
var reservationInfo;


/**
* An utility function that creates a click event to a button.
* Returns a function that shows a modal with the correct information and can
* cancel a reservation. If the reservation is canceled, it updates the view.
* @memberof module:reservations
* @param {string} reservationId - The ID of the reservation to be canceled.
* @param {string} reservationInfo - The information of the reservation to be
* canceled.
* @returns A function that shows a modal with the correct information and can
* cancel a reservation.
*/
function make_cancelReservation(reservationId, reservationInfo) {
    return function () {
        $("#modalButtonYes").off();
        /**
        * Makes a call to cancel the selected reservation.
        *
        * @function
        * @name modalButtonYes click
        * @inner
        * @memberof module:reservations
        */
        $("#modalButtonYes").click(function () {
            kepler.deleteReservation(
                { 'reservation_id': reservationId },
                function(data) {
                    kepler.showResult(data.result, "#notification");
                    if (data.result.success) {
                        reloadReservations();
                        reservationId = 0;
                        reservationInfo = null;
                    }
                }
            );
        });
        $("#modalLabel").text(reservationInfo);
        $("#modalCancel").modal('show');
    };
}

/**
 * Returns an event handler for turning the list arrow icon.
 * @memberof module:reservations
 * @param icon - The icon jQuery element.
 * @param {boolean} open - Specifies if the arrow should be turned to
 * opened or closed position.
 */
function make_listArrowTurn(icon, open) {
    return function () {
        if (open) {
            icon.removeClass("list-closed");
            icon.addClass("list-open");
        } else {
            icon.removeClass("list-open");
            icon.addClass("list-closed");
        }
    };
}

/**
* Creates a list element for each reservation. Creates a toggleable list for
* each reservation, which includes the information of the reservation.
* @memberof module:reservations
*/
function initReservationTable(){
    var resTable = $('#reservationList');
    for (var i = 0; i < reservations.length; i++) {
        var res = reservations[i];
        var resDiv = $('<li>').addClass('reservation').attr('id',"li" + i);

        var unitName = res.unit_group + "/" +
            res.unit_group_qualifier + ', ' +
            res.unit_name;

        var resTableRow = $('<div>').addClass('list-group-item');
        if (res.reservation_status === "superuser_canceled_id") {
            resTableRow.addClass("list-group-item-danger");
        }
        else {
            resTableRow.addClass("list-group-item-info");
        }
        resTableRow.attr("id", "header" + i).attr("data-toggle", "collapse");
        resTableRow.attr("data-target", "#row" + i).css("cursor","pointer");

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

        resTableRow.append(glyphIcon);

        var reservationTime = kepler.datetimeIntervalString(res.start_time,
          res.end_time);
        reservationInfo = " " + unitName + " " + reservationTime;

        var timeSpan = $("<div>").text(reservationTime);
        timeSpan.css("display", "inline-block").css("min-width", "12em");
        timeSpan.css("margin-left", "1em");

        resTableRow.append(timeSpan);

        resTableRow.append($("<div>").text(unitName).css("display",
            "inline-block"));

        if (res.reservation_status === "superuser_canceled_id"){
            var cancelledSpan = $("<div>").text(
                kepler.translate('content.reservations_cancelled_time_slot'));
            cancelledSpan.css("display","inline-block").css("min-width","12em");
            cancelledSpan.css("margin-left", "1em");

            resTableRow.append(cancelledSpan);
        }

        resDiv.append(resTableRow);

        var resTableRowDiv = $('<div>').addClass('collapse');
        resTableRowDiv.attr('id',"row" + i);

        var groupLi = $("<li>").addClass("list-group-item");
        var heading = kepler.translate('label.group') + ": ";
        groupLi.text(heading + res.user_group.name);

        resTableRowDiv.append(groupLi);

        var infoText = "";
        if(res.notes.length !== 0) {
            infoText = res.notes[0].note;
            var infoLi = $("<li>").addClass("list-group-item");
            var infoHead = kepler.translate('content.reservations_extra_info');
            infoHead += ": ";
            infoLi.text(infoHead + infoText);
            resTableRowDiv.append(infoLi);
        }

        resTableRowDiv.on('show.bs.collapse',
                           make_listArrowTurn(glyphIcon, true));
        resTableRowDiv.on('hide.bs.collapse',
                           make_listArrowTurn(glyphIcon, false));

        var rtRowButton = $("<button>").addClass("btn btn-default");
        rtRowButton.text(kepler.translate('button.cancel_reservation'));
        if (res.reservation_status !== "superuser_canceled_id") {
            rtRowButton = $("<button>").addClass("btn btn-default");
            rtRowButton.text(kepler.translate('button.cancel_reservation'));

            rtRowButton.click(make_cancelReservation(res.id, reservationInfo));

            var rtRowButtonDiv = $("<div>").attr("align", "right");
            rtRowButtonDiv.append(rtRowButton);
            resTableRowDiv.append(rtRowButtonDiv);
        }
        resDiv.append(resTableRowDiv);

        resTable.append(resDiv);
    }

}


/**
* Shows the wanted reservations based on which options (past, present, future)
* are checked and hides the rest. If no reservations match the selected time
* frame, shows a notification.
* @memberof module:reservations
*/
function updateReservationTable(){
    $("#noReservationsNotice").hide();

    var displayedCount = 0;
    var showPast = $('#selectionPast').is(':checked');
    var showCurrent = $('#selectionCurrent').is(':checked');
    var showFuture = $('#selectionFuture').is(':checked');
    for (var i = 0; i < reservations.length; i++){
        if ( (showPast && reservations[i].end_time < currentTime) ||
             (showCurrent && (reservations[i].start_time < currentTime &&
              reservations[i].end_time > currentTime) ) ||
             (showFuture && reservations[i].start_time > currentTime) ){
            $("#li" + i).show();
            displayedCount++;
        }
        else $("#li" + i).hide();

    }
    if(displayedCount === 0) {
        $("#noReservationsNotice").show();
    }
}

/**
* Fetches the information from the database and updates the list of
* user's current reservations.
* @memberof module:reservations
*/
function reloadReservations() {
    var resTable = $('#reservationList');
    resTable.empty();

    kepler.getReservationsUser(function (data) {
        currentTime = data.timestamp;
        reservations = data.reservations;
        initReservationTable();
        updateReservationTable();
    });
}

/**
* Stores the reservation ID and reservation information to their own variables.
* @memberof module:reservations
*/
function selectReservation(reservation) {
    if (eventReservation !== null) {
        //eventReservation.backgroundColor = savedTSColor;
       // eventReservation.title = savedTitle;
        eventReservation.k.selected = false;
    }
    eventReservation = reservation;
    reservation.k.selected = true;

    reservationId = reservation.k.reservation_id;
    reservationInfo = reservation.title;

    cal.fullCalendar('rerenderEvents');
}

/**
* Gets the selected timeslot id and sends it to the reservation.
* @memberof module:reservations
*/
function calendarClick (event, data ){
    if (event.k.reservation !== undefined){
        if(event.k.reservation.status === "active_id" ) {
            selectReservation(event);
        }
    }
}

/**
* Calls wanted events to be rendered in the calendar.
* @memberof module:reservations
*/
function calendarEventRender(event, element, view) {
    calUtil.defaultEventRender(event, element, view);
}

/**
* Initialises the calendar with the wanted parameters.
* @memberof module:reservations
*/
function initCalendar() {
    cal = calUtil.initCal(calendarClick, calendarEventRender);

     cal.fullCalendar('addEventSource', {
        events: function(start, end, timezone, callback) {
             var params = {
                'start_time': start.toISOString(),
                'end_time': end.toISOString()
            };

            kepler.getCalendarEvents(params, function(data) {
                 var events = [];
                 for (var i = 0; i < data.events.length; i++) {

                    var event = data.events[i];
                    calEvent = calUtil.makeCalendarEvent(event,
                        {reservation: calUtil.colorPalette.lightBlue} );

                    if (event.type === 'reservation') {
                        calEvent.k.pointer = true;
                        calEvent.k.selectedColor =
                            calUtil.colorPalette.warningRed;
                        calEvent.k.reservation_id = event.reservation.id;
                    }

                    events.push(calEvent);
                }
                callback(events);
            });
        }
    });

}

/**
* Empties the calendar and refetches the events from all calendar sources.
* @memberof module:reservations
*/
function updateCalendar(){
    if (cal !== null) {
        cal.fullCalendar('refetchEvents');
    }
}

/**
* Checks if the user is on the right view and if correct event is selected.
* Then deletes the selected event and refreshes the calendar and the list.
* @function
* @name calendarCancelBtn click
* @memberof module:reservations
*/
$("#calendarCancelBtn").click(function(){
   if(reservationId !== null){
        $("#modalButtonYes").off();
        $("#modalButtonYes").click(function () {
            kepler.deleteReservation(
                { 'reservation_id': reservationId },
                function(data) {
                    kepler.showResult(data.result, "#calNotification");
                    if (data.result.success) {
                        reloadReservations();
                        updateCalendar();
                    }
                }
            );
        });
        $("#modalLabel").text(reservationInfo);
        $("#modalCancel").modal('show');

   }else {
       alert('');
   }
});

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

    reloadReservations();

    $("#timeframeSelection").change(function(v) {
        updateReservationTable();
    });

    $('#displayedSelection').change(function (data) {
        updateReservationTable();
    });

    /**
    * Toggles between the calendar and the list view buttons.
    *
    * @function
    * @name calendarCancelBtn click
    * @inner
    * @memberof module:reservations
    */
     $("#toggleCalendarBtn").click(function(data) {
        if ($("#calendarView").is(":visible")) {
            //initList();
            $("#displayedSelection").show();
            $("#shiftTimeFrame").show();
            $("#reservationList").show();
            $("#calendarView").hide();
            $("#toggleCalendarBtn").text(
                kepler.translate('content.reservation_frame_button_calendar'));
        } else {
            $("#displayedSelection").hide();
            $("#shiftTimeFrame").hide();
            $("#reservationList").hide();
            $("#calendarView").show();
            $("#toggleCalendarBtn").text(
                kepler.translate('content.reservation_frame_button_list'));
            if (cal === null) {
                initCalendar();
            }
        }
    });
}


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