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 listingsScript = listingsScript || function () {
    var isInit = false;
    // var isEditDropzoneActive = false;
    // var isAddDropzoneActive = false;
    var listingsListingDataTable = null;
    var listingReqsListingDataTable = null;
    var trashedListingListingDataTable = null;
    var selectedListings = [];
    var listingDetails = [];
    var uploadedGalleryImages = [];
    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;
        handler();
    };
    var handler = function () {
        listingsListDataTable($('#listingSearchFrom').serialize());
        globalScript.initValidator();
        initDropzone();
        initEditor();

        $('#project_search').selectpicker().ajaxSelectPicker({
            ajax: {
                url: window.APP_URL + '/api/admin/projects-list-admin',
                type: 'GET',
                dataType: 'json',
                data: function () {
                    return {
                        q: '{{{q}}}',
                    };
                }
            },
            minLength: 3,
            cache: false,
            // preserveSelected: false,
            preserveSelectedPosition: 'before',
            locale: {searchPlaceholder: 'Min. 3 characters required'},
            preprocessData: function (data) {
                var i, l = data.length, array = [];
                if (l) {
                    for (i = 0; i < l; i++) {
                        array.push($.extend(true, data[i], {
                            text: data[i].text,
                            value: data[i].id,
                            class: data[i].ref
                        }));
                    }
                }
                return array;
            }
        });

        $('#listing_project').selectpicker().ajaxSelectPicker({
            ajax: {
                url: window.APP_URL + '/api/admin/projects-list-admin',
                type: 'GET',
                dataType: 'json',
                data: function () {
                    return {
                        q: '{{{q}}}',
                    };
                }
            },
            minLength: 3,
            cache: false,
            // preserveSelected: false,
            preserveSelectedPosition: 'before',
            locale: {searchPlaceholder: 'Min. 3 characters required'},
            preprocessData: function (data) {
                var i, l = data.length, array = [];
                if (l) {
                    for (i = 0; i < l; i++) {
                        array.push($.extend(true, data[i], {
                            text: data[i].text,
                            value: data[i].id,
                            class: data[i].ref
                        }));
                    }
                }
                return array;
            }
        });

        $('#edit_listing_project').selectpicker().ajaxSelectPicker({
            ajax: {
                url: window.APP_URL + '/api/admin/projects-list-admin',
                type: 'GET',
                dataType: 'json',
                data: function () {
                    return {
                        q: '{{{q}}}',
                    };
                }
            },
            minLength: 3,
            cache: false,
            // preserveSelected: false,
            preserveSelectedPosition: 'before',
            locale: {searchPlaceholder: 'Min. 3 characters required'},
            preprocessData: function (data) {
                var i, l = data.length, array = [];
                if (l) {
                    for (i = 0; i < l; i++) {
                        array.push($.extend(true, data[i], {
                            text: data[i].text,
                            value: data[i].id,
                            class: data[i].ref
                        }));
                    }
                }
                return array;
            }
        });

        $('body').on('change', '.update_listing_status', function () {
            var status = $(this).val();
            var column = $(this).attr('data-column');
            var listingId = $(this).closest('tr').find('.listing-id').val();
            selectedListings.push(listingId);
            updateListingStatus(status, column, function () {
                toastr.success('Status successfully updated');
                listingsListDataTable($('#listingSearchFrom').serialize());
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var listingId = $(this).closest('tr').find('.listing-id').val();
            var obj = Object.create(globalScript.GET_LISTING_DETAILS);
            obj.url = obj.url(listingId);
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    populateValuesToEditForm(response.records, function () {
                        $('.edit_errors').hide();
                        $('.edit_errors ul').html('');
                        $('#editListingModal').modal('show');
                        initEditDropzone()
                    });
                }
            })
        });

        $('body').on('click', '.view-btn', function () {
            var listingId = $(this).closest('tr').find('.listing-id').val();
            var obj = Object.create(globalScript.GET_PUBLIC_LISTING_DETAILS);
            obj.url = obj.url(listingId);
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    var detailTmpl = _.template($('#listingDetailsTemplate').html());
                    $("#listingDetailsSection").html(detailTmpl(response.records));
                    $('#viewListingModal').modal('show');
                }
            })
        });

        $('body').on('submit', '#create_listing_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            updateListingDetails();
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            createListing(function () {
                // $('#addListingModal').modal('hide');
                // listingsListDataTable();
                window.location.reload()
            });
        });

        $('body').on('submit', '#edit_listing_form', function (e) {
            e.preventDefault();
            if ($('#edit_submit_btn').hasClass('disabled')) {
                return false;
            }
            updateEditListingDetails();
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            updateListing(function () {
                // $('#editListingModal').modal('hide');
                // listingsListDataTable();
                window.location.reload()
            });
        });

        $('body').on('click', '#thumbnail_delete_uploaded_image_btn', function () {
            var imageId = $(this).closest('.thumbnail_add_image_pre_block').find('#thumbnail_add_image_id').val();
            deleteUploadedListingFile(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_listings_dropzone .dz-message span').html("Drop files here to upload");
                // if (!isAddDropzoneActive) {
                //     initDropzone();
                // }
            });
        });

        $('body').on('click', '#primary_delete_uploaded_image_btn', function () {
            var imageId = $(this).closest('.primary_add_image_pre_block').find('#primary_add_image_id').val();
            deleteUploadedListingFile(imageId, '', function () {
                $('body').find('#primary_add_image_id').val('');
                $('body').find('#primary_add_image_pre').attr('href', '');
                $('body').find('#primary_add_image_pre').hide();
                $('body').find('#primary_delete_uploaded_image_btn').hide();
                $('body').find('#primary_listings_dropzone .dz-message span').html("Drop files here to upload");
                // if (!isAddDropzoneActive) {
                //     initDropzone();
                // }
            });
        });

        $('body').on('click', '.gallery_delete_uploaded_image_btn', function () {
            var that = this
            var imageId = $(this).closest('.gallery_add_image_pre_block').find('.gallery_add_image_id').val();
            deleteUploadedListingFile(imageId, '', function () {
                $(that).closest('.col-lg-3').hide()
                const index = uploadedGalleryImages.findIndex(element => {
                    if (element.id == imageId) {
                        return true;
                    }
                });
                if (index !== -1) uploadedGalleryImages.splice(index, 1);
            });
        });

        $('body').on('click', '.edit_gallery_delete_uploaded_image_btn', function () {
            var that = this
            var imageId = $(this).closest('.gallery_add_image_pre_block').find('.gallery_add_image_id').val();
            deleteUploadedListingFile('', imageId, function () {
                $(that).closest('.col-lg-3').hide()
                const index = uploadedGalleryImages.findIndex(element => {
                    if (element.path == imageId) {
                        return true;
                    }
                });
                if (index !== -1) uploadedGalleryImages.splice(index, 1);
            });
        });

        $('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 !== '') {
                deleteUploadedListingFile(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_listings_dropzone .dz-message span').html("Drop files here to upload");
                    // if (!isEditDropzoneActive) {
                    //     initEditDropzone();
                    // }
                });
            } else {
                deleteUploadedListingFile('', 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_listings_dropzone .dz-message span').html("Drop files here to upload");
                    // if (!isEditDropzoneActive) {
                    //     initEditDropzone();
                    // }
                });
            }
        });

        $('body').on('click', '.primary_delete_edit_uploaded_image_btn', function () {
            var imageId = $(this).closest('.primary_add_image_pre_block').find('#primary_edit_image_id').val();
            var imagePath = $(this).closest('.primary_add_image_pre_block').find('#primary_edit_image_path').val();
            if (imageId && imageId !== '') {
                deleteUploadedListingFile(imageId, '', function () {
                    $('body').find('#primary_edit_image_id').val('');
                    $('body').find('#primary_edit_image_pre').attr('href', '');
                    $('body').find('#primary_edit_image_pre').hide();
                    $('body').find('.primary_delete_edit_uploaded_image_btn').hide();
                    $('body').find('#primary_edit_listings_dropzone .dz-message span').html("Drop files here to upload");
                    // if (!isEditDropzoneActive) {
                    //     initEditDropzone();
                    // }
                });
            } else {
                deleteUploadedListingFile('', imagePath, function () {
                    $('body').find('#primary_edit_image_preview_row').hide();
                    $('body').find('#primary_edit_image_row').show();
                    $('body').find('#primary_edit_image_id').val('');
                    $('body').find('#primary_edit_image_pre').attr('href', '');
                    $('body').find('#primary_edit_image_pre').hide();
                    $('body').find('.primary_delete_edit_uploaded_image_btn').hide();
                    $('body').find('#primary_edit_listings_dropzone .dz-message span').html("Drop files here to upload");
                    // if (!isEditDropzoneActive) {
                    //     initEditDropzone();
                    // }
                });
            }
        });

        $('body').on('click', '.delete-btn', function () {
            selectedListings = [];
            $(".bulkRow, .select_all").prop('checked', false);
            var listingId = $(this).closest('tr').find('.listing-id').val();
            selectedListings.push(listingId);
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteListings(function () {
                        toastr.success('Listing successfully moved to trash!');
                        listingsListDataTable($('#listingSearchFrom').serialize());
                    });
                }
            )
        });

        $('body').on('keyup', '.gallery_sort_input', function (e) {
            var imageId = $(this).closest('.gallery_add_image_pre_block').find('.gallery_add_image_id').val();
            const index = uploadedGalleryImages.findIndex(element => {
                if (element.id == imageId) {
                    element.sort_order = e.target.value
                }
            });
        });

        $('body').on('keyup', '.edit_gallery_sort_input', function (e) {
            var imageId = $(this).closest('.gallery_add_image_pre_block').find('.gallery_add_image_id').val();
            const index = uploadedGalleryImages.findIndex(element => {
                if (element.path == imageId) {
                    element.sort_order = e.target.value
                }
            });
        });

        $('#addListingModal').on('hidden.bs.modal', function (e) {
            // var imageId = $('body').find('#thumbnail_add_image_id').val();
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            $('#create_listing_form').trigger("reset");
            $('#listing_full_description').summernote('reset');
            $('#listing_features').selectpicker('val', '');
            $('#listing_contacts').selectpicker('val', '');
            $('#listing_purpose').selectpicker('val', '');
            $('#listing_project').selectpicker('val', '');
            $('#listing_developer').selectpicker('val', '');
            $('#listing_unit_type').selectpicker('val', '');
            $('#listing_property_type').selectpicker('val', '');
            $('#listing_completion_status').selectpicker('val', '');
            $('#listing_ownership_status').selectpicker('val', '');
            $('#listing_development_status').selectpicker('val', '');
            $('#listing_sale_status').selectpicker('val', '');
            $('#listing_rent_frequency').selectpicker('val', '');
            $('#listing_cheque').selectpicker('val', '');
            var ld = '<div class="row edit_lis-entry mb-2"><div class="col-md-2"><label>Title</label><input maxlength="20" type="text" class="form-control lis-d-title"></div><div class="col-md-2"><label>Price</label><input maxlength="10" type="text" class="form-control lis-d-price"></div><div class="col-md-1"><label>Min Beds</label><input maxlength="10" type="text" class="form-control lis-d-min-beds"></div><div class="col-md-1"><label>Max Beds</label><input maxlength="10" type="text" class="form-control lis-d-max-beds"></div><div class="col-md-2"><label>Min Area</label><input maxlength="10" type="text" class="form-control lis-d-min-area"></div><div class="col-md-2"><label>Max Area</label><input maxlength="10" type="text" class="form-control lis-d-max-area"></div><div class="col-md-2" style="align-content: end"><button type="button" class="btn btn-danger edit_remove-entry"><i class="fa fa-minus"></i></button></div></div>'
            $('#lis-container').html(ld);
            uploadedGalleryImages = []
            listingDetails = []
            resetAddListingImages();
            // if (imageId !== '') {
            //     deleteUploadedListingFile(imageId, '', function () {
            //         resetAddListingImages();
            //     });
            // }
        });

        $('#editListingModal').on('hidden.bs.modal', function (e) {
            // var imageId = $('body').find('#thumbnail_edit_image_id').val();
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            $('body').find('#edit_listing_form #edit_listing_project').empty();
            $('body').find('#edit_listing_form #edit_listing_project').append('<option value="">Select Project</option>');
            $('body').find('#edit_listing_form #edit_listing_project').selectpicker('val', '');
            $('body').find('#edit_listing_form #edit_listing_project').selectpicker('refresh');
            $('#edit_lis-container').html("");
            uploadedGalleryImages = []
            listingDetails = []
            resetEditListingImages();
        });

        $('body').on('click', '#trash-btn', function () {
            trashedListingListDataTable();
        });

        $('body').on('click', '.recover-btn', function () {
            var fid = $(this).closest('tr').find('.trashed-listing-id').val();
            var obj = Object.create(globalScript.RECOVER_LISTING);
            var url = obj.url(fid);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    toastr.success(response._metadata.message);
                    trashedListingListDataTable();
                    listingsListDataTable($('#listingSearchFrom').serialize());
                }
            })
        });

        $('body').on('click', '.per-delete-btn', function () {
            var fid = $(this).closest('tr').find('.trashed-listing-id').val();
            var obj = Object.create(globalScript.PER_DELETE_LISTING);
            var url = obj.url(fid);
            obj.url = url;
            globalScript.showConfirmationAlert(
                'You want to permanently delete this listing?',
                function () {
                    globalScript.ajaxCall(obj).done(function (response) {
                        if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                            toastr.success(response._metadata.message);
                            trashedListingListDataTable();
                        }
                    })
                }
            )
        });

        $('body').on('click', '#add-entry', function () {
            let entry = $('.lis-entry:first').clone();
            entry.find('input').val('');
            $('#lis-container').append(entry);
        });

        $('body').on('click', '#edit_add-entry', function () {
            let entry = $('.edit_lis-entry:first').clone();
            entry.find('input').val('');
            $('#edit_lis-container').append(entry);
        });

        $('body').on('click', '.remove-entry', function () {
            if ($('.lis-entry').length > 1) {
                $(this).closest('.lis-entry').remove();
                updateListingDetails();
            }
        });

        $('body').on('click', '.edit_remove-entry', function () {
            if ($('.edit_lis-entry').length > 1) {
                $(this).closest('.edit_lis-entry').remove();
                updateEditListingDetails();
            }
        });

        $('body').on('click', '#listingSearchFormReset', function () {
            $('body').find('#project_search').empty();
            $('body').find('#project_search').append('<option value="">Select Project</option>');
            $('body').find('#project_search').selectpicker('val', '');
            $('body').find('#project_search').selectpicker('refresh');
            $('#purpose_search').selectpicker('val', '');
            $('#contact_search').selectpicker('val', '');
            $('#developer_search').selectpicker('val', '');
            $('#property_type_search').selectpicker('val', '');
            $('#unit_type_search').selectpicker('val', '');
            $('#cs_search').selectpicker('val', '');
            $('#os_search').selectpicker('val', '');
            $('#ds_search').selectpicker('val', '');
            $('#ss_search').selectpicker('val', '');
            $('#rf_search').selectpicker('val', '');
            listingsListDataTable('');
        });

        $('body').on('submit', '#listingSearchFrom', function (e) {
            e.preventDefault();
            listingsListDataTable($('#listingSearchFrom').serialize());
        });

        $('body').on('click', '.match-btn', function () {
            var lid = $(this).closest('tr').find('.listing-id').val();
            $("#ListingReqsModal").modal('show');
            listingReqsListDataTable(lid);
        });
    };

    var updateListingDetails = function () {
        listingDetails = [];
        $('.lis-entry').each(function () {
            let entry = {
                title: $(this).find('.lis-d-title').val(),
                price: $(this).find('.lis-d-price').val(),
                minBeds: $(this).find('.lis-d-min-beds').val(),
                maxBeds: $(this).find('.lis-d-max-beds').val(),
                minArea: $(this).find('.lis-d-min-area').val(),
                maxArea: $(this).find('.lis-d-max-area').val()
            };
            listingDetails.push(entry);
        });
    };

    var updateEditListingDetails = function () {
        listingDetails = [];
        $('.edit_lis-entry').each(function () {
            let entry = {
                title: $(this).find('.lis-d-title').val(),
                price: $(this).find('.lis-d-price').val(),
                minBeds: $(this).find('.lis-d-min-beds').val(),
                maxBeds: $(this).find('.lis-d-max-beds').val(),
                minArea: $(this).find('.lis-d-min-area').val(),
                maxArea: $(this).find('.lis-d-max-area').val()
            };
            listingDetails.push(entry);
        });
    };

    var resetAddListingImages = 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_listings_dropzone .dz-message span').html("Drop files here to upload");
        $('body').find('#primary_add_image_id').val('');
        $('body').find('#gallery_images').html('');
        $('body').find('#primary_add_image_pre').attr('href', '');
        $('body').find('#primary_add_image_pre').hide();
        $('body').find('#primary_delete_uploaded_image_btn').hide();
        $('body').find('#primary_listings_dropzone .dz-message span').html("Drop files here to upload");
        // if (!isAddDropzoneActive) {
        //     initDropzone();
        // }
    };

    var resetEditListingImages = 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_listings_dropzone .dz-message span').html("Drop files here to upload");
        $('body').find('#primary_edit_image_id').val('');
        $('body').find('#edit_gallery_images').html('');
        $('body').find('#primary_edit_image_pre').attr('href', '');
        $('body').find('#primary_edit_image_pre').hide();
        $('body').find('.primary_delete_edit_uploaded_image_btn').hide();
        $('body').find('#primary_edit_listings_dropzone .dz-message span').html("Drop files here to upload");
        // if (!isEditDropzoneActive) {
        //     initEditDropzone();
        // }
    };

    var createListing = function (callback) {
        var listing_title = $('#listing_title').val();
        var listing_project = $('#listing_project').val();
        var listing_developer = $('#listing_developer').val();
        var listing_unit_type = $('#listing_unit_type').val();
        var listing_purpose = $('#listing_purpose').val();
        var listing_property_type = $('#listing_property_type').val();
        var listing_features = $('#listing_features').val();
        var listing_contacts = $('#listing_contacts').val();
        var listing_completion_status = $('#listing_completion_status').val();
        var listing_ownership_status = $('#listing_ownership_status').val();
        var listing_development_status = $('#listing_development_status').val();
        var listing_sale_status = $('#listing_sale_status').val();
        var listing_rent_frequency = $('#listing_rent_frequency').val();
        var listing_cheque = $('#listing_cheque').val();
        var listing_price = $('#listing_price').val();
        var listing_area = $('#listing_area').val();
        var listing_max_area = $('#listing_max_area').val();
        var listing_beds = $('#listing_beds').val();
        var listing_max_beds = $('#listing_max_beds').val();
        var listing_baths = $('#listing_baths').val();
        var listing_max_baths = $('#listing_max_baths').val();
        var listing_lat = $('#listing_lat').val();
        var listing_lng = $('#listing_lng').val();
        var listing_pcd = $('#listing_pcd').val();
        var listing_meta_title = $('#listing_meta_title').val();
        var listing_meta_keywords = $('#listing_meta_keywords').val();
        var listing_meta_description = $('#listing_meta_description').val();
        var listing_full_description = $('#listing_full_description').summernote('code');
        var imageId = $('#thumbnail_add_image_id').val();
        var primaryImageId = $('#primary_add_image_id').val();
        var obj = Object.create(globalScript.CREATE_LISTING);
        obj.data = {
            'type': 2,
            'title': listing_title,
            'project_id': listing_project,
            'developer_id': listing_developer,
            'unit_type_id': listing_unit_type,
            'purpose_id': listing_purpose,
            'property_type_id': listing_property_type,
            'listing_features': listing_features,
            'listing_contacts': listing_contacts,
            'completion_status_id': listing_completion_status,
            'ownership_status_id': listing_ownership_status,
            'development_status_id': listing_development_status,
            'sale_status_id': listing_sale_status,
            'rent_frequency_id': listing_rent_frequency,
            'cheque_id': listing_cheque,
            'price': listing_price,
            'area': listing_area,
            'max_area': listing_max_area,
            'beds': listing_beds,
            'max_beds': listing_max_beds,
            'baths': listing_baths,
            'max_baths': listing_max_baths,
            'lat': listing_lat,
            'lng': listing_lng,
            'pcd': listing_pcd,
            'meta_title': listing_meta_title,
            'meta_keywords': listing_meta_keywords,
            'meta_desc': listing_meta_description,
            'full_desc': listing_full_description,
            'thumb_image_id': imageId,
            'primary_image_id': primaryImageId,
            'gallery_images': uploadedGalleryImages,
            'listing_details': listingDetails
        };
        globalScript.ajaxCall(obj).done(function (response) {
            if (response.errors && response.errors.length !== 0) {
                $('.add_errors').show();
                _.each(response.errors, function (v, k) {
                    $('.add_errors ul').append('<li>' + v + '</li>');
                });
                return false;
            } else if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                toastr.success(response._metadata.message);
                $('body').find('#thumbnail_add_image_id').val('');
                $('body').find('#primary_add_image_id').val('');
                if (typeof callback == 'function') callback();
            }
        });
    };

    var updateListing = function (callback) {
        var listingId = $('#listing_id').val();
        var listing_title = $('#edit_listing_title').val();
        var listing_project = $('#edit_listing_project').val();
        var listing_developer = $('#edit_listing_developer').val();
        var listing_unit_type = $('#edit_listing_unit_type').val();
        var listing_purpose = $('#edit_listing_purpose').val();
        var listing_property_type = $('#edit_listing_property_type').val();
        var listing_features = $('#edit_listing_features').val();
        var listing_contacts = $('#edit_listing_contacts').val();
        var listing_completion_status = $('#edit_listing_completion_status').val();
        var listing_ownership_status = $('#edit_listing_ownership_status').val();
        var listing_development_status = $('#edit_listing_development_status').val();
        var listing_sale_status = $('#edit_listing_sale_status').val();
        var listing_rent_frequency = $('#edit_listing_rent_frequency').val();
        var listing_cheque = $('#edit_listing_cheque').val();
        var listing_price = $('#edit_listing_price').val();
        var listing_area = $('#edit_listing_area').val();
        var listing_max_area = $('#edit_listing_max_area').val();
        var listing_beds = $('#edit_listing_beds').val();
        var listing_max_beds = $('#edit_listing_max_beds').val();
        var listing_baths = $('#edit_listing_baths').val();
        var listing_max_baths = $('#edit_listing_max_baths').val();
        var listing_lat = $('#edit_listing_lat').val();
        var listing_lng = $('#edit_listing_lng').val();
        var listing_pcd = $('#edit_listing_pcd').val();
        var listing_meta_title = $('#edit_listing_meta_title').val();
        var listing_meta_keywords = $('#edit_listing_meta_keywords').val();
        var listing_meta_description = $('#edit_listing_meta_description').val();
        var listing_full_description = $('#edit_listing_full_description').summernote('code');
        var imageId = $('#thumbnail_edit_image_id').val();
        var primaryId = $('#primary_edit_image_id').val();
        var obj = Object.create(globalScript.UPDATE_LISTING);
        obj.url = obj.url(listingId);
        obj.data = {
            'title': listing_title,
            'project_id': listing_project,
            'developer_id': listing_developer,
            'unit_type_id': listing_unit_type,
            'purpose_id': listing_purpose,
            'property_type_id': listing_property_type,
            'listing_features': listing_features,
            'listing_contacts': listing_contacts,
            'completion_status_id': listing_completion_status,
            'ownership_status_id': listing_ownership_status,
            'development_status_id': listing_development_status,
            'sale_status_id': listing_sale_status,
            'rent_frequency_id': listing_rent_frequency,
            'cheque_id': listing_cheque,
            'price': listing_price,
            'lat': listing_lat,
            'lng': listing_lng,
            'pcd': listing_pcd,
            'area': listing_area,
            'max_area': listing_max_area,
            'beds': listing_beds,
            'max_beds': listing_max_beds,
            'baths': listing_baths,
            'max_baths': listing_max_baths,
            'meta_title': listing_meta_title,
            'meta_keywords': listing_meta_keywords,
            'meta_desc': listing_meta_description,
            'full_desc': listing_full_description,
            'thumb_image_id': imageId,
            'primary_image_id': primaryId,
            'gallery_images': uploadedGalleryImages,
            'listing_details': listingDetails
        };
        globalScript.ajaxCall(obj).done(function (response) {
            if (response.errors && response.errors.length !== 0) {
                _.each(response.errors, function (v, k) {
                    $('.edit_errors ul').append('<li>' + v + '</li>');
                    $('.edit_errors').show();
                });
                return false;
            } else {
                $('body').find('#edit_image_id').val('');
                toastr.success(response._metadata.message);
                if (typeof callback == 'function') callback();
            }
        });
    };

    var populateValuesToEditForm = function (data, callback) {
        $('body').find('#listing_id').val(data.id);
        $('body').find('#edit_listing_form #edit_listing_title').val(data.title);
        $('body').find('#edit_listing_form #edit_listing_price').val(data.price);
        $('body').find('#edit_listing_form #edit_listing_area').val(data.area);
        $('body').find('#edit_listing_form #edit_listing_max_area').val(data.max_area);
        $('body').find('#edit_listing_form #edit_listing_beds').val(data.beds);
        $('body').find('#edit_listing_form #edit_listing_max_beds').val(data.max_beds);
        $('body').find('#edit_listing_form #edit_listing_baths').val(data.baths);
        $('body').find('#edit_listing_form #edit_listing_max_baths').val(data.max_baths);
        $('body').find('#edit_listing_form #edit_listing_lat').val(data.lat);
        $('body').find('#edit_listing_form #edit_listing_lng').val(data.lng);
        $('body').find('#edit_listing_form #edit_listing_pcd').val(data.project_completion_date);
        if (data.project) {
            $('body').find('#edit_listing_form #edit_listing_project').append('<option value="' + data.project.id + '">' + data.project.name + '</option>');
            $('body').find('#edit_listing_form #edit_listing_project').selectpicker('val', data.project.id);
            $('body').find('#edit_listing_form #edit_listing_project').selectpicker('refresh');
        }
        $('body').find('#edit_listing_form #edit_listing_developer').selectpicker('val', data.developer_id);
        $('body').find('#edit_listing_form #edit_listing_unit_type').selectpicker('val', data.unit_type_id);
        $('body').find('#edit_listing_form #edit_listing_purpose').selectpicker('val', data.purpose_id);
        $('body').find('#edit_listing_form #edit_listing_property_type').selectpicker('val', data.property_type_id);
        $('body').find('#edit_listing_form #edit_listing_features').selectpicker('val', data.features);
        $('body').find('#edit_listing_form #edit_listing_contacts').selectpicker('val', data.contacts);
        $('body').find('#edit_listing_form #edit_listing_completion_status').selectpicker('val', data.completion_status_id);
        $('body').find('#edit_listing_form #edit_listing_ownership_status').selectpicker('val', data.ownership_status_id);
        $('body').find('#edit_listing_form #edit_listing_development_status').selectpicker('val', data.development_status_id);
        $('body').find('#edit_listing_form #edit_listing_sale_status').selectpicker('val', data.sale_status_id);
        $('body').find('#edit_listing_form #edit_listing_rent_frequency').selectpicker('val', data.rent_frequency_id);
        $('body').find('#edit_listing_form #edit_listing_cheque').selectpicker('val', data.cheque_id);
        $('body').find('#edit_listing_form #edit_listing_meta_title').val(data.meta_title);
        $('body').find('#edit_listing_form #edit_listing_meta_keywords').val(data.meta_keywords);
        $('body').find('#edit_listing_form #edit_listing_meta_description').val(data.meta_desc);
        $('body').find('#edit_listing_form #edit_listing_full_description').summernote("code", data.full_desc);
        uploadedGalleryImages = data.gallery
        $.each(data.gallery, function (k, v) {
            var img = '<div class="col-lg-3"><div class="card"><div class="card-body" style="background-color: #eee"><div class="gallery_add_image_pre_block pre_block"><input value="' + v.path + '" type="hidden" class="gallery_add_image_id"><img src="/' + v.path + '" alt="image" class="gallery_add_image_pre img-fluid" /><input class="form-control edit_gallery_sort_input white-input" type="text" maxlength="10" value="' + v.sort_order + '" placeholder="Sort Order" /><button type="button" class="edit_gallery_delete_uploaded_image_btn btn btn-danger"><i class="fa fa-times"></i></button></div></div></div></div>'
            $('#edit_gallery_images').append(img);
        });
        $('body').find('#edit_gallery_images').selectpicker(data.gallery);
        if (data.listing_details.length > 0) {
            listingDetails = data.listing_details
            $.each(data.listing_details, function (k, v) {
                var ld = '<div class="row edit_lis-entry mb-2"><div class="col-md-2"><label>Title</label><input value="' + v.title + '" maxlength="20" type="text" class="form-control lis-d-title"></div><div class="col-md-2"><label>Price</label><input value="' + v.price + '" maxlength="10" type="text" class="form-control lis-d-price"></div><div class="col-md-1"><label>Min Beds</label><input value="' + v.minBeds + '" maxlength="10" type="text" class="form-control lis-d-min-beds"></div><div class="col-md-1"><label>Max Beds</label><input value="' + v.maxBeds + '" maxlength="10" type="text" class="form-control lis-d-max-beds"></div><div class="col-md-2"><label>Min Area</label><input value="' + v.minArea + '" maxlength="10" type="text" class="form-control lis-d-min-area"></div><div class="col-md-2"><label>Max Area</label><input value="' + v.maxArea + '" maxlength="10" type="text" class="form-control lis-d-max-area"></div><div class="col-md-2" style="align-content: end"><button type="button" class="btn btn-danger edit_remove-entry"><i class="fa fa-minus"></i></button></div></div>'
                $('#edit_lis-container').append(ld);
            });
        } else {
            var ld = '<div class="row edit_lis-entry mb-2"><div class="col-md-2"><label>Title</label><input maxlength="20" type="text" class="form-control lis-d-title"></div><div class="col-md-2"><label>Price</label><input maxlength="10" type="text" class="form-control lis-d-price"></div><div class="col-md-1"><label>Min Beds</label><input maxlength="10" type="text" class="form-control lis-d-min-beds"></div><div class="col-md-1"><label>Max Beds</label><input maxlength="10" type="text" class="form-control lis-d-max-beds"></div><div class="col-md-2"><label>Min Area</label><input maxlength="10" type="text" class="form-control lis-d-min-area"></div><div class="col-md-2"><label>Max Area</label><input maxlength="10" type="text" class="form-control lis-d-max-area"></div><div class="col-md-2" style="align-content: end"><button type="button" class="btn btn-danger edit_remove-entry"><i class="fa fa-minus"></i></button></div></div>'
            $('#edit_lis-container').append(ld);
        }

        if (data.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', data.thumb_image_public_url);
            $('body').find('#thumbnail_edit_image_path').val(data.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();
        }
        if (data.brochure_public_url === '') {
            $('body').find('#primary_edit_image_preview_row').hide();
            $('body').find('.primary_delete_edit_uploaded_image_btn').hide();
            $('body').find('#primary_edit_image_row').show();
            // if (!isEditDropzoneActive) {
            //     initEditDropzone();
            // }
        } else {
            $('body').find('#primary_edit_image').attr('href', data.brochure_public_url);
            $('body').find('#primary_edit_image_path').val(data.brochure);
            $('body').find('#primary_edit_image_preview_row').show();
            $('body').find('.primary_delete_edit_uploaded_image_btn').show();
            $('body').find('#primary_edit_image_row').hide();
        }
        if (typeof callback == 'function') callback();
    };

    var deleteListings = function (callback) {
        var obj = Object.create(globalScript.DELETE_LISTING);
        obj.data = {
            'listing_ids[]': selectedListings
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedListings = [];
            if (typeof callback == 'function') callback();
        });
    };

    var updateListingStatus = function (status, column, callback) {
        var obj = Object.create(globalScript.UPDATE_LISTING_STATUS);
        obj.data = {
            'listing_ids[]': selectedListings,
            'status': status,
            'column': column
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedListings = [];
            if (typeof callback == 'function') callback();
        });
    };

    var initDropzone = function () {
        Dropzone.autoDiscover = false;
        Dropzone.options.myAwesomeDropzone = {
            thumbnailWidth: 250,
            thumbnailHeight: 250
        };
        var dropZoneConfiguration1 = {
            url: globalScript.APP_URL + "uploadlistingfile", // 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_listings_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"
        };
        var dropZoneConfiguration2 = {
            url: globalScript.APP_URL + "uploadlistingfile", // laravel route
            addRemoveLinks: true,
            init: function () {
                // isAddDropzoneActive = true;
                var _this = this;
                this.on("success", function (file, res) {
                    $('.primary_add_image_errors').hide();
                    $('.primary_add_image_errors ul').html('');
                    if (res && res.errors && res.errors.length !== 0) {
                        $.each(res.errors, function (k, v) {
                            $('.primary_add_image_errors ul').append('<li>' + v + '</li>');
                            $('.primary_add_image_errors').show();
                            _this.removeFile(file);
                        });
                    }
                    if (res && res.records && res.records.id) {
                        $('body').find('#primary_add_image_id').val(res.records.id);
                        $('body').find('#primary_add_image_pre').attr('href', res.records.url);
                        $('body').find('#primary_add_image_pre').show();
                        $('body').find('#primary_delete_uploaded_image_btn').show();
                        // $('body').find('#primary_listings_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: "application/pdf"
        };
        var dropZoneConfiguration3 = {
            url: globalScript.APP_URL + "uploadlistingfiles",
            addRemoveLinks: true,
            init: function () {
                let response = null;
                // isAddDropzoneActive = true;
                var _this = this;
                this.on("success", function (file, res) {
                    response = res
                    $('.gallery_add_image_errors').hide();
                    $('.gallery_add_image_errors ul').html('');
                    if (res && res.errors && res.errors.length !== 0) {
                        $.each(res.errors, function (k, v) {
                            $('.gallery_add_image_errors ul').append('<li>' + v + '</li>');
                            $('.gallery_add_image_errors').show();
                            _this.removeFile(file);
                        });
                    }
                    _this.removeFile(file);
                });
                this.on('queuecomplete', function () {
                    if (this.getActiveFiles().length === 0) {
                        if (response && response.records && response.records.length > 0) {
                            $.each(response.records, function (k, v) {
                                var img = '<div class="col-lg-3"><div class="card"><div class="card-body" style="background-color: #eee"><div class="gallery_add_image_pre_block pre_block"><input value="' + v.id + '" type="hidden" class="gallery_add_image_id"><img src="/' + v.path + '" alt="image" class="gallery_add_image_pre img-fluid" /><input class="form-control gallery_sort_input white-input" type="text" maxlength="10" placeholder="Sort Order" /><button type="button" class="gallery_delete_uploaded_image_btn btn btn-danger"><i class="fa fa-times"></i></button></div></div></div></div>'
                                $('#gallery_images').append(img);
                                v.sort_order = 0
                                uploadedGalleryImages.push(v)
                            });
                            // $('body').find('#primary_add_image_id').val(res.records.id);
                            // $('body').find('#primary_add_image_pre').attr('src', res.records.url);
                            // $('body').find('#primary_delete_uploaded_image_btn').show();
                        }
                    }
                });
                this.on('error', function (file, errorMessage) {
                    _this.removeFile(file);
                });
                this.on('resetFiles', function () {
                    this.removeAllFiles();
                });
            },
            parallelUploads: 10,
            maxFiles: 10,
            maxFilesize: 1,
            uploadMultiple: true,
            maxfilesexceeded: function (file) {
                this.removeAllFiles();
                this.addFile(file);
            },
            acceptedFiles: "image/jpeg,image/png,image/webp"
        };
        $('#thumbnail_listings_dropzone').addClass('dropzone');
        $('#thumbnail_listings_dropzone').dropzone(dropZoneConfiguration1);
        $('#primary_listings_dropzone').addClass('dropzone');
        $('#primary_listings_dropzone').dropzone(dropZoneConfiguration2);
        $('#gallery_listings_dropzone').addClass('dropzone');
        $('#gallery_listings_dropzone').dropzone(dropZoneConfiguration3);
    };

    var initEditDropzone = function () {
        Dropzone.autoDiscover = false;
        Dropzone.options.myAwesomeDropzone = {
            thumbnailWidth: 250,
            thumbnailHeight: 250
        };
        var dropZoneConfiguration1 = {
            url: globalScript.APP_URL + "uploadlistingfile", // 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_listings_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"
        };
        var dropZoneConfiguration2 = {
            url: globalScript.APP_URL + "uploadlistingfile", // laravel route
            addRemoveLinks: true,
            init: function () {
                // isEditDropzoneActive = true;
                var _this = this;
                this.on("success", function (file, res) {
                    $('.primary_edit_image_errors').hide();
                    $('.primary_edit_image_errors ul').html('');
                    if (res && res.errors && res.errors.length !== 0) {
                        $.each(res.errors, function (k, v) {
                            $('.primary_edit_image_errors ul').append('<li>' + v + '</li>');
                            $('.primary_edit_image_errors').show();
                            _this.removeFile(file);
                        });
                    }
                    if (res && res.records && res.records.id) {
                        $('body').find('#primary_edit_image_id').val(res.records.id);
                        $('body').find('#primary_edit_image_pre').attr('href', res.records.url);
                        $('body').find('#primary_edit_image_pre').show();
                        $('body').find('.primary_delete_edit_uploaded_image_btn').show();
                        // $('body').find('#primary_edit_listings_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: "application/pdf"
        };
        var dropZoneConfiguration3 = {
            url: globalScript.APP_URL + "uploadlistingfiles",
            addRemoveLinks: true,
            init: function () {
                let response = null;
                // isAddDropzoneActive = true;
                var _this = this;
                this.on("success", function (file, res) {
                    response = res
                    $('.gallery_edit_image_errors').hide();
                    $('.gallery_edit_image_errors ul').html('');
                    if (res && res.errors && res.errors.length !== 0) {
                        $.each(res.errors, function (k, v) {
                            $('.gallery_edit_image_errors ul').append('<li>' + v + '</li>');
                            $('.gallery_edit_image_errors').show();
                            _this.removeFile(file);
                        });
                    }
                    _this.removeFile(file);
                });
                this.on('queuecomplete', function () {
                    if (this.getActiveFiles().length === 0) {
                        if (response && response.records && response.records.length > 0) {
                            $.each(response.records, function (k, v) {
                                var img = '<div class="col-lg-3"><div class="card"><div class="card-body" style="background-color: #eee"><div class="gallery_add_image_pre_block pre_block"><input value="' + v.path + '" type="hidden" class="gallery_add_image_id"><img src="/' + v.path + '" alt="image" class="gallery_add_image_pre img-fluid" /><input class="form-control gallery_sort_input white-input" type="text" maxlength="10" placeholder="Sort Order" /><button type="button" class="edit_gallery_delete_uploaded_image_btn btn btn-danger"><i class="fa fa-times"></i></button></div></div></div></div>'
                                $('#edit_gallery_images').append(img);
                                v.sort_order = 0
                                uploadedGalleryImages.push(v)
                            });
                            // $('body').find('#primary_add_image_id').val(res.records.id);
                            // $('body').find('#primary_add_image_pre').attr('src', res.records.url);
                            // $('body').find('#primary_delete_uploaded_image_btn').show();
                        }
                    }
                });
                this.on('error', function (file, errorMessage) {
                    _this.removeFile(file);
                });
                this.on('resetFiles', function () {
                    this.removeAllFiles();
                });
            },
            parallelUploads: 10,
            maxFiles: 10,
            maxFilesize: 1,
            uploadMultiple: true,
            maxfilesexceeded: function (file) {
                this.removeAllFiles();
                this.addFile(file);
            },
            acceptedFiles: "image/jpeg,image/png,image/webp"
        };
        $('#thumbnail_edit_listings_dropzone').addClass('dropzone');
        $('#thumbnail_edit_listings_dropzone').dropzone(dropZoneConfiguration1);
        $('#primary_edit_listings_dropzone').addClass('dropzone');
        $('#primary_edit_listings_dropzone').dropzone(dropZoneConfiguration2);
        $('#edit_gallery_listings_dropzone').addClass('dropzone');
        $('#edit_gallery_listings_dropzone').dropzone(dropZoneConfiguration3);
    };

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

    var getQueryParam = function (param) {
        var urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(param);
    }

    var listingsListDataTable = function (query) {
        if (listingsListingDataTable != null) {
            listingsListingDataTable.clear().destroy();
        }
        listingsListingDataTable = $('#listingsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "publiclistings?" + query,
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) { // Manipulate the data returned from the server
                    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": true,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'created_at',
                    "visible": false
                },
                {"data": "p_id", "title": "Ref.", "name": "p_id", "searchable": true, "orderable": false},
                {"data": "title", "title": "Title", "name": "title", "searchable": true, "orderable": true},
                {"data": "purpose", "title": "Purpose", "name": "purpose.name", "searchable": true, "orderable": false},
                {"data": "project", "title": "Project", "name": "project.name", "searchable": true, "orderable": false},
                {
                    "data": 'price',
                    "title": 'Price',
                    "name": 'price',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'area',
                    "title": 'Area',
                    "name": 'Area',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'beds',
                    "title": 'Beds',
                    "name": 'Beds',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'baths',
                    "title": 'Baths',
                    "name": 'Baths',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'added_by',
                    "title": 'Listed By',
                    "name": 'added_by.name',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#listingsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var listingReqsListDataTable = function (id) {
        if (listingReqsListingDataTable != null) {
            listingReqsListingDataTable.clear().destroy();
        }
        listingReqsListingDataTable = $('#listingReqsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "listingreqs?listing_id=" + id,
                type: "GET",
                xhrFields: {
                    withCredentials: true
                },
                dataSrc: function (json) { // Manipulate the data returned from the server
                    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_reqs').html(json.records.recordsTotal);
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": true,
            "serverSide": true,
            "paging": true,
            "stateSave": true,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'created_at',
                    "visible": false
                },
                {"data": "title", "title": "Title", "name": "title", "searchable": true, "orderable": false},
                {
                    "data": "purpose",
                    "title": "Purpose",
                    "name": "purpose.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "project",
                    "title": "Project",
                    "name": "project.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "district",
                    "title": "Community",
                    "name": "district.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "property_type",
                    "title": "Property Type",
                    "name": "property_type.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "lead_status",
                    "title": "Status",
                    "name": "lead_status.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "lead_source",
                    "title": "Source",
                    "name": "lead_source.name",
                    "searchable": false,
                    "orderable": false
                },
                {"data": "price", "title": "Price", "name": "price", "searchable": false, "orderable": false},
                {"data": "area", "title": "Area", "name": "area", "searchable": false, "orderable": false},
                {"data": "beds", "title": "Beds", "name": "beds", "searchable": false, "orderable": false},
                {"data": "baths", "title": "Baths", "name": "baths", "searchable": false, "orderable": false},
                {"data": "added_by", "title": "Added by", "name": "added_by.name", "searchable": false, "orderable": false}
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#listingReqsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var trashedListingListDataTable = function () {
        if (trashedListingListingDataTable != null) {
            trashedListingListingDataTable.clear().destroy();
        }
        trashedListingListingDataTable = $('#trashedListingListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "trashedlistings",
                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;
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": false,
            "serverSide": true,
            "paging": true,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'deleted_at',
                    "visible": false
                },
                {
                    "data": 'title',
                    "title": 'Title',
                    "name": 'title',
                    "searchable": true,
                    "orderable": true,
                    "visible": true
                },
                {
                    "data": 'price',
                    "title": 'Price',
                    "name": 'price',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'sale_price',
                    "title": 'Sale Price',
                    "name": 'sale_price',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'sku',
                    "title": 'SKU',
                    "name": 'sku',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": 'stock',
                    "title": 'Stock',
                    "name": 'stock',
                    "searchable": false,
                    "orderable": false,
                    "visible": true
                },
                {
                    "data": null,
                    "title": "Action",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[0, 'asc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#trashedListingListTemplate').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 () {
    listingsScript.init();
});
