(function (window, document, $) {
    'use strict';

    if (!$) { return; }

    function getUrl(path) {
        var base = document.querySelector('base');
        var prefix = base ? base.getAttribute('href') || '' : '';
        return (prefix.replace(/\/$/, '') || '') + path;
    }

    function getSelectize($select) {
        return $select.length && $select[0] && $select[0].selectize ? $select[0].selectize : null;
    }

    function setOptions($select, items, placeholder, keepRequired) {
        if (!$select || !$select.length) { return; }
        var selectize = getSelectize($select);
        var list = Array.isArray(items) ? items : [];

        if (selectize) {
            selectize.clear(true);
            selectize.clearOptions();
            selectize.addOption({ id: '', value: '', name: placeholder, text: placeholder });
            list.forEach(function (item) {
                selectize.addOption({
                    id: String(item.id),
                    value: String(item.id),
                    name: item.name,
                    text: item.name
                });
            });
            selectize.refreshOptions(false);
            if (list.length === 1) {
                selectize.setValue(String(list[0].id), true);
            } else {
                selectize.setValue('', true);
            }
        } else {
            var html = '<option value="">' + placeholder + '</option>';
            list.forEach(function (item) {
                html += '<option value="' + item.id + '">' + item.name + '</option>';
            });
            $select.html(html);
            if (list.length === 1) {
                $select.val(String(list[0].id));
            }
        }

        if (list.length === 0 && keepRequired === false) {
            $select.prop('required', false);
        } else {
            $select.prop('required', true);
        }
        $select.trigger('change.selectize');
    }

    function ensureCategorySelect() {
        var $category = $('#nstatuscategory, #ns_categornsy, select[name="ns_categornsy"], select[name="national_status_category"], select[name="national_status_category_id"]').first();
        if (!$category.length && $('#ns_category').length) {
            $('#ns_category').html('<select class="form-control search-select" name="ns_categornsy" id="nstatuscategory" required><option value="">Choose One</option></select>');
            $category = $('#nstatuscategory');
        }
        if ($category.length && !$category.attr('id')) {
            $category.attr('id', 'nstatuscategory');
        }
        return $category;
    }

    function syncSurvivorCode() {
        var reference = $.trim($('#crb_number, input[name="crb_number"]').first().val() || '');
        var $survivorCode = $('#survivor_code, input[name="survivor_code"]').first();
        if ($survivorCode.length) {
            $survivorCode.val(reference);
        }
    }

    function loadNationalStatusCategory(statusId) {
        var $category = ensureCategorySelect();
        if (!$category.length) { return; }

        if (!statusId) {
            setOptions($category, [], 'Choose Nationality Status First', false);
            return;
        }

        setOptions($category, [], 'Loading...', false);
        $.ajax({
            type: 'GET',
            url: getUrl('/findNSCategory'),
            data: { id: statusId },
            dataType: 'json'
        }).done(function (data) {
            var list = Array.isArray(data) ? data : [];
            if (!list.length) {
                setOptions($category, [], 'No category configured', false);
                return;
            }
            setOptions($category, list, 'Choose One', true);
        }).fail(function () {
            setOptions($category, [], 'Unable to load categories', false);
        });
    }

    function toggleReporterRelationRequired() {
        var reporterType = $('input[name="reporter_type"]:checked').val();
        var $relation = $('select[name="reporter_relation"]');
        if (!$relation.length) { return; }
        if (reporterType === '1') {
            $relation.prop('required', false);
        } else {
            $relation.prop('required', true);
        }
    }

    function prepareFormForSave(form) {
        syncSurvivorCode();
        toggleReporterRelationRequired();

        var $form = $(form);
        $form.find(':input:disabled').each(function () {
            if ($(this).is('[name]')) {
                $(this).prop('disabled', false).attr('data-ngbvd-reenabled', '1');
            }
        });

        var $nstatus = $('#nstatus, select[name="national_status"]').first();
        var $category = ensureCategorySelect();
        if ($nstatus.val() && $category.length && !$category.val() && $category.find('option').length <= 1) {
            $category.prop('required', false);
        }
    }

    $(document)
        .off('input.ngbvdFinalReference paste.ngbvdFinalReference change.ngbvdFinalReference', '#crb_number, input[name="crb_number"]')
        .on('input.ngbvdFinalReference paste.ngbvdFinalReference change.ngbvdFinalReference', '#crb_number, input[name="crb_number"]', function () {
            setTimeout(syncSurvivorCode, 0);
        });

    $(document)
        .off('change.ngbvdFinalNationalStatus', '#nstatus, select[name="national_status"]')
        .on('change.ngbvdFinalNationalStatus', '#nstatus, select[name="national_status"]', function () {
            loadNationalStatusCategory($(this).val());
        });

    $(document)
        .off('change.ngbvdFinalReporterType', 'input[name="reporter_type"]')
        .on('change.ngbvdFinalReporterType', 'input[name="reporter_type"]', toggleReporterRelationRequired);

    $(document)
        .off('submit.ngbvdFinalDataEntry', '#indexform')
        .on('submit.ngbvdFinalDataEntry', '#indexform', function (event) {
            prepareFormForSave(this);
            if (this.checkValidity && !this.checkValidity()) {
                event.preventDefault();
                this.reportValidity();
                return false;
            }
            return true;
        });

    $(document)
        .off('click.ngbvdFinalSaveButton', '.savebutton, .savecontinue, button[type="submit"]')
        .on('click.ngbvdFinalSaveButton', '.savebutton, .savecontinue, button[type="submit"]', function () {
            var form = $(this).closest('form').get(0);
            if (form) {
                prepareFormForSave(form);
            }
        });

    $(function () {
        ensureCategorySelect();
        syncSurvivorCode();
        toggleReporterRelationRequired();
        var currentStatus = $('#nstatus, select[name="national_status"]').first().val();
        if (currentStatus && !ensureCategorySelect().val()) {
            loadNationalStatusCategory(currentStatus);
        }
    });
})(window, document, window.jQuery);
