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 contactsScript = contactsScript || function () {
    var isInit = false;
    var contactsListingDataTable = null;
    var contactListingsListingDataTable = null;
    var selectedContacts = [];
    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 () {
        contactsListDataTable($('#contactSearchFrom').serialize());
        globalScript.initValidator();

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

        $('body').on('click', '.bulkRow', function () {
            var status = this.checked;
            var cdId = $(this).closest('tr').find('.contact-id').val();
            if (status === true) {
                $('#deleteAllBtn').fadeIn();
                $('#bulkActionsBtn').fadeIn();
                if (selectedContacts.indexOf(cdId) === -1) {
                    selectedContacts.push(cdId);
                }
                // $('#bulk-action-checkbox').prop('checked', true);
            } else {
                selectedContacts.remove(cdId);
            }
            if (selectedContacts.length === 0) {
                $('#deleteAllBtn').fadeOut();
                $('#bulkActionsBtn').fadeOut();
                $(".bulkRow, .select_all").prop('checked', false);
            }
        });

        $('body').on('click', '#deleteAllBtn', function () {
            globalScript.showConfirmationAlert(
                'You want to delete?',
                function () {
                    deleteContacts(function () {
                        toastr.success('Deleted successfully');
                        selectedContacts = [];
                        $(".bulkRow, .select_all").prop('checked', false);
                        $('#deleteAllBtn').fadeOut();
                        $('#bulkActionsBtn').fadeOut();
                        contactsListDataTable($('#contactSearchFrom').serialize());
                    });
                }
            )
        });

        $('body').on('change', '#contact_type', function (e) {
            if (e.target.value == 2) {
                $('#cSalutation').hide();
                $('#cName').html('Company Name*');
                $('#cPhone').html('Company Phone');
                $('#cAltPhone').html('Company Alternate Phone');
                $('#cEmail').html('Company Email');
                $('#cBrn').hide();
                $('#cOrn').show();
                $('#cTln').show();
                $('#cAddress').show();
                $('#cUrl').show();
                $('#cContactRole').hide();
            }
            if (e.target.value == 1) {
                $('#cSalutation').show();
                $('#cName').html('Name*');
                $('#cPhone').html('Phone');
                $('#cAltPhone').html('Alternate Phone');
                $('#cEmail').html('Email');
                $('#cBrn').show();
                $('#cOrn').hide();
                $('#cTln').hide();
                $('#cAddress').hide();
                $('#cUrl').hide();
                $('#cContactRole').show();
            }
        });

        $('body').on('change', '#edit_contact_type', function (e) {
            if (e.target.value == 2) {
                $('#ecSalutation').hide();
                $('#ecName').html('Company Name*');
                $('#ecPhone').html('Company Phone');
                $('#ecAltPhone').html('Company Alternate Phone');
                $('#ecEmail').html('Company Email');
                $('#ecBrn').hide();
                $('#ecOrn').show();
                $('#ecTln').show();
                $('#ecAddress').show();
                $('#ecUrl').show();
                $('#ecContactRole').hide();
            }
            if (e.target.value == 1) {
                $('#ecSalutation').show();
                $('#ecName').html('Name*');
                $('#ecPhone').html('Phone');
                $('#ecAltPhone').html('Alternate Phone');
                $('#ecEmail').html('Email');
                $('#ecBrn').show();
                $('#ecOrn').hide();
                $('#ecTln').hide();
                $('#ecAddress').hide();
                $('#ecUrl').hide();
                $('#ecContactRole').show();
            }
        });

        $('body').on('submit', '#create_contact_form', function (e) {
            e.preventDefault();
            if ($('#submit_btn').hasClass('disabled')) {
                return false;
            }
            $('#submit_btn').addClass('disabled');
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            var contact_type = $('#contact_type').val();
            var contact_salutation = $('#contact_salutation').val();
            var contact_name = $('#contact_name').val();
            var contact_phone = $('#contact_phone').val();
            var contact_alt_phone = $('#contact_alt_phone').val();
            var contact_email = $('#contact_email').val();
            var contact_brn = $('#contact_brn').val();
            var contact_orn = $('#contact_orn').val();
            var contact_tln = $('#contact_tln').val();
            var contact_address = $('#contact_address').val();
            var contact_website = $('#contact_website').val();
            var contact_source = $('#contact_source').val();
            var contact_role = $('#contact_role').val();
            var contact_assign_to = $('#contact_assign_to').val();
            var obj = Object.create(globalScript.CREATE_CONTACT);
            obj.data = {
                'type': contact_type,
                'salutation': contact_salutation,
                'name': contact_name,
                'phone': contact_phone,
                'alt_phone': contact_alt_phone,
                'email': contact_email,
                'brn': contact_brn,
                'orn': contact_orn,
                'tln': contact_tln,
                'address': contact_address,
                'website': contact_website,
                'source_id': contact_source,
                'contact_role_id': contact_role,
                'assign_to': contact_assign_to
            };
            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);
                    $('#addContactModal').modal('hide');
                    contactsListDataTable($('#contactSearchFrom').serialize());
                }
            });
        });

        $('body').on('submit', '#edit_contact_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 = $('#contact_id').val();
            var contact_type = $('#edit_contact_type').val();
            var contact_salutation = $('#edit_contact_salutation').val();
            var contact_name = $('#edit_contact_name').val();
            var contact_phone = $('#edit_contact_phone').val();
            var contact_alt_phone = $('#edit_contact_alt_phone').val();
            var contact_email = $('#edit_contact_email').val();
            var contact_brn = $('#edit_contact_brn').val();
            var contact_orn = $('#edit_contact_orn').val();
            var contact_tln = $('#edit_contact_tln').val();
            var contact_address = $('#edit_contact_address').val();
            var contact_website = $('#edit_contact_website').val();
            var contact_source = $('#edit_contact_source').val();
            var contact_role = $('#edit_contact_role').val();
            var contact_assign_to = $('#edit_contact_assign_to').val();
            var obj = Object.create(globalScript.UPDATE_CONTACT);
            obj.url = obj.url(cdId);
            obj.data = {
                'type': contact_type,
                'salutation': contact_salutation,
                'name': contact_name,
                'phone': contact_phone,
                'alt_phone': contact_alt_phone,
                'email': contact_email,
                'brn': contact_brn,
                'orn': contact_orn,
                'tln': contact_tln,
                'address': contact_address,
                'website': contact_website,
                'source_id': contact_source,
                'contact_role_id': contact_role,
                'assign_to': contact_assign_to
            };
            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);
                    $('#editContactModal').modal('hide');
                    contactsListDataTable($('#contactSearchFrom').serialize());
                }
            });
        });

        $('body').on('click', '.edit-btn', function () {
            var contactId = $(this).closest('tr').find('.contact-id').val();
            var obj = Object.create(globalScript.GET_CONTACT_DETAILS);
            var url = obj.url(contactId);
            obj.url = url;
            globalScript.ajaxCall(obj).done(function (response) {
                if (response.hasOwnProperty('_metadata') && response._metadata.hasOwnProperty('outcomeCode') && response._metadata.outcomeCode === 0) {
                    $('body').find('#contact_id').val(response.records.id);
                    if (response.records.type === 1) {
                        $('#ecSalutation').show();
                        $('#ecName').html('Name*');
                        $('#ecPhone').html('Phone');
                        $('#ecAltPhone').html('Alternate Phone');
                        $('#ecEmail').html('Email');
                        $('#ecBrn').show();
                        $('#ecOrn').hide();
                        $('#ecTln').hide();
                        $('#ecAddress').hide();
                        $('#ecUrl').hide();
                        $('#ecContactRole').show();
                    }
                    if (response.records.type === 2) {
                        $('#ecSalutation').hide();
                        $('#ecName').html('Company Name*');
                        $('#ecPhone').html('Company Phone');
                        $('#ecAltPhone').html('Company Alternate Phone');
                        $('#ecEmail').html('Company Email');
                        $('#ecBrn').hide();
                        $('#ecOrn').show();
                        $('#ecTln').show();
                        $('#ecAddress').show();
                        $('#ecUrl').show();
                        $('#ecContactRole').hide();
                    }
                    $('body').find('#edit_contact_form #edit_contact_type').val(response.records.type);
                    $('body').find('#edit_contact_form #edit_contact_salutation').val(response.records.salutation);
                    $('body').find('#edit_contact_form #edit_contact_name').val(response.records.name);
                    $('body').find('#edit_contact_form #edit_contact_phone').val(response.records.phone);
                    $('body').find('#edit_contact_form #edit_contact_alt_phone').val(response.records.alt_phone);
                    $('body').find('#edit_contact_form #edit_contact_email').val(response.records.email);
                    $('body').find('#edit_contact_form #edit_contact_brn').val(response.records.brn);
                    $('body').find('#edit_contact_form #edit_contact_orn').val(response.records.orn);
                    $('body').find('#edit_contact_form #edit_contact_tln').val(response.records.tln);
                    $('body').find('#edit_contact_form #edit_contact_address').val(response.records.address);
                    $('body').find('#edit_contact_form #edit_contact_website').val(response.records.website);
                    $('body').find('#edit_contact_form #edit_contact_source').selectpicker('val', response.records.source_id);
                    $('body').find('#edit_contact_form #edit_contact_role').selectpicker('val', response.records.contact_role_id);
                    $('body').find('#edit_contact_form #edit_contact_assign_to').selectpicker('val', response.records.assign_to);
                    $('.edit_errors').hide();
                    $('.edit_errors ul').html('');
                    $('#editContactModal').modal('show');
                }
            })
        });

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

        $('#addContactModal').on('hidden.bs.modal', function (e) {
            $('.add_errors').hide();
            $('.add_errors ul').html('');
            $('#create_contact_form').trigger("reset");
            $('#contact_source').selectpicker('val', '');
            $('#contact_role').selectpicker('val', '');
            $('#contact_assign_to').selectpicker('val', '');
        });

        $('#editContactModal').on('hidden.bs.modal', function (e) {
            $('.edit_errors').hide();
            $('.edit_errors ul').html('');
            $('#edit_contact_form').trigger("reset");
            $('#edit_contact_source').selectpicker('val', '');
            $('#edit_contact_role').selectpicker('val', '');
            $('#edit_contact_assign_to').selectpicker('val', '');
        });

        $('body').on('click', '#contactSearchFormReset', function () {
            $('#property_type_search').selectpicker('val', '');
            $('#contact_role_search').selectpicker('val', '');
            contactsListDataTable('');
        });

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

        $('body').on('click', '.property-btn', function () {
            var cId = $(this).closest('tr').find('.contact-id').val();
            $("#contactListingsModal").modal('show');
            contactListingsListDataTable(cId);
        });
    };

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

    var deleteContacts = function (callback) {
        var obj = Object.create(globalScript.DELETE_CONTACT);
        obj.data = {
            'contact_ids[]': selectedContacts
        };
        globalScript.ajaxCall(obj).done(function (response) {
            selectedContacts = [];
            if (typeof callback == 'function') callback();
        });
    };

    var contactsListDataTable = function (query) {
        if (contactsListingDataTable != null) {
            contactsListingDataTable.clear().destroy();
        }
        contactsListingDataTable = $('#contactsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "contacts?" + 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
                },
                {"orderable": false, "searchable": false, "data": null, "title": customCheckBox},
                {"data": "reference_number", "title": "Ref.", "name": "reference_number", "searchable": true, "orderable": false},
                {"data": "type", "title": "Type", "name": "type", "searchable": false, "orderable": false},
                {"data": "name", "title": "Name", "name": "name", "searchable": true, "orderable": true},
                {"data": "phone", "title": "Phone", "name": "phone", "searchable": true, "orderable": true},
                {"data": "email", "title": "Email", "name": "email", "searchable": true, "orderable": true},
                {
                    "data": "source",
                    "title": "Lead Source",
                    "name": "source.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "contact_role",
                    "title": "Role",
                    "name": "contact_role.name",
                    "searchable": false,
                    "orderable": false
                },
                {"data": "assignee", "title": "Assigned To", "name": "assignee.name", "searchable": false, "orderable": false},
                {
                    "data": null,
                    "title": "Actions",
                    "searchable": false,
                    "orderable": false
                }
            ],
            "order": [[2, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#contactsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    var contactListingsListDataTable = function (id) {
        if (contactListingsListingDataTable != null) {
            contactListingsListingDataTable.clear().destroy();
        }
        contactListingsListingDataTable = $('#contactListingsListTable').DataTable({
            "ajax": {
                url: globalScript.APP_URL + "contactlistings?contact_id=" + id,
                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_listings').html(json.records.recordsTotal);
                    return json.records.data;
                }
            },
            "searching": true,
            "ordering": true,
            "serverSide": true,
            "paging": true,
            "stateSave": false,
            "columns": [
                {
                    "orderable": true,
                    "searchable": false,
                    "data": 'created_at',
                    "visible": false
                },
                {
                    "orderable": false,
                    "searchable": true,
                    "data": 'p_id',
                    "visible": false
                },
                {"data": "title", "title": "Title", "name": "title", "searchable": true, "orderable": true},
                {
                    "data": "purpose",
                    "title": "Purpose",
                    "name": "purpose.name",
                    "searchable": false,
                    "orderable": false
                },
                {
                    "data": "project",
                    "title": "Project",
                    "name": "project.name",
                    "searchable": false,
                    "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
                }
            ],
            "order": [[0, 'desc']],
            "rowCallback": function (row, data) {
                var tmpl = _.template($('#contactListingsListTemplate').html());
                $(row).html(tmpl(data));
            }
        });
    };

    return {
        'init': init
    }

}();

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