<file_sep>var tableDiv = document.getElementById('tableDiv');
function getReservationsByDate(){
    var date = document.getElementById('dateField').value;
    var data = {dt: date};

    $.post('http://localhost:3000/reservations/restaurant/all_reservations/', data, function(response){
        var reservationArray = response;
        var sortedReservations = [];

        //Sort reservations by table
        reservationArray.forEach(function(reservation){
            sortedReservations[reservation.table_id] = sortedReservations[reservation.table_id] || [];
            sortedReservations[reservation.table_id].push(reservation);
        });
        console.log(sortedReservations);
        tableDiv.innerHTML = tableBuilder(sortedReservations);
        sortTable();
    })

}

function tableBuilder(reservationArray){
    var table = "<div class='row'>";
    for(var key in reservationArray){
        var table = table + "<div class='col-lg-6'><h3>Table " + key +"</h3>\n<table class='table table-hover table-bordered reservationTable'><tr><th>Name</th><th>Number of people</th><th>Start Time</th><th>End Time</th><th>Phone</th></tr>";
        var j;
        for(j = 0; j < reservationArray[key].length; j++){
            var startTime = new Date(reservationArray[key][j].start_dateTime);
            startTime = startTime.getHours() - 1 + ":" + (startTime.getMinutes()<10?'0':'') + startTime.getMinutes();
            var endTime = new Date(reservationArray[key][j].end_dateTime);
            endTime = endTime.getHours() - 1 + ":" + (endTime.getMinutes()<10?'0':'') + endTime.getMinutes();


            table += "<tr>";
            table = table + "<td>" + reservationArray[key][j].name + "</td>";
            table = table + "<td>" + reservationArray[key][j].number_of_people + "</td>";
            table = table + "<td>" + startTime + "</td>";
            table = table + "<td>" + endTime + "</td>";
            table = table + "<td>" + reservationArray[key][j].phone_number + "</td>";
            table += "</tr>";
        }
        table += "</table></div>";
    }
    table += "</div>";
    return table;
}

function sortTable() {
    var table, rows, switching, i, x, y, shouldSwitch;
    table = document.getElementsByClassName('reservationTable');

    var j;
    for(j = 0; j < table.length; j++){
        switching = true;
        /* Make a loop that will continue until
        no switching has been done: */
        while (switching) {
            // Start by saying: no switching is done:
            switching = false;
            rows = table[j].rows;
            /* Loop through all table rows (except the
            first, which contains table headers): */
            for (i = 1; i < (rows.length - 1); i++) {
                // Start by saying there should be no switching:
                shouldSwitch = false;
                /* Get the two elements you want to compare,
                one from current row and one from the next: */
                x = rows[i].getElementsByTagName("TD")[2];
                y = rows[i + 1].getElementsByTagName("TD")[2];
                // Check if the two rows should switch place:
                if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
                    // If so, mark as a switch and break the loop:
                    shouldSwitch = true;
                    break;
                }
            }
            if (shouldSwitch) {
                /* If a switch has been marked, make the switch
                and mark that a switch has been done: */
                rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
                switching = true;
            }
        }
    }

}<file_sep># Lotus Garden
Distributed Systems Project
<file_sep>var tbls = [];
var tblMinSeats = [1,1,2,1,1,3,4,4,3];
var tblMaxSeats = [2,2,4,2,2,6,8,8,6];
var numTables = 9;
var seats = 1;

$(document).ready(function(){
    createDropDownMenu();
    $("#reserveButton").on("click", reserveButtonHandler);
    disableAllTables();
});

// Adds the items to the Dropdown menu
function createDropDownMenu() {
    var dropdown = $("#numberSeatsItems");

    for (var i = 1; i < 9; i++) {
        dropdown.append('<a class="dropdown-item" onclick="changeNumberSeats(' + i + ')">' + i + '</a>');
    }
}

// The function that is called when the user selects a value from the dropdown
function changeNumberSeats (numseats) {
    $("#numberSeats").html(numseats);
    seats = numseats;
    selected = null;

    if (timePicked) {
        getReservedFromDb();
    }
}

function mouseOverHandler(e) {
    var id = e.currentTarget.id;
    if ( (tbls[id.replace("rtb","")-1].minutes_available) < 120) colorYellow(id);
    else colorGreen(id);
}

function mouseOffHandler(e) {
    var id = e.currentTarget.id;
    if (id != selected) removeGreen(id);
}

function colorGreen (tableID) {
    var src = $("#" + tableID).attr("src");
    if (src.indexOf("_green") == -1 && src.indexOf("_yellow") == -1 ) {
        $("#" + tableID).attr("src", src.replace(".png", "_green.png"));
    }    
}

function colorYellow (tableID) {
    var src = $("#" + tableID).attr("src");
    if (src.indexOf("_green") == -1 && src.indexOf("_yellow") == -1 ) {
        $("#" + tableID).attr("src", src.replace(".png", "_yellow.png"));
    }    
}

function removeGreen (tableID) {
    var src = $("#" + tableID).attr("src");
    src = src.replace("_green", "");
    src = src.replace("_yellow", "");
    $("#" + tableID).attr("src", src);
}

function createTableList (tblList) {

    enableAllTables();

    tbls = [];

    for (var i = 1; i <= numTables; i++) {
        var tbl = {
            id: i,
            elem: $("#rtb" + i),
            minutes_available: 120,
            free: true,
            minSeats: seats >= tblMinSeats[i-1],
            maxSeats: seats <= tblMaxSeats[i-1]
        }
        tbls.push(tbl);
    }    

    for(table of tblList) {
        
        var id = table.table_id - 1;
        if(!tbls[id]) continue;
        tbls[id].minutes_available = table.minutes_available;
        tbls[id].free = table.minutes_available >= 60;
        
    }

    mangageTableViewer();
}

function getReservedFromDb () {
    var dateTime = selectedDate + " " + timePicked + "Z";
    console.log("Fetch reservations for "+ dateTime);

    $.post("/reservations/tables/", {
        dt: dateTime
    },
    function (data) {
        console.log(data);
        createTableList(data);
    });
}

// Gray out all the tables that are not to be reserved
function mangageTableViewer () {
    for (table of tbls) {
        table.elem.attr("title", "");
        if (!table.free || !(table.maxSeats && table.minSeats)) {
            table.elem.fadeTo(500, 0.3);
            table.elem.unbind('mouseenter mouseleave click');
            table.elem.attr("title", "This table is not available");
            if (table.free && !table.minSeats) table.elem.attr("title", "Please reserve more seats for this table");
            if (table.free && !table.maxSeats) table.elem.attr("title", "This table has not enough seats");
        } else {
            if (table.minutes_available < 120) {
                table.elem.attr("title", "This is only available for " + table.minutes_available + " Minutes!");
            }
        }
    }
}

function enableAllTables () {
    $(".reserveTable").unbind("click");
    $(".reserveTable").fadeTo(800, 1);    
    $(".reserveTable").bind("mouseenter", mouseOverHandler);
    $(".reserveTable").bind("mouseleave", mouseOffHandler);
    $(".reserveTable").bind("click", clickHandler);
    selected = null;
    $("#reserveButton").removeClass("btn-success");
    $("#personalDataInputContainer").slideUp("fast");
    for (var i = 1; i < 10; i++) {
        removeGreen("rtb" + i);
    }
}

function disableAllTables () {
    $(".reserveTable").fadeTo(100, 0.2);
    $(".reserveTable").bind("click", function() {
        alert("Please select a time first!");
    });
}

function clickHandler(e) {
    for (table of tbls) {
        removeGreen("rtb" + table.id);
    }

    selected = e.currentTarget.id;
    colorGreen(selected);
    $("#personalDataInputContainer").slideDown("slow", function () {
        $("#reserveButton").addClass("btn-success");
        $("#nameInput").focus();
    });
    console.log("Click on: " + selected);
}

function refreshTableView () {
    getReservedFromDb();
}

function reserveButtonHandler () {
    if (!$("#reserveButton").hasClass('btn-success')) return false;

    var reservation = {
        name: $("#nameInput").val(),
        email: $("#mailInput").val(),
        phone_number: $("#phoneInput").val(),
        start_dateTime: selectedDate + " " + timePicked + "Z",
        end_dateTime: calcEndTime(selected.replace("rtb", "")),
        table_id: selected.replace("rtb", ""),
        number_of_people: seats
    }
    $.post("/reservations/add/", reservation, function (data, err) {
        console.log(err, data);
        if (data) {
            alert("Reservation was SUCCESSFULL!");
            $("#reserveButton").removeClass("btn-success");
            $("#personalDataInputContainer").slideUp("fast");
            disableAllTables();
        }
    });
}

function calcEndTime (tableID) {
    var time = timePicked;
    var available = tbls[tableID-1].minutes_available;
    var endTime = time.split(":");

    endTime[0] = parseInt(endTime[0]) + Math.floor(available / 60);
    endTime[1] = (parseInt(endTime[1]) + available) % 60

    if (endTime[1].toString().length == 1) endTime[1] = "0" + endTime[1];

    var endDateTime = selectedDate + " " + endTime[0] + ":" + endTime[1] + "Z";

    return (endDateTime);
}<file_sep>var selectedDate;

function setDateToToday () {
    //Prevent previous dates in datepicker
    var input = document.getElementById("dateField");
    var today = new Date();
    var day = today.getDate();
    // Set month to string to add leading 0
    var mon = new String(today.getMonth()+1); //January is 0!
    var yr = today.getFullYear();
    if(mon.length < 2) { mon = "0" + mon; }
    var date = new String( yr + '-' + mon + '-' + day );
    selectedDate = date;
    input.value = date;
    input.disabled = false;
    input.setAttribute('min', date);
}

function setDate () {
    console.log($("#dateField").val());
    selectedDate = $("#dateField").val();
    if (timePicked) {
        refreshTableView();
    }
}

$(document).ready(function(){
    //$("#dateField").datepicker();
    setDateToToday();
    $("#dateField").change(setDate);
});<file_sep>
//Set datetime in form to current time
var now = new Date();
var utcString = now.toISOString().substring(0,19);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();

var localDatetime = year + "-" +
    (month < 10 ? "0" + month.toString() : month) + "-" +
    (day < 10 ? "0" + day.toString() : day) + "T" +
    (hour < 10 ? "0" + hour.toString() : hour) + ":" +
    (minute < 10 ? "0" + minute.toString() : minute) +
    utcString.substring(16,19);

var datetimeField = document.getElementById("dateField");
datetimeField.value = localDatetime;