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