1jQuery(function() {
2    var $ = jQuery;
3    // txt is the text to measure, font is the full CSS font declaration,
4    // e.g. "bold 12px Verdana"
5    function measureText(txt, font) {
6        var id = 'structinputstretch__text-width-tester',
7            $tag = $('#' + id);
8        if (!$tag.length) {
9            $tag = $('<span id="' + id + '" style="display:none;font:' + font + ';">' + txt + '</span>');
10            $('body').append($tag);
11        } else {
12            $tag.css({font:font}).html(txt);
13        }
14        return {
15            width: $tag.width(),
16            height: $tag.height()
17        }
18    }
19
20    function stretchInput() {
21        var $input = $(this);
22        //save start value
23        if (!$input.data('structinputstretch__minWidth')) {
24            $input.data('structinputstretch__minWidth', $input.width());
25            $input.data('structinputstretch__maxWidth', $input.closest('fieldset').width());
26        }
27        var minWidth = $input.data('structinputstretch__minWidth'),
28            maxWidth = $input.data('structinputstretch__maxWidth'),
29            inputFont = $input.css('font'),
30            inputTextWidth = measureText($input.val(), inputFont).width + 20;
31
32        if (inputTextWidth <= minWidth) {
33            $input.width(minWidth);
34        } else if (inputTextWidth >= maxWidth) {
35            $input.width(maxWidth);
36        } else {
37            $input.width(inputTextWidth);
38        }
39    }
40
41    $('body').on('input autocompleteclose', 'input[id^=struct__]', stretchInput);
42});