{% load i18n static %}
{% load common %}
{#{% autoescape off %}#}
{% block extend_js %}
  <link rel="stylesheet" type="text/css" href="{% static "css/fullcalendar.min.css" %}"/>
{% endblock %}

<div style="padding: 10px;min-height: 350px;max-height: 450px;width: 1266px">
  <form class="layui-form action-form" action="" method="post" id="{{ model_name }}_{{ action_repr }}"
        layui-filter="tmpScheduleForm">
    <input type="hidden" id="id_model_pk" name="pk" value="{{ object_id }}"/>
    <div id="id_events" name="events" class="layui-hide"></div>
    {% csrf_token %}
    <div class="layui-row">
      <div class="layui-col-md3" style="width:25%">
        <div class="layui-card">
          <div class="layui-card-header" style="padding: 0 0 0 3px;background-color: #f2f2f2;">
            <div class="layui-form">
              <div class="layui-form-item">
                <div class="layui-inline" style="margin-right: 0px;">
                  <div class="layui-input-inline" style="width: 115px">
                    <select id="employee_search" class="layui-input" lay-filter="empSearchSelect">
                      <option value="emp">{% trans 'schedule_empFrameOption_employee' %}</option>
                      <option value="dept">{% trans 'schedule_empFrameOption_department' %}</option>
                        <option value="area">{% trans 'schedule_empFrameOption_area' %}</option>
                        <option value="pos">{% trans 'schedule_empFrameOption_position' %}</option>
                    </select>
                  </div>
                </div>
                <div class="layui-inline layui-inline-emp" style="margin-right: 0px;">
                  <div class="layui-input-inline" style="width: 110px">
                    <input id="id_frameEmpSearch" type="text" style="min-width: 120px"
                           placeholder="{% trans 'schedule_empFrameSearch_placeholder_employee' %}"
                           name="frame-emp-search" autocomplete="off"
                           class="layui-input" style="min-width: 120px">
                  </div>
                  <div id="id_frameEmpContainer" class="layui-hide"></div>
                </div>
                <div class="layui-inline layui-inline-dept layui-hide" style="margin-right: 0px;">
                  <div class="layui-input-inline" style="width: 110px">
                    <input id="id_frameDeptSearch" type="text" style="min-width: 120px"
                           placeholder="{% trans 'schedule_empFrameSearch_placeholder_department' %}"
                           name="frame-dept-search" autocomplete="off"
                           class="layui-input" readonly>
                  </div>
                  <div id="id_frameDeptContainer" class="layui-hide"></div>
                </div>
                  <div class="layui-inline layui-inline-area layui-hide" style="margin-right: 0px;">
                      <div class="layui-input-inline" style="width: 110px">
                        <input id="id_frameAreaSearch" type="text" style="min-width: 120px"
                               placeholder="{% trans 'schedule_empFrameSearch_placeholder_area' %}"
                               name="frame-area-search" autocomplete="off"
                               class="layui-input" readonly>
                      </div>
                      <div id="id_frameAreaContainer" class="layui-hide"></div>
                    </div>
                      <div class="layui-inline layui-inline-pos layui-hide" style="margin-right: 0px;">
                      <div class="layui-input-inline" style="width: 110px">
                          <input id="id_framePosSearch" type="text" style="min-width: 120px"
                               placeholder="{% trans 'schedule_empFrameSearch_placeholder_position' %}"
                               name="frame-pos-search" autocomplete="off"
                               class="layui-input" readonly>
                      </div>
                      <div id="id_framePosContainer" class="layui-hide"></div>
                    </div>
                <div class="layui-inline layui-inline-dept layui-hide"
                     title="{% trans 'add_temp_schedule_select_all' %}" style="margin-right: 0px;">
                  <input id="id_frameAllEmp" type="checkbox" name="dept_emp" lay-skin="primary" lay-filter="allEmp">
                </div>
                  <div class="layui-inline layui-inline-area layui-hide"
                         title="{% trans 'schedule_empFrameSearch_placeholder_allEmployee' %}" style="margin-right: 0px;">
                      <input id="id_frameAllEmp1" type="checkbox" name="area_emp" lay-skin="primary" lay-filter="allEmp">
                    </div>
                       <div class="layui-inline layui-inline-pos layui-hide"
                         title="{% trans 'schedule_empFrameSearch_placeholder_allEmployee' %}" style="margin-right: 0px;">
                      <input id="id_frameAllEmp2" type="checkbox" name="pos_emp" lay-skin="primary" lay-filter="allEmp">
                    </div>
                <div class="layui-inline" style="margin-right: 0px;">
                  <div class="button-3d" lay-submit="" lay-filter="employeeSearch"
                       style="background-color: #f2f2f2;">
                    <i class="fa fa-fw fa-search"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div id="id_empFrame" class="layui-card-body">
            <table id="schedule_employee" class="layui-hide" lay-filter="scheduleEmployee"></table>
          </div>
        </div>
      </div>
      <div class="layui-col-md7" style="width:47%">
        <div class="layui-card">
          <div class="layui-card-body" style="padding: 0 5px;">
            <div id="fullcalendar" style="height: 500px"></div>
          </div>
        </div>
      </div>
      <div class="layui-col-md2" style="width:28%">
        <div class="layui-card">
          <div class="layui-card-header"
               style="padding: 0 0 0 3px;background-color: #f2f2f2;height: auto;line-height: inherit">
            <div class="layui-form">
              <div class="layui-form-item">
                <label for="id_ruleFlag" class="layui-form-label"
                       style="width: auto; text-align: left;">{% trans 'tempSchedule_field_rule' %}</label>
                <div class="layui-input-inline">
                  <select name="rule_flag" id="id_ruleFlag">
                    <option value="1">{% trans 'tempSchedule_ruleFlagOption_activateTempSchedule' %}</option>
                    <option value="2">{% trans 'tempSchedule_ruleFlagOption_addAdditionalTempSchedule' %}</option>
                  </select>
                </div>
              </div>
              <div class="layui-form-item" style="border-bottom: 1px solid #e6e6e6; padding: 0 0 10px 0;">
                <div class="layui-input-inline">
                  <label for="id_workType" class="layui-form-label"
                         style="width: auto; text-align: left;">{% trans 'tempSchedule_field_workType' %}</label>
                  <div class="layui-input-inline">
                    <select name="work_type" id="id_workType">
                      <option value="0">{% trans 'tempSchedule_workTypeOption_normalWork' %}</option>
                      <option value="1">{% trans 'tempSchedule_workTypeOption_normalOvertime' %}</option>
                      <option value="2">{% trans 'tempSchedule_workTypeOption_weekendOvertime' %}</option>
                      <option value="3">{% trans 'tempSchedule_workTypeOption_holidayOvertime' %}</option>
                    </select>
                  </div>
                </div>
              </div>
              <div class="layui-form-item">
                <div class="layui-inline">
                  <div class="layui-input-inline" style="width: 120px">
                    <input id="id_frameTimetableSearch" type="text"
                           placeholder="{% trans 'schedule_timetableFrameSearch_placeholder_timetable' %}"
                           name="frame-timetabel-search" autocomplete="off"
                           class="layui-input" style="min-width: 140px">
                  </div>
                </div>
                <div class="layui-inline">
                  <div class="button-3d" lay-submit="" lay-filter="timetableSearch"
                       style="background-color: #f2f2f2;">
                    <i class="fa fa-fw fa-search"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="layui-card-body">
            <table id="schedule_timetable" class="layui-hide" lay-filter="scheduleTimetable"></table>
          </div>
        </div>
      </div>
    </div>
  </form>
</div>
<script>
  $(function () {
      var gloable_pm_codes = new Array();
    var table_data = new Array();
    layui.use(['form', 'laydate', 'table', 'tablePlug'], function () {
      var table = layui.table, tablePlug = layui.tablePlug, form = layui.form, laydate = layui.laydate;
      tablePlug.smartReload.enable(true);
      var empOpts = {
        elem: "#schedule_employee"
        , height: 480
        , text: {none: gettext('none_data')}
        , request: {
          pageName: 'page',
          limitName: 'page_size'
        }
        , page: {
          layout: ['limit', 'prev', 'page', 'next', 'count']
          , limit: 50
          , limits: [20, 50, 80, 100, 200]
          , groups: 1
        }
        , cols: [[
          {field: 'id', type: 'checkbox'}
          , {field: 'emp_code', title: "{% trans 'emp_field_employeeCode' %}"}
          , {field: 'first_name', title: "{% trans 'emp_field_firstName' %}"}
        ]]
        , url: '/personnel/api/employee/'
        , done: function (res, curr, count) {
          //this.where = {};
            table_data = res.data;
            for(var i=0;i<res.data.length;i++){
                for(var j=0;j<gloable_pm_codes.length;j++){
                    if(res.data[i].id===gloable_pm_codes[j]){
                        res.data[i]["LAY_CHECKED"]='true';
                        var index= res.data[i]['LAY_TABLE_INDEX'];
                        $('#id_empFrame .layui-table tr[data-index=' + index + '] input[type="checkbox"]').prop('checked', true);
                        $('#id_empFrame .layui-table tr[data-index=' + index + '] input[type="checkbox"]').next().addClass('layui-form-checked');
                    }
                }
            }
            var checkStatus = table.checkStatus('scheduleEmployee');
            if(checkStatus.isAll){
                $('#id_empFrame .layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                $('#id_empFrame .layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
            }
        }
      };
      var selected_employees = [];
      var empTable = table.render(empOpts);
      form.on('select(empSearchSelect)', function (data) {
        switch (data.value) {
          case 'emp':
            $(".layui-inline-emp").removeClass('layui-hide');
            $(".layui-inline-dept").addClass('layui-hide');
            $(".layui-inline-area").addClass('layui-hide');
            $(".layui-inline-pos").addClass('layui-hide');
            $("#id_frameDeptSearch").val("");
            $("#id_frameAreaSearch").val("");
            $("#id_framePosSearch").val("");
            $("#id_frameDeptContainer").empty();
            $("#id_frameAreaContainer").empty();
            $("#id_framePosContainer").empty();
            table.reload(empTable.config.id, {where: {departments: ""}});
            table.reload(empTable.config.id, {where: {areas: ""}});
            table.reload(empTable.config.id, {where: {positions: ""}});
            break;
          case 'dept':
            $(".layui-inline-dept").removeClass('layui-hide');
            $(".layui-inline-emp").addClass('layui-hide');
            $(".layui-inline-pos").addClass('layui-hide');
            $(".layui-inline-area").addClass('layui-hide');
            $("#id_frameEmpContainer").empty();
            table.reload(empTable.config.id, {where: {emp_code_icontains: ""}});
            break;
          case 'area':
            $(".layui-inline-area").removeClass('layui-hide');
            $(".layui-inline-emp").addClass('layui-hide');
            $(".layui-inline-dept").addClass('layui-hide');
            $(".layui-inline-pos").addClass('layui-hide');
            $("#id_frameEmpContainer").empty();
            table.reload(empTable.config.id, {where: {emp_code_icontains: ""}});
            gloable_pm_codes = [];
            break;
          case 'pos':
            $(".layui-inline-pos").removeClass('layui-hide');
            $(".layui-inline-emp").addClass('layui-hide');
            $(".layui-inline-area").addClass('layui-hide');
            $(".layui-inline-dept").addClass('layui-hide');
            $("#id_frameEmpContainer").empty();
            table.reload(empTable.config.id, {where: {emp_code_icontains: ""}});
            gloable_pm_codes = [];
            break;
        }
      });
      table.on('checkbox(scheduleEmployee)', function (obj) {
        $("#id_frameEmpContainer").empty();
        //var checkedData = table.checkStatus("schedule_employee");
        //if (checkedData.data.length > 0) {
        //  checkedData.data.forEach(function (item, index) {
        //    $("#id_frameEmpContainer").append('<input name="employee" value="' + item.id + '"/>');
        //  });
        //}
        if(obj.checked===true){
           if(obj.type==='one'){
               if (!selected_employees.includes(obj.data.id))
                    selected_employees.push(obj.data.id);
          }else{
               for(var i=0;i<table_data.length;i++){
                   if (!selected_employees.includes(table_data[i].id))
                        selected_employees.push(table_data[i].id);
               }
           }
        }else{
           if(obj.type==='one'){
               for(var i=0;i<selected_employees.length;i++){
                  if(selected_employees[i]===obj.data.id){
                       selected_employees.remove(i);
                   }
              }
           }else{
               for(var j=0;j<table_data.length;j++){
                    for(var i=0;i<selected_employees.length;i++){
                        if(selected_employees[i]===table_data[j].id){
                            selected_employees.remove(i);
                            break;
                        }
                    }
                }
           }
       }
       gloable_pm_codes = selected_employees;
       gloable_pm_codes.forEach(function (item) {
           $("#id_frameEmpContainer").append('<input name="employee" value="' + item + '"/>');
        });
      });

      Array.prototype.remove=function(dx)
      {
        if(isNaN(dx)||dx>this.length){return false;}
        for(var i=0,n=0;i<this.length;i++)
        {
            if(this[i]!=this[dx])
            {
                this[n++]=this[i]
            }
        }
        this.length-=1
      };

      form.on('submit(employeeSearch)', function () {
        var v = $("#employee_search").val();
        switch (v) {
          case 'emp':
            var emp = $("#id_frameEmpSearch").val();
            table.reload(empTable.config.id, {where: {search: emp}, page: {curr: 1}});
            gloable_pm_codes = [];
            break;
          case 'dept':
            break;
          case 'area':
                break;
          case 'pos':
                break;
          default :
            break;
        }
      });
      $("#id_frameDeptSearch").click(function () {
        $.ajax({
          url: "/personnel/getDepartmentList/"
          , type: "GET"
          , dataType: "html"
          , success: function (response) {
            layer.open({
              type: 1
              , title: ' '
              , closeBtn: 1
              , area: ['450px', '400px']
              , maxmin: false
              , shadeClose: false
              , content: response
              , btn: [gettext('btn_confirm'), gettext('btn_cancel')]
              , yes: function (index, layero) {
                var selectedDepts = $(layero).find("#id_selectedDepartment").val();
                $("#id_frameDeptContainer").empty();
                if (selectedDepts) {
                  var depts = JSON.parse(selectedDepts);
                  var alias = [];
                  var ids = [];
                  depts.forEach(function (item, index) {
                    alias.push(item.dept_name);
                    ids.push(item.id);
                    $("#id_frameDeptContainer").append('<input name="department" value="' + item.id + '"/>');
                  });
                  $("#id_frameDeptSearch").val(alias.join(','));
                  table.reload(empTable.config.id, {where: {departments: ids.join(',')}});
                  gloable_pm_codes = [];
                } else {
                  $("#id_frameDeptSearch").val("");
                }
                layer.close(index);
              }
            });
          }
        });
        form.on('checkbox(allEmp)', function (data) {
            if (data.elem.checked) {
             var selected_drop = $("#employee_search").val();
             if (selected_drop == "dept"){
                var depts = $("#id_frameDeptContainer").find("input[name='department']");
                var text = 'Department Not Found'
             }
             if (selected_drop == "area"){
                var depts = $("#id_frameAreaContainer").find("input[name='area']");
                var text = 'Area Not Found'
             }
             if (selected_drop == "pos"){
                var depts = $("#id_framePosContainer").find("input[name='position']");
                var text = 'Position Not Found'
             }
            if (depts.length == 0) {
                form.val('shiftForm', {is_department: false});
                layer.alert(gettext(text),
                    {title: gettext('layer_title_error'), icon: 2, time: 3000, btn: []});
            } else {
                $("#id_empFrame").addClass('layui-admin-shade ');
            }
            } else {
            $("#id_empFrame").removeClass('layui-admin-shade ');
            }
        });
      });
      $("#id_frameAreaSearch").click(function () {
        $.ajax({
          url: "/personnel/getAreaList/"
          , type: "GET"
          , dataType: "html"
          , success: function (response) {
            layer.open({
              type: 1
              , title: ' '
              , closeBtn: 1
              , area: ['450px', '400px']
              , maxmin: false
              , shadeClose: false
              , content: response
              , btn: [gettext('btn_confirm'), gettext('btn_cancel')]
              , yes: function (index, layero) {
                var selectedAreas = $(layero).find("#id_selectedArea").val();
                $("#id_frameAreaContainer").empty();
                if (selectedAreas) {
                  var areas = JSON.parse(selectedAreas);
                  var alias = [];
                  var ids = [];
                  areas.forEach(function (item, index) {
                    alias.push(item.area_name);
                    ids.push(item.id);
                    $("#id_frameAreaContainer").append('<input name="area" value="' + item.id + '"/>');
                  });
                  $("#id_frameAreaSearch").val(alias.join(','));
                  table.reload(empTable.config.id, {where: {areas: ids.join(',')}});
                  gloable_pm_codes = [];
                } else {
                  $("#id_frameAreaSearch").val("");
                }
                layer.close(index);
              }
            });
          }
        });
        form.on('checkbox(allEmp)', function (data) {
            if (data.elem.checked) {
                     var selected_drop = $("#employee_search").val();
             if (selected_drop == "area"){
                var areas = $("#id_frameAreaContainer").find("input[name='area']");
                var text = 'Area Not Found'
             }
             if (selected_drop == "dept"){
                var areas = $("#id_frameDeptContainer").find("input[name='department']");
                var text = 'Department Not Found'
             }
             if (selected_drop == "pos"){
                var areas = $("#id_framePosContainer").find("input[name='position']");
                var text = 'Position Not Found'
             }
            if (areas.length == 0) {
                form.val('shiftForm', {is_area: false});
                layer.alert(gettext(text),
                    {title: gettext('layer_title_error'), icon: 2, time: 3000, btn: []});
            } else {
                $("#id_empFrame").addClass('layui-admin-shade ');
            }
            } else {
            $("#id_empFrame").removeClass('layui-admin-shade ');
            }
         });
      });
      $("#id_framePosSearch").click(function () {
        $.ajax({
          url: "/personnel/getPositionList/"
          , type: "GET"
          , dataType: "html"
          , success: function (response) {
            layer.open({
              type: 1
              , title: ' '
              , closeBtn: 1
              , area: ['450px', '400px']
              , maxmin: false
              , shadeClose: false
              , content: response
              , btn: [gettext('btn_confirm'), gettext('btn_cancel')]
              , yes: function (index, layero) {
                var selectedPositions = $(layero).find("#id_selectedPosition").val();
                $("#id_framePosContainer").empty();
                if (selectedPositions) {
                  var positions = JSON.parse(selectedPositions);
                  var alias = [];
                  var ids = [];
                  positions.forEach(function (item, index) {
                    alias.push(item.position_name);
                    ids.push(item.id);
                    $("#id_framePosContainer").append('<input name="position" value="' + item.id + '"/>');
                  });
                  $("#id_framePosSearch").val(alias.join(','));
                  table.reload(empTable.config.id, {where: {positions: ids.join(',')}});
                  gloable_pm_codes = [];
                } else {
                  $("#id_framePosSearch").val("");
                }
                layer.close(index);
              }
            });
          }
        });
        form.on('checkbox(allEmp)', function (data) {
            if (data.elem.checked) {
                 var selected_drop = $("#employee_search").val();
             if (selected_drop == "pos"){
                var positions = $("#id_framePosContainer").find("input[name='position']");
                var text = 'Position Not Found'
             }
             if (selected_drop == "dept"){
                var positions = $("#id_frameDeptContainer").find("input[name='department']");
                var text = 'Department Not Found'
             }
             if (selected_drop == "area"){
                var positions = $("#id_frameAreaContainer").find("input[name='area']");
                var text = 'Area Not Found'
             }
            if (positions.length == 0) {
                form.val('shiftForm', {is_area: false});
                layer.alert(gettext(text),
                    {title: gettext('layer_title_error'), icon: 2, time: 3000, btn: []});
            } else {
                $("#id_empFrame").addClass('layui-admin-shade ');
            }
            } else {
            $("#id_empFrame").removeClass('layui-admin-shade ');
            }
        });
      });
      $("#id_frameEmpSearch").keypress(function (event) {
        if (event.keyCode == "13") {
          var emp = $(this).val();
          table.reload(empTable.config.id, {where: {search: emp}, page: {curr: 1}});
          gloable_pm_codes = [];
        }
      });
      var timetableOpts = {
        id: 'schedule_timetable'
        , elem: "#schedule_timetable"
        , height: 335
        , text: {none: gettext('none_data')}
        , request: {
          pageName: 'page',
          limitName: 'page_size'
        }
        , page: {
          layout: ['limit', 'prev', 'page', 'next', 'count']
          , limit: 50
          , limits: [20, 50, 80, 100, 200]
          , groups: 1
        }
        , cols: [[
          {field: 'id', type: 'checkbox'},
          {field: 'alias', title: "{% trans 'timeInterval_field_alias' %}", width: 120},
          {field: 'in_time', title: "{% trans 'timeInterval_field_checkIn' %}", width: 80},
          {field: 'out_time', title: "{% trans 'timeInterval_field_checkOut' %}", width: 90, templet: function (data) {
            if(data.cross_day > 0){
                return data.out_time + '<sup>+'+data.cross_day + '</sup>';
            }else{
                return data.out_time;
            }
          }},
          {field: 'break_time_duration', title: "{% trans 'timeInterval_field_breakTime' %}", width: 60}
        ]]
        , url: '/att/api/timeintervals/'
      };
      var timeTable = table.render(timetableOpts);
      form.val('tmpScheduleForm', {rule_flag: 1, work_type: 0});
      form.on('submit(timetableSearch)', function () {
        var alias = $("#id_frameTimetableSearch").val();
        table.reload(timeTable.config.id, {where: {alias__icontains: alias}});
      });
      $("#id_frameTimetableSearch").keypress(function (event) {
        if (event.keyCode == "13") {
          var alias = $(this).val();
          table.reload(timeTable.config.id, {where: {alias__icontains: alias}});
        }
      });

      function getEvents() {
        var events = [];
        var checkStatus = table.checkStatus('schedule_timetable');
        var workType = $("#id_workType").val();
        var flag = $("#id_ruleFlag").val();
        if (checkStatus.data.length === 0){
            layer.alert(gettext('Please_select_the_time_table'), {
                icon: 5, title: gettext('system_exception'),
                btn: gettext('btn_confirm')
            });
            return
        }
        if (checkStatus.data.length > 0) {
          checkStatus.data.forEach(function (item, index) {
            let event = {
              item: item
              , workType: workType
              , flag: flag
              , title: item.alias
            };
            events.push(event);
          });
        }
        return events;
      }

      var updateEvents = function () {
        $("#id_events").empty();
        $('#fullcalendar').fullCalendar('clientEvents', function (event) {
          var start = event.start.format();
          var end = event.end.format();
          var val = [event.item.id, start, end, event.workType, event.flag].join(',');
          var e = '<input name="event" type="hidden" value="' + val + '"/>';
          $("#id_events").append(e);
        });
      };

      var selectedDates = {};
      $('#fullcalendar').fullCalendar({
        height: 420
        , header: {
          center: '',
          right: 'today prev,next'
        }
        , isRTL:false
        , monthNames : [
          gettext('fullcal_January'), gettext('fullcal_February'), gettext('fullcal_March'), gettext('fullcal_April')
          , gettext('fullcal_May'), gettext('fullcal_June'), gettext('fullcal_July'), gettext('fullcal_August')
          , gettext('fullcal_September'), gettext('fullcal_October'), gettext('fullcal_November'), gettext('fullcal_December')
        ]
        , monthNamesShort : [
          gettext('fullcal_Jan'), gettext('fullcal_Feb'), gettext('fullcal_Mar'), gettext('fullcal_Apr')
          , gettext('fullcal_May'), gettext('fullcal_Jun'), gettext('fullcal_Jul'), gettext('fullcal_Aug')
          , gettext('fullcal_Sep'), gettext('fullcal_Oct'), gettext('fullcal_Nov'), gettext('fullcal_Dec')
        ]
        , dayNames : [
          gettext('fullcal_Sunday'), gettext('fullcal_Monday'), gettext('fullcal_Tuesday'), gettext('fullcal_Wednesday')
          , gettext('fullcal_Thursday'), gettext('fullcal_Friday'), gettext('fullcal_Saturday')
        ]
        , dayNamesShort : [
          gettext('fullcal_Sun'), gettext('fullcal_Mon'), gettext('fullcal_Tue'), gettext('fullcal_Wed')
          , gettext('fullcal_Thur'), gettext('fullcal_Fri'), gettext('fullcal_Sat')
        ]
        , editable: false
        , selectable: true
        , select: function (start, end) {
            let startKey = start.format();
            let events = getEvents();
            if (events.length > 0) {
                events.forEach(function (item, index) {
                    let event = $.extend({start: start, end: end}, item);
                    $('#fullcalendar').fullCalendar('renderEvent', event, true); // stick? = true
                });
            }
            if (selectedDates[startKey]) {
                  $('#fullcalendar').fullCalendar('removeEvents', function (event) {
                      return event.start.format() === startKey;
                  });
                  delete selectedDates[startKey];
            }
            else {
                  selectedDates[startKey] = true;
            }
            updateEvents();
        },
        eventClick: function (event) {
          $('#fullcalendar').fullCalendar('removeEvents', event._id);
          updateEvents();
        }
      });

    });
  });
</script>
{#{% endautoescape %}#}
