<style>
    
    .tbl td{padding:10px 10px 0 0;}
    .tbl-white td  {color:#fff;}
    .tbl-white th  {color:#fff;}
    
    
    .daytable , th, td {
        
        padding:5px;
        
      }
    
</style>
<div class="wrapper">
    <div class="container-full">
         <?php if ($this->session->flashdata('Success') && $this->session->flashdata('Success') != "") { ?>
                    <div class="row hidden-print">
                        <div class="col-sm-12">
                            <div class="alert alert-success">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                <strong>Success!</strong> <?php echo $this->session->flashdata('Success'); ?>
                            </div>
                        </div>
                    </div>
                <?php } ?>
                <?php if ($this->session->flashdata('Error') && $this->session->flashdata('Error') != "") { ?>
                    <div class="row hidden-print">
                        <div class="col-sm-12">
                            <div class="alert alert-danger">
                                <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
                                <strong>Error!</strong> <?php echo $this->session->flashdata('Error'); ?>
                            </div>
                        </div>
                    </div>
                <?php } ?>
         <!--Page-Title--> 
                <div class="row">
                    <div class="col-sm-12">
                        <h4 class="page-title">Group Session Scheduling: </h4>                        
                    </div>
                </div>
                <div class="row">
                    <div class="card-box">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="card-box bg-primary ">
                                    <div class="row">
                                        <div class="col-md-12 text-white" >
                                            <h3 class="text-white">Details:</h3>
                                            <table id="" class="tbl tbl-white text-white" style="border-bottom: 1px solid #fff; ">
                                                <tr>
                                                    <td style="font-weight:bold;">Group Name:</td>
                                                    <td><?php echo $group->program_group; ?> <input type="hidden" id="txtgroupid" value="<?php echo  $group->id_program_groups;;?>"></td>
                                                </tr>
                                                <tr>
                                                    <td style="font-weight:bold;">Linked Service:</td>
                                                    <td><?php echo $group->program_service_name; ?></td>
                                                </tr>
                                            </table><!-- comment -->
                                        </div>                            
                                    </div>
                                </div>
                                <div class="card-box bg-primary">
                                    <div class="row">
                                        <div class="col-md-12" style="margin-right: 5px;">
                                            <h3 class="text-white">Schedule: </h3>
                                            <form id="addevent" class="form" method="post" action="<?php echo base_url();?>coaching_controller/add_group_visit">
                                                <input type="hidden" class="form-control" name="program_group_id" value="<?php echo $group->id_program_groups; ?>">
                                                <input type="hidden" class="form-control" name="service_id" value="<?php echo $group->program_service_id; ?>"/>
                                                <div class="form-group">
                                                    
                                                    <label class="text-white">Staff</label>
                                                    <select onchange="refresh_staff_schedule();" class="form-control" name="staffid" id="staffid">
                                                        <?php foreach ($staff as $s) { ?>
                                                            <option value="<?php echo $s['id_staff']; ?>"><?php echo $s['staff_fullname']; ?></option>                                                
                                                        <?php } ?>
                                                    </select>
                                                </div>

                                                <div class="form-group">
                                                    <label class="text-white">Day</label>
                                                    <input readonly="readonly" onchange="refresh_staff_schedule();" class="form-control" id="day" name="day">
                                                </div>
                                                <div class="form-group">
                                                    <label class="text-white">Time Start</label>
                                                    <input readonly="readonly" class="form-control time" id="starttime" name="start">
                                                </div>
                                                <div class="form-group">
                                                    <label class="text-white">Time End</label>
                                                    <input readonly="readonly" class="form-control time" id="endtime" name="end">
                                                </div>
                                                <div class="form-group">
                                                    <label class="text-white">Repeat</label>
                                                    <input onchange="if(this.value < 1){this.value=1;}" class="form-control" type="number" min="1" max="100" id="repeat" name="repeat" value="1">
                                                    <small class="text-sm">Repeat this over so many days</small>
                                                </div>
                                                <div style="display:none;" class="form-group">
                                                    <label class="text-white">Repeat Type</label>
                                                    <select class="form-control" id="repeattype" name="repeattype">
                                                        <option value="1">Daily</option>
                                                        <option value="2">Every 2nd Day</option>
                                                        <option value="3">Every 3rd Day</option>
                                                        <option value="4">Every 4th Day</option>
                                                        <option value="5">Every 5th Day</option>
                                                        <option value="6">Every 6th Day</option>
                                                        <option value="7">Every Week</option>
                                                        <option value="0">Custom</option>
                                                    </select>        
                                                </div>
                                                <div class="form-group">
                                                    <table class="daytable" style="border-spacing: 2px;">
                                                        <tbody>
                                                            <tr>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="mon" class="checkbox" value="1"></td>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="tue" class="checkbox" value="2"></td>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="wed" class="checkbox" value="3"></td>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="thu" class="checkbox" value="4"></td>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="fri" class="checkbox" value="5"></td>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="sat" class="checkbox" value="6"></td>
                                                                <td style="text-align: center;"><input type="checkbox" name="weekday[]" id="sun" class="checkbox" value="0"></td>
                                                                
                                                            </tr>
                                                            <tr>
                                                                <td style="text-align: left;"><label style="color:#fff;" for="mon">Mon</label></td>
                                                                <td style="text-align: left;"><label style="color:#fff;"  for="mon">Tue</label></td>
                                                                <td style="text-align: left;"><label style="color:#fff;" for="mon">Wed</label></td>
                                                                <td style="text-align: left;"><label style="color:#fff;"  for="mon">Thu</label></td>
                                                                <td style="text-align: left;"><label style="color:#fff;" for="mon">Fri</label></td>
                                                                <td style="text-align: left;"><label style="color:#fff;"  for="mon">Sat</label></td>
                                                                <td style="text-align: left;"><label style="color:#fff;"  for="mon">Sun</label></td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                    
                                                </div>
                                                <div class="form-group">
                                                    <button style="float: right;" type="submit" class="btn btn-default waves-effect waves-light text-white">Create Appointment</button>
                                                </div>

                                            </form>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div class="col-md-9 bg-warning" style="border-radius:4px; color:#fff !important;">
                                <div class="row">
                                    <div class="col-md-12 " >
                                        <div class="row">                                             
                                            <div class="col-md-4" style="border-radius:4px; color:#fff !important;">
                                                <div ><div class="col-md-12"><h3 style="color:#fff !important;"><span id="staff_name_span">Staff</span> </h3></div></div>
                                                <div id="staffcalendar"  style="color:#fff !important;"></div>
                                                <div id="StaffCalendarOverlay" style="display: none; position: absolute; top: 20px; left: 20px; z-index: 5; background: #fff; opacity: 0.6; text-align: center;">
                                                    <img style="height: 50px; margin-top: 100px;" src="<?php echo base_url() . 'assets/images/spin-pink.gif'; ?>">
                                                </div>
                                            </div>

                                            <div class="col-md-8" >
                                                <div class="row">
                                                    <div class="col-md-12">
                                                        <h3 style="color:#fff !important;"><?php echo $group->program_group; ?> </h3>
                                                    </div>
                                                </div>
                                                <div class="col-md-12">
                                                    <div class="pull-right " style="margin-left: 6px;" data-toggle="tooltip" data-placement="top">
                                                        <div id="customercalendar" style=""></div>                                                        
                                                    </div>
                                                </div>
                                            </div>
                                           
                                        <div class="row m-t-20" id="printsection" style="padding: 15px;">
                                            <div class="col-md-12">
                                                <div class="row">
                                                    
                                                </div>
                                                <div class="row">
                                                     <div class="col-md-12">
                                                        <table id='visittable' class='table table-responsive m-t-20' >
                                                            <thead>
                                                                <tr>
                                                                    <th style="color:#fff;">Group ID</th>
                                                                    <th style="color:#fff;">Staff ID</th>
                                                                    <th style="color:#fff;">Staff</th>
                                                                    <th style="color:#fff;">Start</th>
                                                                    <th style="color:#fff;">End</th>
                                                                    <th style="color:#fff;"></th>
                                                                </tr>
                                                            <thead>
                                                            <tbody id="tbody">
                                                            
                                                            </tbody>
                                                        </table>
                                                     </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-12" >
                                                        <button style="float:right;" onclick="printsection('#printsection');" class="btn btn-sm btn-inverse hidden-print"><i class="fa fa-icon fa-print"></i></button>
                                                    </div>
                                                </div>
                                                     
                                            </div>
                                        </div>                        
                                    </div>     
                                </div>
                            </div>
                        </div>    
                </div>
            </div>
        </div><!-- end col -->
    </div>

    <div class="modal fade none-border" id="eventview" tabindex="-1" role="dialog" aria-labelledby="Event View" aria-hidden="true">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <form method="post" action="<?php echo base_url();?>coaching_controller/update_group_visit">
                <div class="modal-header">
                    <button type="button" class="close" onclick="$('#eventview').modal('hide');" aria-hidden="true">×</button>
                    <h2 class="modal-title" id="eventview-heading">Visit details: <strong id="visitcustomername"></strong> </h2>
                    <h4 id="visiteventtitle"></h4>
                    <h4>On: <span id="visiteventstart"></span></h4>
                    <h4>To: <span id="visiteventend"></span></h4>
                    <span>visit #:</span><span name="modal_visit_id" id="modal_visit_id"></span>
                    <input type="hidden" id="visit-event-id" value=""/>
                    <input type="text" name="group_id" value='<?php echo $group->id_program_groups; ?>' />
                    <input type="text" name="id_group_visits" id="id_group_visits" />
                    <input type="text" name="old_staff_id" />
                    <input type="text" name="end" />
                    <input type="text" name="id_visit_services" value="<?php echo $service_id;?>" />
                    
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4 form-group">
                            <label class="form-label" for="">Date</label>
                            <input required="required" class="form-control" id="modal_start_date" name="modal_start_date"/>
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="form-label" for="">Time Start</label>
                            <input required="required" onchange="check_modal_start();" class="form-control" id="modal_start_time" name="modal_start_time"/>
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="form-label" for="">Time End</label>
                            <input required="required" onchange="check_modal_start();" class="form-control" id="modal_end_time" name="modal_end_time"/>
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="form-label" for="">Staff</label>
                            <select required="required" class="form-control" id="modal_staff_id" name="staff_id">
                                <?php foreach ($staff as $s) { ?>
                                    <option value="<?php echo $s['id_staff']; ?>"><?php echo $s['staff_fullname']; ?></option>                                                
                                <?php } ?>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <div class="row">
                        <div class="col-md-12">
                            <button type="button" onclick="$('#eventview').modal('hide');" id="modal_btn_cancel" class="btn btn-md btn-default">Close</button>
                            <button type="submit" id="modal_btn_save" class="btn btn-md btn-pink">Update Visit</button>                            
                        </div>
                    </div>
                </div>
            </form>
            </div>
        </div>
    </div>

    <!-- end row -->
    <style>
        .calendar {
            float: left;
            margin-bottom: 0px;
        }
        .fc-view {
            margin-top: 30px;
        }
        .none-border .modal-footer {
            border-top: none;
        }
        .fc-toolbar {
            margin-bottom: 5px;
            margin-top: 15px;
            color:#fff !important;
        }
        .fc-toolbar h2 {
            font-size: 14px;
            font-weight: 400;
            line-height: 30px;
            text-transform: uppercase;
            color:#fff !important;
        }
        .fc-day {
            background: #ffffff;
        }
        .fc-today{
            background: #a5a5a5;
        }
        .fc-toolbar .fc-state-active,
        .fc-toolbar .ui-state-active,
        .fc-toolbar button:focus,
        .fc-toolbar button:hover,
        .fc-toolbar .ui-state-hover {
            z-index: 0;
        }
        .fc-widget-header {
            border: 1px solid #fff;
        }
        .fc-widget-content {
            border: 1px solid #fff;
        }
        .fc th.fc-widget-header {
            background: transparent;   
            color:#fff;
            font-size: 12px;
            line-height: 20px;
            padding: 10px 0px;
            text-transform: uppercase;
        }
        .fc-button {
            background: #59a9f8;
            border: 1px solid #ebeff2;
            color: #fff;
            text-transform: capitalize;
        }
        .fc-text-arrow {
            font-family: inherit;
            font-size: 16px;
        }
        .fc-state-hover {
            background: #f3f3f3;
        }
        .fc-state-highlight {
            background: #f0f0f0;
        }
        .fc-resource-cell{
            color: #fff;
        }
        .fc-time {
            color: #fff;
        }
        .fc-cell-overlay {
            background: #f0f0f0;
        }
        .fc-unthemed .fc-today {
            background: #ffffff;
        }
        .fc-event {
            border-width: 4px;
            border-radius: 4px;            
            cursor: move;
            font-size: 10px;
            margin: 5px 7px;
            padding: 5px 5px;
            text-align: center;
            word-wrap: break-word;
            color:#000;
        }
        .external-event {
            color: #ffffff;
            cursor: move;
            margin: 10px 0;
            padding: 6px 10px;
        }
        .fc-basic-view td.fc-week-number span {
            padding-right: 5px;
        }
        .fc-basic-view td.fc-day-number {
            padding-right: 5px;
        }

    </style>
    <script>
        $(document).ready(function () {
            $('#txtDate').datepicker({
                autoclose: true,
                todayHighlight: true,
                format: 'yyyy-mm-dd'
            });

            $("#staffid").select2();
            
            <?php if($staff_id >0){?>
                $("#staffid").select2("val", <?php echo $staff_id;?>);    
            <?php } ?>
            
            
            $("#modal_staff_id").select2();
            
            $("#day").val('<?php echo date('Y-m-d');?>');
            
            $("#modal_start_date").datepicker({
                autoclose: true,
                todayHighlight: true,
                format: 'yyyy-mm-dd',
                setDate: new Date()
            }).datepicker("setDate", "0");
            
            $('#starttime').val('10:00');
            $('#endtime').val('11:00');
            
            // $('#starttime').timepicker({
            //     showMeridian: false
            //     , showInputs: false
            //     ,timeFormat: 'H:i:s'
            //    // ,defaultTime: '09:00:00'
            //     });
            // $('#endtime').timepicker({
            //     showMeridian: false
            //     , showInputs: false
            //     ,timeFormat: 'H:i:s'
            //    // ,defaultTime: '09:00:00'
            //     });
            $('#modal_start_time').timepicker({
                showMeridian: false
                , showInputs: false
                ,timeFormat: 'H:i:s'
               // ,defaultTime: '09:00:00'
                });
            $('#modal_end_time').timepicker({
                showMeridian: false
                , showInputs: false
                ,timeFormat: 'H:i:s'
               // ,defaultTime: '09:00:00'
                });    


            customer_calendar();
            
            refresh_staff_schedule();
            

        });

        function refresh_group_schedule(day){
           
            if(day==''){
                day = $('#day').val();
            }
            
            $.ajax({
                url: '<?php echo base_url() . 'coaching_controller/get_group_schedule_ajax'; ?>',
                type: 'POST',
                data: {group_id: $("#txtgroupid").val(), day: day},
                success: function (data) {
                    //console.log(data);
                    var data = $.parseJSON(data);
                    var events = new Array();

                    if (data['visit_events'].length > 0) {
                        for (var k = 0; data['visit_events'].length > k; k++) {
                            events.push({
                                id: data['visit_events'][k].id,
                                resourceId: data['visit_events'][k].resourceId,
                                start: data['visit_events'][k].start,
                                end: data['visit_events'][k].end,
                                title: data['visit_events'][k].title,
                                editable: true,
                                borderColor: data['visit_events'][k].borderColor,
                                backgroundColor: data['visit_events'][k].backgroundColor,
                                textColor: data['visit_events'][k].textColor,
                                id_visit_services: data['visit_events'][k].id_visit_services,
                                id_visit_service_staffs: data['visit_events'][k].id_visit_service_staffs
                            });
                        }
                    }
                    //$('#staffcalendar').fullCalendar('destroy');
                    //customer_calendar(events);
                    //console.log(events);
                    return events;
                }
            });
            
        }
        
        
        
        
        
        
        
        
        function customer_calendar(){
            
            //console.log(e);
            var oldResourceId = null;
            var oldStart = null;
            var icons=null;
            var customercalendar = $('#customercalendar').fullCalendar({
                schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
                defaultView: 'month',
                bootstrapFontAwesome: 1,
                button: {
                    today: "Today",
                    day: "Day",
                    prev: "Prev",
                    next: "Next"
                },
                initialView: "dayGridMonth",
                handleWindowResize: !0,
                header: {
                    left: 'title',
                    center: '',
                    right: 'prev,next today'
                },
                nowIndicator : true,                
                droppable: 1,
                selectable: 1,  
                eventLimit: true, // allow "more" link when too many events
                slotWidth: 60,
                events: function(start, end, timezone, callback) {
                    var start = start.format('YYYY-MM-DD');
                    var end = end.format('YYYY-MM-DD');
                     $.ajax({
                        url: '<?php echo base_url() . 'coaching_controller/get_group_schedule_ajax'; ?>',
                        type: 'POST',
                        data: {group_id: $("#txtgroupid").val(), start: start, end:end},
                        success: function (data) {
                            //console.log("data=" + data);
                            var data = $.parseJSON(data);
                            var events = new Array();

                            if (data['visit_events'].length > 0) {
                                for (var k = 0; data['visit_events'].length > k; k++) {
                                    events.push({
                                        id: data['visit_events'][k].id,
                                        resourceId: data['visit_events'][k].resourceId,
                                        id_groups: data['visit_events'][k].id_program_groups,
                                        group_name: data['visit_events'][k].program_group,
                                        start: data['visit_events'][k].start,
                                        end: data['visit_events'][k].end,
                                        title: data['visit_events'][k].title,
                                        editable: true,                                        
                                        backgroundColor: data['visit_events'][k].backgroundColor,
                                        borderColor: data['visit_events'][k].borderColor,
                                        textColor: data['visit_events'][k].textColor,
                                        id_visit_services: data['visit_events'][k].service_id,
                                        id_visit_service_staffs: data['visit_events'][k].staff_id
                                    });
                                }
                            }                                
                            //console.log(events);
                            
                            callback(events);
                            showtable(start, end)
                        }
                    });
                },
                eventClick: function (calEvent, jsEvent, view) {
                    //console.log(calEvent);
                    var event_id = calEvent.id;
                    $("#modal_visit_id").html(event_id);
                    $("#visit-event-id").val(event_id); 
                    $("#id_group_visits").val(event_id);
                    $("#old_staff_id").val(calEvent.resourceId);
                    $("#visitcustomername").html(calEvent.group_name);
                    $("#visiteventtitle").html(calEvent.title);
                    
                    var dt = calEvent.start._i.split("T");
                    var edt = calEvent.end._i.split("T");
                    
                    var start = new Date(calEvent.start._i);
                    var end = new Date (calEvent.end._i);
                    $("#visiteventstart").html(start.toString().substring(0,24));
                    $("#visiteventend").html(end.toString().substring(0,24));
                    
                    $("#modal_staff_id").select2("val", calEvent.resourceId);
                    
                    
                    $("[name='id_visit_services']").val(calEvent.id_visit_services);
                    $("[name='id_visit_service_staffs']").val(calEvent.id_visit_service_staffs);
                    $("[name='old_staff_id']").val(calEvent.resourceId);
                    
                    $("[name='visit_status']").val(calEvent.visit_status);
                    $("[name='end']").val();
                    
                    $("#modal_start_date").val(dt[0]);
                    $("#modal_start_time").val(dt[1]);
                    $("#modal_end_time").val(edt[1]);
                    
                    $("#eventview").modal('show');
                },                
                dayClick: function(start, end, jsEvent, view, resource) {
                    $('#day').val(start.format('YYYY-MM-DD'));
                    refresh_staff_schedule();
                },
                eventMouseover: function(calEvent, jsEvent) {
                    var mTitle=calEvent.title.split('-');
                    var tooltip = '<div class="tooltipevent" style="width:220px;height:105px;background:'+calEvent.backgroundColor+';color:#fff; padding:10px; position:absolute;z-index:10090; border-radius:4px;">' + mTitle[0]+' <br> '+ mTitle[1]+' <br> '+mTitle[2] + ' <br> '+mTitle[3] +  '</div>';
                    var $tooltip = $(tooltip).appendTo('body');

                    $(this).mouseover(function(e) {
                        $(this).css('z-index', 10000);
                        $tooltip.fadeIn('500');
                        $tooltip.fadeTo('10', 1.9);
                    }).mousemove(function(e) {
                        $tooltip.css('top', e.pageY + 30);
                        $tooltip.css('left', e.pageX - 100);
                    });
                },
                eventMouseout: function(calEvent, jsEvent) {
                    $(this).css('z-index', 8);
                    $('.tooltipevent').remove();
                },                     
                eventDragStart: function(event) {
                    oldResourceId = event.resourceId;
                    oldStart = event.start.format();
                },
                eventDrop: function(event, delta, revertFunc, jsEvent, ui, view) {
                    
                    var ee=event;
                    //console.log(ee); return false;
                    $.ajax({
                        url: '<?php echo base_url().'coaching_controller/update_group_visit'; ?>',
                        //data: 'id_visit_services=' +event.id+ '&staff_id=' +event.resourceId+ '&start=' +event.start.format()+ '&end=' +event.end.format(),
                        data: {
                            id_group_visits:event.id,
                            id_visit_services:event.id_visit_services,
                            id_visit_service_staffs:event.id_visit_service_staffs,
                            start:event.start.format(),
                            end:event.end.format(),
                            staff_id:event.resourceId,
                            oldStaffId: oldResourceId,
                            oldStart: oldStart,
                            visit_status: event.visit_status
                        },
                        type: 'POST',
                        success: function(response){
                            if(response==='sessionexpired'){
                                window.location.assign('<?php echo base_url();?>');
                                return false;
                            }
                            
                            var result = response.split('|');

                            if(result[0] === 'success'){
                                $('#customercalendar').fullCalendar('refetchEvents');
                                toastr.success(result[1], 'Done!');

                            } else {
                                swal({
                                    title: "eventDrop Error",
                                    text: result[0],
                                    type: "error",
                                    confirmButtonText: 'OK!'
                                });
                            }
                                
                        }
                    
                    });
                },
                eventRender: function(event, element) {
                    if(event.inservice && event.inservice!==''){
                        icons = "<i style='color:#fff; font-weight:bold;' class='zmdi zmdi-"+event.inservice+"'></i> ";        
                        element.find(".fc-title").prepend(icons + "<br/> ");
                    }
                }
                
            });
            
        }

        function refresh_staff_schedule() {
        //console.log('here');
            var staffid = $('#staffid option:selected').val();
            var day = $('#day').val();
            $("#staff_name_span").html($("#staffid option:selected").text());
            console.log(staffid);
            console.log(day);
            $.ajax({
                url: '<?php echo base_url() . 'coaching_controller/get_staff_schedule_ajax'; ?>',
                type: 'POST',
                data: {staff_id: staffid, day: day},
                success: function (data) {
                    console.log(data);
                    var data = $.parseJSON(data);
                    var events = new Array();

                    if (data['visit_events'].length > 0) {
                        for (var k = 0; data['visit_events'].length > k; k++) {
                            events.push({
                                id: data['visit_events'][k].id,
                                resourceId: data['visit_events'][k].resourceId,
                                start: data['visit_events'][k].start,
                                end: data['visit_events'][k].end,
                                title: data['visit_events'][k].title,
                                editable: true,
                                borderColor: data['visit_events'][k].borderColor,
                                backgroundColor: data['visit_events'][k].backgroundColor,
                                textColor: data['visit_events'][k].textColor,
                                id_visit_services: data['visit_events'][k].id_visit_services,
                                id_visit_service_staffs: data['visit_events'][k].id_visit_service_staffs
                            });
                        }
                    }
                    $('#staffcalendar').fullCalendar('destroy');
                    staffcalendar(events);
                    
                }
            });
        }


        function staffcalendar(e) {
            var staffid = $('#staffid option:selected').val();
            var day = $('#day').val();            
            $("#staff_name_span").html($("#staffid option:selected").text());
            
            var staffcalendar = $('#staffcalendar').fullCalendar({
                schedulerLicenseKey: 'CC-Attribution-NonCommercial-NoDerivatives',
                defaultView: 'agendaDay',
                initialView: 'agendaDay',    
                defaultDate: moment(day),
                bootstrapFontAwesome: !1,
                timeFormat: 'h:mm',
                slotLabelFormat: "hh:mm",
                displayEventTime : true,
                slotDuration: '00:10',
                minTime: '08:00',
                maxTime: '23:55',
                button: {
                },

                handleWindowResize: !0,
                header: {
                    left: 'title',
                    center: '',
                    right: 'agendaDay, agendaWeek, month'
                },

                editable: 1,
                droppable: 1,
                selectable: 1,
                allDaySlot: false,
                height: 740,
                resourceLabelText: 'Staff List',
                resources: [{'id': $("#staffid option:selected").val(), 'title': $("#staffid option:selected").text()}],
                events: e,
                eventClick: function (calEvent, jsEvent, view) {
                    
                    //console.log(calEvent);
                },
                select: function(start, end, jsEvent, view, resource) {
                    //console.log(jsEvent);
                    var temp=jsEvent.target['className'];
                                
                    //console.log(temp);
                    //console.log(temp.indexOf("fc-scroller"));
                    if(temp.indexOf("fc-scroller")<0){
                        //console.log(temp);
                        //console.log(start.format('HH:mm'));
                        $('#starttime').val(start.format('HH:mm'));
                            
                        var starttime = start.format('HH:mm');
                        var duration = '<?php if($service != null){ echo $service->service_duration ;}else {echo '15';}?>';
                        //console.log(starttime);
                        //console.log(duration);
                        var endtime = addTimes(starttime.toString(), duration);
                        //console.log(endtime);
            
                        var starthour=start.format('HH');
                        var endhour=parseInt(starthour)+1;
                        $('#endtime').val(endtime);
                    }
                },
                dayClick: function(date, jsEvent, view, resource) {
                  $('#day').val(date.format('YYYY-MM-DD'));
                    refresh_staff_schedule();
                },
                eventMouseover: function(calEvent, jsEvent) {
                    var mTitle=calEvent.title.split('-');
                    var tooltip = '<div class="tooltipevent" style="width:220px;height:105px;background:'+calEvent.backgroundColor+';color:#fff; padding:10px; position:absolute;z-index:10090; border-radius:4px;">' + mTitle[0]+' <br> '+ mTitle[1]+' <br> '+mTitle[2] + ' <br> '+mTitle[3] +  '</div>';
                    var $tooltip = $(tooltip).appendTo('body');

                    $(this).mouseover(function(e) {
                        $(this).css('z-index', 10000);
                        $tooltip.fadeIn('500');
                        $tooltip.fadeTo('10', 1.9);
                    }).mousemove(function(e) {
                        $tooltip.css('top', e.pageY + 30);
                        $tooltip.css('left', e.pageX - 100);
                    });
                },
                eventMouseout: function(calEvent, jsEvent) {
                    $(this).css('z-index', 8);
                    $('.tooltipevent').remove();
                },                     
                eventDragStart: function(event) {
                    oldResourceId = event.resourceId;
                    oldStart = event.start.format();
                },
                eventDrop: function(event, delta, revertFunc, jsEvent, ui, view) {
                    
                    var ee=event;
                    //console.log(ee); return false;
                    $.ajax({
                        url: '<?php echo base_url().'coaching_controller/updatevisit'; ?>',
                        //data: 'id_visit_services=' +event.id+ '&staff_id=' +event.resourceId+ '&start=' +event.start.format()+ '&end=' +event.end.format(),
                        data: {
                            id_visit_services:event.id_visit_services,
                            id_visit_service_staffs:event.id_visit_service_staffs,                            
                            start:event.start.format(),
                            end:event.end.format(),
                            staff_id:event.resourceId,
                            oldStaffId: oldResourceId,
                            oldStart: oldStart,
                            visit_status: event.visit_status
                        },
                        type: 'POST',
                        success: function(response){
                            if(response==='sessionexpired'){
                                window.location.assign('<?php echo base_url();?>');
                                return false;
                            }
                            
                            var result = response.split('|');

                            if(result[0] === 'success'){
                                //$('#calendar').fullCalendar('refetchEvents');
                                toastr.success('Visit has been updated!', 'Done!');

                            } else {
                                swal({
                                    title: "eventDrop Error",
                                    text: result[0],
                                    type: "error",
                                    confirmButtonText: 'OK!'
                                });
                            }
                                
                        }
                    
                    });
                }
            });
            
            // $("#staffcalendar").fullCalendar('rerenderEvents');
        }


        function showCalendarOverlay() {
            var h = $('#calendar').height();
            var w = $('#calendar').width();
            $('#StaffCalendarOverlay').css({
                'width': w + 16,
                'height': h
            });
            $('#StaffCalendarOverlay').show();
        }

        function hideCalendarOverlay() {
            $('#StaffCalendarOverlay').css({
                'display': 'none'
            });
        }
        
       
        
        
    function cancelVisit(group_visit_id, groupid, staffid, date) {
        
        swal({
                title: "Are you sure?",
                text: "Give Reason For Cancelling This Visit:",
                type: "input",
                showCancelButton: true,
                closeOnConfirm: false,
                inputPlaceholder: "reason for cancelling"
              }, function (inputValue) {
                if (inputValue === false) return false;
                if (inputValue === "") {
                  swal.showInputError("You need to write something!");
                  return false
                } 

            $.ajax({
                
                url: "<?php echo base_url() . 'coaching_controller/cancel_group_visits'; ?>",
                
                data: {
                    group_id: groupid, staff_id: staffid, date:date, cancelreason: inputValue
                },
                type: 'POST',
                success: function(response) {
                    if (response > 0) {
                        swal(
                            'Canceled!',
                            'Visit has been canceled.',
                            'success'
                        );
                        location.reload();
                    }
                }
            });

        });
    }        
    
    function printsection(elem)
    {
        var html='<table class="table"><thead><tr><th style="color:#000;">Staff Name</th><th style="color:#000;">Program</th><th style="color:#000;">Scheduled Date</th><th style="color:#000;">Scheduled Time</th><th style="color:#000;">To</th></tr></thead><tbody>';
        $.ajax({
            url: "<?php echo base_url() . 'coaching_controller/print_student_schedule/'.$id_program_groups.'/0'; ?>",

                type: 'GET',
                success: function(response) {

                    var data = $.parseJSON(response);
                    if (data.length > 0) {
                        for (x = 0; x < data.length; x++) {
                            html+='<tr>';
                            html+='<td>'+data[x]['staff_name']+'</td>';
                            html+='<td>'+data[x]['service_name']+'</td>';
                            html+='<td>'+data[x]['scheduled_date']+'</td>';
                            html+='<td>'+data[x]['scheduled_time']+'</td>';
                            html+='<td>'+data[x]['end_time']+'</td>';
                            html+='</tr>';
                        }
                        html+='</tbody></table>';
                        var mywindow = window.open('', 'PRINT', 'height=600,width=800');

                        mywindow.document.write('<html><head><title><?php echo $group->program_group;?></title>');
                        mywindow.document.write('<link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />');
                        mywindow.document.write('</head><body style="color:#000 !important;">');
                        mywindow.document.write('<h1>Session Schedule <?php echo $group->program_group;?></h1>');
                        mywindow.document.write(html);
                        mywindow.document.write('<footer><script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></footer>');
                        //mywindow.document.write('');
                        mywindow.document.write('</body></html>');

                        setTimeout(() => {mywindow.document.close(); // necessary for IE >= 10
                                            mywindow.focus(); // necessary for IE >= 10*/
                                            mywindow.print();
                                            mywindow.close();
                                        }
                                ,1000);
                        
                    }
                }
        });
        


        return true;
    }
    
    
    function showtable(start, end){

                        
        var mhtml='';
        
        $.ajax({
            url: '<?php echo base_url() . 'coaching_controller/get_group_schedule_groupedby'; ?>',
            type: 'POST',
            data: {group_id: $("#txtgroupid").val(), start: start, end:end},
            success: function (data) {
                console.log(data);
                var data = $.parseJSON(data);
                var events = new Array();

                if (data['groupevents'].length > 0) {
                    for (var k = 0; data['groupevents'].length > k; k++) {
                        mhtml += '<tr>';
                        mhtml += '<td style="color:#fff;">' + data['groupevents'][k].staff_id + '</td>';
                        mhtml += '<td style="color:#fff;">' + data['groupevents'][k].group_id + '</td>';
                        mhtml += '<td style="color:#fff;">' + data['groupevents'][k].staff_name + '</td>';
                        mhtml += '<td style="color:#fff;">' + data['groupevents'][k].startformatted +' '+data['groupevents'][k].starttime + '</td>';
                        mhtml += '<td style="color:#fff;">' + data['groupevents'][k].endformatted  +' '+data['groupevents'][k].endtime + '</td>';
                        
                        mhtml += '<td style="color:#fff;"><button onclick=cancelVisit("'+data['groupevents'][k].group_id+'","'+data['groupevents'][k].staff_id+'","'+data['groupevents'][k].visit_service_start+'") class="btn btn-xs btn-danger hidden-print">Cancel</button></td>';
                        mhtml += '</tr>';
                        
                    }
                }        
                $("#tbody").html(mhtml);
            }
        });    
    }
    
    function check_modal_start(){
        
        var start = $('#modal_start_time').val().split(":");
        var end = $('#modal_end_time').val().split(":");
        //console.log("start "+ start[0]);
        //console.log("end " + end[0]);
        if(start[0] >= end[0]){
            var endhour = parseInt(start[0])+1;
            //console.log("endhour " + endhour);
            $('#modal_end_time').val(endhour+":"+end[1]);
        }
    
    }
    
    function addTimes(startTime, endTime) {
        var times = [0, 0, 0];
        var max = times.length;

        var a = (startTime || '').split(':');
        var b = (endTime || '').split(':');

        // normalize time values
        for (var i = 0; i < max; i++) {
          a[i] = isNaN(parseInt(a[i])) ? 0 : parseInt(a[i]);
          b[i] = isNaN(parseInt(b[i])) ? 0 : parseInt(b[i]);
        }

        // store time values
        for (var i = 0; i < max; i++) {
          times[i] = a[i] + b[i];
        }

        var hours = times[0];
        var minutes = times[1];
        var seconds = times[2];

        if (seconds >= 60) {
          var m = (seconds / 60) << 0;
          minutes += m;
          seconds -= 60 * m;
        }

        if (minutes >= 60) {
          var h = (minutes / 60) << 0;
          hours += h;
          minutes -= 60 * h;
        }

        return (
          Number('0' + hours) +
          ':' +
          ('0' + minutes).slice(-2) 
          //+
          //':' +
          //('0' + seconds).slice(-2)
        );
      }
    </script>
