Array.prototype.remove = function () {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};
var testimonialsScript = testimonialsScript || function () {
    var isInit = false;
    var testimonialListingDataTable = null;
    var selectedTestimonials = [];
    var customCheckBox = '<div class="icheck-material-primary f_custom_checkbox" style="pointer-events: none"><input type="checkbox" id="bulk-action-checkbox" class="select_all" /><label for="bulk-action-checkbox"></label></div>';

    var init = function () {
        if (isInit) return;
        isInit = true;
        initDropzone();
        handler();
    };

    var handler = function () {
        testimonialListDataTable();
        globalScript.initValidator();

        $('body').on('click', '#thumbnail_delete_uploaded_image_btn', function () {
            var imageId = $(this).closest('.thumbnail_add_image_pre_block').find('#thumbnail_add_image_id').val();
            deleteUploadedProductFile(imageId, '', function () {
                $('body').find('#thumbnail_add_image_id').val('');
                $('body').find('#thumbnail_add_image_pre').attr('src', '/public/images/banner-placeholder.jpg');
                $('body').find('#thumbnail_delete_uploaded_image_btn').hide();
                $('body').find('#thumbnail_products_dropzone .dz-message span').html("Drop files here to upload");
                // if (!isAddDropzoneActive) {
                //     initDropzone();
                // }
            });
        });

        $('body').on('click', '.thumbnail_delete_edit_uploaded_image_btn', function () {
            var imageId = $(this).closest('.thumbnail_add_image_pre_block').find('#thumbnail_edit_image_id').val();
            var imagePath = $(this).closest('.thumbnail_add_image_pre_block').find('#thumbnail_edit_image_path').val();
            if (imageId && imageId !== '') {
                deleteUploadedProductFile(imageId, '', function () {
                    $('body').find('#thumbnail_edit_image_id').val('');
                    $('body').find('#thumbnail_edit_image_pre').attr('src', '/public/images/banner-placeholder.jpg');
                    $('body').find('.thumbnail_delete_edit_uploaded_image_btn').hide();
                    $('body').find('#thumbnail_edit_products_dropzone .dz-message span').html("Drop files here to upload");
                    // if (!isEditDropzoneActive) {
                    //     initEditDropzone();
                    // }
                });
            } else {
                deleteUploadedProductFile('', imagePath, function () {
                    $('body').find('#thumbnail_edit_image_preview_row').hide();
                    $('body').find('#thumbnail_edit_image_row').show();
                    $('body').find('#thumbnail_edit_image_id').val('');
                    $('body').find('#thumbnail_edit_image_pre').attr('src', '/public/images/banner-placeholder.jpg');
                    $('body').find('.thumbnail_delete_edit_uploaded_image_btn').hide();
                    $('body').find('#thumbnail_edit_products_dropzone .dz-message span').html("Drop files here to upload");
                    // if (!isEditDropzoneActive) {
                    //     initEditDropzone();
                    // }
                });
            }
        });

        $("body").on('click', '.select_all', function () { // bulk checked
            var status = this.checked;
            if (status === true) {
                $('#bulk-action-checkbox').prop('checked', true);
                $('body').find(".bulkRow").each(function () {
                    $(this).prop("checked", status);
                    var roleId = $(this).closest('tr').find('.testimonial-id').val();
                    if (selectedTestimonials.indexOf(roleId) === -1) {
                        selectedTestimonials.push(roleId);
                    }
                });
            } else {
                $(".bulkRow, .select_all").prop('checked', false);
                $('#bulk-action-checkbox').prop('checked', false);
                selectedTestimonials = [];
            }
        });

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var roleId = $(this).closest('tr').find('.testimonial-id').val();
            if (status === true) {
                if (selectedTestimonials.indexOf(roleId) === -1) {
                    selectedTestimonials.push(roleId);
                }
                $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedTestimonials.remove(roleId);
            }
            if (selectedTestimonials.length === 0) {
                $(".bulkRow, .select_all").prop('checked', false);
            }
        });

        $('body').on('click', '#apply_bulk_actions_btn', function () {
            var bulkOption = $('#bulk_actions').val();
            if (bulkOption === '') {
                $('#bulk_actions_error').html('Please select an action first').show();
            } else {
                if (selectedTestimonials.length === 0) {
                    $('#bulk_actions_error').html('Please select testimonial(s) first').show();
                } else {
                    $('#bulk_actions_error').hide();
                    if (bulkOption === 'delete_bulk') {
                        globalScript.showConfirmationAlert(
                            'You want to delete selected testimonial(s)?',
                            function () {
                                deleteTestimonials(function () {
                                    toastr.success('Testimonial(s) deleted successfully');
                                    testimonialListDataTable();
                                    $(".bulkRow, .select_all").prop('checked', false);
                                });
                            }
                        )
                    }
                }
            }
        });

        $('body').on('submit', '#create_testimonial_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var test_title = $('#test_title').val();
            var test_designation = $('#test_designation').val();
            var test_message = $('#test_message').val();
            var imageId = $('#thumbnail_add_image_id').val();
            var obj = Object.create(globalScript.CREATE_TESTIMONIAL);
            obj.data = {
                'title': test_title,
                'designation': test_designation,
                'message': test_message,
                'thumb_image_id': imageId
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('.add_errors').show();
                    $('#submit_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.add_errors ul').append('<li>' + v + '</li>');
                    });
                    return false;
                } else {
                    toastr.success(response._metadata.message);
                    $('#addTestimonialModal').modal('hide');
                    testimonialListDataTable();
                }
            });
        });

        $('body').on('submit', '#edit_testimonial_form', function (e) {
            e.preventDefault();
            if ($('#edit_submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#edit_submit_btn').addClass('disabled');
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            var attrId = $('#testimonial_id').val();
            var test_title = $('#edit_test_title').val();
            var test_designation = $('#edit_test_designation').val();
            var test_message = $('#edit_test_message').val();
            var imageId = $('#thumbnail_edit_image_id').val();
            var obj = Object.create(globalScript.UPDATE_TESTIMONIAL);
            obj.url = obj.url(attrId);
            obj.data = {
                'title': test_title,
                'designation': test_designation,
                'message': test_message,
                'thumb_image_id': imageId
            };
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.errors && response.errors.length !== 0) {
                    $('#edit_submit_btn').removeClass('disabled');
                    _.each(response.errors, function (v, k) {
                        $('.edit_errors ul').append('<li>' + v + '</li>');
                        $('.edit_errors').show();
                    });
                } else {
                    toastr.success(response._metadata.message);
                    $('#editTestimonialModal').modal('hide');
                    testimonialListDataTable();
                }
            });
        });

        $('body').on('change', '.update_testimonial_status', function () {
            var status = $(this).val();
            var column = $(this).attr('data-column');
            var testimonialId = $(this).closest('tr').find('.testimonial-id').val();
            selectedTestimonials.push(testimonialId);
            updateTestimonialStatus(status, column, function () {
                toastr.success('Status successfully updated');
                testimonialListDataTable();
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var testimonialId = $(this).closest('tr').find('.testimonial-id').val();
            var obj = Object.create(globalScript.GET_TESTIMONIAL_DETAILS);
            var url = obj.url(testimonialId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#testimonial_id').val(response.records.id);
                    $('body').find('#edit_testimonial_form #edit_test_title').val(response.records.title);
                    $('body').find('#edit_testimonial_form #edit_test_designation').val(response.records.designation);
                    $('body').find('#edit_testimonial_form #edit_test_message').val(response.records.message);
                    if (response.records.thumb_image_public_url === 'public/images/banner-placeholder.jpg') {
                        $('body').find('#thumbnail_edit_image_preview_row').hide();
                        $('body').find('.thumbnail_delete_edit_uploaded_image_btn').hide();
                        $('body').find('#thumbnail_edit_image_row').show();
                        // if (!isEditDropzoneActive) {
                        //     initEditDropzone();
                        // }
                    } else {
                        $('body').find('#thumbnail_edit_image').attr('src', response.records.thumb_image_public_url);
                        $('body').find('#thumbnail_edit_image_path').val(response.records.thumb_image);
                        $('body').find('#thumbnail_edit_image_preview_row').show();
                        $('body').find('.thumbnail_delete_edit_uploaded_image_btn').show();
                        $('body').find('#thumbnail_edit_image_row').hide();
                    }
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editTestimonialModal').modal('show');
                    initEditDropzone();
                }
            })
        });

        $('body').on('click', '.delete-btn', function () {
            selectedTestimonials = [];
            $(".bulkRow, .select_all").prop('checked', false);
            var testimonialId = $(this).closest('tr').find('.testimonial-id').val();
            selectedTestimonials.push(testimonialId);
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteTestimonials(function () {
                        toastr.success('Deleted successfully');
                        testimonialListDataTable();
                    });
                }
            )
        });

        $('#addTestimonialModal').on('hidden.bs.modal', function (e) {
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            $('#create_testimonial_form').trigger("reset");
            resetAddProductImages();
        });

        $('#editTestimonialModal').on('hidden.bs.modal', function (e) {
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            $('#edit_testimonial_form').trigger("reset");
            resetEditProductImages();
        });
    };

    var resetAddProductImages = function () {
        $('body').find('#thumbnail_add_image_id').val('');
        $('body').find('#thumbnail_add_image_pre').attr('src', '/public/images/banner-placeholder.jpg');
        $('body').find('#thumbnail_delete_uploaded_image_btn').hide();
        $('body').find('#thumbnail_products_dropzone .dz-message span').html("Drop files here to upload");
        // if (!isAddDropzoneActive) {
        //     initDropzone();
        // }
    };

    var resetEditProductImages = function () {
        $('body').find('#thumbnail_edit_image_id').val('');
        $('body').find('#thumbnail_edit_image_pre').attr('src', '/public/images/banner-placeholder.jpg');
        $('body').find('.thumbnail_delete_edit_uploaded_image_btn').hide();
        $('body').find('#thumbnail_edit_products_dropzone .dz-message span').html("Drop files here to upload");
        // if (!isEditDropzoneActive) {
        //     initEditDropzone();
        // }
    };

    var initDropzone = function () {
        Dropzone.autoDiscover = false;
        Dropzone.options.myAwesomeDropzone = {
            thumbnailWidth: 250,
            thumbnailHeight: 250
        };
        var dropZoneConfiguration1 = {
            url: globalScript.APP_URL + "uploadtestimonialfile", // laravel route
            addRemoveLinks: true,
            init: function () {
                // isAddDropzoneActive = true;
                var _this = this;
                this.on("success", function (file, res) {
                    $('.thumbnail_add_image_errors').hide();
                    $('.thumbnail_add_image_errors ul').html('');
                    if (res && res.errors && res.errors.length !== 0) {
                        $.each(res.errors, function (k, v) {
                            $('.thumbnail_add_image_errors ul').append('<li>' + v + '</li>');
                            $('.thumbnail_add_image_errors').show();
                            _this.removeFile(file);
                        });
                    }
                    if (res && res.records && res.records.id) {
                        $('body').find('#thumbnail_add_image_id').val(res.records.id);
                        $('body').find('#thumbnail_add_image_pre').attr('src', res.records.url);
                        $('body').find('#thumbnail_delete_uploaded_image_btn').show();
                        // $('body').find('#thumbnail_products_dropzone .dz-message span').html("You can upload only one image");
                        _this.removeFile(file);
                        // _this.destroy();
                        // isAddDropzoneActive = false;
                    }
                });
                this.on('error', function (file, errorMessage) {
                    _this.removeFile(file);
                });
                this.on('resetFiles', function () {
                    this.removeAllFiles();
                });
            },
            maxFiles: 1,
            uploadMultiple: false,
            maxfilesexceeded: function (file) {
                this.removeAllFiles();
                this.addFile(file);
            },
            acceptedFiles: "image/jpeg,image/png,image/webp"
        };
        $('#thumbnail_products_dropzone').addClass('dropzone');
        $('#thumbnail_products_dropzone').dropzone(dropZoneConfiguration1);
    };

    var initEditDropzone = function () {
        Dropzone.autoDiscover = false;
        Dropzone.options.myAwesomeDropzone = {
            thumbnailWidth: 250,
            thumbnailHeight: 250
        };
        var dropZoneConfiguration1 = {
            url: globalScript.APP_URL + "uploadtestimonialfile", // laravel route
            addRemoveLinks: true,
            init: function () {
                // isEditDropzoneActive = true;
                var _this = this;
                this.on("success", function (file, res) {
                    $('.thumbnail_edit_image_errors').hide();
                    $('.thumbnail_edit_image_errors ul').html('');
                    if (res && res.errors && res.errors.length !== 0) {
                        $.each(res.errors, function (k, v) {
                            $('.thumbnail_edit_image_errors ul').append('<li>' + v + '</li>');
                            $('.thumbnail_edit_image_errors').show();
                            _this.removeFile(file);
                        });
                    }
                    if (res && res.records && res.records.id) {
                        $('body').find('#thumbnail_edit_image_id').val(res.records.id);
                        $('body').find('#thumbnail_edit_image_pre').attr('src', res.records.url);
                        $('body').find('.thumbnail_delete_edit_uploaded_image_btn').show();
                        // $('body').find('#thumbnail_edit_products_dropzone .dz-message span').html("You can upload only one image");
                        _this.removeFile(file);
                        // _this.destroy();
                        // isEditDropzoneActive = false;
                    }
                });

                this.on('error', function (file, errorMessage) {
                    _this.removeFile(file);
                });

                this.on('resetFiles', function () {
                    this.removeAllFiles();
                });
            },
            maxFiles: 1,
            uploadMultiple: false,
            maxfilesexceeded: function (file) {
                this.removeAllFiles();
                this.addFile(file);
            },
            acceptedFiles: "image/jpeg,image/png,image/gif,image/webp"
        };
        $('#thumbnail_edit_products_dropzone').addClass('dropzone');
        $('#thumbnail_edit_products_dropzone').dropzone(dropZoneConfiguration1);
    };

    var deleteUploadedProductFile = function (id, path, callback) {
        var obj = Object.create(globalScript.DELETE_UPLOADED_TESTIMONIAL_FILE);
        obj.data = {
            'image_id': id !== '' ? id : '',
            'image_path': path !== '' ? path : ''
        };
        globalScript.ajaxCall(obj).done(function (response) {
            if (typeof callback == 'function') callback();
        });
    };

    var deleteTestimonials = function (callback) {
        var obj = Object.create(globalScript.DELETE_TESTIMONIAL);
        obj.data = {
            'testimonial_ids[]': selectedTestimonials
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedTestimonials = [];
            if (typeof callback == 'function') callback();
        });
    };

    var testimonialListDataTable = function () {
        if (testimonialListingDataTable != null) {
            testimonialListingDataTable.clear().destroy();
        }
        testimonialListingDataTable = $('#testimonialsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "testimonials",
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) {
                    if (json.hasOwnProperty('_metadata') && json._metadata.hasOwnProperty('outcomeCode') && json._metadata.outcomeCode === 4) {
                        window.top.location.href = "login";
                        return;
                    }
                    json.draw = json.records.draw;
                    json.recordsTotal = json.records.recordsTotal;
                    json.recordsFiltered = json.records.recordsFiltered;
                    $('body').find('#module_total_count').html(json.records.recordsTotal);
                    if (json.records.data.length !== 0) {
                        $("body").find(".f_custom_checkbox").css('pointer-events', 'all');
                        $("body").find(".f_custom_card_footer").show();
                    } else {
                        $("body").find(".f_custom_card_footer").hide();
                    }
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": true,
            "serverSide": true,
            "paging": true,
            "stateSave": false,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'created_at',
                    "visible": false
                },
                {
                    "data": "title",
                    "title": "Name",
                    "name": "title",
                    "searchable": true,
                    "orderable": true
                },
                { "data": "designation", "title": "Designation", "name": "designation", "searchable": false, "orderable": false },
                {"data": "status", "title": "Status", "name": "status", "searchable": false, "orderable": false},
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#testimonialsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var updateTestimonialStatus = function (status, column, callback) {
        var obj = Object.create(globalScript.UPDATE_TESTIMONIAL_STATUS);
        obj.data = {
            'testimonial_ids[]': selectedTestimonials,
            'status': status,
            'column': column
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedTestimonials = [];
            if (typeof callback == 'function') callback();
        });
    };

    return {
        'init': init
    }

}();

$(document).ready(function () {
    testimonialsScript.init();
});
