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 offplanScript = offplanScript || function () {
    var isInit = false;
    var offplansListingDataTable = null;
    var selectedOffplans = [];

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

    var handler = function () {
        offplansListDataTable($('#offplanSearchFrom').serialize());
        globalScript.initValidator();

        $('#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;
            }
        });

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

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

        $('body').on('submit', '#create_offplan_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var offplan_project = $('#offplan_project').val();
            var offplan_developer = $('#offplan_developer').val();
            var offplan_unit_type = $('#offplan_unit_type').val();
            var offplan_development_status = $('#offplan_development_status').val();
            var offplan_sale_status = $('#offplan_sale_status').val();
            var offplan_unit_no = $('#offplan_unit_no').val();
            var offplan_floor = $('#offplan_floor').val();
            var offplan_view = $('#offplan_view').val();
            var offplan_price = $('#offplan_price').val();
            var offplan_area = $('#offplan_area').val();
            var offplan_unit_area = $('#offplan_unit_area').val();
            var offplan_beds = $('#offplan_beds').val();
            var offplan_parking = $('#offplan_parking').val();
            var offplan_cd = $('#offplan_cd').val();
            var obj = Object.create(globalScript.CREATE_OFFPLAN);
            obj.data = {
                'project_id': offplan_project,
                'developer_id': offplan_developer,
                'unit_type_id': offplan_unit_type,
                'development_status_id': offplan_development_status,
                'sale_status_id': offplan_sale_status,
                'unit_no': offplan_unit_no,
                'floor': offplan_floor,
                'view': offplan_view,
                'price': offplan_price,
                'area': offplan_area,
                'unit_area': offplan_unit_area,
                'beds': offplan_beds,
                'cd': offplan_cd,
                'parking': offplan_parking
            };
            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);
                    setTimeout(function () {
                        window.location.reload()
                    }, 500)
                    // $('#addCallingDatabaseModal').modal('hide');
                    // offplansListDataTable($('#offplanSearchFrom').serialize());
                }
            });
        });

        $('body').on('submit', '#edit_offplan_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 cdId = $('#offplan_id').val();
            var offplan_title = $('#edit_offplan_title').val();
            var offplan_phone = $('#edit_offplan_phone').val();
            var offplan_name = $('#edit_offplan_name').val();
            var offplan_unit_no = $('#edit_offplan_unit_no').val();
            var offplan_project = $('#edit_offplan_project').val();
            var offplan_purpose = $('#edit_offplan_purpose').val();
            var offplan_property_type = $('#edit_offplan_property_type').val();
            var offplan_community = $('#edit_offplan_community').val();
            var offplan_offplan_status = $('#edit_offplan_offplan_status').val();
            var offplan_offplan_source = $('#edit_offplan_offplan_source').val();
            var offplan_price = $('#edit_offplan_price').val();
            var offplan_area = $('#edit_offplan_area').val();
            var offplan_beds = $('#edit_offplan_beds').val();
            var offplan_baths = $('#edit_offplan_baths').val();
            var obj = Object.create(globalScript.UPDATE_LEAD);
            obj.url = obj.url(cdId);
            obj.data = {
                'title': offplan_title,
                'phone': offplan_phone,
                'name': offplan_name,
                'unit_no': offplan_unit_no,
                'project_id': offplan_project,
                'purpose_id': offplan_purpose,
                'property_type_id': offplan_property_type,
                'district_id': offplan_community,
                'offplan_status_id': offplan_offplan_status,
                'offplan_source_id': offplan_offplan_source,
                'price': offplan_price,
                'area': offplan_area,
                'beds': offplan_beds,
                'baths': offplan_baths
            };
            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);
                    setTimeout(function () {
                        window.location.reload()
                    }, 500)
                }
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var offplanId = $(this).closest('tr').find('.offplan-id').val();
            var obj = Object.create(globalScript.GET_LEAD_DETAILS);
            var url = obj.url(offplanId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#offplan_id').val(response.records.id);
                    $('body').find('#edit_offplan_form #edit_offplan_location_ref').val(response.records.location_ref);
                    $('body').find('#edit_offplan_form #edit_offplan_title').val(response.records.title);
                    $('body').find('#edit_offplan_form #edit_offplan_phone').val(response.records.phone);
                    $('body').find('#edit_offplan_form #edit_offplan_name').val(response.records.name);
                    $('body').find('#edit_offplan_form #edit_offplan_unit_no').val(response.records.unit_no);
                    if (response.records.project) {
                        $('body').find('#edit_offplan_form #edit_offplan_project').append('<option value="' + response.records.project.id + '">' + response.records.project.name + '</option>');
                        $('body').find('#edit_offplan_form #edit_offplan_project').selectpicker('val', response.records.project.id);
                        $('body').find('#edit_offplan_form #edit_offplan_project').selectpicker('refresh');
                    }
                    $('body').find('#edit_offplan_form #edit_offplan_purpose').selectpicker('val', response.records.purpose_id);
                    $('body').find('#edit_offplan_form #edit_offplan_community').selectpicker('val', response.records.district_id);
                    $('body').find('#edit_offplan_form #edit_offplan_property_type').selectpicker('val', response.records.property_type_id);
                    $('body').find('#edit_offplan_form #edit_offplan_offplan_status').selectpicker('val', response.records.offplan_status_id);
                    $('body').find('#edit_offplan_form #edit_offplan_offplan_source').selectpicker('val', response.records.offplan_source_id);
                    $('body').find('#edit_offplan_form #edit_offplan_price').val(response.records.price);
                    $('body').find('#edit_offplan_form #edit_offplan_area').val(response.records.area);
                    $('body').find('#edit_offplan_form #edit_offplan_beds').val(response.records.beds);
                    $('body').find('#edit_offplan_form #edit_offplan_baths').val(response.records.baths);
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editOffplanModal').modal('show');
                }
            })
        });

        $('body').on('change', '.update_offplan_status', function () {
            var status = $(this).val();
            var column = $(this).attr('data-column');
            var offplanId = $(this).closest('tr').find('.offplan-id').val();
            selectedOffplans.push(offplanId);
            updateStatus(status, column, function () {
                toastr.success('Status successfully updated');
                offplansListDataTable($('#offplanSearchFrom').serialize());
            });
        });

        $('body').on('click', '.delete-btn', function () {
            selectedOffplans = [];
            $(".bulkRow, .select_all").prop('checked', false);
            var cdId = $(this).closest('tr').find('.offplan-id').val();
            selectedOffplans.push(cdId);
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteOffplans(function () {
                        toastr.success('Deleted successfully');
                        offplansListDataTable($('#offplanSearchFrom').serialize());
                    });
                }
            )
        });

        $('#addOffplanModal').on('hidden.bs.modal', function (e) {
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            $('#create_offplan_form').trigger("reset");
            $('#offplan_project').selectpicker('val', '');
            $('#offplan_developer').selectpicker('val', '');
            $('#offplan_unit_type').selectpicker('val', '');
            $('#offplan_development_status').selectpicker('val', '');
            $('#offplan_sale_status').selectpicker('val', '');
        });

        $('#editOffplanModal').on('hidden.bs.modal', function (e) {
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            $('#edit_offplan_form').trigger("reset");
            $('#edit_offplan_location_ref').val("");
            $('#edit_offplan_project').selectpicker('val', '');
            $('#edit_offplan_community').selectpicker('val', '');
            $('#edit_offplan_property_type').selectpicker('val', '');
            $('#edit_offplan_purpose').selectpicker('val', '');
            $('#edit_offplan_offplan_status').selectpicker('val', '');
            $('#edit_offplan_offplan_source').selectpicker('val', '');
        });

        $('body').on('click', '#offplanSearchFormReset', 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');
            $('#developer_search').selectpicker('val', '');
            $('#unit_type_search').selectpicker('val', '');
            $('#development_status_search').selectpicker('val', '');
            $('#sale_status_search').selectpicker('val', '');
            offplansListDataTable('');
        });

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

    var updateStatus = function (status, column, callback) {
        var obj = Object.create(globalScript.UPDATE_LEAD_STATUS);
        obj.data = {
            'offplan_ids[]': selectedOffplans,
            'status': status,
            'column': column
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedOffplans = [];
            if (typeof callback == 'function') callback();
        });
    };

    var deleteOffplans = function (callback) {
        var obj = Object.create(globalScript.DELETE_LEAD);
        obj.data = {
            'offplan_ids[]': selectedOffplans
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedOffplans = [];
            if (typeof callback == 'function') callback();
        });
    };

    var offplansListDataTable = function (query) {
        if (offplansListingDataTable != null) {
            offplansListingDataTable.clear().destroy();
        }
        offplansListingDataTable = $('#offplanListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "offplan?" + query,
                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": "project","title": "Project","name": "project.name","searchable": false,"orderable": false},
                {"data": "developer","title": "Developer","name": "developer.name","searchable": false,"orderable": false},
                {"data": "unit_type","title": "Unit Type","name": "unit_type.name","searchable": false,"orderable": false},
                {"data": "development_status","title": "Development Status","name": "development_status.name","searchable": false,"orderable": false},
                {"data": "sale_status","title": "Sale Status","name": "sale_status.name","searchable": false,"orderable": false},
                {"data": "unit_no", "title": "Unit No.", "name": "unit_no", "searchable": true, "orderable": false},
                {"data": "price", "title": "Price", "name": "price", "searchable": true, "orderable": false},
                {"data": "area", "title": "Area", "name": "area", "searchable": true, "orderable": false},
                {"data": "unit_area", "title": "Unit Area", "name": "unit_area", "searchable": true, "orderable": false},
                {"data": "beds", "title": "Beds", "name": "beds", "searchable": true, "orderable": false},
                {"data": "floor", "title": "Floor", "name": "floor", "searchable": true, "orderable": false},
                {"data": "view", "title": "View", "name": "view", "searchable": true, "orderable": false},
                {"data": "parking", "title": "Parking", "name": "parking", "searchable": true, "orderable": false},
                {"data": "completion_date", "title": "Completion Date", "name": "completion_date", "searchable": true, "orderable": false},
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#offplansListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    return {
        'init': init
    }

}();

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