var Admin = function () {
    /// <summary>Constructor function of the event admin class.</summary>
    /// <returns type="Home" />
    // Uploading files

    var file_frame;
    var file_target_input;
    var file_target_wrapper;
    return {

        ///<summary>
        ///Initializes the admin.
        ///</summary>
        ///<returns type="initialization settings" />
        /// <since>1.0.0</since>
        init: function () {
            //Tooltips
            jQuery(".tips, .help_tip").tipTip({
                'attribute': 'data-tip',
                'fadeIn': 50,
                'fadeOut': 50,
                'delay': 200,
                keepAlive: true
            });

            //load chosen
            if (jQuery(".event-manager-select-chosen").length > 0){
                jQuery(".event-manager-select-chosen").chosen();
            }

            //time settings change
            jQuery('input[name=_event_time_format]').on('change', Admin.actions.showSelectedTimeFormat);
            jQuery(".wpem-tabs li a").on('click', Admin.actions.tabClick);
            jQuery('.wpem-tabs li a:first').click();
            jQuery(document).on("click", ".event-manager-remove-uploaded-file", function (e) {
                e.preventDefault(); // Prevent default anchor behavior
                var parentDiv = jQuery(this).closest(".event-manager-uploaded-files");
                // Remove the preview span
                parentDiv.find(".event-manager-uploaded-file-preview").remove();
                // Clear the hidden input field value
                parentDiv.find('input[type="hidden"]').val('');
            });

            if (jQuery('input[data-picker="datepicker"]#_event_start_date').length > 0) {
                wp_event_manager_admin_js.start_of_week = parseInt(wp_event_manager_admin_js.start_of_week);

                if (wp_event_manager_admin_js.show_past_date) {
                    jQuery('input[data-picker="datepicker"]#_event_start_date').datepicker({
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week
                    }).on('change', function () {
                        jQuery("#_event_end_date").datepicker("destroy");
                        
                        jQuery('input[data-picker="datepicker"]#_event_end_date').datepicker({
                            minDate: jQuery('#_event_start_date').val(),
                            dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                            firstDay: wp_event_manager_admin_js.start_of_week,
                        });
                    });
                } else  {                    
                    jQuery('input[data-picker="datepicker"]#_event_start_date').datepicker({
                        minDate: 0,
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week
                    }).on('change', function ()  {
                        jQuery("#_event_end_date").datepicker("destroy");
                        
                        jQuery('input[data-picker="datepicker"]#_event_end_date').datepicker({
                            minDate: jQuery('#_event_start_date').val(),
                            dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                            firstDay: wp_event_manager_admin_js.start_of_week,
                        });
                    });
                }
            }

            if (jQuery('input[data-picker="datepicker"]#_event_end_date').length > 0) {
                jQuery('input[data-picker="datepicker"]#_event_end_date').datepicker({
                    dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                    firstDay: wp_event_manager_admin_js.start_of_week,
                    beforeShow: function (input, inst)  {
                        var mindate = jQuery('input[data-picker="datepicker"]#_event_start_date').datepicker('getDate');
                        jQuery(this).datepicker('option', 'minDate', mindate);
                    }
                }).on('change', function () {
                    jQuery("#_event_registration_deadline").datepicker("destroy");
                    
                    if(wp_event_manager_admin_js.show_past_date) {
                        jQuery('input[data-picker="datepicker"]#_event_registration_deadline').datepicker({
                            maxDate: jQuery('#_event_end_date').val(),
                            dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                            firstDay: wp_event_manager_admin_js.start_of_week,
                        });
                    } else  {
                        jQuery('input[data-picker="datepicker"]#_event_registration_deadline').datepicker({
                            minDate: 0,
                            maxDate: jQuery('#_event_end_date').val(),
                            dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                            firstDay: wp_event_manager_admin_js.start_of_week,
                        });
                    }
                });
            }

            if (jQuery('#_event_start_time').length > 0) {
                jQuery('#_event_start_time').timepicker({
                    'timeFormat': wp_event_manager_admin_js.i18n_timepicker_format,
                    'step': wp_event_manager_admin_js.i18n_timepicker_step,
                });
            }

            if (jQuery('#_event_end_time').length > 0) {
                jQuery('#_event_end_time').timepicker({
                    'timeFormat': wp_event_manager_admin_js.i18n_timepicker_format,
                    'step': wp_event_manager_admin_js.i18n_timepicker_step,
                });
            }

            if (jQuery('#_event_timezone').length > 0) {
                jQuery("#_event_timezone").chosen({search_contains: !0});
            }


            if (jQuery('input[data-picker="datepicker"]#_event_registration_deadline').length > 0)  {
                if(wp_event_manager_admin_js.show_past_date) {
                    jQuery('input[data-picker="datepicker"]#_event_registration_deadline').datepicker({
                        maxDate: jQuery('#_event_end_date').val(),
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week
                    });
                }  else  {
                    jQuery('input[data-picker="datepicker"]#_event_registration_deadline').datepicker({
                        minDate: 0,
                        maxDate: jQuery('#_event_end_date').val(),
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week
                    });
                }
            }

            /*show default value of the expiry date based on settings */
            if (jQuery('input[data-picker="datepicker"]#_event_expiry_date').length > 0) {
                if (wp_event_manager_admin_js.show_past_date)  {
                    jQuery('input#_event_expiry_date').datepicker({
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week,
                        beforeShow: function (input, inst)   {
                            var mindate = jQuery('input[data-picker="datepicker"]#_event_end_date').datepicker('getDate');
                            jQuery(this).datepicker('option', 'minDate', mindate);
                        }
                    });
                }  else {
                    jQuery('input#_event_expiry_date').datepicker({
                        minDate: 0,
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week,
                        beforeShow: function (input, inst)
                        {
                            var mindate = jQuery('input[data-picker="datepicker"]#_event_end_date').datepicker('getDate');
                            jQuery(this).datepicker('option', 'minDate', mindate);
                        }
                    });
                }
            }
            
            //if field type is date then load datepicker
            if (jQuery('input[data-picker="datepicker"]').length > 0) {
                if (wp_event_manager_admin_js.show_past_date) {
                    jQuery('input[data-picker="datepicker"]').datepicker({
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week
                    });
                } else {
                    jQuery('input[data-picker="datepicker"]').datepicker({
                        minDate: 0, 
                        dateFormat: wp_event_manager_admin_js.i18n_datepicker_format,
                        firstDay: wp_event_manager_admin_js.start_of_week
                    });
                }
            }

            //Author
            jQuery("p.form-field-author").on('click', Admin.author.changeAuthor);
            jQuery("#setting-event_manager_submission_expire_options").on('change', Admin.settings.selectEventExpiryOption);

            //file upload
            jQuery('body').on('click', '.wp_event_manager_upload_file_button', Admin.fileUpload.addFile);
            jQuery(".wp_event_manager_add_another_file_button").on('click', Admin.fileUpload.addAnotherFile);

            jQuery('body').on('click', '.wp_event_manager_upload_file_button_multiple', Admin.fileUpload.multipleFile);
            jQuery('body').on('click', '.wp_event_manager_upload_file_button', Admin.fileUpload.addFile);
            jQuery(".wp_event_manager_add_another_file_button").on('click', Admin.fileUpload.addAnotherFile);
            jQuery('body').on('change', '#_event_end_date, #_event_start_date, #_event_start_time, #_event_end_time', Admin.actions.checkEndDate);
            Admin.actions.checkEndDate();
            //upgrade database
            jQuery("#wp_event_manager_upgrade_database").on('click', Admin.actions.upgradeDatabase);

            
            jQuery("input[name=_enable_health_guideline]").on('change', Admin.actions.guidelineEvent);
            if (jQuery('input[name=_enable_health_guideline]:checked').length > 0) {
                jQuery('input[name=_enable_health_guideline]:checked').trigger('change');
            } else {
                jQuery("input[name=_enable_health_guideline][value='no']").prop("checked", true).trigger("change");
            }

            jQuery("input[name=_enable_health_guideline_other]").on('change', Admin.actions.otherguidelineEvent);
            if (jQuery('input[name=_enable_health_guideline_other]:checked').length > 0) {
                jQuery('input[name=_enable_health_guideline_other]:checked').trigger('change');
            } else {
                jQuery("input[name=_enable_health_guideline_other][value='no']").prop("checked", true).trigger("change");
            }

            //online event
            jQuery("input[name=_event_online]").on('change', Admin.actions.onlineEvent);
            if (jQuery('input[name=_event_online]:checked').length > 0) {
                jQuery('input[name=_event_online]:checked').trigger('change');
            }

            //online event
            jQuery("input[name=_event_ticket_options]").on('change', Admin.actions.ticketPriceOption);
            if (jQuery('input[name=_event_ticket_options]:checked').length > 0) {
                jQuery('input[name=_event_ticket_options]:checked').trigger('change');
            }
            jQuery('body').on('change', '#_event_end_date', Admin.actions.setListingExpery);

             //upgrade database
             jQuery("#shortcode_list_filter_action").on('click', Admin.actions.getShortcodeList);
        },
        actions:
                {
                    /// <summary>
                    /// used to redirect page on selected plugin shortcode list.
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>3.1.35</since>
                    getShortcodeList: function (event) {
                        event.preventDefault();

                        var plugin_slug = jQuery('#wpem_shortcode_filter').val();
                        var old_url = window.location.href;
                        window.location = old_url + "&plugin=" + plugin_slug;
                        
                    },

                    /// <summary>
                    /// Click on tab event manager genera or other event tab.     
                    /// </summary>
                    /// <param name="parent" type="Event"></param>    
                    /// <returns type="actions" />
                    /// <since>1.0.0</since>    
                    tabClick: function (event) {
                        event.preventDefault();
                        jQuery('.wpem_panel').hide();
                        jQuery('.nav-tab-active').removeClass('nav-tab-active');
                        jQuery(jQuery(this).attr('href')).show();
                        jQuery(this).addClass('nav-tab-active');
                        return false;
                    },

                    /// <summary>
                    /// Show selected time format : 12 hour format or 24 hour format.
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>1.0.0</since>
                    showSelectedTimeFormat: function (event) {
                        event.preventDefault();

                        if (jQuery('input[name="_event_time_format"]').length > 0) {
                            Admin.timeFormatSettings();
                        }
                    },

                    /// <summary>
                    /// upgrade database when we create seperate post type for Organiizer
                    /// </summary>
                    /// <since>3.1.14</since>
                    upgradeDatabase: function (event)  {
                        jQuery.ajax({
                            url: wp_event_manager_admin_js.ajax_url,
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                action: 'wpem_upgrade_database',
                                wpem_upgrade_database_nonce: jQuery('#wpem_upgrade_database_nonce').val()
                            },
                            beforeSend: function() {
                                jQuery('.update-message').remove();
                                jQuery('hr.wp-header-end.extra').remove();
                                jQuery('.wp_event_manager_upgrade_database').before('<div class="update-message notice inline notice-warning notice-alt updating-message"><p>' + wp_event_manager_admin_js.upgrade_database_before_send_text + '...</p></div><hr class="wp-header-end extra">');
                            },
                            success: function (responce) {
                                jQuery('.update-message').remove();
                                jQuery('hr.wp-header-end.extra').remove();
                                jQuery('.wpem-upgrade-database-notice').remove();
                                jQuery('.wp_event_manager_upgrade_database').before('<div class="update-message notice inline notice-alt updated-message notice-success"><p>' + wp_event_manager_admin_js.upgrade_database_success_send_text + '</p></div><hr class="wp-header-end extra">');
                                jQuery('.wp_event_manager_upgrade_database').remove();

                            }
                        });
                    },

                    /// <summary>
                    /// Hide address,location and pincode filed when online event.
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>3.1.16</since>
                    onlineEvent: function (event) {
                        event.preventDefault();

                        if (jQuery(this).val() == "yes")  {
                            jQuery('#_event_venue_name').closest('.form-field').hide();
                            jQuery('#_event_pincode').closest('.form-field').hide();
                            jQuery('#_event_location').closest('.form-field').hide();
                            jQuery('#_event_venue_ids').closest('.form-field').hide();
                            jQuery('#_event_country').closest('.form-field').hide();
                        } else {
                            jQuery('#_event_venue_name').closest('.form-field').show();
                            jQuery('#_event_pincode').closest('.form-field').show();
                            jQuery('#_event_location').closest('.form-field').show();
                            jQuery('#_event_venue_ids').closest('.form-field').show();
                            jQuery('#_event_country').closest('.form-field').show();
                        }
                    },

                    /// <summary>
                    /// Hide guideline
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>3.1.16</since>
                    guidelineEvent: function (event) {
                        event.preventDefault();

                        if (jQuery(this).val() == "yes")  {
                            jQuery('._event_health_guidelines').closest('.form-field').show();
                            jQuery('[name="_enable_health_guideline_other"]').closest('.form-field').show();
                        } else {
                            jQuery('._event_health_guidelines').closest('.form-field').hide();
                            jQuery('[name="_enable_health_guideline_other"]').closest('.form-field').hide();
                            jQuery('input[name="_enable_health_guideline_other"][value="no"]').prop('checked', true).trigger('change');
                        }
                    },

                    /// <summary>
                    /// Set listing expiry
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>3.1.16</since>
                    setListingExpery: function (event) {
                        event.preventDefault();
                        var endDate = jQuery(this).val();
                        var expiryDate = jQuery('#_event_expiry_date').val();

                        if (expiryDate === '') {
                            jQuery('#_event_expiry_date').val(endDate);
                        }
                    },

                    /// <summary>
                    /// Check end date and time time
                    /// </summary>
                    /// <param name="parent" type="Event"></param>
                    /// <returns type="actions" />
                    /// <since>1.0.0</since>
                    checkEndDate: function (event) {

                        const startDate = jQuery('#_event_start_date').val();
                        const endDate = jQuery('#_event_end_date').val();
                        const startTime = jQuery('#_event_start_time').val();

                        if (startDate && endDate && startDate === endDate && startTime) {

                            jQuery('#_event_end_time').timepicker('remove');
                            jQuery('#_event_end_time').timepicker({
                                'timeFormat': wp_event_manager_admin_js.i18n_timepicker_format,
                                'step': wp_event_manager_admin_js.i18n_timepicker_step,
                                'disableTimeRanges': [['12:00am', startTime]],
                                'forceRoundTime': true,
                                'showDuration': false
                            });
                        } else {

                            jQuery('#_event_end_time').timepicker('remove');

                            if (typeof wp_event_manager_admin_js !== 'undefined') {
                                jQuery('#_event_end_time').timepicker({
                                    'timeFormat': wp_event_manager_admin_js.i18n_timepicker_format,
                                    'step': wp_event_manager_admin_js.i18n_timepicker_step
                                });
                            }
                        }
                    },


                    /// <summary>
                    /// Hide other guideline text
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>3.1.16</since>
                    otherguidelineEvent: function (event) {
                        event.preventDefault();

                        if (jQuery(this).val() == "yes")  {
                            jQuery('#_event_health_guidelines_other').closest('.form-field').show();
                        } else {
                            jQuery('#_event_health_guidelines_other').closest('.form-field').hide();
                        }
                    },

                    /// <summary>
                    /// Hide ticket price when ticket option free.
                    /// </summary>
                    /// <returns type="initialization settings" />
                    /// <since>3.1.16</since>
                    ticketPriceOption: function (event)  {
                        event.preventDefault();

                        if (jQuery(this).val() == "paid"){
                            jQuery('#_event_ticket_price').closest('.form-field').show();
                        } else {
                            jQuery('#_event_ticket_price').closest('.form-field').hide();
                        }
                    },
                },

        author: {
            /// <summary>
            /// Change Author.
            /// </summary>
            /// <param name="parent" type="Event"></param>
            /// <returns type="actions" />
            /// <since>1.0.0</since>
            changeAuthor: function (event){
                jQuery(this).closest('p').find('.current-author').hide();
                jQuery(this).closest('p').find('.change-author').show();
                return false;
                event.preventDefault();
            },
        },
        settings: {
            /// <summary>
            /// You can set event submission expiry time either event end date or specific days..
            /// </summary>
            /// <param name="parent" type="Event"></param>
            /// <returns type="actions" />
            /// <since>1.0.0</since>
            selectEventExpiryOption: function (event) {
                var option = jQuery("#setting-event_manager_submission_expire_options option:selected").val();
                if (option == 'days')
                    jQuery('#setting-event_manager_submission_duration').closest('tr').show();
                else
                    jQuery('#setting-event_manager_submission_duration').closest('tr').hide();
                event.preventDefault();
            }
        },
        fileUpload: {
            /// <summary>
            /// Upload new file from admin area.
            /// </summary>
            /// <param name="parent" type="Event"></param>
            /// <returns type="actions" />
            /// <since>1.0.0</since>
            addFile: function (event) {
                event.preventDefault();
                file_target_wrapper = jQuery(this).closest('.event-manager-uploaded-file');
                file_target_input = file_target_wrapper.find('input');
                var data_field_name = jQuery(this).parents(".form-field")[0].dataset.fieldName;

                var image_types = ['jpg', 'gif', 'png', 'jpeg', 'jpe', 'webp'];
                file_target_wrapper_append = jQuery(this).closest('.event-manager-uploaded-file2');
                // If the media frame already exists, reopen it.
                if (file_frame) {
                    file_frame.open();
                    return;
                }
                // Create the media frame.
                file_frame = wp.media.frames.file_frame = wp.media({
                    title: jQuery(this).data('uploader_title'),
                    button: {
                        text: jQuery(this).data('uploader_button_text'),
                    },
                    multiple: false  // Set to true to allow multiple files to be selected.
                });
                // When an image is selected, run a callback.
                file_frame.on('select', function () {
                    // We set multiple to false so only get one image from the uploader.
                    attachment = file_frame.state().get('selection').first().toJSON();
                    jQuery(file_target_input).val(attachment.url);
                    jQuery(file_target_wrapper_append).find(".event-manager-uploaded-file").remove();
                    if (jQuery.inArray(attachment.subtype, image_types) >= 0) {
                        jQuery(file_target_wrapper_append).prepend("<span class='event-manager-uploaded-file'><input type='hidden' name='" + data_field_name + "' id='" + data_field_name + "' placeholder='' value='" + attachment.url + "'><span class='event-manager-uploaded-file-preview'><img src='" + attachment.url + "'><a class='event-manager-remove-uploaded-file' href='javascript:void(0);'>[remove]</a></span>");
                    } else {
                        jQuery(file_target_wrapper_append).prepend("<span class='event-manager-uploaded-file'><input type='hidden' name='" + data_field_name + "' id='" + data_field_name + "' placeholder='' value='" + attachment.url + "'><span class='event-manager-uploaded-file-preview'><a class='event-manager-remove-uploaded-file' href='javascript:void(0);'>[remove]</a></span></span>");
                    }
                });
                // Finally, open the modal.
                file_frame.open();
            },
            multipleFile: function (event) {
                event.preventDefault();
                file_target_wrapper = jQuery(this).parent(".file_url").find('.event-manager-uploaded-file.multiple-file');
                file_target_input = file_target_wrapper.find('input');
                var data_field_name = jQuery(this).parents(".form-field")[0].dataset.fieldName;
                var image_types = ['jpg', 'gif', 'png', 'jpeg', 'jpe', 'webp'];
                file_target_wrapper_apeend = jQuery(this).prev();
                // If the media frame already exists, reopen it.
                if (file_frame) {
                    file_frame.open();
                    return;
                }
                // Create the media frame.
                file_frame = wp.media.frames.file_frame = wp.media({
                    title: jQuery(this).data('uploader_title'),
                    button: {
                        text: jQuery(this).data('uploader_button_text'),
                    },
                    multiple: true  // Set to true to allow multiple files to be selected.
                });
                // When an image is selected, run a callback.
                file_frame.on('select', function () {
                    // We set multiple to false so only get one image from the uploader.
                    attachment = file_frame.state().get('selection').map(
                        function (attachment) {
                            attachment.toJSON();
                            return attachment;
                        });
                    jQuery.each(attachment, function (index, attach) {
                        jQuery(file_target_input).val(attach.attributes.url);
                        if (jQuery.inArray(attach.attributes.subtype, image_types) >= 0) {
                            jQuery(file_target_wrapper_apeend).append("<span class='event-manager-uploaded-file multiple-file'><input type='hidden' name='" + data_field_name + "[]' placeholder='' value='" + attach.attributes.url + "'><span class='event-manager-uploaded-file-preview'><img src='" + attach.attributes.url + "'><a class='event-manager-remove-uploaded-file' href='javascript:void(0);'>[remove]</a></span>");
                        } else {
                            jQuery(file_target_wrapper_apeend).append("<span class='event-manager-uploaded-file multiple-file'><input type='hidden' name='" + data_field_name + "[]' placeholder='' value='" + attach.attributes.url + "'><span class='event-manager-uploaded-file-preview'><a class='event-manager-remove-uploaded-file' href='javascript:void(0);'>[remove]</a></span></span>");
                        }
                    });
                });
                // Finally, open the modal.
                file_frame.open();
            },
            /// <summary>
            /// Upload new file from admi area. when admin want to add another file then admin can add new file.
            /// </summary>
            /// <param name="parent" type="Event"></param>
            /// <returns type="actions" />
            /// <since>1.0.0</since>
            addAnotherFile: function (event) {
                event.preventDefault();
                var wrapper = jQuery(this).closest('.form-field');
                var field_name = jQuery(this).data('field_name');
                var field_placeholder = jQuery(this).data('field_placeholder');
                var button_text = jQuery(this).data('uploader_button_text');
                var button = jQuery(this).data('uploader_button');
                jQuery(this).before('<span class="file_url"><input type="text" name="' + field_name + '[]" placeholder="' + field_placeholder + '" /><button class="button button-small wp_event_manager_upload_file_button" data-uploader_button_text="' + button_text + '">' + button + '</button></span>');
            },
            
        }
    } //enf of return
}; //end of class

Admin = Admin();
jQuery(document).ready(function ($){
    Admin.init();
});