(function ($) {
    'use strict';

    const template = $('#ld_cms_tooltip_template');

    var LD_CMS_Admin = {
        searchTimeoutID: null,
        searchPageNum: 1,
        isLoadMore: false,
        init: function () {
            this.loadCourseList();
            this.initSearchField();
            this.loadMoreInit();
            this.initEventSelect2();
            tippy.setDefaultProps({
                delay: 500,
                theme: 'ld_cms',
                allowHTML: true,
            });
            this.loadCalendar();

            $(document).on('change', '#ld-cms-event-is-enrollment-start', function () {
                if ($(this).is(':checked')) {
                    $('#ld-cms-event-start-fields').hide();
                    $('#ld-cms-event-duration-fields').show();
                } else {
                    $('#ld-cms-event-start-fields').show();
                    $('#ld-cms-event-duration-fields').hide();
                }
            });
            var select_users_list = $('#select_users_id option').map(function () {
                return [[this.value, $(this).text()]];
            });
            $('#ld-cms-event-groups').on('change',function () {
                select_users_list = $('#select_users_id option').map(function () {
                    return [[this.value, $(this).text()]];
                });
                var selected_group_users = $('#ld-cms-event-groups option:selected').data('id');
                $('#select_users_id').empty();
                var select_users_id = $('#select_users_id');
                select_users_list.each(function () {
                    if ($('#ld-cms-event-groups').val() == '' || selected_group_users.indexOf(','+this[0].trim()+',') >= 0) {
                        select_users_id.append($('<option/>').attr('value', this[0]).text(this[1]));
                    } else{
                        select_users_id.append($('<option/>').attr('value', this[0]).text(this[1]).addClass("hidden"));
                    }
                });

                $(".hidden").toggleOption(false);
            });
            $(document).on('change', '.ld-cms-event-is-end-date', function () {
                var is_end_date = $('.ld-cms-event-is-end-date:checked').val();
                if( is_end_date == 'one_day_end_date' || is_end_date == 'no_end_date' ) {
                    $('#ld-cms-event-end-fields').hide();
                }else {
                    $('#ld-cms-event-end-fields').show();
                }
				 // nab*** changes
                if (is_end_date == 'end_date_yearly') {

                    $('#ld-cms-event-end-fields').hide();
                    $('#ld-cms-event-end-fields-yearly').show();
                } else {
                    $('#ld-cms-event-end-fields-yearly').hide();
                }
            });

            $(document).on('click', '.ld_cms_tree_link', LD_CMS_Admin.loadSubNode);
            $(document).on('click', '.ld-cms-event-close-link', function (e) {
                e.preventDefault();
                if (confirm(LDCSAdminVars.are_u_sure_to_delete)) {
                    var id = $(this).data('id');
                    LD_CMS_Admin.calendar.getEventById(id).remove();
                    //LD_CMS_Admin.calendar.refetchEvents();

                    jQuery.ajax({
                        url: LDCSAdminVars.ajax_url,
                        method: 'POST',
                        data: {
                            action: 'ld_cms_delete_event',
                            ld_cms_event: {
                                event_id: id
                            },
                        },
                        success: function (response) {
                            if (response.status === 'success') {
                                /*LD_CMS_Admin.calendar.removeAllEvents();
                                LD_CMS_Admin.calendar.refetchEvents();*/
                            }
                        }
                    });
                }
            });
            $('#ld-cms-event-form').on('submit', LD_CMS_Admin.eventSubmit);
            $(document).on('click', '.ld_cms_add_event_by_category_tag_link', function (e) {
                e.preventDefault();
                var object_type = $(this).data('object_type');
                var name = $(this).text();
                LD_CMS_Admin.loadEventPopup(0, 0, object_type, name);
            });

            
            $('.ld-cms-event-is-end-date').on('click', function(){
                LD_CMS_Admin.ld_cms_change_min_max_date();
                var is_end_date = $('.ld-cms-event-is-end-date:checked').val();
                if( is_end_date == 'one_day_end_date' || is_end_date == 'no_end_date' ) {
                    $('#ld-cms-event-end-fields').hide();
                }else {
                    $('#ld-cms-event-end-fields').show();
                }
            }); 
            LD_CMS_Admin.ld_cms_change_min_max_date();
            
            $('.ld-cms-event-time-field').timepicker({
                timeFormat: 'h:mm p',
                interval: 30,
                defaultTime: 'now',
                startTime: '00',
                zindex: 123050,
                dynamic: false,
                dropdown: true,
                scrollbar: true
            });

            $('body').on('thickbox:removed', function () {
                $('.ui-timepicker-container').hide(); //Hide timepicker dropdown on thickbox closed
            });

            $("#ld-cms-event-form1").on("submit", function (e) {
                e.preventDefault();
                var params = $("#ld-cms-event-form").serialize();

                $.ajax({
                    type: "post",
                    url: LDCSAdminVars.ajax_url,
                    dataType: "json",
                    data: params,
                    success: function (response) {
                        if (response.status == 'success') {
                            $(".invalid-date").hide();
                            tb_remove();
                        } else {
                            $("#ld-cms-thickbox-message").html("<div>" + response.status + "</div>").show();
                        }
                    },
                    error: function () {

                    }
                });
            });
        },
        ld_cms_change_min_max_date: function () {  
            var is_end_date = $('.ld-cms-event-is-end-date:checked').val();
            if( is_end_date == 'one_day_end_date' || is_end_date == 'no_end_date' ) {
                $("#ld-cms-event-start-date").datepicker("option", "maxDate", '');
                $("#ld-cms-event-end-date").datepicker("option", "maxDate", '');
            } else {
                if( $("#ld-cms-event-start-date").val()!='' ) {
                    var dt = new Date($("#ld-cms-event-start-date").val());
                    $("#ld-cms-event-end-date").datepicker("option", "minDate", dt);
                }
                if( $("#ld-cms-event-end-date").val()!='' ) {
                    var dt = new Date($("#ld-cms-event-end-date").val());
                    $("#ld-cms-event-start-date").datepicker("option", "maxDate", dt);
                }
            }

            $("#ld-cms-event-start-date").datepicker({
                numberOfMonths: 1,
                dateFormat: 'yy-mm-dd',
                onSelect: function (selected) {
                    var dt = new Date(selected);
                    dt.setDate(dt.getDate() + 1);
                    $("#ld-cms-event-end-date").datepicker("option", "minDate", dt);
                    var dt2 = new Date($("#ld-cms-event-end-date").val());
                    if( jQuery('#ld-cms-event-is-end-date').prop('checked') == false ) {
                        $("#ld-cms-event-start-date").datepicker("option", "maxDate", '');
                    } else{
                        $("#ld-cms-event-start-date").datepicker("option", "maxDate", dt2);
                    }
                }
            });
            $("#ld-cms-event-end-date").datepicker({
                numberOfMonths: 1,
                dateFormat: 'yy-mm-dd',
                onSelect: function (selected) {
                    var dt = new Date(selected);
                    dt.setDate(dt.getDate() - 1);
                    if( jQuery('#ld-cms-event-is-end-date').prop('checked') == true ) {
                        $("#ld-cms-event-start-date").datepicker("option", "maxDate", dt);
                        
                        var dt2 = new Date($("#ld-cms-event-start-date").val());
                        $("#ld-cms-event-end-date").datepicker("option", "minDate", dt2);
                    } else {
                        $("#ld-cms-event-start-date").datepicker("option", "maxDate", '');
                    }
                    
                }
            });
        },
        load_taxonomy_category: function (object, val) {
            var type = '';
            if (object == 'schedule_courses') {
                type = 'ld_course_category';
            }

            if (object == 'schedule_lessons') {
                type = 'ld_lesson_category';
            }

            if (object == 'schedule_topics') {
                type = 'ld_topic_category';
            }

            $.ajax({
                type: 'post',
                url: LDCSAdminVars.ajax_url,
                data: { action: 'cs_ld_load_taxonomy', object_type: type, section: 'category' },
                success: function (response) {
                    $("#ld-cms-event-categories").html(response);
                    if (parseInt(val) > 0) {
                        $("#ld-cms-event-categories").val(val).trigger('change');
                    }
                }
            });
        },
        load_taxonomy_tags: function (object, val) {
            var type = '';
            if (object == 'schedule_courses') {
                type = 'ld_course_tag';
            }

            if (object == 'schedule_lessons') {
                type = 'ld_lesson_tag';
            }

            if (object == 'schedule_topics') {
                type = 'ld_topic_tag';
            }

            $.ajax({
                type: 'post',
                url: LDCSAdminVars.ajax_url,
                data: { action: 'cs_ld_load_taxonomy', object_type: type, section: 'tag' },
                success: function (response) {
                    $('#ld-cms-event-tags').html(response);
                    if (parseInt(val) > 0) {
                        $("#ld-cms-event-tags").val(val).trigger('change');
                    }
                }
            });

        },
        initEventSelect2: function () {
            $('#ld-cms-group-roles-schedule').select2({ minimumInputLength: 2, multiple: true });
            // $('#ld-cms-event-user-roles').select2({ minimumInputLength: 2, multiple: true });
            $('#ld-cms-schedule-excluded-roles').select2({ minimumInputLength: 2, multiple: true });
        },
        loadCourseList: function () {
            this.doSearch();
        },
        initSearchField: function () {
            $('#ld_cms_search_courses').keyup(function (e) {
                clearTimeout(this.searchTimeoutID);
                this.searchTimeoutID = setTimeout(() => LD_CMS_Admin.triggerSearch(e.target.value), 500);
            });
        },
        triggerSearch: function (str) {
            if (str.length == 0 || str.length >= 3) {
                LD_CMS_Admin.searchPageNum = 1;
                LD_CMS_Admin.isLoadMore = false;
                this.doSearch();
            }
        },
        doSearch: function () {
            $.ajax({
                type: "post",
                url: LDCSAdminVars.ajax_url,
                dataType: "json",
                data: {
                    action: 'cs_ld_search_courses',
                    security: LDCSAdminVars.check_nonce,
                    search_text: $('#ld_cms_search_courses').val(),
                    ld_cms_course_list_page_num: LD_CMS_Admin.searchPageNum,

                },
                beforeSend: function () {
                    $('#ld_cms_course_list_loader').show();
                    if (!LD_CMS_Admin.isLoadMore) {
                        $('#ld_cms_course_list').hide();
                    } else {
                        $('#ld_cms_course_list').show();
                    }
                },
                success: function (response) {

                    if (LD_CMS_Admin.isLoadMore) {
                        $('#ld_cms_course_list > #ld_cms_course_sub_list').append(response.content);
                    } else {
                        $('#ld_cms_course_list').html(response.content);
                    }

                    if (response.next_page == 0) {
                        $('#ld_cms_load_more').hide();
                    } else {
                        LD_CMS_Admin.searchPageNum = response.next_page;
                        $('#ld_cms_load_more').show();
                    }

                    LD_CMS_Admin.refreshCalendarEvents();
                },
                complete: function () {
                    $('#ld_cms_course_list_loader').hide();
                    $('#ld_cms_course_list').show();
                }
            });
        },
        loadMoreInit: function () {
            $(document).on('click', '#ld_cms_load_more', function (e) {
                e.preventDefault();
                LD_CMS_Admin.isLoadMore = true;
                LD_CMS_Admin.doSearch();
            });

        },
        refreshCalendarEvents: function () {

            $(document).on('mouseover touchmove', 'div#external-events div.fc-event', function () {
                // store data so the calendar knows to render an event upon drop
                $(this).data('event', {
                    title: $.trim($(this).text()), // use the element's text as the event title
                    course_id: $.trim($(this).data('course-id')),
                    cid: $.trim($(this).data('cid')),
                    lid: $.trim($(this).data('lid')),
                    course_type: $.trim($(this).data('course-type')),
                    className: $.trim($(this).text()),
                    stick: true // maintain when user navigates (see docs on the renderEvent method)
                });

                // make the event draggable using jQuery UI
                $(this).draggable({
                    zIndex: 999,
                    revert: true,      // will cause the event to go back to its
                    revertDuration: 0, //  original position after the drag

                });
            });
        },
        loadSubNode: function () {
            var id = $(this).attr('id');

            var child = $("#" + id).parent().next(".children");

            var is_append = false;
            if (child.length == 0) {
                $("#" + id).parent().after('<div class="children"></div>');
                child = $("#" + id).parent().next(".children");
                is_append = true;
            }
            var current_html = $("#" + id).html();
            if (current_html == "+") {
                var my_course_id = $("#" + id).attr("data-id");
                var my_cid = $("#" + id).attr("data-cid");
                var my_lid = $("#" + id).attr("data-lid");
                var image = '<img src="' + LDCSAdminVars.preloader + '" />';
                $("#" + id).html(image);
                $.ajax({
                    type: "post",
                    url: LDCSAdminVars.ajax_url,
                    data: { action: "cs_ld_load_courses", course_id: my_course_id, cid: my_cid, lid: my_lid },
                    dataType: "json",
                    success: function (response) {
                        child.html('');
                        if (response.length > 0) {
                            for (var i = 0; i < response.length; i++) {
                                if (response[i].load_on_demand == true) {
                                    child.append('<div class="independant_node"><div class="fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event" data-course-type="' + response[i].post_type + '" data-cid="' + response[i].cid + '" data-lid="' + response[i].lid + '" data-course-id="' + response[i].id + '"><a href="javascript:;" id="csld_tree_node_' + response[i].id + '_' + response[i].cid + '_' + response[i].lid + '" class="ld_cms_tree_link" data-id="' + response[i].id + '" data-cid="' + response[i].cid + '" data-lid="' + response[i].lid + '" data-type="' + response[i].post_type + '">+</a>&nbsp;' + response[i].name + '</div></div>');
                                } else {
                                    child.append('<div class="independant_node"><div class="fc-event fc-h-event fc-daygrid-event fc-daygrid-block-event" data-course-type="' + response[i].post_type + '" data-cid="' + response[i].cid + '" data-lid="' + response[i].lid + '" data-course-id="' + response[i].id + '"><a href="javascript:;" id="csld_tree_node_' + response[i].id + '_' + response[i].cid + '_' + response[i].lid + '" class="ld_cms_tree_link" data-id="' + response[i].id + '" data-cid="' + response[i].cid + '" data-lid="' + response[i].lid + '" data-type="' + response[i].post_type + '"></a>&nbsp;' + response[i].name + '</div></div>');
                                }
                            }
                            $('#external-events .fc-event').each(function () {
                                // store data so the calendar knows to render an event upon drop
                                $(this).data('event', {
                                    title: $.trim($(this).text()), // use the element's text as the event title
                                    course_id: $.trim($(this).data('course-id')),
                                    cid: $.trim($(this).data('cid')),
                                    lid: $.trim($(this).data('lid')),
                                    course_type: $.trim($(this).data('course-type')),
                                    className: $.trim($(this).text()),
                                    stick: true // maintain when user navigates (see docs on the renderEvent method)
                                });

                                // make the event draggable using jQuery UI
                                $(this).draggable({
                                    zIndex: 999,
                                    revert: true,      // will cause the event to go back to its
                                    revertDuration: 0, //  original position after the drag

                                });
                            });
                        } else {
                            $("#" + id).css("display", "none");
                        }
                        $("#" + id).html("-");
                    }
                });
            } else {
                child.html('');
                $("#" + id).html("+");
            }

        },
        eventSubmit: function (e) {
            //ld-cms-event-form
            e.preventDefault();
            jQuery.ajax({
                url: LDCSAdminVars.ajax_url,
                method: 'POST',
                data: $(this).serialize(),
                success: function (response) {
                    $('#ld-cms-thickbox-message').html(response.status).css('display', 'block');
                    if (response.status == 'success') {
                        $('#ld-cms-thickbox-message').html('').css('display', 'none');
                        LD_CMS_Admin.calendar.refetchEvents();
                        tb_remove();
                        
                    }
                }
            });

        },
        updateEventDuration: function (object_id, rec_id, event_start_at, event_end_at, info) {
            jQuery.ajax({
                url: LDCSAdminVars.ajax_url,
                method: 'POST',
                data: {
                    action: 'increase_course_schedule_time',
                    start: event_start_at,
                    end: event_end_at,
                    object_id: object_id,
                    rec_id: rec_id,
                },
                success: function (response) {
                    if (response.status === 'success') {
                        LD_CMS_Admin.calendar.refetchEvents();
                    }
                }
            });
        },
        resetEventPopup: function () {
            $('#ld_cms_event_edit_thickbox form').trigger('reset');
            // $('#ld-cms-event-users').val(null).trigger('change');
            // $('#ld-cms-event-user-roles').val(null).trigger('change');
            $('#ld-cms-event-is-end-date').trigger('change');
            $('#ld-cms-thickbox-message').hide();
        },
        loadEventPopup: function (rec_id, object_id, object_type, name) {
            $( "#ld_cms_calendar" ).css('opacity', '0.5');
            $( ".ld-cms-preloader-div").css('display', 'block');
            var x_c_object_type = '';
            var x_t_object_type = '';
            switch (object_type) {
                case 'schedule_courses':
                case 'sfwd-courses':
                    x_c_object_type = 'ld_course_category';
                    x_t_object_type = 'ld_course_tag';
                    break;
                case 'schedule_lessons':
                case 'sfwd-lessons':
                    x_c_object_type = 'ld_lesson_category';
                    x_t_object_type = 'ld_lesson_tag';
                    break;
                case 'schedule_topics':
                case 'sfwd-topic':
                    x_c_object_type = 'ld_topic_category';
                    x_t_object_type = 'ld_topic_tag';
                    break;
            }
            if (LD_CMS_Admin.tooltip_instance) {
                LD_CMS_Admin.tooltip_instance.hide(); //Hide tooltip
            }

            LD_CMS_Admin.loadGroupsbyCourse(object_id, object_type);
            LD_CMS_Admin.resetEventPopup();
            if (['schedule_courses', 'schedule_lessons', 'schedule_topics', 'sfwd-courses', 'sfwd-lessons', 'sfwd-topic', 'sfwd-quiz'].includes(object_type)) {
                 
                $('#ld-cms-event-action').val('ld_cms_update_event');
                if (['schedule_courses', 'schedule_lessons', 'schedule_topics'].includes(object_type)) {
                    if (object_type == 'sfwd-courses') {
                        $('#ld-cms-event-group-fields').show();

                    } else {
                        $('#ld-cms-event-group-fields').hide();
                    }
                    $('#ld-cms-event-category-tag-fields').show();
                } else {
                    if (object_type == 'sfwd-courses' || object_type == 'sfwd-lessons' || object_type == 'sfwd-topic' || object_type == 'sfwd-quiz') {
                        $('#ld-cms-event-group-fields').show();

                    } else {
                        $('#ld-cms-event-group-fields').hide();
                    }
                    $('#ld-cms-event-category-tag-fields').hide();
                }

                if (rec_id === 0) {
                    $('#ld-cms-event-object-type').val(object_type);
                    tb_show(name, '#TB_inline?width=640&height=430&inlineId=ld_cms_event_edit_thickbox');
                    $( "#ld_cms_calendar" ).css('opacity', '1');
                    $( ".ld-cms-preloader-div").css('display', 'none');
                }
                jQuery.ajax({
                    url: LDCSAdminVars.ajax_url,
                    method: 'POST',
                    data: {
                        action: 'cs_ld_get_record',
                        rec_id: rec_id,
                        object_id: object_id,
                    },
                    success: function (response) {
                        console.log(response);
                        if (response.id > 0) {
                            if (response.title != '')
                                name = response.title;
                            jQuery.ajax({
                                url: LDCSAdminVars.ajax_url,
                                method: 'POST',
                                data: {
                                    action: 'cs_ld_load_taxonomy',
                                    section: 'category',
                                    object_type: x_c_object_type,
                                },
                                success: function (response) {
                                    jQuery("#ld-cms-event-categories").html(response);
                                }
                            });
                            jQuery.ajax({
                                url: LDCSAdminVars.ajax_url,
                                method: 'POST',
                                data: {
                                    action: 'cs_ld_load_taxonomy',
                                    section: 'tag',
                                    object_type: x_t_object_type,
                                },
                                success: function (response) {
                                    jQuery("#ld-cms-event-tags").html(response);


                                    if (rec_id === 0) {
                                        $('#ld-cms-event-object-type').val(object_type);
                                        tb_show(name, '#TB_inline?width=640&height=430&inlineId=ld_cms_event_edit_thickbox');
                                        $( "#ld_cms_calendar" ).css('opacity', '1');
                                        $( ".ld-cms-preloader-div").css('display', 'none');
                                    }

                                    jQuery.ajax({
                                        url: LDCSAdminVars.ajax_url,
                                        method: 'POST',
                                        data: {
                                            action: 'cs_ld_get_record',
                                            rec_id: rec_id,
                                            object_id: object_id,
                                        },
                                        success: function (response) {
                                            if (response.id > 0) {

                                                jQuery('#ld-cms-event-rec-id').val(response.id);
                                                jQuery('#ld-cms-event-object-id').val(response.object_id);
                                                jQuery('#ld-cms-event-object-type').val(response.object_type);
                                                jQuery('#ld-cms-event-course-id').val(response.object_parent_course);
                                                jQuery('#ld-cms-event-lesson-id').val(response.object_parent_lesson);

                                                jQuery('#ld-cms-event-start-date').val(response.start);
                                                jQuery('#ld-cms-event-start-time').val(response.start_time);
                                                if( response.is_end_date != 'one_day_end_date' ) {
                                                    jQuery('#ld-cms-event-end-date').val(response.end);
                                                    jQuery('#ld-cms-event-end-time').val(response.end_time);
                                                    $("#ld-cms-event-start-date").datepicker("option", "maxDate", response.end);
                                                    $("#ld-cms-event-end-date").datepicker("option", "minDate", response.start);
                                                } else {
                                                    jQuery('#ld-cms-event-end-date').val(response.start);
                                                    jQuery('#ld-cms-event-end-time').val("11:59 PM");
                                                }

                                                if (response.is_end_date == 'one_day_end_date') {
                                                    jQuery('#ld-cms-event-is-end-date2').prop('checked', true);
                                                    jQuery('#ld-cms-event-is-end-date2').trigger("click");
                                                } else if (response.is_end_date == 'no_end_date') {
                                                    jQuery('#ld-cms-event-is-end-date1').prop('checked', true);
                                                    jQuery('#ld-cms-event-is-end-date1').trigger("click");
                                                } else if (response.is_end_date == 'end_date') {
                                                    jQuery('#ld-cms-event-is-end-date').prop('checked', true);
                                                    jQuery('#ld-cms-event-is-end-date').trigger("click");
                                                }

                                                LD_CMS_Admin.ld_cms_change_min_max_date();
                                                // New Code Here 
                                                jQuery.ajax({
                                                    url: LDCSAdminVars.ajax_url,
                                                    method: 'POST',
                                                    data: {
                                                        action: 'cs_ld_excluded_users',
                                                        excluded_user_ids: response.excluded_users,
                                                        selected_roles:response.excluded_role,
                                                    },
                                                    success: function (response1) {
                                                        

                                                        // Role Field
                                                        var opt_role = '';
                                                        var chosen_opt_role = '';

                                                        jQuery.each(response1.data.roles, function (index, value) {
                                                            opt_role +='<option value='+value.role+'>'+value.name+'</option>';
                                                            window.select_roles_list = [[value.role, value.name]];
                                                        });
                                                        jQuery("#select_roles_id").html(opt_role);

                                                        
                                                        jQuery.each(response1.data.selected_roles, function (index, value) {
                                                            chosen_opt_role +='<option value='+value.role+'>'+value.name+'</option>';
                                                        });
                                                        jQuery("#chosen_roles_id").html(chosen_opt_role);



                                                        //User Fileds

                                                        var opt = '';
                                                        var chosen_opt = '';

                                                        jQuery.each(response1.data.users_list, function (index, value) {
                                                            opt +='<option value='+value.id+'>'+value.text+'</option>';
                                                        });
                                                        jQuery("#select_users_id").html(opt);

                                                        
                                                        jQuery.each(response1.data.selected_users_list, function (index, value) {
                                                            chosen_opt +='<option value='+value.id+'>'+value.text+'</option>';
                                                        });
                                                        jQuery("#chosen_users_id").html(chosen_opt);
                                            
                            
                                                    }
                                                });
                                                
                                                // New Code End Here
                                                jQuery('#ld-cms-event-groups').val(response.ld_group);
                                                jQuery("#ld-cms-event-categories").val(response.category);
                                                jQuery("#ld-cms-event-tags").val(response.tag);

                                                if (response.is_subsdate_as_startdate == 'Yes') {
                                                    jQuery('#ld-cms-event-is-enrollment-start').prop('checked', true);
                                                } else {
                                                    jQuery('#ld-cms-event-is-enrollment-start').prop('checked', false);
                                                }

                                                if (response.user_filter_type == 'Exclude') {
                                                    jQuery('#ld-cms-event-filter-type-exclude').prop('checked', true);
                                                } else {
                                                    jQuery('#ld-cms-event-filter-type-include').prop('checked', true);
                                                }

                                                var d_interval = '1';
                                                if (response.duration != 0) {
                                                    d_interval = response.duration;
                                                }

                                                var d_type = 'Day';
                                                if (response.duration_type.length != 0) {
                                                    d_type = response.duration_type;
                                                }

                                                jQuery('#ld-cms-event-duration').val(d_interval);
                                                jQuery('#ld-cms-event-duration-type').val(d_type);
                                            }

                                            tb_show(name, '#TB_inline?width=640&height=430&inlineId=ld_cms_event_edit_thickbox');
                                            $( "#ld_cms_calendar" ).css('opacity', '1');
                                            $( ".ld-cms-preloader-div").css('display', 'none');
                                        }
                                    });

                                }
                            });

                        } else {
                            $('#ld-cms-event-group-fields').show();
                    
                            if (rec_id === 0) {
                                $('#ld-cms-event-object-type').val(object_type);
                                tb_show(name, '#TB_inline?width=640&height=430&inlineId=ld_cms_event_edit_thickbox');
                                $( "#ld_cms_calendar" ).css('opacity', '1');
                                $( ".ld-cms-preloader-div").css('display', 'none');
                            }

                            jQuery.ajax({
                                url: LDCSAdminVars.ajax_url,
                                method: 'POST',
                                data: {
                                    action: 'cs_ld_get_record',
                                    rec_id: rec_id,
                                    object_id: object_id,
                                },
                                success: function (response) {
                                    if (response.id > 0) {
                                        if (response.title != '')
                                            name = response.title;
                                        jQuery('#ld-cms-event-rec-id').val(response.id);
                                        jQuery('#ld-cms-event-object-id').val(response.object_id);
                                        jQuery('#ld-cms-event-object-type').val(response.object_type);
                                        jQuery('#ld-cms-event-course-id').val(response.object_parent_course);
                                        jQuery('#ld-cms-event-lesson-id').val(response.object_parent_lesson);


                                        jQuery('#ld-cms-event-start-date').val(response.start);
                                        jQuery('#ld-cms-event-start-time').val(response.start_time);
                                        if( response.is_end_date != 'one_day_end_date' ) {
                                            jQuery('#ld-cms-event-end-date').val(response.end);
                                            jQuery('#ld-cms-event-end-time').val(response.end_time);
                                        } else {
                                            jQuery('#ld-cms-event-end-date').val(response.start);
                                            jQuery('#ld-cms-event-end-time').val("11:59 PM");
                                        }
                                        

                                        if (response.is_end_date == 'one_day_end_date') {
                                            jQuery('#ld-cms-event-is-end-date2').prop('checked', true);
                                            jQuery('#ld-cms-event-is-end-date2').trigger("click");
                                        } else if (response.is_end_date == 'no_end_date') {
                                            jQuery('#ld-cms-event-is-end-date1').prop('checked', true);
                                            jQuery('#ld-cms-event-is-end-date1').trigger("click");
                                        } else if (response.is_end_date == 'end_date') {
                                            jQuery('#ld-cms-event-is-end-date').prop('checked', true);
                                            jQuery('#ld-cms-event-is-end-date').trigger("click");
                                        }

                                        //jQuery('#ld-cms-event-is-end-date').change();

                                        jQuery.each(response.excluded_role, function (index, value) {
                                            jQuery("#ld-cms-event-user-roles").data('select2').trigger('select', {
                                                data: value
                                            });
                                        });

                                        jQuery('#ld-cms-event-user-roles').trigger('change');

                                        jQuery('#ld-cms-event-groups').val(response.ld_group);

                                        if (parseInt(response.category) > 0) {
                                            jQuery('#ld-cms-event-categories').val(response.category).trigger('change');
                                        }

                                        if (parseInt(response.tag) > 0) {
                                            jQuery('#ld-cms-event-tags').val(response.tag).trigger('change');
                                        }

                                        jQuery('#ld-cms-event-users').trigger('change');

                                        jQuery('#ld-cms-event-groups').val(response.ld_group);
                                        jQuery("#ld-cms-event-categories").val(response.category);
                                        jQuery("#ld-cms-event-tags").val(response.tag);

                                        if (response.is_subsdate_as_startdate == 'Yes') {
                                            jQuery('#ld-cms-event-is-enrollment-start').prop('checked', true);
                                        } else {
                                            jQuery('#ld-cms-event-is-enrollment-start').prop('checked', false);
                                        }

                                        if (response.user_filter_type == 'Exclude') {
                                            jQuery('#ld-cms-event-filter-type-exclude').prop('checked', true);
                                        } else {
                                            jQuery('#ld-cms-event-filter-type-include').prop('checked', true);
                                        }

                                        var d_interval = '1';
                                        if (response.duration != 0) {
                                            d_interval = response.duration;
                                        }

                                        var d_type = 'Day';
                                        if (response.duration_type.length != 0) {
                                            d_type = response.duration_type;
                                        }

                                        jQuery('#ld-cms-event-duration').val(d_interval);
                                        jQuery('#ld-cms-event-duration-type').val(d_type);
                                    }

                                    tb_show(name, '#TB_inline?width=640&height=430&inlineId=ld_cms_event_edit_thickbox');
                                    $( "#ld_cms_calendar" ).css('opacity', '1');
                                    $( ".ld-cms-preloader-div").css('display', 'none');
                                    return;
                                }
                            });
                        }
                    }
                }).done(function (e) {
                    LD_CMS_Admin.load_taxonomy_category(object_type, e.category);
                    LD_CMS_Admin.load_taxonomy_tags(object_type, e.tag);
                });
            } 
        },
        loadGroupsbyCourse: function (object_id, object_type) {
            jQuery.ajax({
                url: LDCSAdminVars.ajax_url,
                method: 'POST',
                data: {
                    action: 'cs_ld_get_dropdown_vals',
                    object_id: object_id,
                    object_type: object_type,
                },
                success: function (response) {
                    $('#ld-cms-event-groups').html(response.group_ddl);
                }
            });
        },
        loadCalendar: function () {
            var calendarEl = $('#ld_cms_calendar_wrap')[0];
            var caller_type = $(calendarEl).data('type');
            var caltype = $(calendarEl).data('caltype');
            
            var start   = $(calendarEl).data('start');
            var end     = $(calendarEl).data('end');
            var nowdate     = LDCSAdminVars.now_calendar_time;
            if( start ) {
                nowdate     = start;
            } else {
                start   = LDCSAdminVars.start_calendar;
            }
            
            if( end == '' || end == undefined ) {
                end   = LDCSAdminVars.end_calendar;
            }
            
            var default_tool = {
                            start: 'title', // will normally be on the left. if RTL, will be on the right
                            center: '',
                            end: 'today, prev, next' // will normally be on the right. if RTL, will be on the left
                        };
            if( caltype == 'monthly'  ) {
                default_tool = {
                    start: 'title', // will normally be on the left. if RTL, will be on the right
                    center: '',
                    end: '' // will normally be on the right. if RTL, will be on the left
                };
            }

            if (calendarEl) {
                LD_CMS_Admin.calendar = new FullCalendar.Calendar(calendarEl, {
                    initialView: 'dayGridMonth',
                    defaultDate: start,
                    contentHeight: 'auto',
                    locale: LDCSAdminVars.lang,
                    dayMaxEventRows: 4,
                    header:false,
                    editable: false,
                    forceEventDuration: true,
                    eventResizableFromStart: true,
                    lazyFetching: true,header: false, // don't display the default header
                    headerToolbar: default_tool,
                    now:nowdate,
                    eventConstraint: {
                        start: "'" + start + "'",
                        end: "'" + end + "'"
                    },
                    eventSources: [
                        // event source
                        {
                            url: LDCSAdminVars.ajax_url,
                            method: 'POST', 
                            extraParams: {
                                action: 'getEvents',
                                user_id: $(calendarEl).data('user-id'),
                                type: caller_type,
                                start_at: start,
                                end_at: end
                            },
                            success: function (data) {
                                // console.log("result");
                                //console.log(data);
                            },
                            failure: function () {
                                //console.log('there was an error while fetching events!');
                                //alert('there was an error while fetching events!');
                            },
                        }
                        // any other sources.
                    ],
                    eventClassNames: function (arg) {
                        if (LDCSAdminVars.show_options == 'show') {
                            return ['fc-event-show'];
                        } else {
                            return ['fc-event-hide'];
                        }

                        // if (arg.event.extendedProps.isEventShow) {
                        //     return ['fc-event-show'];
                        // } else {
                        //     return ['fc-event-hide'];
                        // }
                    },
                    eventDidMount: function (info) {
                        LD_CMS_Admin.updateTooltip(info);
                    },
                    eventWillUnmount: function (info) {
                        info.el._tippy.destroy();
                    },
                    eventDrop: function (info) {

                        var object_id = info.event.extendedProps.object_id;
                        var rec_id = info.event.extendedProps.rec_id;
                        var event_start_at = moment(info.event.start.toISOString()).format("YYYY-MM-DD");
                        var event_end_at = moment(info.event.end.toISOString()).format("YYYY-MM-DD");

                        if (!confirm(LDCSAdminVars.are_u_sure_about_change)) {
                            info.revert();
                        } else {
                            LD_CMS_Admin.updateEventDuration(object_id, rec_id, event_start_at, event_end_at, info);
                        }
                    },
                    eventContent: function (arg) {
                        var event_title = arg.event.title;

                        let html = '<span class="ld-cms-event-title abnas' + arg.event.extendedProps.can_edit + '">' + event_title + '</span>';
                        
                        if (arg.event.extendedProps.can_edit === 1 && caller_type != 'student') {
                            html += '<a class="ld-cms-event-close-link" data-id="' + arg.event.extendedProps.rec_id + '"><i class="fa fa-window-close"></i></a>';
                        }

                        return { html: html }
                    },
                    drop: function (info) {
                        var start_date = info.dateStr;
                        var course_id = info.draggedEl.dataset.courseId;
                        var parent_course_id = info.draggedEl.dataset.cid;
                        var parent_lesson_id = info.draggedEl.dataset.lid;

                        jQuery.ajax({
                            url: LDCSAdminVars.ajax_url,
                            method: 'POST',
                            data: {
                                action: 'ld_cms_update_event',
                                ld_cms_event: {
                                    object_id: course_id,
                                    parent_course_id: parent_course_id,
                                    parent_lesson_id: parent_lesson_id,
                                    start_date: start_date,
                                },
                            },
                            success: function (response) {
                                $('#ld-cms-thickbox-message').html(response.status).css('display', 'block');
                                if (response.status === 'success') {
                                    LD_CMS_Admin.calendar.removeAllEvents();
                                    LD_CMS_Admin.calendar.refetchEvents();
                                    $('#ld-cms-thickbox-message').html('').css('display', 'none');
                                }
                            }
                        });
                    },
                    eventResize: function (info) {

                        var object_id = info.event.extendedProps.object_id;
                        var rec_id = info.event.extendedProps.rec_id;
                        var name = info.event.extendedProps.name;
                        var event_start_at = moment(info.event.start.toISOString()).format("YYYY-MM-DD");
                        var event_end_at = moment(info.event.end.toISOString()).format("YYYY-MM-DD");

                        if (!confirm(LDCSAdminVars.are_u_sure_about_change)) {
                            info.revert();
                        } else {
                            LD_CMS_Admin.updateEventDuration(object_id, rec_id, event_start_at, event_end_at, info);
                        }

                        if (LD_CMS_Admin.tooltip_instance) {
                            LD_CMS_Admin.tooltip_instance.hide(); //Hide tooltip
                        }
                    },
                    eventClick: function (info) {

                        $('#ldcms-view-detail-page').attr('href', info.event.extendedProps.object_link);
                        $('#ldcms-view-detail-page').html(info.event.extendedProps.object_link_text);
                        if (info.event.extendedProps.object_link_text == '') {
                            $('#ldcms-view-detail-page').css('display', 'none');
                        } else {
                            $('#ldcms-view-detail-page').css('display', 'inline-block');
                        }

                        if (caller_type == 'student') {
                            if (info.event.extendedProps.object_link != '') {
                                document.location = info.event.extendedProps.object_link;
                            } else {
                                alert(info.event.extendedProps.group_alert_text);
                                return;
                            }
                        }

                        if (info.jsEvent.target.className == 'fa fa-window-close') {
                            return;
                        }

                        if (info.event.extendedProps.can_edit === 0) {
                            return;
                        }

                        var object_id = info.event.extendedProps.object_id;
                        var rec_id = info.event.extendedProps.rec_id;
                        var name = info.event.extendedProps.name;
                        var object_type = info.event.extendedProps.object_type;

                        /*if( ['schedule_courses','schedule_lessons','schedule_topics'].includes(object_type) ) {
                            if($('.ld_cms_event_' + object_type).length) {
                                name = $('.ld_cms_event_' + object_type).text();
                            }
                        }*/

                        LD_CMS_Admin.loadEventPopup(rec_id, object_id, object_type, name);
                    }
                });

                LD_CMS_Admin.calendar.render(); //LD_CMS_Admin.calendar.gotoDate('2022-04-21');
                var containerEl = document.getElementById('ld_cms_events');

                if (containerEl) {
                    new FullCalendar.Draggable(containerEl, {
                        itemSelector: '.fc-event',
                        eventData: function (eventEl) {
                            return {
                                title: eventEl.innerText.trim()
                            }
                        }
                    });
                }
            }


        },
        updateTooltip: function (info) {
            var event_start_at = moment(info.event.start).format("DD-MM-YYYY h:mm a");
            var event_end_at = moment(info.event.end).format("DD-MM-YYYY h:mm a");
            //var event_end_at = new Date(info.event.end);

            //event_end_at.setDate( event_end_at.getDate() + (-1) );
            //event_end_at = moment(event_end_at).format("DD-MM-YYYY HH:mm")


            template.find('#ld_cms_tt_id').html(info.event.id);
            template.find('#ld_cms_tt_title').html(info.event.title);
            template.find('#ld_cms_tt_start').html(event_start_at);
            template.find('#ld_cms_tt_end').html(event_end_at);

            tippy(info.el, {
                content: $(template).html(),
            });

            LD_CMS_Admin.tooltip_instance = info.el._tippy;
        }
    };

    LD_CMS_Admin.init();

    /*function setDatepickerPos(input, inst) {
        var rect = input.getBoundingClientRect();
        // use 'setTimeout' to prevent effect overridden by other scripts
        setTimeout(function () {
            var scrollTop = $("body").scrollTop();
            inst.dpDiv.css({ top: rect.top + input.offsetHeight + scrollTop });
        }, 0);
    }*/

})(jQuery);