luci-base: cbi.js: untangle dropdown and dynlists from dependency update
[oweals/luci.git] / modules / luci-base / htdocs / luci-static / resources / cbi.js
1 /*
2         LuCI - Lua Configuration Interface
3
4         Copyright 2008 Steven Barth <steven@midlink.org>
5         Copyright 2008-2018 Jo-Philipp Wich <jo@mein.io>
6
7         Licensed under the Apache License, Version 2.0 (the "License");
8         you may not use this file except in compliance with the License.
9         You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 var cbi_d = [];
15 var cbi_strings = { path: {}, label: {} };
16
17 function s8(bytes, off) {
18         var n = bytes[off];
19         return (n > 0x7F) ? (n - 256) >>> 0 : n;
20 }
21
22 function u16(bytes, off) {
23         return ((bytes[off + 1] << 8) + bytes[off]) >>> 0;
24 }
25
26 function sfh(s) {
27         if (s === null || s.length === 0)
28                 return null;
29
30         var bytes = [];
31
32         for (var i = 0; i < s.length; i++) {
33                 var ch = s.charCodeAt(i);
34
35                 if (ch <= 0x7F)
36                         bytes.push(ch);
37                 else if (ch <= 0x7FF)
38                         bytes.push(((ch >>>  6) & 0x1F) | 0xC0,
39                                    ( ch         & 0x3F) | 0x80);
40                 else if (ch <= 0xFFFF)
41                         bytes.push(((ch >>> 12) & 0x0F) | 0xE0,
42                                    ((ch >>>  6) & 0x3F) | 0x80,
43                                    ( ch         & 0x3F) | 0x80);
44                 else if (code <= 0x10FFFF)
45                         bytes.push(((ch >>> 18) & 0x07) | 0xF0,
46                                    ((ch >>> 12) & 0x3F) | 0x80,
47                                    ((ch >>   6) & 0x3F) | 0x80,
48                                    ( ch         & 0x3F) | 0x80);
49         }
50
51         if (!bytes.length)
52                 return null;
53
54         var hash = (bytes.length >>> 0),
55             len = (bytes.length >>> 2),
56             off = 0, tmp;
57
58         while (len--) {
59                 hash += u16(bytes, off);
60                 tmp   = ((u16(bytes, off + 2) << 11) ^ hash) >>> 0;
61                 hash  = ((hash << 16) ^ tmp) >>> 0;
62                 hash += hash >>> 11;
63                 off  += 4;
64         }
65
66         switch ((bytes.length & 3) >>> 0) {
67         case 3:
68                 hash += u16(bytes, off);
69                 hash  = (hash ^ (hash << 16)) >>> 0;
70                 hash  = (hash ^ (s8(bytes, off + 2) << 18)) >>> 0;
71                 hash += hash >>> 11;
72                 break;
73
74         case 2:
75                 hash += u16(bytes, off);
76                 hash  = (hash ^ (hash << 11)) >>> 0;
77                 hash += hash >>> 17;
78                 break;
79
80         case 1:
81                 hash += s8(bytes, off);
82                 hash  = (hash ^ (hash << 10)) >>> 0;
83                 hash += hash >>> 1;
84                 break;
85         }
86
87         hash  = (hash ^ (hash << 3)) >>> 0;
88         hash += hash >>> 5;
89         hash  = (hash ^ (hash << 4)) >>> 0;
90         hash += hash >>> 17;
91         hash  = (hash ^ (hash << 25)) >>> 0;
92         hash += hash >>> 6;
93
94         return (0x100000000 + hash).toString(16).substr(1);
95 }
96
97 function _(s) {
98         return (window.TR && TR[sfh(s)]) || s;
99 }
100
101 function Int(x) {
102         return (/^-?\d+$/.test(x) ? +x : NaN);
103 }
104
105 function Dec(x) {
106         return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
107 }
108
109 function IPv4(x) {
110         if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
111                 return null;
112
113         if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
114                 return null;
115
116         return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
117 }
118
119 function IPv6(x) {
120         if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
121                 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
122
123                 if (!v4)
124                         return null;
125
126                 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
127                        + ':' + (v4[2] * 256 + v4[3]).toString(16);
128         }
129
130         if (!x.match(/^[a-fA-F0-9:]+$/))
131                 return null;
132
133         var prefix_suffix = x.split(/::/);
134
135         if (prefix_suffix.length > 2)
136                 return null;
137
138         var prefix = (prefix_suffix[0] || '0').split(/:/);
139         var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
140
141         if (suffix.length ? (prefix.length + suffix.length > 7)
142                           : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
143                 return null;
144
145         var i, word;
146         var words = [];
147
148         for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
149                 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
150                         words.push(word);
151                 else
152                         return null;
153
154         for (i = 0; i < (8 - prefix.length - suffix.length); i++)
155                 words.push(0);
156
157         for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
158                 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
159                         words.push(word);
160                 else
161                         return null;
162
163         return words;
164 }
165
166 var CBIValidatorPrototype = {
167         apply: function(name, value, args) {
168                 var func;
169
170                 if (typeof(name) === 'function')
171                         func = name;
172                 else if (typeof(this.types[name]) === 'function')
173                         func = this.types[name];
174                 else
175                         return false;
176
177                 if (value !== undefined && value !== null)
178                         this.value = value;
179
180                 return func.apply(this, args);
181         },
182
183         assert: function(condition, message) {
184                 if (!condition) {
185                         this.field.classList.add('cbi-input-invalid');
186                         this.error = message;
187                         return false;
188                 }
189
190                 this.field.classList.remove('cbi-input-invalid');
191                 this.error = null;
192                 return true;
193         },
194
195         compile: function(code) {
196                 var pos = 0;
197                 var esc = false;
198                 var depth = 0;
199                 var stack = [ ];
200
201                 code += ',';
202
203                 for (var i = 0; i < code.length; i++) {
204                         if (esc) {
205                                 esc = false;
206                                 continue;
207                         }
208
209                         switch (code.charCodeAt(i))
210                         {
211                         case 92:
212                                 esc = true;
213                                 break;
214
215                         case 40:
216                         case 44:
217                                 if (depth <= 0) {
218                                         if (pos < i) {
219                                                 var label = code.substring(pos, i);
220                                                         label = label.replace(/\\(.)/g, '$1');
221                                                         label = label.replace(/^[ \t]+/g, '');
222                                                         label = label.replace(/[ \t]+$/g, '');
223
224                                                 if (label && !isNaN(label)) {
225                                                         stack.push(parseFloat(label));
226                                                 }
227                                                 else if (label.match(/^(['"]).*\1$/)) {
228                                                         stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
229                                                 }
230                                                 else if (typeof this.types[label] == 'function') {
231                                                         stack.push(this.types[label]);
232                                                         stack.push(null);
233                                                 }
234                                                 else {
235                                                         throw "Syntax error, unhandled token '"+label+"'";
236                                                 }
237                                         }
238
239                                         pos = i+1;
240                                 }
241
242                                 depth += (code.charCodeAt(i) == 40);
243                                 break;
244
245                         case 41:
246                                 if (--depth <= 0) {
247                                         if (typeof stack[stack.length-2] != 'function')
248                                                 throw "Syntax error, argument list follows non-function";
249
250                                         stack[stack.length-1] = this.compile(code.substring(pos, i));
251                                         pos = i+1;
252                                 }
253
254                                 break;
255                         }
256                 }
257
258                 return stack;
259         },
260
261         validate: function() {
262                 /* element is detached */
263                 if (!findParent(this.field, 'form'))
264                         return true;
265
266                 this.field.classList.remove('cbi-input-invalid');
267                 this.value = matchesElem(this.field, 'select') ? this.field.options[this.field.selectedIndex].value : this.field.value;
268                 this.error = null;
269
270                 var valid;
271
272                 if (this.value.length === 0)
273                         valid = this.assert(this.optional, _('non-empty value'));
274                 else
275                         valid = this.vstack[0].apply(this, this.vstack[1]);
276
277                 if (!valid) {
278                         this.field.setAttribute('data-tooltip', _('Expecting %s').format(this.error));
279                         this.field.setAttribute('data-tooltip-style', 'error');
280                         this.field.dispatchEvent(new CustomEvent('validation-failure', { bubbles: true }));
281                 }
282                 else {
283                         this.field.removeAttribute('data-tooltip');
284                         this.field.removeAttribute('data-tooltip-style');
285                         this.field.dispatchEvent(new CustomEvent('validation-success', { bubbles: true }));
286                 }
287
288                 return valid;
289         },
290
291         types: {
292                 integer: function() {
293                         return this.assert(Int(this.value) !== NaN, _('valid integer value'));
294                 },
295
296                 uinteger: function() {
297                         return this.assert(Int(this.value) >= 0, _('positive integer value'));
298                 },
299
300                 float: function() {
301                         return this.assert(Dec(this.value) !== NaN, _('valid decimal value'));
302                 },
303
304                 ufloat: function() {
305                         return this.assert(Dec(this.value) >= 0, _('positive decimal value'));
306                 },
307
308                 ipaddr: function(nomask) {
309                         return this.assert(this.apply('ip4addr', null, [nomask]) || this.apply('ip6addr', null, [nomask]),
310                                 nomask ? _('valid IP address') : _('valid IP address or prefix'));
311                 },
312
313                 ip4addr: function(nomask) {
314                         var re = nomask ? /^(\d+\.\d+\.\d+\.\d+)$/ : /^(\d+\.\d+\.\d+\.\d+)(?:\/(\d+\.\d+\.\d+\.\d+)|\/(\d{1,2}))?$/,
315                             m = this.value.match(re);
316
317                         return this.assert(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? this.apply('ip4prefix', m[3]) : true)),
318                                 nomask ? _('valid IPv4 address') : _('valid IPv4 address or network'));
319                 },
320
321                 ip6addr: function(nomask) {
322                         var re = nomask ? /^([0-9a-fA-F:.]+)$/ : /^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/,
323                             m = this.value.match(re);
324
325                         return this.assert(m && IPv6(m[1]) && (m[2] ? this.apply('ip6prefix', m[2]) : true),
326                                 nomask ? _('valid IPv6 address') : _('valid IPv6 address or prefix'));
327                 },
328
329                 ip4prefix: function() {
330                         return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 32,
331                                 _('valid IPv4 prefix value (0-32)'));
332                 },
333
334                 ip6prefix: function() {
335                         return this.assert(!isNaN(this.value) && this.value >= 0 && this.value <= 128,
336                                 _('valid IPv6 prefix value (0-128)'));
337                 },
338
339                 cidr: function() {
340                         return this.assert(this.apply('cidr4') || this.apply('cidr6'), _('valid IPv4 or IPv6 CIDR'));
341                 },
342
343                 cidr4: function() {
344                         var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
345                         return this.assert(m && IPv4(m[1]) && this.apply('ip4prefix', m[2]), _('valid IPv4 CIDR'));
346                 },
347
348                 cidr6: function() {
349                         var m = this.value.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
350                         return this.assert(m && IPv6(m[1]) && this.apply('ip6prefix', m[2]), _('valid IPv6 CIDR'));
351                 },
352
353                 ipnet4: function() {
354                         var m = this.value.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
355                         return this.assert(m && IPv4(m[1]) && IPv4(m[2]), _('IPv4 network in address/netmask notation'));
356                 },
357
358                 ipnet6: function() {
359                         var m = this.value.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
360                         return this.assert(m && IPv6(m[1]) && IPv6(m[2]), _('IPv6 network in address/netmask notation'));
361                 },
362
363                 ip6hostid: function() {
364                         if (this.value == "eui64" || this.value == "random")
365                                 return true;
366
367                         var v6 = IPv6(this.value);
368                         return this.assert(!(!v6 || v6[0] || v6[1] || v6[2] || v6[3]), _('valid IPv6 host id'));
369                 },
370
371                 ipmask: function() {
372                         return this.assert(this.apply('ipmask4') || this.apply('ipmask6'),
373                                 _('valid network in address/netmask notation'));
374                 },
375
376                 ipmask4: function() {
377                         return this.assert(this.apply('cidr4') || this.apply('ipnet4') || this.apply('ip4addr'),
378                                 _('valid IPv4 network'));
379                 },
380
381                 ipmask6: function() {
382                         return this.assert(this.apply('cidr6') || this.apply('ipnet6') || this.apply('ip6addr'),
383                                 _('valid IPv6 network'));
384                 },
385
386                 port: function() {
387                         var p = Int(this.value);
388                         return this.assert(p >= 0 && p <= 65535, _('valid port value'));
389                 },
390
391                 portrange: function() {
392                         if (this.value.match(/^(\d+)-(\d+)$/)) {
393                                 var p1 = +RegExp.$1;
394                                 var p2 = +RegExp.$2;
395                                 return this.assert(p1 <= p2 && p2 <= 65535,
396                                         _('valid port or port range (port1-port2)'));
397                         }
398
399                         return this.assert(this.apply('port'), _('valid port or port range (port1-port2)'));
400                 },
401
402                 macaddr: function() {
403                         return this.assert(this.value.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null,
404                                 _('valid MAC address'));
405                 },
406
407                 host: function(ipv4only) {
408                         return this.assert(this.apply('hostname') || this.apply(ipv4only == 1 ? 'ip4addr' : 'ipaddr'),
409                                 _('valid hostname or IP address'));
410                 },
411
412                 hostname: function(strict) {
413                         if (this.value.length <= 253)
414                                 return this.assert(
415                                         (this.value.match(/^[a-zA-Z0-9_]+$/) != null ||
416                                                 (this.value.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
417                                                  this.value.match(/[^0-9.]/))) &&
418                                         (!strict || !this.value.match(/^_/)),
419                                         _('valid hostname'));
420
421                         return this.assert(false, _('valid hostname'));
422                 },
423
424                 network: function() {
425                         return this.assert(this.apply('uciname') || this.apply('host'),
426                                 _('valid UCI identifier, hostname or IP address'));
427                 },
428
429                 hostport: function(ipv4only) {
430                         var hp = this.value.split(/:/);
431                         return this.assert(hp.length == 2 && this.apply('host', hp[0], [ipv4only]) && this.apply('port', hp[1]),
432                                 _('valid host:port'));
433                 },
434
435                 ip4addrport: function() {
436                         var hp = this.value.split(/:/);
437                         return this.assert(hp.length == 2 && this.apply('ip4addr', hp[0], [true]) && this.apply('port', hp[1]),
438                                 _('valid IPv4 address:port'));
439                 },
440
441                 ipaddrport: function(bracket) {
442                         var m4 = this.value.match(/^([^\[\]:]+):(\d+)$/),
443                             m6 = this.value.match((bracket == 1) ? /^\[(.+)\]:(\d+)$/ : /^([^\[\]]+):(\d+)$/);
444
445                         if (m4)
446                                 return this.assert(this.apply('ip4addr', m4[1], [true]) && this.apply('port', m4[2]),
447                                         _('valid address:port'));
448
449                         return this.assert(m6 && this.apply('ip6addr', m6[1], [true]) && this.apply('port', m6[2]),
450                                 _('valid address:port'));
451                 },
452
453                 wpakey: function() {
454                         var v = this.value;
455
456                         if (v.length == 64)
457                                 return this.assert(v.match(/^[a-fA-F0-9]{64}$/), _('valid hexadecimal WPA key'));
458
459                         return this.assert((v.length >= 8) && (v.length <= 63), _('key between 8 and 63 characters'));
460                 },
461
462                 wepkey: function() {
463                         var v = this.value;
464
465                         if (v.substr(0, 2) === 's:')
466                                 v = v.substr(2);
467
468                         if ((v.length == 10) || (v.length == 26))
469                                 return this.assert(v.match(/^[a-fA-F0-9]{10,26}$/), _('valid hexadecimal WEP key'));
470
471                         return this.assert((v.length === 5) || (v.length === 13), _('key with either 5 or 13 characters'));
472                 },
473
474                 uciname: function() {
475                         return this.assert(this.value.match(/^[a-zA-Z0-9_]+$/), _('valid UCI identifier'));
476                 },
477
478                 range: function(min, max) {
479                         var val = Dec(this.value);
480                         return this.assert(val >= +min && val <= +max, _('value between %f and %f').format(min, max));
481                 },
482
483                 min: function(min) {
484                         return this.assert(Dec(this.value) >= +min, _('value greater or equal to %f').format(min));
485                 },
486
487                 max: function(max) {
488                         return this.assert(Dec(this.value) <= +max, _('value smaller or equal to %f').format(max));
489                 },
490
491                 rangelength: function(min, max) {
492                         var val = '' + this.value;
493                         return this.assert((val.length >= +min) && (val.length <= +max),
494                                 _('value between %d and %d characters').format(min, max));
495                 },
496
497                 minlength: function(min) {
498                         return this.assert((''+this.value).length >= +min,
499                                 _('value with at least %d characters').format(min));
500                 },
501
502                 maxlength: function(max) {
503                         return this.assert((''+this.value).length <= +max,
504                                 _('value with at most %d characters').format(max));
505                 },
506
507                 or: function() {
508                         var errors = [];
509
510                         for (var i = 0; i < arguments.length; i += 2) {
511                                 if (typeof arguments[i] != 'function') {
512                                         if (arguments[i] == this.value)
513                                                 return this.assert(true);
514                                         errors.push('"%s"'.format(arguments[i]));
515                                         i--;
516                                 }
517                                 else if (arguments[i].apply(this, arguments[i+1])) {
518                                         return this.assert(true);
519                                 }
520                                 else {
521                                         errors.push(this.error);
522                                 }
523                         }
524
525                         return this.assert(false, _('one of:\n - %s'.format(errors.join('\n - '))));
526                 },
527
528                 and: function() {
529                         for (var i = 0; i < arguments.length; i += 2) {
530                                 if (typeof arguments[i] != 'function') {
531                                         if (arguments[i] != this.value)
532                                                 return this.assert(false, '"%s"'.format(arguments[i]));
533                                         i--;
534                                 }
535                                 else if (!arguments[i].apply(this, arguments[i+1])) {
536                                         return this.assert(false, this.error);
537                                 }
538                         }
539
540                         return this.assert(true);
541                 },
542
543                 neg: function() {
544                         return this.apply('or', this.value.replace(/^[ \t]*![ \t]*/, ''), arguments);
545                 },
546
547                 list: function(subvalidator, subargs) {
548                         this.field.setAttribute('data-is-list', 'true');
549
550                         var tokens = this.value.match(/[^ \t]+/g);
551                         for (var i = 0; i < tokens.length; i++)
552                                 if (!this.apply(subvalidator, tokens[i], subargs))
553                                         return this.assert(false, this.error);
554
555                         return this.assert(true);
556                 },
557
558                 phonedigit: function() {
559                         return this.assert(this.value.match(/^[0-9\*#!\.]+$/),
560                                 _('valid phone digit (0-9, "*", "#", "!" or ".")'));
561                 },
562
563                 timehhmmss: function() {
564                         return this.assert(this.value.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/),
565                                 _('valid time (HH:MM:SS)'));
566                 },
567
568                 dateyyyymmdd: function() {
569                         if (this.value.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
570                                 var year  = +RegExp.$1,
571                                     month = +RegExp.$2,
572                                     day   = +RegExp.$3,
573                                     days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
574
575                                 function is_leap_year(year) {
576                                         return ((!(year % 4) && (year % 100)) || !(year % 400));
577                                 }
578
579                                 function get_days_in_month(month, year) {
580                                         return (month === 2 && is_leap_year(year)) ? 29 : days_in_month[month - 1];
581                                 }
582
583                                 /* Firewall rules in the past don't make sense */
584                                 return this.assert(year >= 2015 && month && month <= 12 && day && day <= get_days_in_month(month, year),
585                                         _('valid date (YYYY-MM-DD)'));
586
587                         }
588
589                         return this.assert(false, _('valid date (YYYY-MM-DD)'));
590                 },
591
592                 unique: function(subvalidator, subargs) {
593                         var ctx = this,
594                                 option = findParent(ctx.field, '[data-type][data-name]'),
595                             section = findParent(option, '.cbi-section'),
596                             query = '[data-type="%s"][data-name="%s"]'.format(option.getAttribute('data-type'), option.getAttribute('data-name')),
597                             unique = true;
598
599                         section.querySelectorAll(query).forEach(function(sibling) {
600                                 if (sibling === option)
601                                         return;
602
603                                 var input = sibling.querySelector('[data-type]'),
604                                     values = input ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
605
606                                 if (values !== null && values.indexOf(ctx.value) !== -1)
607                                         unique = false;
608                         });
609
610                         if (!unique)
611                                 return this.assert(false, _('unique value'));
612
613                         if (typeof(subvalidator) === 'function')
614                                 return this.apply(subvalidator, undefined, subargs);
615
616                         return this.assert(true);
617                 },
618
619                 hexstring: function() {
620                         return this.assert(this.value.match(/^([a-f0-9][a-f0-9]|[A-F0-9][A-F0-9])+$/),
621                                 _('hexadecimal encoded value'));
622                 }
623         }
624 };
625
626 function CBIValidator(field, type, optional)
627 {
628         this.field = field;
629         this.optional = optional;
630         this.vstack = this.compile(type);
631 }
632
633 CBIValidator.prototype = CBIValidatorPrototype;
634
635
636 function cbi_d_add(field, dep, index) {
637         var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
638         if (obj) {
639                 var entry
640                 for (var i=0; i<cbi_d.length; i++) {
641                         if (cbi_d[i].id == obj.id) {
642                                 entry = cbi_d[i];
643                                 break;
644                         }
645                 }
646                 if (!entry) {
647                         entry = {
648                                 "node": obj,
649                                 "id": obj.id,
650                                 "parent": obj.parentNode.id,
651                                 "deps": [],
652                                 "index": index
653                         };
654                         cbi_d.unshift(entry);
655                 }
656                 entry.deps.push(dep)
657         }
658 }
659
660 function cbi_d_checkvalue(target, ref) {
661         var value = null,
662             query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
663                     'select[id="'+target+'"], select[name="'+target+'"]';
664
665         document.querySelectorAll(query).forEach(function(i) {
666                 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
667                         value = i.value;
668         });
669
670         return (((value !== null) ? value : "") == ref);
671 }
672
673 function cbi_d_check(deps) {
674         var reverse;
675         var def = false;
676         for (var i=0; i<deps.length; i++) {
677                 var istat = true;
678                 reverse = false;
679                 for (var j in deps[i]) {
680                         if (j == "!reverse") {
681                                 reverse = true;
682                         } else if (j == "!default") {
683                                 def = true;
684                                 istat = false;
685                         } else {
686                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
687                         }
688                 }
689
690                 if (istat ^ reverse) {
691                         return true;
692                 }
693         }
694         return def;
695 }
696
697 function cbi_d_update() {
698         var state = false;
699         for (var i=0; i<cbi_d.length; i++) {
700                 var entry = cbi_d[i];
701                 var node  = document.getElementById(entry.id);
702                 var parent = document.getElementById(entry.parent);
703
704                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
705                         node.parentNode.removeChild(node);
706                         state = true;
707                 }
708                 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
709                         var next = undefined;
710
711                         for (next = parent.firstChild; next; next = next.nextSibling) {
712                                 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
713                                         break;
714                         }
715
716                         if (!next)
717                                 parent.appendChild(entry.node);
718                         else
719                                 parent.insertBefore(entry.node, next);
720
721                         state = true;
722                 }
723
724                 // hide optionals widget if no choices remaining
725                 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
726                         parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
727         }
728
729         if (entry && entry.parent)
730                 cbi_tag_last(parent);
731
732         if (state)
733                 cbi_d_update();
734         else if (parent)
735                 parent.dispatchEvent(new CustomEvent('dependency-update', { bubbles: true }));
736 }
737
738 function cbi_init() {
739         var nodes;
740
741         nodes = document.querySelectorAll('[data-strings]');
742
743         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
744                 var str = JSON.parse(node.getAttribute('data-strings'));
745                 for (var key in str) {
746                         for (var key2 in str[key]) {
747                                 var dst = cbi_strings[key] || (cbi_strings[key] = { });
748                                     dst[key2] = str[key][key2];
749                         }
750                 }
751         }
752
753         nodes = document.querySelectorAll('[data-depends]');
754
755         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
756                 var index = parseInt(node.getAttribute('data-index'), 10);
757                 var depends = JSON.parse(node.getAttribute('data-depends'));
758                 if (!isNaN(index) && depends.length > 0) {
759                         for (var alt = 0; alt < depends.length; alt++)
760                                 cbi_d_add(node, depends[alt], index);
761                 }
762         }
763
764         nodes = document.querySelectorAll('[data-update]');
765
766         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
767                 var events = node.getAttribute('data-update').split(' ');
768                 for (var j = 0, event; (event = events[j]) !== undefined; j++)
769                         node.addEventListener(event, cbi_d_update);
770         }
771
772         nodes = document.querySelectorAll('[data-choices]');
773
774         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
775                 var choices = JSON.parse(node.getAttribute('data-choices'));
776                 var options = {};
777
778                 for (var j = 0; j < choices[0].length; j++)
779                         options[choices[0][j]] = choices[1][j];
780
781                 var def = (node.getAttribute('data-optional') === 'true')
782                         ? node.placeholder || '' : null;
783
784                 cbi_combobox_init(node, options, def,
785                                   node.getAttribute('data-manual'));
786         }
787
788         nodes = document.querySelectorAll('[data-dynlist]');
789
790         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
791                 var choices = JSON.parse(node.getAttribute('data-dynlist'));
792                 var options = null;
793
794                 if (choices[0] && choices[0].length) {
795                         options = {};
796
797                         for (var j = 0; j < choices[0].length; j++)
798                                 options[choices[0][j]] = choices[1][j];
799                 }
800
801                 cbi_dynlist_init(node, choices[2], choices[3], options);
802                 node.addEventListener('cbi-dynlist-change', cbi_d_update);
803         }
804
805         nodes = document.querySelectorAll('[data-type]');
806
807         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
808                 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
809                                    node.getAttribute('data-type'));
810         }
811
812         document.querySelectorAll('.cbi-dropdown').forEach(function(node) {
813                 cbi_dropdown_init(node);
814                 node.addEventListener('cbi-dropdown-change', cbi_d_update);
815         });
816
817         document.querySelectorAll('[data-browser]').forEach(cbi_browser_init);
818
819         document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
820                 s.parentNode.classList.add('cbi-tooltip-container');
821         });
822
823         document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
824                 var handler = function(ev) {
825                         var bits = this.name.split(/\./),
826                             section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
827
828                     section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
829                 };
830
831                 i.addEventListener('mouseover', handler);
832                 i.addEventListener('mouseout', handler);
833         });
834
835         cbi_d_update();
836 }
837
838 function cbi_combobox_init(id, values, def, man) {
839         var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
840         var sb = E('div', {
841                 'name': obj.name,
842                 'class': 'cbi-dropdown',
843                 'display-items': 5,
844                 'optional': obj.getAttribute('data-optional'),
845                 'placeholder': _('-- Please choose --'),
846                 'data-type': obj.getAttribute('data-type'),
847                 'data-optional': obj.getAttribute('data-optional')
848         }, [ E('ul') ]);
849
850         if (!(obj.value in values) && obj.value.length) {
851                 sb.lastElementChild.appendChild(E('li', {
852                         'data-value': obj.value,
853                         'selected': ''
854                 }, obj.value.length ? obj.value : (def || _('-- Please choose --'))));
855         }
856
857         for (var i in values) {
858                 sb.lastElementChild.appendChild(E('li', {
859                         'data-value': i,
860                         'selected': (i == obj.value) ? '' : null
861                 }, values[i]));
862         }
863
864         sb.lastElementChild.appendChild(E('li', { 'data-value': '-' }, [
865                 E('input', {
866                         'type': 'text',
867                         'class': 'create-item-input',
868                         'data-type': obj.getAttribute('data-type'),
869                         'data-optional': true,
870                         'placeholder': (man || _('-- custom --'))
871                 })
872         ]));
873
874         sb.value = obj.value;
875         obj.parentNode.replaceChild(sb, obj);
876 }
877
878 function cbi_filebrowser(id, defpath) {
879         var field   = L.dom.elem(id) ? id : document.getElementById(id);
880         var browser = window.open(
881                 cbi_strings.path.browser + (field.value || defpath || '') + '?field=' + field.id,
882                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
883         );
884
885         browser.focus();
886 }
887
888 function cbi_browser_init(field)
889 {
890         field.parentNode.insertBefore(
891                 E('img', {
892                         'src': L.resource('cbi/folder.gif'),
893                         'class': 'cbi-image-button',
894                         'click': function(ev) {
895                                 cbi_filebrowser(field, field.getAttribute('data-browser'));
896                                 ev.preventDefault();
897                         }
898                 }), field.nextSibling);
899 }
900
901 CBIDynamicList = {
902         addItem: function(dl, value, text, flash) {
903                 var exists = false,
904                     new_item = E('div', { 'class': flash ? 'item flash' : 'item', 'tabindex': 0 }, [
905                                 E('span', {}, text || value),
906                                 E('input', {
907                                         'type': 'hidden',
908                                         'name': dl.getAttribute('data-prefix'),
909                                         'value': value })]);
910
911                 dl.querySelectorAll('.item, .add-item').forEach(function(item) {
912                         if (exists)
913                                 return;
914
915                         var hidden = item.querySelector('input[type="hidden"]');
916
917                         if (hidden && hidden.value === value)
918                                 exists = true;
919                         else if (!hidden || hidden.value >= value)
920                                 exists = !!item.parentNode.insertBefore(new_item, item);
921                 });
922
923                 dl.dispatchEvent(new CustomEvent('cbi-dynlist-change', {
924                         bubbles: true,
925                         detail: {
926                                 instance: this,
927                                 element: dl,
928                                 value: value,
929                                 add: true
930                         }
931                 }));
932         },
933
934         removeItem: function(dl, item) {
935                 var value = item.querySelector('input[type="hidden"]').value;
936                 var sb = dl.querySelector('.cbi-dropdown');
937                 if (sb)
938                         sb.querySelectorAll('ul > li').forEach(function(li) {
939                                 if (li.getAttribute('data-value') === value)
940                                         li.removeAttribute('unselectable');
941                         });
942
943                 item.parentNode.removeChild(item);
944
945                 dl.dispatchEvent(new CustomEvent('cbi-dynlist-change', {
946                         bubbles: true,
947                         detail: {
948                                 instance: this,
949                                 element: dl,
950                                 value: value,
951                                 remove: true
952                         }
953                 }));
954         },
955
956         handleClick: function(ev) {
957                 var dl = ev.currentTarget,
958                     item = findParent(ev.target, '.item');
959
960                 if (item) {
961                         this.removeItem(dl, item);
962                 }
963                 else if (matchesElem(ev.target, '.cbi-button-add')) {
964                         var input = ev.target.previousElementSibling;
965                         if (input.value.length && !input.classList.contains('cbi-input-invalid')) {
966                                 this.addItem(dl, input.value, null, true);
967                                 input.value = '';
968                         }
969                 }
970         },
971
972         handleDropdownChange: function(ev) {
973                 var dl = ev.currentTarget,
974                     sbIn = ev.detail.instance,
975                     sbEl = ev.detail.element,
976                     sbVal = ev.detail.value;
977
978                 if (sbVal === null)
979                         return;
980
981                 sbIn.setValues(sbEl, null);
982                 sbVal.element.setAttribute('unselectable', '');
983
984                 this.addItem(dl, sbVal.value, sbVal.text, true);
985         },
986
987         handleKeydown: function(ev) {
988                 var dl = ev.currentTarget,
989                     item = findParent(ev.target, '.item');
990
991                 if (item) {
992                         switch (ev.keyCode) {
993                         case 8: /* backspace */
994                                 if (item.previousElementSibling)
995                                         item.previousElementSibling.focus();
996
997                                 this.removeItem(dl, item);
998                                 break;
999
1000                         case 46: /* delete */
1001                                 if (item.nextElementSibling) {
1002                                         if (item.nextElementSibling.classList.contains('item'))
1003                                                 item.nextElementSibling.focus();
1004                                         else
1005                                                 item.nextElementSibling.firstElementChild.focus();
1006                                 }
1007
1008                                 this.removeItem(dl, item);
1009                                 break;
1010                         }
1011                 }
1012                 else if (matchesElem(ev.target, '.cbi-input-text')) {
1013                         switch (ev.keyCode) {
1014                         case 13: /* enter */
1015                                 if (ev.target.value.length && !ev.target.classList.contains('cbi-input-invalid')) {
1016                                         this.addItem(dl, ev.target.value, null, true);
1017                                         ev.target.value = '';
1018                                         ev.target.blur();
1019                                         ev.target.focus();
1020                                 }
1021
1022                                 ev.preventDefault();
1023                                 break;
1024                         }
1025                 }
1026         }
1027 };
1028
1029 function cbi_dynlist_init(dl, datatype, optional, choices)
1030 {
1031         if (!(this instanceof cbi_dynlist_init))
1032                 return new cbi_dynlist_init(dl, datatype, optional, choices);
1033
1034         dl.classList.add('cbi-dynlist');
1035         dl.appendChild(E('div', { 'class': 'add-item' }, E('input', {
1036                 'type': 'text',
1037                 'name': 'cbi.dynlist.' + dl.getAttribute('data-prefix'),
1038                 'class': 'cbi-input-text',
1039                 'placeholder': dl.getAttribute('data-placeholder'),
1040                 'data-type': datatype,
1041                 'data-optional': true
1042         })));
1043
1044         if (choices)
1045                 cbi_combobox_init(dl.lastElementChild.lastElementChild, choices, '', _('-- custom --'));
1046         else
1047                 dl.lastElementChild.appendChild(E('div', { 'class': 'cbi-button cbi-button-add' }, '+'));
1048
1049         dl.addEventListener('click', this.handleClick.bind(this));
1050         dl.addEventListener('keydown', this.handleKeydown.bind(this));
1051         dl.addEventListener('cbi-dropdown-change', this.handleDropdownChange.bind(this));
1052
1053         try {
1054                 var values = JSON.parse(dl.getAttribute('data-values') || '[]');
1055
1056                 if (typeof(values) === 'object' && Array.isArray(values))
1057                         for (var i = 0; i < values.length; i++)
1058                                 this.addItem(dl, values[i], choices ? choices[values[i]] : null);
1059         }
1060         catch (e) {}
1061 }
1062
1063 cbi_dynlist_init.prototype = CBIDynamicList;
1064
1065
1066 function cbi_validate_form(form, errmsg)
1067 {
1068         /* if triggered by a section removal or addition, don't validate */
1069         if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1070                 return true;
1071
1072         if (form.cbi_validators) {
1073                 for (var i = 0; i < form.cbi_validators.length; i++) {
1074                         var validator = form.cbi_validators[i];
1075
1076                         if (!validator() && errmsg) {
1077                                 alert(errmsg);
1078                                 return false;
1079                         }
1080                 }
1081         }
1082
1083         return true;
1084 }
1085
1086 function cbi_validate_reset(form)
1087 {
1088         window.setTimeout(
1089                 function() { cbi_validate_form(form, null) }, 100
1090         );
1091
1092         return true;
1093 }
1094
1095 function cbi_validate_field(cbid, optional, type)
1096 {
1097         var field = isElem(cbid) ? cbid : document.getElementById(cbid);
1098         var validatorFn;
1099
1100         try {
1101                 var cbiValidator = new CBIValidator(field, type, optional);
1102                 validatorFn = cbiValidator.validate.bind(cbiValidator);
1103         }
1104         catch(e) {
1105                 validatorFn = null;
1106         };
1107
1108         if (validatorFn !== null) {
1109                 var form = findParent(field, 'form');
1110
1111                 if (!form.cbi_validators)
1112                         form.cbi_validators = [ ];
1113
1114                 form.cbi_validators.push(validatorFn);
1115
1116                 field.addEventListener("blur",  validatorFn);
1117                 field.addEventListener("keyup", validatorFn);
1118                 field.addEventListener("cbi-dropdown-change", validatorFn);
1119
1120                 if (matchesElem(field, 'select')) {
1121                         field.addEventListener("change", validatorFn);
1122                         field.addEventListener("click",  validatorFn);
1123                 }
1124
1125                 validatorFn();
1126         }
1127 }
1128
1129 function cbi_row_swap(elem, up, store)
1130 {
1131         var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1132
1133         if (!tr)
1134                 return false;
1135
1136         tr.classList.remove('flash');
1137
1138         if (up) {
1139                 var prev = tr.previousElementSibling;
1140
1141                 if (prev && prev.classList.contains('cbi-section-table-row'))
1142                         tr.parentNode.insertBefore(tr, prev);
1143                 else
1144                         return;
1145         }
1146         else {
1147                 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1148
1149                 if (next && next.classList.contains('cbi-section-table-row'))
1150                         tr.parentNode.insertBefore(tr, next);
1151                 else if (!next)
1152                         tr.parentNode.appendChild(tr);
1153                 else
1154                         return;
1155         }
1156
1157         var ids = [ ];
1158
1159         for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1160                 var node = tr.parentNode.childNodes[i];
1161                 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1162                         node.classList.remove('cbi-rowstyle-1');
1163                         node.classList.remove('cbi-rowstyle-2');
1164                         node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1165
1166                         if (/-([^\-]+)$/.test(node.id))
1167                                 ids.push(RegExp.$1);
1168                 }
1169         }
1170
1171         var input = document.getElementById(store);
1172         if (input)
1173                 input.value = ids.join(' ');
1174
1175         window.scrollTo(0, tr.offsetTop);
1176         void tr.offsetWidth;
1177         tr.classList.add('flash');
1178
1179         return false;
1180 }
1181
1182 function cbi_tag_last(container)
1183 {
1184         var last;
1185
1186         for (var i = 0; i < container.childNodes.length; i++) {
1187                 var c = container.childNodes[i];
1188                 if (matchesElem(c, 'div')) {
1189                         c.classList.remove('cbi-value-last');
1190                         last = c;
1191                 }
1192         }
1193
1194         if (last)
1195                 last.classList.add('cbi-value-last');
1196 }
1197
1198 function cbi_submit(elem, name, value, action)
1199 {
1200         var form = elem.form || findParent(elem, 'form');
1201
1202         if (!form)
1203                 return false;
1204
1205         if (action)
1206                 form.action = action;
1207
1208         if (name) {
1209                 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1210                         E('input', { type: 'hidden', name: name });
1211
1212                 hidden.value = value || '1';
1213                 form.appendChild(hidden);
1214         }
1215
1216         form.submit();
1217         return true;
1218 }
1219
1220 String.prototype.format = function()
1221 {
1222         if (!RegExp)
1223                 return;
1224
1225         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1226         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1227
1228         function esc(s, r) {
1229                 if (typeof(s) !== 'string' && !(s instanceof String))
1230                         return '';
1231
1232                 for (var i = 0; i < r.length; i += 2)
1233                         s = s.replace(r[i], r[i+1]);
1234
1235                 return s;
1236         }
1237
1238         var str = this;
1239         var out = '';
1240         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1241         var a = b = [], numSubstitutions = 0, numMatches = 0;
1242
1243         while (a = re.exec(str)) {
1244                 var m = a[1];
1245                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1246                 var pPrecision = a[6], pType = a[7];
1247
1248                 numMatches++;
1249
1250                 if (pType == '%') {
1251                         subst = '%';
1252                 }
1253                 else {
1254                         if (numSubstitutions < arguments.length) {
1255                                 var param = arguments[numSubstitutions++];
1256
1257                                 var pad = '';
1258                                 if (pPad && pPad.substr(0,1) == "'")
1259                                         pad = leftpart.substr(1,1);
1260                                 else if (pPad)
1261                                         pad = pPad;
1262                                 else
1263                                         pad = ' ';
1264
1265                                 var justifyRight = true;
1266                                 if (pJustify && pJustify === "-")
1267                                         justifyRight = false;
1268
1269                                 var minLength = -1;
1270                                 if (pMinLength)
1271                                         minLength = +pMinLength;
1272
1273                                 var precision = -1;
1274                                 if (pPrecision && pType == 'f')
1275                                         precision = +pPrecision.substring(1);
1276
1277                                 var subst = param;
1278
1279                                 switch(pType) {
1280                                         case 'b':
1281                                                 subst = (+param || 0).toString(2);
1282                                                 break;
1283
1284                                         case 'c':
1285                                                 subst = String.fromCharCode(+param || 0);
1286                                                 break;
1287
1288                                         case 'd':
1289                                                 subst = ~~(+param || 0);
1290                                                 break;
1291
1292                                         case 'u':
1293                                                 subst = ~~Math.abs(+param || 0);
1294                                                 break;
1295
1296                                         case 'f':
1297                                                 subst = (precision > -1)
1298                                                         ? ((+param || 0.0)).toFixed(precision)
1299                                                         : (+param || 0.0);
1300                                                 break;
1301
1302                                         case 'o':
1303                                                 subst = (+param || 0).toString(8);
1304                                                 break;
1305
1306                                         case 's':
1307                                                 subst = param;
1308                                                 break;
1309
1310                                         case 'x':
1311                                                 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1312                                                 break;
1313
1314                                         case 'X':
1315                                                 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1316                                                 break;
1317
1318                                         case 'h':
1319                                                 subst = esc(param, html_esc);
1320                                                 break;
1321
1322                                         case 'q':
1323                                                 subst = esc(param, quot_esc);
1324                                                 break;
1325
1326                                         case 't':
1327                                                 var td = 0;
1328                                                 var th = 0;
1329                                                 var tm = 0;
1330                                                 var ts = (param || 0);
1331
1332                                                 if (ts > 60) {
1333                                                         tm = Math.floor(ts / 60);
1334                                                         ts = (ts % 60);
1335                                                 }
1336
1337                                                 if (tm > 60) {
1338                                                         th = Math.floor(tm / 60);
1339                                                         tm = (tm % 60);
1340                                                 }
1341
1342                                                 if (th > 24) {
1343                                                         td = Math.floor(th / 24);
1344                                                         th = (th % 24);
1345                                                 }
1346
1347                                                 subst = (td > 0)
1348                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1349                                                         : String.format('%dh %dm %ds', th, tm, ts);
1350
1351                                                 break;
1352
1353                                         case 'm':
1354                                                 var mf = pMinLength ? +pMinLength : 1000;
1355                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1356
1357                                                 var i = 0;
1358                                                 var val = (+param || 0);
1359                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1360
1361                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1362                                                         val /= mf;
1363
1364                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
1365                                                 pMinLength = null;
1366                                                 break;
1367                                 }
1368                         }
1369                 }
1370
1371                 if (pMinLength) {
1372                         subst = subst.toString();
1373                         for (var i = subst.length; i < pMinLength; i++)
1374                                 if (pJustify == '-')
1375                                         subst = subst + ' ';
1376                                 else
1377                                         subst = pad + subst;
1378                 }
1379
1380                 out += leftpart + subst;
1381                 str = str.substr(m.length);
1382         }
1383
1384         return out + str;
1385 }
1386
1387 String.prototype.nobr = function()
1388 {
1389         return this.replace(/[\s\n]+/g, '&#160;');
1390 }
1391
1392 String.format = function()
1393 {
1394         var a = [ ];
1395
1396         for (var i = 1; i < arguments.length; i++)
1397                 a.push(arguments[i]);
1398
1399         return ''.format.apply(arguments[0], a);
1400 }
1401
1402 String.nobr = function()
1403 {
1404         var a = [ ];
1405
1406         for (var i = 1; i < arguments.length; i++)
1407                 a.push(arguments[i]);
1408
1409         return ''.nobr.apply(arguments[0], a);
1410 }
1411
1412 if (window.NodeList && !NodeList.prototype.forEach) {
1413         NodeList.prototype.forEach = function (callback, thisArg) {
1414                 thisArg = thisArg || window;
1415                 for (var i = 0; i < this.length; i++) {
1416                         callback.call(thisArg, this[i], i, this);
1417                 }
1418         };
1419 }
1420
1421 if (!window.requestAnimationFrame) {
1422         window.requestAnimationFrame = function(f) {
1423                 window.setTimeout(function() {
1424                         f(new Date().getTime())
1425                 }, 1000/30);
1426         };
1427 }
1428
1429
1430 function isElem(e) { return L.dom.elem(e) }
1431 function toElem(s) { return L.dom.parse(s) }
1432 function matchesElem(node, selector) { return L.dom.matches(node, selector) }
1433 function findParent(node, selector) { return L.dom.parent(node, selector) }
1434 function E() { return L.dom.create.apply(L.dom, arguments) }
1435
1436 if (typeof(window.CustomEvent) !== 'function') {
1437         function CustomEvent(event, params) {
1438                 params = params || { bubbles: false, cancelable: false, detail: undefined };
1439                 var evt = document.createEvent('CustomEvent');
1440                     evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1441                 return evt;
1442         }
1443
1444         CustomEvent.prototype = window.Event.prototype;
1445         window.CustomEvent = CustomEvent;
1446 }
1447
1448 CBIDropdown = {
1449         openDropdown: function(sb) {
1450                 var st = window.getComputedStyle(sb, null),
1451                     ul = sb.querySelector('ul'),
1452                     li = ul.querySelectorAll('li'),
1453                     fl = findParent(sb, '.cbi-value-field'),
1454                     sel = ul.querySelector('[selected]'),
1455                     rect = sb.getBoundingClientRect(),
1456                     items = Math.min(this.dropdown_items, li.length);
1457
1458                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1459                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1460                 });
1461
1462                 sb.setAttribute('open', '');
1463
1464                 var pv = ul.cloneNode(true);
1465                     pv.classList.add('preview');
1466
1467                 if (fl)
1468                         fl.classList.add('cbi-dropdown-open');
1469
1470                 if ('ontouchstart' in window) {
1471                         var vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
1472                             vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
1473                             scrollFrom = window.pageYOffset,
1474                             scrollTo = scrollFrom + rect.top - vpHeight * 0.5,
1475                             start = null;
1476
1477                         ul.style.top = sb.offsetHeight + 'px';
1478                         ul.style.left = -rect.left + 'px';
1479                         ul.style.right = (rect.right - vpWidth) + 'px';
1480                         ul.style.maxHeight = (vpHeight * 0.5) + 'px';
1481                         ul.style.WebkitOverflowScrolling = 'touch';
1482
1483                         var scrollStep = function(timestamp) {
1484                                 if (!start) {
1485                                         start = timestamp;
1486                                         ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1487                                 }
1488
1489                                 var duration = Math.max(timestamp - start, 1);
1490                                 if (duration < 100) {
1491                                         document.body.scrollTop = scrollFrom + (scrollTo - scrollFrom) * (duration / 100);
1492                                         window.requestAnimationFrame(scrollStep);
1493                                 }
1494                                 else {
1495                                         document.body.scrollTop = scrollTo;
1496                                 }
1497                         };
1498
1499                         window.requestAnimationFrame(scrollStep);
1500                 }
1501                 else {
1502                         ul.style.maxHeight = '1px';
1503                         ul.style.top = ul.style.bottom = '';
1504
1505                         window.requestAnimationFrame(function() {
1506                                 var height = items * li[Math.max(0, li.length - 2)].offsetHeight;
1507
1508                                 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1509                                 ul.style[((rect.top + rect.height + height) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1510                                 ul.style.maxHeight = height + 'px';
1511                         });
1512                 }
1513
1514                 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1515                         c.checked = true;
1516                 });
1517
1518                 ul.classList.add('dropdown');
1519
1520                 sb.insertBefore(pv, ul.nextElementSibling);
1521
1522                 li.forEach(function(l) {
1523                         l.setAttribute('tabindex', 0);
1524                 });
1525
1526                 sb.lastElementChild.setAttribute('tabindex', 0);
1527
1528                 this.setFocus(sb, sel || li[0], true);
1529         },
1530
1531         closeDropdown: function(sb, no_focus) {
1532                 if (!sb.hasAttribute('open'))
1533                         return;
1534
1535                 var pv = sb.querySelector('ul.preview'),
1536                     ul = sb.querySelector('ul.dropdown'),
1537                     li = ul.querySelectorAll('li'),
1538                     fl = findParent(sb, '.cbi-value-field');
1539
1540                 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1541                 sb.lastElementChild.removeAttribute('tabindex');
1542
1543                 sb.removeChild(pv);
1544                 sb.removeAttribute('open');
1545                 sb.style.width = sb.style.height = '';
1546
1547                 ul.classList.remove('dropdown');
1548                 ul.style.top = ul.style.bottom = ul.style.maxHeight = '';
1549
1550                 if (fl)
1551                         fl.classList.remove('cbi-dropdown-open');
1552
1553                 if (!no_focus)
1554                         this.setFocus(sb, sb);
1555
1556                 this.saveValues(sb, ul);
1557         },
1558
1559         toggleItem: function(sb, li, force_state) {
1560                 if (li.hasAttribute('unselectable'))
1561                         return;
1562
1563                 if (this.multi) {
1564                         var cbox = li.querySelector('input[type="checkbox"]'),
1565                             items = li.parentNode.querySelectorAll('li'),
1566                             label = sb.querySelector('ul.preview'),
1567                             sel = li.parentNode.querySelectorAll('[selected]').length,
1568                             more = sb.querySelector('.more'),
1569                             ndisplay = this.display_items,
1570                             n = 0;
1571
1572                         if (li.hasAttribute('selected')) {
1573                                 if (force_state !== true) {
1574                                         if (sel > 1 || this.optional) {
1575                                                 li.removeAttribute('selected');
1576                                                 cbox.checked = cbox.disabled = false;
1577                                                 sel--;
1578                                         }
1579                                         else {
1580                                                 cbox.disabled = true;
1581                                         }
1582                                 }
1583                         }
1584                         else {
1585                                 if (force_state !== false) {
1586                                         li.setAttribute('selected', '');
1587                                         cbox.checked = true;
1588                                         cbox.disabled = false;
1589                                         sel++;
1590                                 }
1591                         }
1592
1593                         while (label.firstElementChild)
1594                                 label.removeChild(label.firstElementChild);
1595
1596                         for (var i = 0; i < items.length; i++) {
1597                                 items[i].removeAttribute('display');
1598                                 if (items[i].hasAttribute('selected')) {
1599                                         if (ndisplay-- > 0) {
1600                                                 items[i].setAttribute('display', n++);
1601                                                 label.appendChild(items[i].cloneNode(true));
1602                                         }
1603                                         var c = items[i].querySelector('input[type="checkbox"]');
1604                                         if (c)
1605                                                 c.disabled = (sel == 1 && !this.optional);
1606                                 }
1607                         }
1608
1609                         if (ndisplay < 0)
1610                                 sb.setAttribute('more', '');
1611                         else
1612                                 sb.removeAttribute('more');
1613
1614                         if (ndisplay === this.display_items)
1615                                 sb.setAttribute('empty', '');
1616                         else
1617                                 sb.removeAttribute('empty');
1618
1619                         more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1620                 }
1621                 else {
1622                         var sel = li.parentNode.querySelector('[selected]');
1623                         if (sel) {
1624                                 sel.removeAttribute('display');
1625                                 sel.removeAttribute('selected');
1626                         }
1627
1628                         li.setAttribute('display', 0);
1629                         li.setAttribute('selected', '');
1630
1631                         this.closeDropdown(sb, true);
1632                 }
1633
1634                 this.saveValues(sb, li.parentNode);
1635         },
1636
1637         transformItem: function(sb, li) {
1638                 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1639                     label = E('label');
1640
1641                 while (li.firstChild)
1642                         label.appendChild(li.firstChild);
1643
1644                 li.appendChild(cbox);
1645                 li.appendChild(label);
1646         },
1647
1648         saveValues: function(sb, ul) {
1649                 var sel = ul.querySelectorAll('li[selected]'),
1650                     div = sb.lastElementChild,
1651                     strval = '',
1652                     values = [];
1653
1654                 while (div.lastElementChild)
1655                         div.removeChild(div.lastElementChild);
1656
1657                 sel.forEach(function (s) {
1658                         if (s.hasAttribute('placeholder'))
1659                                 return;
1660
1661                         var v = {
1662                                 text: s.innerText,
1663                                 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText,
1664                                 element: s
1665                         };
1666
1667                         div.appendChild(E('input', {
1668                                 type: 'hidden',
1669                                 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1670                                 value: v.value
1671                         }));
1672
1673                         values.push(v);
1674
1675                         strval += strval.length ? ' ' + v.value : v.value;
1676                 });
1677
1678                 var detail = {
1679                         instance: this,
1680                         element: sb
1681                 };
1682
1683                 if (this.multi)
1684                         detail.values = values;
1685                 else
1686                         detail.value = values.length ? values[0] : null;
1687
1688                 sb.value = strval;
1689
1690                 sb.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1691                         bubbles: true,
1692                         detail: detail
1693                 }));
1694         },
1695
1696         setValues: function(sb, values) {
1697                 var ul = sb.querySelector('ul');
1698
1699                 if (this.multi) {
1700                         ul.querySelectorAll('li[data-value]').forEach(function(li) {
1701                                 if (values === null || !(li.getAttribute('data-value') in values))
1702                                         this.toggleItem(sb, li, false);
1703                                 else
1704                                         this.toggleItem(sb, li, true);
1705                         });
1706                 }
1707                 else {
1708                         var ph = ul.querySelector('li[placeholder]');
1709                         if (ph)
1710                                 this.toggleItem(sb, ph);
1711
1712                         ul.querySelectorAll('li[data-value]').forEach(function(li) {
1713                                 if (values !== null && (li.getAttribute('data-value') in values))
1714                                         this.toggleItem(sb, li);
1715                         });
1716                 }
1717         },
1718
1719         setFocus: function(sb, elem, scroll) {
1720                 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1721                         return;
1722
1723                 if (sb.target && findParent(sb.target, 'ul.dropdown'))
1724                         return;
1725
1726                 document.querySelectorAll('.focus').forEach(function(e) {
1727                         if (!matchesElem(e, 'input')) {
1728                                 e.classList.remove('focus');
1729                                 e.blur();
1730                         }
1731                 });
1732
1733                 if (elem) {
1734                         elem.focus();
1735                         elem.classList.add('focus');
1736
1737                         if (scroll)
1738                                 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1739                 }
1740         },
1741
1742         createItems: function(sb, value) {
1743                 var sbox = this,
1744                     val = (value || '').trim(),
1745                     ul = sb.querySelector('ul');
1746
1747                 if (!sbox.multi)
1748                         val = val.length ? [ val ] : [];
1749                 else
1750                         val = val.length ? val.split(/\s+/) : [];
1751
1752                 val.forEach(function(item) {
1753                         var new_item = null;
1754
1755                         ul.childNodes.forEach(function(li) {
1756                                 if (li.getAttribute && li.getAttribute('data-value') === item)
1757                                         new_item = li;
1758                         });
1759
1760                         if (!new_item) {
1761                                 var markup,
1762                                     tpl = sb.querySelector(sbox.template);
1763
1764                                 if (tpl)
1765                                         markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1766                                 else
1767                                         markup = '<li data-value="{{value}}">{{value}}</li>';
1768
1769                                 new_item = E(markup.replace(/{{value}}/g, item));
1770
1771                                 if (sbox.multi) {
1772                                         sbox.transformItem(sb, new_item);
1773                                 }
1774                                 else {
1775                                         var old = ul.querySelector('li[created]');
1776                                         if (old)
1777                                                 ul.removeChild(old);
1778
1779                                         new_item.setAttribute('created', '');
1780                                 }
1781
1782                                 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1783                         }
1784
1785                         sbox.toggleItem(sb, new_item, true);
1786                         sbox.setFocus(sb, new_item, true);
1787                 });
1788         },
1789
1790         closeAllDropdowns: function() {
1791                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1792                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1793                 });
1794         },
1795
1796         handleClick: function(ev) {
1797                 var sb = ev.currentTarget;
1798
1799                 if (!sb.hasAttribute('open')) {
1800                         if (!matchesElem(ev.target, 'input'))
1801                                 this.openDropdown(sb);
1802                 }
1803                 else {
1804                         var li = findParent(ev.target, 'li');
1805                         if (li && li.parentNode.classList.contains('dropdown'))
1806                                 this.toggleItem(sb, li);
1807                         else if (li && li.parentNode.classList.contains('preview'))
1808                                 this.closeDropdown(sb);
1809                 }
1810
1811                 ev.preventDefault();
1812                 ev.stopPropagation();
1813         },
1814
1815         handleKeydown: function(ev) {
1816                 var sb = ev.currentTarget;
1817
1818                 if (matchesElem(ev.target, 'input'))
1819                         return;
1820
1821                 if (!sb.hasAttribute('open')) {
1822                         switch (ev.keyCode) {
1823                         case 37:
1824                         case 38:
1825                         case 39:
1826                         case 40:
1827                                 this.openDropdown(sb);
1828                                 ev.preventDefault();
1829                         }
1830                 }
1831                 else {
1832                         var active = findParent(document.activeElement, 'li');
1833
1834                         switch (ev.keyCode) {
1835                         case 27:
1836                                 this.closeDropdown(sb);
1837                                 break;
1838
1839                         case 13:
1840                                 if (active) {
1841                                         if (!active.hasAttribute('selected'))
1842                                                 this.toggleItem(sb, active);
1843                                         this.closeDropdown(sb);
1844                                         ev.preventDefault();
1845                                 }
1846                                 break;
1847
1848                         case 32:
1849                                 if (active) {
1850                                         this.toggleItem(sb, active);
1851                                         ev.preventDefault();
1852                                 }
1853                                 break;
1854
1855                         case 38:
1856                                 if (active && active.previousElementSibling) {
1857                                         this.setFocus(sb, active.previousElementSibling);
1858                                         ev.preventDefault();
1859                                 }
1860                                 break;
1861
1862                         case 40:
1863                                 if (active && active.nextElementSibling) {
1864                                         this.setFocus(sb, active.nextElementSibling);
1865                                         ev.preventDefault();
1866                                 }
1867                                 break;
1868                         }
1869                 }
1870         },
1871
1872         handleDropdownClose: function(ev) {
1873                 var sb = ev.currentTarget;
1874
1875                 this.closeDropdown(sb, true);
1876         },
1877
1878         handleDropdownSelect: function(ev) {
1879                 var sb = ev.currentTarget,
1880                     li = findParent(ev.target, 'li');
1881
1882                 if (!li)
1883                         return;
1884
1885                 this.toggleItem(sb, li);
1886                 this.closeDropdown(sb, true);
1887         },
1888
1889         handleMouseover: function(ev) {
1890                 var sb = ev.currentTarget;
1891
1892                 if (!sb.hasAttribute('open'))
1893                         return;
1894
1895                 var li = findParent(ev.target, 'li');
1896
1897                 if (li && li.parentNode.classList.contains('dropdown'))
1898                         this.setFocus(sb, li);
1899         },
1900
1901         handleFocus: function(ev) {
1902                 var sb = ev.currentTarget;
1903
1904                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1905                         if (s !== sb || sb.hasAttribute('open'))
1906                                 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1907                 });
1908         },
1909
1910         handleCanaryFocus: function(ev) {
1911                 this.closeDropdown(ev.currentTarget.parentNode);
1912         },
1913
1914         handleCreateKeydown: function(ev) {
1915                 var input = ev.currentTarget,
1916                     sb = findParent(input, '.cbi-dropdown');
1917
1918                 switch (ev.keyCode) {
1919                 case 13:
1920                         ev.preventDefault();
1921
1922                         if (input.classList.contains('cbi-input-invalid'))
1923                                 return;
1924
1925                         this.createItems(sb, input.value);
1926                         input.value = '';
1927                         input.blur();
1928                         break;
1929                 }
1930         },
1931
1932         handleCreateFocus: function(ev) {
1933                 var input = ev.currentTarget,
1934                     cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
1935                     sb = findParent(input, '.cbi-dropdown');
1936
1937                 if (cbox)
1938                         cbox.checked = true;
1939
1940                 sb.setAttribute('locked-in', '');
1941         },
1942
1943         handleCreateBlur: function(ev) {
1944                 var input = ev.currentTarget,
1945                     cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
1946                     sb = findParent(input, '.cbi-dropdown');
1947
1948                 if (cbox)
1949                         cbox.checked = false;
1950
1951                 sb.removeAttribute('locked-in');
1952         },
1953
1954         handleCreateClick: function(ev) {
1955                 ev.currentTarget.querySelector(this.create).focus();
1956         }
1957 };
1958
1959 function cbi_dropdown_init(sb) {
1960         if (!(this instanceof cbi_dropdown_init))
1961                 return new cbi_dropdown_init(sb);
1962
1963         this.multi = sb.hasAttribute('multiple');
1964         this.optional = sb.hasAttribute('optional');
1965         this.placeholder = sb.getAttribute('placeholder') || '---';
1966         this.display_items = parseInt(sb.getAttribute('display-items') || 3);
1967         this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
1968         this.create = sb.getAttribute('item-create') || '.create-item-input';
1969         this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
1970
1971         var ul = sb.querySelector('ul'),
1972             more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
1973             open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
1974             canary = sb.appendChild(E('div')),
1975             create = sb.querySelector(this.create),
1976             ndisplay = this.display_items,
1977             n = 0;
1978
1979         if (this.multi) {
1980                 var items = ul.querySelectorAll('li');
1981
1982                 for (var i = 0; i < items.length; i++) {
1983                         this.transformItem(sb, items[i]);
1984
1985                         if (items[i].hasAttribute('selected') && ndisplay-- > 0)
1986                                 items[i].setAttribute('display', n++);
1987                 }
1988         }
1989         else {
1990                 if (this.optional && !ul.querySelector('li[data-value=""]')) {
1991                         var placeholder = E('li', { placeholder: '' }, this.placeholder);
1992                         ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
1993                 }
1994
1995                 var items = ul.querySelectorAll('li'),
1996                     sel = sb.querySelectorAll('[selected]');
1997
1998                 sel.forEach(function(s) {
1999                         s.removeAttribute('selected');
2000                 });
2001
2002                 var s = sel[0] || items[0];
2003                 if (s) {
2004                         s.setAttribute('selected', '');
2005                         s.setAttribute('display', n++);
2006                 }
2007
2008                 ndisplay--;
2009         }
2010
2011         this.saveValues(sb, ul);
2012
2013         ul.setAttribute('tabindex', -1);
2014         sb.setAttribute('tabindex', 0);
2015
2016         if (ndisplay < 0)
2017                 sb.setAttribute('more', '')
2018         else
2019                 sb.removeAttribute('more');
2020
2021         if (ndisplay === this.display_items)
2022                 sb.setAttribute('empty', '')
2023         else
2024                 sb.removeAttribute('empty');
2025
2026         more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
2027
2028
2029         sb.addEventListener('click', this.handleClick.bind(this));
2030         sb.addEventListener('keydown', this.handleKeydown.bind(this));
2031         sb.addEventListener('cbi-dropdown-close', this.handleDropdownClose.bind(this));
2032         sb.addEventListener('cbi-dropdown-select', this.handleDropdownSelect.bind(this));
2033
2034         if ('ontouchstart' in window) {
2035                 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2036                 window.addEventListener('touchstart', this.closeAllDropdowns);
2037         }
2038         else {
2039                 sb.addEventListener('mouseover', this.handleMouseover.bind(this));
2040                 sb.addEventListener('focus', this.handleFocus.bind(this));
2041
2042                 canary.addEventListener('focus', this.handleCanaryFocus.bind(this));
2043
2044                 window.addEventListener('mouseover', this.setFocus);
2045                 window.addEventListener('click', this.closeAllDropdowns);
2046         }
2047
2048         if (create) {
2049                 create.addEventListener('keydown', this.handleCreateKeydown.bind(this));
2050                 create.addEventListener('focus', this.handleCreateFocus.bind(this));
2051                 create.addEventListener('blur', this.handleCreateBlur.bind(this));
2052
2053                 var li = findParent(create, 'li');
2054
2055                 li.setAttribute('unselectable', '');
2056                 li.addEventListener('click', this.handleCreateClick.bind(this));
2057         }
2058 }
2059
2060 cbi_dropdown_init.prototype = CBIDropdown;
2061
2062 function cbi_update_table(table, data, placeholder) {
2063         var target = isElem(table) ? table : document.querySelector(table);
2064
2065         if (!isElem(target))
2066                 return;
2067
2068         target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2069                 var titles = [];
2070
2071                 thead.querySelectorAll('.th').forEach(function(th) {
2072                         titles.push(th);
2073                 });
2074
2075                 if (Array.isArray(data)) {
2076                         var n = 0, rows = target.querySelectorAll('.tr');
2077
2078                         data.forEach(function(row) {
2079                                 var trow = E('div', { 'class': 'tr' });
2080
2081                                 for (var i = 0; i < titles.length; i++) {
2082                                         var text = (titles[i].innerText || '').trim();
2083                                         var td = trow.appendChild(E('div', {
2084                                                 'class': titles[i].className,
2085                                                 'data-title': (text !== '') ? text : null
2086                                         }, row[i] || ''));
2087
2088                                         td.classList.remove('th');
2089                                         td.classList.add('td');
2090                                 }
2091
2092                                 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2093
2094                                 if (rows[n])
2095                                         target.replaceChild(trow, rows[n]);
2096                                 else
2097                                         target.appendChild(trow);
2098                         });
2099
2100                         while (rows[++n])
2101                                 target.removeChild(rows[n]);
2102
2103                         if (placeholder && target.firstElementChild === target.lastElementChild) {
2104                                 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2105                                 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2106
2107                                 td.classList.remove('th');
2108                                 td.classList.add('td');
2109                         }
2110                 }
2111                 else {
2112                         thead.parentNode.style.display = 'none';
2113
2114                         thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2115                                 if (trow !== thead) {
2116                                         var n = 0;
2117                                         trow.querySelectorAll('.th, .td').forEach(function(td) {
2118                                                 if (n < titles.length) {
2119                                                         var text = (titles[n++].innerText || '').trim();
2120                                                         if (text !== '')
2121                                                                 td.setAttribute('data-title', text);
2122                                                 }
2123                                         });
2124                                 }
2125                         });
2126
2127                         thead.parentNode.style.display = '';
2128                 }
2129         });
2130 }
2131
2132 function showModal(title, children)
2133 {
2134         return L.showModal(title, children);
2135 }
2136
2137 function hideModal()
2138 {
2139         return L.hideModal();
2140 }
2141
2142
2143 document.addEventListener('DOMContentLoaded', function() {
2144         document.addEventListener('validation-failure', function(ev) {
2145                 if (ev.target === document.activeElement)
2146                         L.showTooltip(ev);
2147         });
2148
2149         document.addEventListener('validation-success', function(ev) {
2150                 if (ev.target === document.activeElement)
2151                         L.hideTooltip(ev);
2152         });
2153
2154         document.querySelectorAll('.table').forEach(cbi_update_table);
2155 });