<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>EMhub {{ emhub_title }}</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/fonts/circular-std/style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='libs/css/style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='libs/css/emhub.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/fonts/fontawesome/css/fontawesome-all.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/vector-map/jqvmap.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/jvectormap/jquery-jvectormap-2.0.2.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/charts/chartist-bundle/chartist.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/charts/c3charts/c3.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/charts/morris-bundle/morris.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/daterangepicker/daterangepicker.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/datatables/css/dataTables.bootstrap4.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/datatables/css/buttons.bootstrap4.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/datatables/css/select.bootstrap4.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/datatables/css/fixedHeader.bootstrap4.css') }}">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='vendor/daterangepicker/daterangepicker.css') }}">

    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/full-calendar/packages/core/main.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/full-calendar/packages/daygrid/main.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/full-calendar/packages/timegrid/main.min.css') }}">

    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/bootstrap-select/css/bootstrap-select.css') }}">

    <link rel="stylesheet" href="{{ url_for('static', filename='vendor/datepicker/tempusdominus-bootstrap-4.css') }}">

    <link rel="shortcut icon" href="{{ url_for('static', filename='images/emhub.ico') }}">

</head>

<body>
<!-- main wrapper -->
<div class="dashboard-main-wrapper">

    {% include 'main_topbar.html' %}

    {% include 'main_left_sidebar.html' %}

    <div class="dashboard-wrapper">

        <div class="container-fluid dashboard-content" id="main-content">
        </div>

        <!-- footer -->
        <div class="footer">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-xl-6 col-lg-6 col-md-12 col-sm-12 col-12">
                        Copyright © 2018 Concept. All rights reserved. Dashboard by <a href="https://colorlib.com/wp/">Colorlib</a>.
                    </div>
                    <div class="col-xl-6 col-lg-6 col-md-12 col-sm-12 col-12">
                        <div class="text-md-right footer-links d-none d-sm-block">
                            Version: {{ version }}
{#                            <a href="javascript: void(0);">Version: </a>#}
{#                            <a href="javascript: void(0);">Support</a>#}
{#                            <a href="javascript: void(0);">Contact Us</a>#}
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- end footer -->
    </div>

    <!-- ============================================================== -->
    <!-- User Modal -->
    <!-- ============================================================== -->
    <div class="modal fade" id="user-modal" tabindex="-1" role="dialog" aria-labelledby="userModal" aria-hidden="true">
    </div>

    <!-- ============================================================== -->
    <!-- Application Modal -->
    <!-- ============================================================== -->
    <div class="modal fade" id="application-modal" tabindex="-1" role="dialog" aria-labelledby="applicationModal" aria-hidden="true">
    </div>

</div>
<!-- end main wrapper -->

<!-- JavaScript libraries -->
<script src="{{ url_for('static', filename='vendor/jquery/jquery-3.3.1.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/bootstrap/js/bootstrap.bundle.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/slimscroll/jquery.slimscroll.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/bootstrap-select/js/bootstrap-select.js') }}"></script>

<script src="{{ url_for('static', filename='vendor/full-calendar/packages/core/main.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/full-calendar/packages/daygrid/main.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/full-calendar/packages/timegrid/main.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/full-calendar/packages/interaction/main.min.js') }}"></script>


<script src="{{ url_for('static', filename='libs/js/main-js.js') }}"></script>

<!-- chart chartist js -->
<script src="{{ url_for('static', filename='vendor/charts/chartist-bundle/chartist.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/charts/chartist-bundle/chartist-plugin-threshold.js') }}"></script>
<!-- chart C3 js -->
<script src="{{ url_for('static', filename='vendor/charts/c3charts/c3.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/charts/c3charts/d3-5.4.0.min.js') }}"></script>
<!-- chartjs js -->
<script src="{{ url_for('static', filename='vendor/charts/charts-bundle/Chart.bundle.js') }}"></script>
<!-- sparkline js -->
<script src="{{ url_for('static', filename='vendor/charts/sparkline/jquery.sparkline.js') }}"></script>
<!-- gauge js -->
<script src="{{ url_for('static', filename='vendor/gauge/gauge.min.js') }}"></script>
<!-- morris js -->
<script src="{{ url_for('static', filename='vendor/charts/morris-bundle/raphael.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/charts/morris-bundle/morris.js') }}"></script>

<!-- parsley -->
<script src="{{ url_for('static', filename='vendor/parsley/parsley.js') }}"></script>

<!-- datepicker -->
<script src="{{ url_for('static', filename='vendor/datepicker/datepicker.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/datepicker/moment.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/datepicker/tempusdominus-bootstrap-4.js') }}"></script>

<!-- emhub -->
<script src="{{ url_for('static', filename='libs/js/emhub.js') }}"></script>
<script src="{{ url_for('static', filename='libs/js/emhub_applications.js') }}"></script>
<script src="{{ url_for('static', filename='libs/js/emhub_forms.js') }}"></script>


<script type="text/javascript">
    /* Some variables */
    var possible_owners = {{ possible_owners|tojson }};
    var resources = {{ resources|tojson }};
    var possible_operators = {{ possible_operators|tojson }};

    var is_devel = {{ is_devel|tojson }};
    var booking_type = 'booking';
    var repeat_value = null;
    var has_calendar = true;
    var content_url = "{{ url_for('get_content') }}";

    Api.urls = {
        application: {
            create: "{{ url_for('api.create_application') }}",
            update: "{{ url_for('api.update_application') }}",
            delete: "{{ url_for('api.delete_application') }}"
        },
        project: {
            create: "{{ url_for('api.create_project') }}",
            update: "{{ url_for('api.update_project') }}",
            delete: "{{ url_for('api.delete_project') }}"
        },
        entry: {
            create: "{{ url_for('api.create_entry') }}",
            update: "{{ url_for('api.update_entry') }}",
            delete: "{{ url_for('api.delete_entry') }}"
        },
        template: {
            create: "{{ url_for('api.create_template') }}",
            update: "{{ url_for('api.update_template') }}",
            delete: "{{ url_for('api.delete_template') }}"
        },
        resource: {
            create: "{{ url_for('api.create_resource') }}",
            update: "{{ url_for('api.update_resource') }}",
            delete: "{{ url_for('api.delete_resource') }}"
        },
        user: {
            create: "{{ url_for('api.create_user') }}",
            update: "{{ url_for('api.update_user') }}",
            delete: "{{ url_for('api.delete_user') }}",
            register: "{{ url_for('api.register_user') }}"
        }
    };

    var application_config = {
        on_update: null,
        modal_status: null
    };


    (function(window, document, $, undefined) {
    "use strict";

    $('select').selectpicker();

    $('.datetimepicker-input').datetimepicker({
        format: 'YYYY/MM/DD'
    });

    /* Register when the Booking type change */
    $('input[type=radio][name=booking-type-radio]').change(function() {
        booking_type = this.value;
        $('#booking-slot-auth').prop('readonly', this.value != 'slot');
    });

    $('input[type=radio][name=booking-repeat-radio]').change(function() {
        repeat_value = this.value;
    });

    $('input[type=radio][name=booking-modify-radio]').change(function() {
        modify_all = this.value == 'yes';
    });

    })(window, document, window.jQuery);


    function load_main_content(content_id, params) {
        load_html_from_ajax("main-content", get_ajax_content(content_id, params));
    }

    function load_content_fromlink(e) {
        var content_id = e.currentTarget.dataset.contentId;
        load_main_content(content_id);
        e.preventDefault();
    }

    $(document).ready(function(){
        load_main_content("{{ content_id }}", {{ params|tojson }});
    });

    /* ---------------- RESOURCE functions ------------------*/
    /** Get the resource object from its id */
    function getResource(resourceId) {
        for (var r of resources)
            if (r.id == resourceId)
                return r;
        return null;
    }

    /* ---------------- BOOKING functions ------------------ */
    /** Return how many days this booking expands.
     * (Used to calculate costs based on daily costs of the
     * used resource.)
     **/
    function getBookingDays(booking) {
         var time_difference = dateNoTime(booking.end).getTime() - dateNoTime(booking.start).getTime();
         //calculate days difference by dividing total milliseconds in a day
         var days_difference = time_difference / (1000 * 60 * 60 * 24);
         return days_difference + 1;
    }

    /** Helper functions to handle AJAX response or failure */
    function handleBookingAjaxDone(jsonResponse) {
        let error = null;

        if ('bookings_created' in jsonResponse) {
            if (has_calendar)
                add_bookings(jsonResponse.bookings_created);
        }
        else if ('bookings_updated' in jsonResponse) {
            if (has_calendar) {
                remove_bookings(jsonResponse.bookings_updated);
                add_bookings(jsonResponse.bookings_updated);
            }
        }
        else if ('bookings_deleted' in jsonResponse) {
            if (has_calendar)
                remove_bookings(jsonResponse.bookings_deleted);
        }
        else if ('error' in jsonResponse) {
            error = jsonResponse.error;
        }
        else {
            error = 'Unexpected response from server.'
        }

        if (error)
            showError(error);
        else {
            $('#booking-modal').modal('hide');
            if (has_calendar)
                calendar.render();
        }
    }


    function handleAjaxFail(jqXHR, textStatus) {
        showError("Request failed: " + textStatus );
    }

    /* Show the Booking Form, either for a new booking or an existing one */
    function showBookingForm(booking) {
        booking_type = booking.type;
        repeat_value = booking.repeat_value;

        var titlePrefix = null;
        if (booking.id == null) {  // New booking
            titlePrefix = 'Create ';
            booking.user_can_modify = true;
            $('#booking-btn-ok').show();
            $('#booking-btn-delete').hide();
            $('#application-label').html('Not set');
        }
        else {
            titlePrefix = 'Update ';
            if (booking.user_can_modify) {
                $('#booking-btn-delete').show();
                $('#booking-btn-ok').show();
            }
            else {
                $('#booking-btn-delete').hide();
                $('#booking-btn-ok').hide();
            }
            $('#application-label').html(booking.application_label);
        }

        let htmlStr = titlePrefix + ' Booking - ' + booking.resource.name;
        if (is_devel)
            htmlStr += ' (id=' + booking.id + ')';

        $('#booking-modal-title').html(htmlStr);
        $('#booking-btn-ok').html(titlePrefix);

        if (possible_owners.length) {
            $('#booking-owner-select').selectpicker('val', booking.owner.id);
        }
        else {
            $('#booking-owner-text').val(booking.owner.name);
            $('#booking-owner-text').prop('readonly', true);
        }

        if (possible_operators.length) {
            if (booking.operator)
                $('#booking-operator-select').selectpicker('val', booking.operator.id);
        }
        else {
            if (booking.operator)
                $('#booking-operator-select').val(booking.operator.name);
            $('#booking-operator-select').prop('readonly', true);
        }

        if  (booking.type == 'booking' &&
             booking.resource.is_microscope &&
             booking.user_can_modify)
            $('#div-describe-experiment').show();
        else
            $('#div-describe-experiment').hide();

        $('#booking-start-date').val(dateStr(booking.start));
        $('#booking-start-time').val(timeStr(booking.start));
        $('#booking-end-date').val(dateStr(booking.end));
        $('#booking-end-time').val(timeStr(booking.end));
        $('#booking-slot-auth').selectpicker('val', booking.slot_auth.applications);

        $('#booking-title').val(booking.title);
        $('#booking-description').val(booking.description);
        $("input[name=booking-type-radio][value=" + booking.type + "]").prop('checked', true);
        $("input[name=booking-repeat-radio][value=" + booking.repeat_value + "]").prop('checked', true);
        modify_all = null;
        $('input[type=radio][name=booking-modify-radio]').val([]);
        //$("input[name=booking-repeat-radio][value='no']").prop('checked', true);
        $('#booking-title').focus();
        $('#booking-modal').modal('show');
    }

    /** This function will be called when the OK button in the Booking form
     * is clicked. It can be either Create or Update action.
     */
    function onOkButtonClick() {
        // Create Event object info from
        // confirm("Create Booking", "do you really want to create the booking?",
        //         "No", "Yes", function () { alert('clicked yes')})
        // //showMessage("Testing", "Testing");
        // return;
        var owner_id = last_booking.owner.id;
        var operator_id = last_booking.operator ? last_booking.operator.id : null;

        if (possible_owners.length)
            owner_id = $('#booking-owner-select').selectpicker('val');

        if (possible_operators.length) {
            operator_id = $('#booking-operator-select').selectpicker('val');
        }

        var start = dateFromValue('#booking-start-date', '#booking-start-time');
        var end = dateFromValue('#booking-end-date', '#booking-end-time');
        var resource = getResource(last_booking.resource.id);

        var booking = {
            id: last_booking.id,
            title: $('#booking-title').val(),
            start: start,
            end: end,
            type: booking_type,
            description: $('#booking-description').val(),
            owner_id: owner_id,
            operator_id: operator_id,
            resource_id: last_booking.resource.id,
            modify_all: modify_all,
            repeat_value: repeat_value,
            resource: resource,
            experiment: last_booking.experiment,
            application_label: last_booking.application_label,
            costs: last_booking.costs
        };

        if (booking_type == 'slot') {
            booking.slot_auth = {
                applications: $('#booking-slot-auth').selectpicker('val'),
                users: []
            }
        }
        else if (booking_type == 'booking') {
            if (resource.is_microscope && jQuery.isEmptyObject(booking.experiment)) {
                showError("<p>Please describe your experiment!!! <br> " +
                          "At least the fields in the <b>Basic</b> input tab.<p>");
                return
            }
        }

        let endpoint = null;

        if (booking.id) {
            endpoint = "{{ url_for('api.update_booking') }}"
            if (booking.repeat_value != 'no' && modify_all === null) {
                showError("<p>Please select a value for input <b>Modify repeating</b>: " +
                          "<i>Only this</i> or <i>All upcoming</i>.")
                return
            }
        }
        else {
            // Only take into account repeat value when creating a new booking

            if (repeat_value != 'no') {
                try {
                    booking.repeat_stop = dateIsoFromValue('#booking-repeat-stopdate');
                }
                catch(err) {
                    showError("<p>Please provide a valid <b>Stop date</b> for the repeating event.")
                    return
                }
            }
            endpoint = "{{ url_for('api.create_booking') }}"
        }

        if (has_calendar) {
            var error = validateBooking(booking, true);

            if (error != '') {
                showError(error);
                return;
            }
        }

        delete booking.resource;  // resource_id is enough
        // Set dates to ISO string
        booking.start = start.toISOString();
        booking.end = end.toISOString();

        var ajaxContent = $.ajax({
            url: endpoint,
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({attrs: booking}),
            dataType: "json"
        });

        ajaxContent.done(handleBookingAjaxDone);
        ajaxContent.fail(handleAjaxFail);
    }  // function onOkButtonClick

        /** This function will be called when the Delete button in the Booking form
     * is clicked. It can be either Create or Update action.
     */
    function onDeleteButtonClick() {

        //if (last_booking.repeat_id && modify_all === null) {
        if (last_booking.repeat_value != 'no' && modify_all === null) {
                showError("<p>Please select a value for input <b>Modify repeating</b>: " +
                          "<i>Only this</i> or <i>All upcoming</i>.")
                return
        }

        let deleteInfo = {
            id: last_booking.id,
            modify_all: modify_all,
        };

        var ajaxContent = $.ajax({
            url: "{{ url_for('api.delete_booking') }}",
            type: "POST",
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({attrs: deleteInfo}),
            dataType: "json"
        });

        ajaxContent.done(handleBookingAjaxDone);
        ajaxContent.fail(handleAjaxFail);
    }

    /** This function will be called when the Delete button in the Booking form
     * is clicked. It can be either Create or Update action.
     */
    function onCancelButtonClick() {
        let range = last_booking.original_range;

        if (range != null) {
            var event = calendar.getEventById( last_booking.id );
            event.setDates(range.start, range.end);
            calendar.render();
        }
    }

    function showExperimentForm() {
        var params = {form_id: 2};
        if (last_booking.experiment)
            params.form_values = JSON.stringify(last_booking.experiment);

        ajaxContent = get_ajax_content("experiment_form", params);

        ajaxContent.done(function(html) {
            $("#experiment-modal").html(html);
            $("#dynamic-btn-ok" ).click(function() {
                last_booking.experiment = getFormAsJson('dynamic-form');
                $('#experiment-modal').modal('hide');
            });
            // Show the form after setting html content
            $('#experiment-modal').modal('show');
        });

        ajaxContent.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });

    }  // function showExperimentForm

    function showBookingCosts() {
        var params = {booking_id: last_booking.id};

        ajaxContent = get_ajax_content("booking_costs_table", params);

        ajaxContent.done(function(html) {
            $("#experiment-modal").html(html);
            addBookingCosts(last_booking);

            $("#costs-btn-update" ).click(function() {
                last_booking.costs = getAllCosts();
                $('#experiment-modal').modal('hide');
            });
            // Show the form after setting html content
            $('#experiment-modal').modal('show');
        });

        ajaxContent.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });

    }  // function showBookingCosts
</script>


<script src="{{ url_for('static', filename='vendor/multi-select/js/jquery.multi-select.js') }}"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>



<script src="{{ url_for('static', filename='vendor/datatables/js/dataTables.bootstrap4.min.js') }}"></script>

<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="{{ url_for('static', filename='vendor/datatables/js/buttons.bootstrap4.min.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.colVis.min.js"></script>
<script src="https://cdn.datatables.net/rowgroup/1.0.4/js/dataTables.rowGroup.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.7/js/dataTables.select.min.js"></script>
<script src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="{{ url_for('static', filename='vendor/ace/ace.js') }}"></script>

{#<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.debug.js"></script>#}
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.8.1/html2pdf.bundle.min.js" integrity="sha512-vDKWohFHe2vkVWXHp3tKvIxxXg0pJxeid5eo+UjdjME3DBFBn2F8yWOE0XmiFcFbXxrEOR1JriWEno5Ckpn15A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

</body>
</html>