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 citiesScript = citiesScript || function () {
    var isInit = false;
    var cityListingDataTable = null;
    var selectedCities = [];
    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 () {
        cityListDataTable();
        globalScript.initValidator();
        initEditor();

        $('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('.city-id').val();
                    if (selectedCities.indexOf(roleId) === -1) {
                        selectedCities.push(roleId);
                    }
                });
            } else {
                $(".bulkRow, .select_all").prop('checked', false);
                $('#bulk-action-checkbox').prop('checked', false);
                selectedCities = [];
            }
        });

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var roleId = $(this).closest('tr').find('.city-id').val();
            if (status === true) {
                if (selectedCities.indexOf(roleId) === -1) {
                    selectedCities.push(roleId);
                }
                $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedCities.remove(roleId);
            }
            if (selectedCities.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 (selectedCities.length === 0) {
                    $('#bulk_actions_error').html('Please select city(s) first').show();
                } else {
                    $('#bulk_actions_error').hide();
                    if (bulkOption === 'delete_bulk') {
                        globalScript.showConfirmationAlert(
                            'You want to delete selected city(s)?',
                            function () {
                                deleteCities(function () {
                                    toastr.success('City(s) deleted successfully');
                                    cityListDataTable();
                                    $(".bulkRow, .select_all").prop('checked', false);
                                });
                            }
                        )
                    }
                }
            }
        });

        $('body').on('submit', '#create_city_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var city_name = $('#city_name').val();
            var city_meta_title = $('#city_meta_title').val();
            var city_meta_keywords = $('#city_meta_keywords').val();
            var city_meta_description = $('#city_meta_description').val();
            var city_full_description = $('#city_full_description').summernote('code');
            var imageId = $('#thumbnail_add_image_id').val();
            var obj = Object.create(globalScript.CREATE_ATTRIBUTE);
            obj.data = {
                'type': 'city',
                'name': city_name,
                'full_desc': city_full_description,
                'meta_title': city_meta_title,
                'meta_keywords': city_meta_keywords,
                'meta_desc': city_meta_description,
                '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);
                    $('#addCityModal').modal('hide');
                    cityListDataTable();
                }
            });
        });

        $('body').on('submit', '#edit_city_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 = $('#city_id').val();
            var city_name = $('#edit_city_name').val();
            var city_meta_title = $('#edit_city_meta_title').val();
            var city_meta_keywords = $('#edit_city_meta_keywords').val();
            var city_meta_description = $('#edit_city_meta_description').val();
            var city_full_description = $('#edit_city_full_description').summernote('code');
            var imageId = $('#thumbnail_edit_image_id').val();
            var obj = Object.create(globalScript.UPDATE_ATTRIBUTE);
            obj.url = obj.url(attrId);
            obj.data = {
                'name': city_name,
                'full_desc': city_full_description,
                'meta_title': city_meta_title,
                'meta_keywords': city_meta_keywords,
                'meta_desc': city_meta_description,
                '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);
                    $('#editCityModal').modal('hide');
                    cityListDataTable();
                }
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var cityId = $(this).closest('tr').find('.city-id').val();
            var obj = Object.create(globalScript.GET_ATTRIBUTE_DETAILS);
            var url = obj.url(cityId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#city_id').val(response.records.id);
                    $('body').find('#edit_city_form #edit_city_name').val(response.records.name);
                    $('body').find('#edit_city_form #edit_city_meta_title').val(response.records.meta_title);
                    $('body').find('#edit_city_form #edit_city_meta_keywords').val(response.records.meta_keywords);
                    $('body').find('#edit_city_form #edit_city_meta_description').val(response.records.meta_desc);
                    $('body').find('#edit_city_form #edit_city_full_description').summernote("code", response.records.full_desc);
                    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('');
                    $('#editCityModal').modal('show');
                    initEditDropzone();
                }
            })
        });

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

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

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

        $('body').on('change', '.update_city_status', function () {
            var status = $(this).val();
            var column = $(this).attr('data-column');
            var cityId = $(this).closest('tr').find('.city-id').val();
            selectedCities.push(cityId);
            updateCityStatus(status, column, function () {
                toastr.success('Status successfully updated');
                cityListDataTable();
            });
        });
    };

    var updateCityStatus = function (status, column, callback) {
        var obj = Object.create(globalScript.UPDATE_ATTRIBUTE_STATUS);
        obj.data = {
            'atrribute_ids[]': selectedCities,
            'status': status,
            'column': column
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedCities = [];
            if (typeof callback == 'function') callback();
        });
    };

    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 + "uploadattributefile", // 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 + "uploadattributefile", // 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_ATTRIBUTE_FILE);
        obj.data = {
            'image_id': id !== '' ? id : '',
            'image_path': path !== '' ? path : ''
        };
        globalScript.ajaxCall(obj).done(function (response) {
            if (typeof callback == 'function') callback();
        });
    };

    var deleteCities = function (callback) {
        var obj = Object.create(globalScript.DELETE_ATTRIBUTE);
        obj.data = {
            'attribute_ids[]': selectedCities
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedCities = [];
            if (typeof callback == 'function') callback();
        });
    };

    var cityListDataTable = function () {
        if (cityListingDataTable != null) {
            cityListingDataTable.clear().destroy();
        }
        cityListingDataTable = $('#citiesListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "attributes?type=city",
                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": "name",
                    "title": "Name",
                    "name": "name",
                    "searchable": true,
                    "orderable": true
                },
                {
                    "data": "is_featured",
                    "title": "Featured",
                    "name": "is_featured",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#citiesListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var initEditor = function () {
        $('.content_area').summernote({
            onCreateLink: function (originalLink) {
                return originalLink; // return original link
            },
            dialogsInBody: true,
            height: 300,
            tabsize: 2
        });
    };

    return {
        'init': init
    }

}();

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