function prepare_widget_list_elements() {
        $('input[name$=add_element]').click(
            function() {
                /* get prefix from clicked element */
                var name_attr = $(this).attr('name');
                var prefix = name_attr.substr(0, name_attr.length-12); // 12 == len($add_element)

                /* get last row node */
                var row = $(this).parents('div').parents('div').prev()[0];
                if (row.tagName == 'BR') {
                    row = $(row).prev()[0];
                }
                if (row.tagName == 'TABLE') {
                    row = $(row).find('tr:last');
                }

                if ($(row).find('input[name$=add_element]').length > 0) {
                    /* this has several levels of widget lists, don't use
                     * javascript in that case */
                    return true;
                }

                /* clone the row */
                var new_row = $(row).clone();

                /* fix up form element name */
                $(new_row).find('[name^=' + prefix + ']').each(
                    function() {
                        var cur_name = $(this).attr('name');
                        var pos = cur_name.indexOf('element', prefix.length) + 7; // 7 == len(element)
                        var index = cur_name.substring(pos, cur_name.length);
                        var after_pos = Math.max(index.indexOf('-'), index.indexOf('$'));
                        var after = '';
                        if (after_pos != -1) {
                            after = index.substring(after_pos, index.length);
                        }
                        var new_name = cur_name.substring(0, cur_name.length-index.length) +
                            (parseInt(index)+1) + after;
                        $(this).attr('name', new_name);
                        if ($(this).attr('type') == 'text') {
                            $(this).attr('value', '');
                        }
                    }
                );
                /* add new row after the last row */
                $(row).after($(new_row));

                /* trigger advanced widget setup */
                $(document).trigger('wcs:new-widgets-on-page');

                /* increase hidden $added_elements value */
                var hidden = $($(this).parents('div').parents('div')[0]).prevAll(
                    'input[type=hidden]')[0];
                $(hidden).attr('value', parseInt($(hidden).attr('value'))+1);

                return false;
            }
        );
    }

$(document).ready(prepare_widget_list_elements);
