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