1jQuery(function() {
2    //Verify, if json-plugin is installed. Initialize it, if necessary.
3    if(typeof json_plugin !== 'object') {
4        return;
5    }
6    if(!json_plugin.initialized) {
7        json_plugin.init();
8    }
9
10    jQuery('.jsongendoc-plugin').each(function() {
11
12        var $tabs = jQuery(this),
13            $tab = $tabs.find('.json-gendoc'),
14            $msg = $tabs.find('.json-gendoc-msg'),
15            $select = $tab.find('select'),
16            $button = $tab.find('button'),
17            $filename = $tab.find('input'),
18            filenameTemplate = $tabs.data('docname');
19
20        //button generate new document via ajax call
21        $button.on('click', function (event) {
22            jQuery.post(
23                DOKU_BASE + 'lib/exe/ajax.php',
24                {
25                    call: 'jsongendoc_plugin',//server function
26                    data: $select.val(), //data passed from helper.php
27                    name: $filename.val()
28                },
29                function(data) {
30                    $msg.append(data.msg);
31                    if(data.mime.length > 0) {
32                        //create file for download
33                        var blob = new Blob([data.document], {type : data.mime});
34                        //create link and click it for download to start
35                        var link = document.createElement('a');
36                        link.href = window.URL.createObjectURL(blob);
37                        link.download = $filename.val();
38                        document.body.appendChild(link);
39                        link.click();
40                        document.body.removeChild(link);
41                    }
42                    //increment filename field if necessary (for example,
43                    //filenameTemplate is "P#####" and filename is "P00215")
44                    var incLoc = filenameTemplate.search(/#+$/);
45                    if (incLoc >= 0) {
46                        var filename = $filename.val(),
47                            incBase = filename.substring(0, incLoc),
48                            inc = filename.substring(incLoc),
49                            inc1 = (parseInt(inc) + 1).toString();
50                        for (let i = inc.length - inc1.length; i > 0; i--) {
51                            inc1 = "0" + inc1;
52                        }
53                        $filename.val(incBase + inc1);
54                    }
55                },
56                'json'
57            );
58        });
59    });
60
61});
62