(function() {

    function init() {
        let self = this;
        $('[icd-autocomplete-code]:not([ac-initialized])').each(function() {
            let elem = this, dynID = 'icd-' + Math.ceil(Math.random() * 1000000),
                codeElem = $(this), descElem = $(this).closest('form, tr').first().find('[icd-autocomplete-description]');
            var targetDescElem = $(this).data('target');
            if(targetDescElem){
                descElem = $(this).closest('form').find(targetDescElem);
            }
            $(elem).attr('id', dynID);
            new window.Def.Autocompleter.Search(dynID,
                'https://clinicaltables.nlm.nih.gov/api/icd10cm/v3/search?sf=code,name&ef=name', {
                    tableFormat: true,
                    valueCols: [0],
                    colHeaders: ['Code', 'Name'],
                }
            );
            window.Def.Autocompleter.Event.observeListSelections(dynID, function() {
                let autocomp = elem.autocomp, acData = autocomp.getSelectedItemData();
                codeElem.val(acData[0].code).trigger('change');
                descElem.val(acData[0].data['name']).attr('title', acData[0].data['name']).trigger('change');
                return false;
            });
            $(elem).attr('ac-initialized', 1);
        });
    }

    addMCInitializer('icd-autocomplete', init);

}).call(window);