1window.edittable_plugins = window.edittable_plugins || {};
2window.tablelayout = window.tablelayout || {};
3
4(function (edittable_plugins, tablelayout) {
5    'use strict';
6    var modifyHandsontableConfig = function (handsontable_config, $form) {
7        var $layoutfield = $form.find('input[name=tablelayout]');
8        if (!$layoutfield.length) {
9            return;
10        }
11
12        var colWidths = [];
13        var layout = tablelayout.initLayout($layoutfield.val());
14        layout.colwidth.forEach(function (currentValue, index) {
15            var undefinedValue;
16            if (!currentValue || currentValue.substr(-'px'.length) !== 'px') {
17                colWidths.push(undefinedValue);
18                return;
19            }
20            colWidths[index] = parseInt(currentValue, 10);
21        });
22
23        if (colWidths.length) {
24            handsontable_config.manualColumnResize = colWidths;
25        }
26
27        if (layout.rowsHeader && layout.rowsVisible) {
28            handsontable_config.fixedRowsTop = parseInt(layout.rowsHeader);
29        }
30
31        handsontable_config.afterColumnResize = function (col, width) {
32            if ($layoutfield) {
33                layout.colwidth[col] = parseInt(width, 10) + 'px';
34                $layoutfield.val(JSON.stringify(layout));
35            }
36        };
37
38        var forcePreview = false;
39        var originalBeforeRemoveCol = handsontable_config.beforeRemoveCol;
40        handsontable_config.beforeRemoveCol = function (index, amount) {
41            if (originalBeforeRemoveCol) {
42                originalBeforeRemoveCol.call(this, index, amount);
43            }
44            layout.colwidth.splice(index, amount);
45            $layoutfield.val(JSON.stringify(layout));
46        };
47
48        var originalAfterRemoveCol = handsontable_config.afterRemoveCol;
49        handsontable_config.afterRemoveCol = function (index, amount) {
50            if (originalAfterRemoveCol) {
51                originalAfterRemoveCol.call(this, index, amount);
52            }
53            forcePreview = true;
54        };
55
56        var originalAfterCreateCol = handsontable_config.afterCreateCol;
57        handsontable_config.afterCreateCol = function (index, amount) {
58            if (originalAfterCreateCol) {
59                originalAfterCreateCol.call(this, index, amount);
60            }
61            layout.colwidth.splice(index, 0, null);
62            $layoutfield.val(JSON.stringify(layout));
63        };
64
65        handsontable_config.afterRender = function () {
66            if (forcePreview) {
67                forcePreview = false;
68                $form.find('button[name="do[preview]"]').click();
69            }
70        };
71
72    };
73
74    edittable_plugins.tablelayout = {modifyHandsontableConfig: modifyHandsontableConfig};
75}(window.edittable_plugins, window.tablelayout));
76