luci-base: cbi.js: enable validation for dropdown fields
[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 ? (input.getAttribute('data-is-list') ? input.value.match(/[^ \t]+/g) : [ input.value ]) : null;
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                 'data-type': obj.getAttribute('data-type'),
811                 'data-optional': obj.getAttribute('data-optional')
812         }, [ E('ul') ]);
813
814         if (!(obj.value in values) && obj.value.length) {
815                 sb.lastElementChild.appendChild(E('li', {
816                         'data-value': obj.value,
817                         'selected': ''
818                 }, obj.value.length ? obj.value : (def || _('-- Please choose --'))));
819         }
820
821         for (var i in values) {
822                 sb.lastElementChild.appendChild(E('li', {
823                         'data-value': i,
824                         'selected': (i == obj.value) ? '' : null
825                 }, values[i]));
826         }
827
828         sb.lastElementChild.appendChild(E('li', { 'data-value': '-' }, [
829                 E('input', {
830                         'type': 'text',
831                         'class': 'create-item-input',
832                         'data-type': obj.getAttribute('data-type'),
833                         'data-optional': true,
834                         'placeholder': (man || _('-- custom --'))
835                 })
836         ]));
837
838         sb.value = obj.value;
839         obj.parentNode.replaceChild(sb, obj);
840 }
841
842 function cbi_filebrowser(id, defpath) {
843         var field   = document.getElementById(id);
844         var browser = window.open(
845                 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
846                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
847         );
848
849         browser.focus();
850 }
851
852 function cbi_browser_init(id, resource, defpath)
853 {
854         function cbi_browser_btnclick(e) {
855                 cbi_filebrowser(id, defpath);
856                 return false;
857         }
858
859         var field = document.getElementById(id);
860
861         var btn = document.createElement('img');
862         btn.className = 'cbi-image-button';
863         btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
864         field.parentNode.insertBefore(btn, field.nextSibling);
865
866         btn.addEventListener('click', cbi_browser_btnclick);
867 }
868
869 CBIDynamicList = {
870         addItem: function(dl, value, text, flash) {
871                 var exists = false,
872                     new_item = E('div', { 'class': flash ? 'item flash' : 'item', 'tabindex': 0 }, [
873                                 E('span', {}, text || value),
874                                 E('input', {
875                                         'type': 'hidden',
876                                         'name': dl.getAttribute('data-prefix'),
877                                         'value': value })]);
878
879                 dl.querySelectorAll('.item, .add-item').forEach(function(item) {
880                         if (exists)
881                                 return;
882
883                         var hidden = item.querySelector('input[type="hidden"]');
884
885                         if (hidden && hidden.value === value)
886                                 exists = true;
887                         else if (!hidden || hidden.value >= value)
888                                 exists = !!item.parentNode.insertBefore(new_item, item);
889                 });
890         },
891
892         removeItem: function(dl, item) {
893                 var sb = dl.querySelector('.cbi-dropdown');
894                 if (sb) {
895                         var value = item.querySelector('input[type="hidden"]').value;
896
897                         sb.querySelectorAll('ul > li').forEach(function(li) {
898                                 if (li.getAttribute('data-value') === value)
899                                         li.removeAttribute('unselectable');
900                         });
901                 }
902
903                 item.parentNode.removeChild(item);
904         },
905
906         handleClick: function(ev) {
907                 var dl = ev.currentTarget,
908                     item = findParent(ev.target, '.item');
909
910                 if (item) {
911                         this.removeItem(dl, item);
912                 }
913                 else if (matchesElem(ev.target, '.cbi-button-add')) {
914                         var input = ev.target.previousElementSibling;
915                         if (input.value.length && !input.classList.contains('cbi-input-invalid')) {
916                                 this.addItem(dl, input.value, null, true);
917                                 input.value = '';
918                         }
919                 }
920         },
921
922         handleDropdownChange: function(ev) {
923                 var dl = ev.currentTarget,
924                     sbIn = ev.detail.instance,
925                     sbEl = ev.detail.element,
926                     sbVal = ev.detail.value;
927
928                 if (sbVal === null)
929                         return;
930
931                 sbIn.setValues(sbEl, null);
932                 sbVal.element.setAttribute('unselectable', '');
933
934                 this.addItem(dl, sbVal.value, sbVal.text, true);
935         },
936
937         handleKeydown: function(ev) {
938                 var dl = ev.currentTarget,
939                     item = findParent(ev.target, '.item');
940
941                 if (item) {
942                         switch (ev.keyCode) {
943                         case 8: /* backspace */
944                                 if (item.previousElementSibling)
945                                         item.previousElementSibling.focus();
946
947                                 this.removeItem(dl, item);
948                                 break;
949
950                         case 46: /* delete */
951                                 if (item.nextElementSibling) {
952                                         if (item.nextElementSibling.classList.contains('item'))
953                                                 item.nextElementSibling.focus();
954                                         else
955                                                 item.nextElementSibling.firstElementChild.focus();
956                                 }
957
958                                 this.removeItem(dl, item);
959                                 break;
960                         }
961                 }
962                 else if (matchesElem(ev.target, '.cbi-input-text')) {
963                         switch (ev.keyCode) {
964                         case 13: /* enter */
965                                 if (ev.target.value.length && !ev.target.classList.contains('cbi-input-invalid')) {
966                                         this.addItem(dl, ev.target.value, null, true);
967                                         ev.target.value = '';
968                                         ev.target.blur();
969                                         ev.target.focus();
970                                 }
971
972                                 ev.preventDefault();
973                                 break;
974                         }
975                 }
976         }
977 };
978
979 function cbi_dynlist_init(dl, datatype, optional, choices)
980 {
981         if (!(this instanceof cbi_dynlist_init))
982                 return new cbi_dynlist_init(dl, datatype, optional, choices);
983
984         dl.classList.add('cbi-dynlist');
985         dl.appendChild(E('div', { 'class': 'add-item' }, E('input', {
986                 'type': 'text',
987                 'name': 'cbi.dynlist.' + dl.getAttribute('data-prefix'),
988                 'class': 'cbi-input-text',
989                 'data-type': datatype,
990                 'data-optional': true
991         })));
992
993         if (choices)
994                 cbi_combobox_init(dl.lastElementChild.lastElementChild, choices, '', _('-- custom --'));
995         else
996                 dl.lastElementChild.appendChild(E('div', { 'class': 'cbi-button cbi-button-add' }, '+'));
997
998         dl.addEventListener('click', this.handleClick.bind(this));
999         dl.addEventListener('keydown', this.handleKeydown.bind(this));
1000         dl.addEventListener('cbi-dropdown-change', this.handleDropdownChange.bind(this));
1001
1002         try {
1003                 var values = JSON.parse(dl.getAttribute('data-values') || '[]');
1004
1005                 if (typeof(values) === 'object' && Array.isArray(values))
1006                         for (var i = 0; i < values.length; i++)
1007                                 this.addItem(dl, values[i], choices ? choices[values[i]] : null);
1008         }
1009         catch (e) {}
1010 }
1011
1012 cbi_dynlist_init.prototype = CBIDynamicList;
1013
1014
1015 function cbi_t_add(section, tab) {
1016         var t = document.getElementById('tab.' + section + '.' + tab);
1017         var c = document.getElementById('container.' + section + '.' + tab);
1018
1019         if (t && c) {
1020                 cbi_t[section] = (cbi_t[section] || [ ]);
1021                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1022         }
1023 }
1024
1025 function cbi_t_switch(section, tab) {
1026         if (cbi_t[section] && cbi_t[section][tab]) {
1027                 var o = cbi_t[section][tab];
1028                 var h = document.getElementById('tab.' + section);
1029
1030                 for (var tid in cbi_t[section]) {
1031                         var o2 = cbi_t[section][tid];
1032
1033                         if (o.tab.id != o2.tab.id) {
1034                                 o2.tab.classList.remove('cbi-tab');
1035                                 o2.tab.classList.add('cbi-tab-disabled');
1036                                 o2.container.style.display = 'none';
1037                         }
1038                         else {
1039                                 if(h)
1040                                         h.value = tab;
1041
1042                                 o2.tab.classList.remove('cbi-tab-disabled');
1043                                 o2.tab.classList.add('cbi-tab');
1044                                 o2.container.style.display = 'block';
1045                         }
1046                 }
1047         }
1048
1049         return false;
1050 }
1051
1052 function cbi_t_update() {
1053         var hl_tabs = [ ];
1054         var updated = false;
1055
1056         for (var sid in cbi_t)
1057                 for (var tid in cbi_t[sid]) {
1058                         var t = cbi_t[sid][tid].tab;
1059                         var c = cbi_t[sid][tid].container;
1060
1061                         if (!c.firstElementChild) {
1062                                 t.style.display = 'none';
1063                         }
1064                         else if (t.style.display == 'none') {
1065                                 t.style.display = '';
1066                                 t.classList.add('cbi-tab-highlighted');
1067                                 hl_tabs.push(t);
1068                         }
1069
1070                         cbi_tag_last(c);
1071                         updated = true;
1072                 }
1073
1074         if (hl_tabs.length > 0)
1075                 window.setTimeout(function() {
1076                         for (var i = 0; i < hl_tabs.length; i++)
1077                                 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1078                 }, 750);
1079
1080         return updated;
1081 }
1082
1083
1084 function cbi_validate_form(form, errmsg)
1085 {
1086         /* if triggered by a section removal or addition, don't validate */
1087         if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1088                 return true;
1089
1090         if (form.cbi_validators) {
1091                 for (var i = 0; i < form.cbi_validators.length; i++) {
1092                         var validator = form.cbi_validators[i];
1093
1094                         if (!validator() && errmsg) {
1095                                 alert(errmsg);
1096                                 return false;
1097                         }
1098                 }
1099         }
1100
1101         return true;
1102 }
1103
1104 function cbi_validate_reset(form)
1105 {
1106         window.setTimeout(
1107                 function() { cbi_validate_form(form, null) }, 100
1108         );
1109
1110         return true;
1111 }
1112
1113 function cbi_validate_field(cbid, optional, type)
1114 {
1115         var field = isElem(cbid) ? cbid : document.getElementById(cbid);
1116         var validatorFn;
1117
1118         try {
1119                 var cbiValidator = new CBIValidator(field, type, optional);
1120
1121                 validatorFn = function() {
1122                         return cbiValidator.validate();
1123                 };
1124         }
1125         catch(e) {
1126                 validatorFn = null;
1127         };
1128
1129         if (validatorFn !== null) {
1130                 var form = findParent(field, 'form');
1131
1132                 if (!form.cbi_validators)
1133                         form.cbi_validators = [ ];
1134
1135                 form.cbi_validators.push(validatorFn);
1136
1137                 field.addEventListener("blur",  validatorFn);
1138                 field.addEventListener("keyup", validatorFn);
1139                 field.addEventListener("cbi-dropdown-change", validatorFn);
1140
1141                 if (matchesElem(field, 'select')) {
1142                         field.addEventListener("change", validatorFn);
1143                         field.addEventListener("click",  validatorFn);
1144                 }
1145
1146                 field.setAttribute("cbi_validate", validatorFn);
1147                 field.setAttribute("cbi_datatype", type);
1148                 field.setAttribute("cbi_optional", (!!optional).toString());
1149
1150                 validatorFn();
1151
1152                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1153                 if (fcbox)
1154                         cbi_validate_field(fcbox, optional, type);
1155         }
1156 }
1157
1158 function cbi_row_swap(elem, up, store)
1159 {
1160         var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1161
1162         if (!tr)
1163                 return false;
1164
1165         tr.classList.remove('flash');
1166
1167         if (up) {
1168                 var prev = tr.previousElementSibling;
1169
1170                 if (prev && prev.classList.contains('cbi-section-table-row'))
1171                         tr.parentNode.insertBefore(tr, prev);
1172                 else
1173                         return;
1174         }
1175         else {
1176                 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1177
1178                 if (next && next.classList.contains('cbi-section-table-row'))
1179                         tr.parentNode.insertBefore(tr, next);
1180                 else if (!next)
1181                         tr.parentNode.appendChild(tr);
1182                 else
1183                         return;
1184         }
1185
1186         var ids = [ ];
1187
1188         for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1189                 var node = tr.parentNode.childNodes[i];
1190                 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1191                         node.classList.remove('cbi-rowstyle-1');
1192                         node.classList.remove('cbi-rowstyle-2');
1193                         node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1194
1195                         if (/-([^\-]+)$/.test(node.id))
1196                                 ids.push(RegExp.$1);
1197                 }
1198         }
1199
1200         var input = document.getElementById(store);
1201         if (input)
1202                 input.value = ids.join(' ');
1203
1204         window.scrollTo(0, tr.offsetTop);
1205         void tr.offsetWidth;
1206         tr.classList.add('flash');
1207
1208         return false;
1209 }
1210
1211 function cbi_tag_last(container)
1212 {
1213         var last;
1214
1215         for (var i = 0; i < container.childNodes.length; i++) {
1216                 var c = container.childNodes[i];
1217                 if (matchesElem(c, 'div')) {
1218                         c.classList.remove('cbi-value-last');
1219                         last = c;
1220                 }
1221         }
1222
1223         if (last)
1224                 last.classList.add('cbi-value-last');
1225 }
1226
1227 function cbi_submit(elem, name, value, action)
1228 {
1229         var form = elem.form || findParent(elem, 'form');
1230
1231         if (!form)
1232                 return false;
1233
1234         if (action)
1235                 form.action = action;
1236
1237         if (name) {
1238                 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1239                         E('input', { type: 'hidden', name: name });
1240
1241                 hidden.value = value || '1';
1242                 form.appendChild(hidden);
1243         }
1244
1245         form.submit();
1246         return true;
1247 }
1248
1249 String.prototype.format = function()
1250 {
1251         if (!RegExp)
1252                 return;
1253
1254         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1255         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1256
1257         function esc(s, r) {
1258                 if (typeof(s) !== 'string' && !(s instanceof String))
1259                         return '';
1260
1261                 for (var i = 0; i < r.length; i += 2)
1262                         s = s.replace(r[i], r[i+1]);
1263
1264                 return s;
1265         }
1266
1267         var str = this;
1268         var out = '';
1269         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1270         var a = b = [], numSubstitutions = 0, numMatches = 0;
1271
1272         while (a = re.exec(str)) {
1273                 var m = a[1];
1274                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1275                 var pPrecision = a[6], pType = a[7];
1276
1277                 numMatches++;
1278
1279                 if (pType == '%') {
1280                         subst = '%';
1281                 }
1282                 else {
1283                         if (numSubstitutions < arguments.length) {
1284                                 var param = arguments[numSubstitutions++];
1285
1286                                 var pad = '';
1287                                 if (pPad && pPad.substr(0,1) == "'")
1288                                         pad = leftpart.substr(1,1);
1289                                 else if (pPad)
1290                                         pad = pPad;
1291                                 else
1292                                         pad = ' ';
1293
1294                                 var justifyRight = true;
1295                                 if (pJustify && pJustify === "-")
1296                                         justifyRight = false;
1297
1298                                 var minLength = -1;
1299                                 if (pMinLength)
1300                                         minLength = +pMinLength;
1301
1302                                 var precision = -1;
1303                                 if (pPrecision && pType == 'f')
1304                                         precision = +pPrecision.substring(1);
1305
1306                                 var subst = param;
1307
1308                                 switch(pType) {
1309                                         case 'b':
1310                                                 subst = (+param || 0).toString(2);
1311                                                 break;
1312
1313                                         case 'c':
1314                                                 subst = String.fromCharCode(+param || 0);
1315                                                 break;
1316
1317                                         case 'd':
1318                                                 subst = ~~(+param || 0);
1319                                                 break;
1320
1321                                         case 'u':
1322                                                 subst = ~~Math.abs(+param || 0);
1323                                                 break;
1324
1325                                         case 'f':
1326                                                 subst = (precision > -1)
1327                                                         ? ((+param || 0.0)).toFixed(precision)
1328                                                         : (+param || 0.0);
1329                                                 break;
1330
1331                                         case 'o':
1332                                                 subst = (+param || 0).toString(8);
1333                                                 break;
1334
1335                                         case 's':
1336                                                 subst = param;
1337                                                 break;
1338
1339                                         case 'x':
1340                                                 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1341                                                 break;
1342
1343                                         case 'X':
1344                                                 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1345                                                 break;
1346
1347                                         case 'h':
1348                                                 subst = esc(param, html_esc);
1349                                                 break;
1350
1351                                         case 'q':
1352                                                 subst = esc(param, quot_esc);
1353                                                 break;
1354
1355                                         case 't':
1356                                                 var td = 0;
1357                                                 var th = 0;
1358                                                 var tm = 0;
1359                                                 var ts = (param || 0);
1360
1361                                                 if (ts > 60) {
1362                                                         tm = Math.floor(ts / 60);
1363                                                         ts = (ts % 60);
1364                                                 }
1365
1366                                                 if (tm > 60) {
1367                                                         th = Math.floor(tm / 60);
1368                                                         tm = (tm % 60);
1369                                                 }
1370
1371                                                 if (th > 24) {
1372                                                         td = Math.floor(th / 24);
1373                                                         th = (th % 24);
1374                                                 }
1375
1376                                                 subst = (td > 0)
1377                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1378                                                         : String.format('%dh %dm %ds', th, tm, ts);
1379
1380                                                 break;
1381
1382                                         case 'm':
1383                                                 var mf = pMinLength ? +pMinLength : 1000;
1384                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1385
1386                                                 var i = 0;
1387                                                 var val = (+param || 0);
1388                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1389
1390                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1391                                                         val /= mf;
1392
1393                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
1394                                                 pMinLength = null;
1395                                                 break;
1396                                 }
1397                         }
1398                 }
1399
1400                 if (pMinLength) {
1401                         subst = subst.toString();
1402                         for (var i = subst.length; i < pMinLength; i++)
1403                                 if (pJustify == '-')
1404                                         subst = subst + ' ';
1405                                 else
1406                                         subst = pad + subst;
1407                 }
1408
1409                 out += leftpart + subst;
1410                 str = str.substr(m.length);
1411         }
1412
1413         return out + str;
1414 }
1415
1416 String.prototype.nobr = function()
1417 {
1418         return this.replace(/[\s\n]+/g, '&#160;');
1419 }
1420
1421 String.format = function()
1422 {
1423         var a = [ ];
1424
1425         for (var i = 1; i < arguments.length; i++)
1426                 a.push(arguments[i]);
1427
1428         return ''.format.apply(arguments[0], a);
1429 }
1430
1431 String.nobr = function()
1432 {
1433         var a = [ ];
1434
1435         for (var i = 1; i < arguments.length; i++)
1436                 a.push(arguments[i]);
1437
1438         return ''.nobr.apply(arguments[0], a);
1439 }
1440
1441 if (window.NodeList && !NodeList.prototype.forEach) {
1442         NodeList.prototype.forEach = function (callback, thisArg) {
1443                 thisArg = thisArg || window;
1444                 for (var i = 0; i < this.length; i++) {
1445                         callback.call(thisArg, this[i], i, this);
1446                 }
1447         };
1448 }
1449
1450
1451 var dummyElem, domParser;
1452
1453 function isElem(e)
1454 {
1455         return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1456 }
1457
1458 function toElem(s)
1459 {
1460         var elem;
1461
1462         try {
1463                 domParser = domParser || new DOMParser();
1464                 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1465         }
1466         catch(e) {}
1467
1468         if (!elem) {
1469                 try {
1470                         dummyElem = dummyElem || document.createElement('div');
1471                         dummyElem.innerHTML = s;
1472                         elem = dummyElem.firstChild;
1473                 }
1474                 catch (e) {}
1475         }
1476
1477         return elem || null;
1478 }
1479
1480 function matchesElem(node, selector)
1481 {
1482         return ((node.matches && node.matches(selector)) ||
1483                 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1484 }
1485
1486 function findParent(node, selector)
1487 {
1488         if (node.closest)
1489                 return node.closest(selector);
1490
1491         while (node)
1492                 if (matchesElem(node, selector))
1493                         return node;
1494                 else
1495                         node = node.parentNode;
1496
1497         return null;
1498 }
1499
1500 function E()
1501 {
1502         var html = arguments[0],
1503             attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1504             data = attr ? arguments[2] : arguments[1],
1505             elem;
1506
1507         if (isElem(html))
1508                 elem = html;
1509         else if (html.charCodeAt(0) === 60)
1510                 elem = toElem(html);
1511         else
1512                 elem = document.createElement(html);
1513
1514         if (!elem)
1515                 return null;
1516
1517         if (attr)
1518                 for (var key in attr)
1519                         if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1520                                 switch (typeof(attr[key])) {
1521                                 case 'function':
1522                                         elem.addEventListener(key, attr[key]);
1523                                         break;
1524
1525                                 case 'object':
1526                                         elem.setAttribute(key, JSON.stringify(attr[key]));
1527                                         break;
1528
1529                                 default:
1530                                         elem.setAttribute(key, attr[key]);
1531                                 }
1532
1533         if (typeof(data) === 'function')
1534                 data = data(elem);
1535
1536         if (isElem(data)) {
1537                 elem.appendChild(data);
1538         }
1539         else if (Array.isArray(data)) {
1540                 for (var i = 0; i < data.length; i++)
1541                         if (isElem(data[i]))
1542                                 elem.appendChild(data[i]);
1543                         else
1544                                 elem.appendChild(document.createTextNode('' + data[i]));
1545         }
1546         else if (data !== null && data !== undefined) {
1547                 elem.innerHTML = '' + data;
1548         }
1549
1550         return elem;
1551 }
1552
1553 if (typeof(window.CustomEvent) !== 'function') {
1554         function CustomEvent(event, params) {
1555                 params = params || { bubbles: false, cancelable: false, detail: undefined };
1556                 var evt = document.createEvent('CustomEvent');
1557                     evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1558                 return evt;
1559         }
1560
1561         CustomEvent.prototype = window.Event.prototype;
1562         window.CustomEvent = CustomEvent;
1563 }
1564
1565 CBIDropdown = {
1566         openDropdown: function(sb) {
1567                 var st = window.getComputedStyle(sb, null),
1568                     ul = sb.querySelector('ul'),
1569                     li = ul.querySelectorAll('li'),
1570                     sel = ul.querySelector('[selected]'),
1571                     rect = sb.getBoundingClientRect(),
1572                     h = sb.clientHeight - parseFloat(st.paddingTop) - parseFloat(st.paddingBottom),
1573                     mh = this.dropdown_items * h,
1574                     eh = Math.min(mh, li.length * h);
1575
1576                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1577                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1578                 });
1579
1580                 sb.setAttribute('open', '');
1581
1582                 if ('ontouchstart' in window) {
1583                         var scroll = document.documentElement.scrollTop,
1584                             vpWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
1585                             vpHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
1586
1587                         ul.style.top = h + 'px';
1588                         ul.style.left = -rect.left + 'px';
1589                         ul.style.right = (rect.right - vpWidth) + 'px';
1590
1591                         window.scrollTo(0, (scroll + rect.top - vpHeight * 0.6));
1592                 }
1593                 else {
1594                         ul.style.maxHeight = mh + 'px';
1595                         ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1596                         ul.style.top = ul.style.bottom = '';
1597                         ul.style[((rect.top + rect.height + eh) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1598                 }
1599
1600                 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1601                         c.checked = true;
1602                 });
1603
1604                 ul.classList.add('dropdown');
1605
1606                 var pv = ul.cloneNode(true);
1607                     pv.classList.remove('dropdown');
1608                     pv.classList.add('preview');
1609
1610                 sb.insertBefore(pv, ul.nextElementSibling);
1611
1612                 li.forEach(function(l) {
1613                         l.setAttribute('tabindex', 0);
1614                 });
1615
1616                 sb.lastElementChild.setAttribute('tabindex', 0);
1617
1618                 this.setFocus(sb, sel || li[0], true);
1619         },
1620
1621         closeDropdown: function(sb, no_focus) {
1622                 if (!sb.hasAttribute('open'))
1623                         return;
1624
1625                 var pv = sb.querySelector('ul.preview'),
1626                     ul = sb.querySelector('ul.dropdown'),
1627                     li = ul.querySelectorAll('li');
1628
1629                 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1630                 sb.lastElementChild.removeAttribute('tabindex');
1631
1632                 sb.removeChild(pv);
1633                 sb.removeAttribute('open');
1634                 sb.style.width = sb.style.height = '';
1635
1636                 ul.classList.remove('dropdown');
1637
1638                 if (!no_focus)
1639                         this.setFocus(sb, sb);
1640
1641                 this.saveValues(sb, ul);
1642         },
1643
1644         toggleItem: function(sb, li, force_state) {
1645                 if (li.hasAttribute('unselectable'))
1646                         return;
1647
1648                 if (this.multi) {
1649                         var cbox = li.querySelector('input[type="checkbox"]'),
1650                             items = li.parentNode.querySelectorAll('li'),
1651                             label = sb.querySelector('ul.preview'),
1652                             sel = li.parentNode.querySelectorAll('[selected]').length,
1653                             more = sb.querySelector('.more'),
1654                             ndisplay = this.display_items,
1655                             n = 0;
1656
1657                         if (li.hasAttribute('selected')) {
1658                                 if (force_state !== true) {
1659                                         if (sel > 1 || this.optional) {
1660                                                 li.removeAttribute('selected');
1661                                                 cbox.checked = cbox.disabled = false;
1662                                                 sel--;
1663                                         }
1664                                         else {
1665                                                 cbox.disabled = true;
1666                                         }
1667                                 }
1668                         }
1669                         else {
1670                                 if (force_state !== false) {
1671                                         li.setAttribute('selected', '');
1672                                         cbox.checked = true;
1673                                         cbox.disabled = false;
1674                                         sel++;
1675                                 }
1676                         }
1677
1678                         while (label.firstElementChild)
1679                                 label.removeChild(label.firstElementChild);
1680
1681                         for (var i = 0; i < items.length; i++) {
1682                                 items[i].removeAttribute('display');
1683                                 if (items[i].hasAttribute('selected')) {
1684                                         if (ndisplay-- > 0) {
1685                                                 items[i].setAttribute('display', n++);
1686                                                 label.appendChild(items[i].cloneNode(true));
1687                                         }
1688                                         var c = items[i].querySelector('input[type="checkbox"]');
1689                                         if (c)
1690                                                 c.disabled = (sel == 1 && !this.optional);
1691                                 }
1692                         }
1693
1694                         if (ndisplay < 0)
1695                                 sb.setAttribute('more', '');
1696                         else
1697                                 sb.removeAttribute('more');
1698
1699                         if (ndisplay === this.display_items)
1700                                 sb.setAttribute('empty', '');
1701                         else
1702                                 sb.removeAttribute('empty');
1703
1704                         more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1705                 }
1706                 else {
1707                         var sel = li.parentNode.querySelector('[selected]');
1708                         if (sel) {
1709                                 sel.removeAttribute('display');
1710                                 sel.removeAttribute('selected');
1711                         }
1712
1713                         li.setAttribute('display', 0);
1714                         li.setAttribute('selected', '');
1715
1716                         this.closeDropdown(sb, true);
1717                 }
1718
1719                 this.saveValues(sb, li.parentNode);
1720         },
1721
1722         transformItem: function(sb, li) {
1723                 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1724                     label = E('label');
1725
1726                 while (li.firstChild)
1727                         label.appendChild(li.firstChild);
1728
1729                 li.appendChild(cbox);
1730                 li.appendChild(label);
1731         },
1732
1733         saveValues: function(sb, ul) {
1734                 var sel = ul.querySelectorAll('li[selected]'),
1735                     div = sb.lastElementChild,
1736                     strval = '',
1737                     values = [];
1738
1739                 while (div.lastElementChild)
1740                         div.removeChild(div.lastElementChild);
1741
1742                 sel.forEach(function (s) {
1743                         if (s.hasAttribute('placeholder'))
1744                                 return;
1745
1746                         var v = {
1747                                 text: s.innerText,
1748                                 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText,
1749                                 element: s
1750                         };
1751
1752                         div.appendChild(E('input', {
1753                                 type: 'hidden',
1754                                 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1755                                 value: v.value
1756                         }));
1757
1758                         values.push(v);
1759
1760                         strval += strval.length ? ' ' + v.value : v.value;
1761                 });
1762
1763                 var detail = {
1764                         instance: this,
1765                         element: sb
1766                 };
1767
1768                 if (this.multi)
1769                         detail.values = values;
1770                 else
1771                         detail.value = values.length ? values[0] : null;
1772
1773                 sb.value = strval;
1774
1775                 sb.dispatchEvent(new CustomEvent('cbi-dropdown-change', {
1776                         bubbles: true,
1777                         detail: detail
1778                 }));
1779
1780                 cbi_d_update();
1781         },
1782
1783         setValues: function(sb, values) {
1784                 var ul = sb.querySelector('ul');
1785
1786                 if (this.multi) {
1787                         ul.querySelectorAll('li[data-value]').forEach(function(li) {
1788                                 if (values === null || !(li.getAttribute('data-value') in values))
1789                                         this.toggleItem(sb, li, false);
1790                                 else
1791                                         this.toggleItem(sb, li, true);
1792                         });
1793                 }
1794                 else {
1795                         var ph = ul.querySelector('li[placeholder]');
1796                         if (ph)
1797                                 this.toggleItem(sb, ph);
1798
1799                         ul.querySelectorAll('li[data-value]').forEach(function(li) {
1800                                 if (values !== null && (li.getAttribute('data-value') in values))
1801                                         this.toggleItem(sb, li);
1802                         });
1803                 }
1804         },
1805
1806         setFocus: function(sb, elem, scroll) {
1807                 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1808                         return;
1809
1810                 if (sb.target && findParent(sb.target, 'ul.dropdown'))
1811                         return;
1812
1813                 document.querySelectorAll('.focus').forEach(function(e) {
1814                         if (!matchesElem(e, 'input')) {
1815                                 e.classList.remove('focus');
1816                                 e.blur();
1817                         }
1818                 });
1819
1820                 if (elem) {
1821                         elem.focus();
1822                         elem.classList.add('focus');
1823
1824                         if (scroll)
1825                                 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1826                 }
1827         },
1828
1829         createItems: function(sb, value) {
1830                 var sbox = this,
1831                     val = (value || '').trim().split(/\s+/),
1832                     ul = sb.querySelector('ul');
1833
1834                 if (!sbox.multi)
1835                         val.length = Math.min(val.length, 1);
1836
1837                 if (val.length === 1 && val[0].length === 0)
1838                         val.length = 0;
1839
1840                 val.forEach(function(item) {
1841                         var new_item = null;
1842
1843                         ul.childNodes.forEach(function(li) {
1844                                 if (li.getAttribute && li.getAttribute('data-value') === item)
1845                                         new_item = li;
1846                         });
1847
1848                         if (!new_item) {
1849                                 var markup,
1850                                     tpl = sb.querySelector(sbox.template);
1851
1852                                 if (tpl)
1853                                         markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1854                                 else
1855                                         markup = '<li data-value="{{value}}">{{value}}</li>';
1856
1857                                 new_item = E(markup.replace(/{{value}}/g, item));
1858
1859                                 if (sbox.multi) {
1860                                         sbox.transformItem(sb, new_item);
1861                                 }
1862                                 else {
1863                                         var old = ul.querySelector('li[created]');
1864                                         if (old)
1865                                                 ul.removeChild(old);
1866
1867                                         new_item.setAttribute('created', '');
1868                                 }
1869
1870                                 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1871                         }
1872
1873                         sbox.toggleItem(sb, new_item, true);
1874                         sbox.setFocus(sb, new_item, true);
1875                 });
1876         },
1877
1878         closeAllDropdowns: function() {
1879                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1880                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1881                 });
1882         },
1883
1884         handleClick: function(ev) {
1885                 var sb = ev.currentTarget;
1886
1887                 if (!sb.hasAttribute('open')) {
1888                         if (!matchesElem(ev.target, 'input'))
1889                                 this.openDropdown(sb);
1890                 }
1891                 else {
1892                         var li = findParent(ev.target, 'li');
1893                         if (li && li.parentNode.classList.contains('dropdown'))
1894                                 this.toggleItem(sb, li);
1895                 }
1896
1897                 ev.preventDefault();
1898                 ev.stopPropagation();
1899         },
1900
1901         handleKeydown: function(ev) {
1902                 var sb = ev.currentTarget;
1903
1904                 if (matchesElem(ev.target, 'input'))
1905                         return;
1906
1907                 if (!sb.hasAttribute('open')) {
1908                         switch (ev.keyCode) {
1909                         case 37:
1910                         case 38:
1911                         case 39:
1912                         case 40:
1913                                 this.openDropdown(sb);
1914                                 ev.preventDefault();
1915                         }
1916                 }
1917                 else {
1918                         var active = findParent(document.activeElement, 'li');
1919
1920                         switch (ev.keyCode) {
1921                         case 27:
1922                                 this.closeDropdown(sb);
1923                                 break;
1924
1925                         case 13:
1926                                 if (active) {
1927                                         if (!active.hasAttribute('selected'))
1928                                                 this.toggleItem(sb, active);
1929                                         this.closeDropdown(sb);
1930                                         ev.preventDefault();
1931                                 }
1932                                 break;
1933
1934                         case 32:
1935                                 if (active) {
1936                                         this.toggleItem(sb, active);
1937                                         ev.preventDefault();
1938                                 }
1939                                 break;
1940
1941                         case 38:
1942                                 if (active && active.previousElementSibling) {
1943                                         this.setFocus(sb, active.previousElementSibling);
1944                                         ev.preventDefault();
1945                                 }
1946                                 break;
1947
1948                         case 40:
1949                                 if (active && active.nextElementSibling) {
1950                                         this.setFocus(sb, active.nextElementSibling);
1951                                         ev.preventDefault();
1952                                 }
1953                                 break;
1954                         }
1955                 }
1956         },
1957
1958         handleDropdownClose: function(ev) {
1959                 var sb = ev.currentTarget;
1960
1961                 this.closeDropdown(sb, true);
1962         },
1963
1964         handleDropdownSelect: function(ev) {
1965                 var sb = ev.currentTarget,
1966                     li = findParent(ev.target, 'li');
1967
1968                 if (!li)
1969                         return;
1970
1971                 this.toggleItem(sb, li);
1972                 this.closeDropdown(sb, true);
1973         },
1974
1975         handleMouseover: function(ev) {
1976                 var sb = ev.currentTarget;
1977
1978                 if (!sb.hasAttribute('open'))
1979                         return;
1980
1981                 var li = findParent(ev.target, 'li');
1982
1983                 if (li && li.parentNode.classList.contains('dropdown'))
1984                         this.setFocus(sb, li);
1985         },
1986
1987         handleFocus: function(ev) {
1988                 var sb = ev.currentTarget;
1989
1990                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1991                         if (s !== sb || sb.hasAttribute('open'))
1992                                 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1993                 });
1994         },
1995
1996         handleCanaryFocus: function(ev) {
1997                 this.closeDropdown(ev.currentTarget.parentNode);
1998         },
1999
2000         handleCreateKeydown: function(ev) {
2001                 var input = ev.currentTarget,
2002                     sb = findParent(input, '.cbi-dropdown');
2003
2004                 switch (ev.keyCode) {
2005                 case 13:
2006                         ev.preventDefault();
2007
2008                         if (input.classList.contains('cbi-input-invalid'))
2009                                 return;
2010
2011                         this.createItems(sb, input.value);
2012                         input.value = '';
2013                         input.blur();
2014                         break;
2015                 }
2016         },
2017
2018         handleCreateFocus: 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 = true;
2025
2026                 sb.setAttribute('locked-in', '');
2027         },
2028
2029         handleCreateBlur: function(ev) {
2030                 var input = ev.currentTarget,
2031                     cbox = findParent(input, 'li').querySelector('input[type="checkbox"]'),
2032                     sb = findParent(input, '.cbi-dropdown');
2033
2034                 if (cbox)
2035                         cbox.checked = false;
2036
2037                 sb.removeAttribute('locked-in');
2038         },
2039
2040         handleCreateClick: function(ev) {
2041                 ev.currentTarget.querySelector(this.create).focus();
2042         }
2043 };
2044
2045 function cbi_dropdown_init(sb) {
2046         if (!(this instanceof cbi_dropdown_init))
2047                 return new cbi_dropdown_init(sb);
2048
2049         this.multi = sb.hasAttribute('multiple');
2050         this.optional = sb.hasAttribute('optional');
2051         this.placeholder = sb.getAttribute('placeholder') || '---';
2052         this.display_items = parseInt(sb.getAttribute('display-items') || 3);
2053         this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
2054         this.create = sb.getAttribute('item-create') || '.create-item-input';
2055         this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
2056
2057         var ul = sb.querySelector('ul'),
2058             more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
2059             open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
2060             canary = sb.appendChild(E('div')),
2061             create = sb.querySelector(this.create),
2062             ndisplay = this.display_items,
2063             n = 0;
2064
2065         if (this.multi) {
2066                 var items = ul.querySelectorAll('li');
2067
2068                 for (var i = 0; i < items.length; i++) {
2069                         this.transformItem(sb, items[i]);
2070
2071                         if (items[i].hasAttribute('selected') && ndisplay-- > 0)
2072                                 items[i].setAttribute('display', n++);
2073                 }
2074         }
2075         else {
2076                 if (this.optional && !ul.querySelector('li[data-value=""]')) {
2077                         var placeholder = E('li', { placeholder: '' }, this.placeholder);
2078                         ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
2079                 }
2080
2081                 var items = ul.querySelectorAll('li'),
2082                     sel = sb.querySelectorAll('[selected]');
2083
2084                 sel.forEach(function(s) {
2085                         s.removeAttribute('selected');
2086                 });
2087
2088                 var s = sel[0] || items[0];
2089                 if (s) {
2090                         s.setAttribute('selected', '');
2091                         s.setAttribute('display', n++);
2092                 }
2093
2094                 ndisplay--;
2095         }
2096
2097         this.saveValues(sb, ul);
2098
2099         ul.setAttribute('tabindex', -1);
2100         sb.setAttribute('tabindex', 0);
2101
2102         if (ndisplay < 0)
2103                 sb.setAttribute('more', '')
2104         else
2105                 sb.removeAttribute('more');
2106
2107         if (ndisplay === this.display_items)
2108                 sb.setAttribute('empty', '')
2109         else
2110                 sb.removeAttribute('empty');
2111
2112         more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
2113
2114
2115         sb.addEventListener('click', this.handleClick.bind(this));
2116         sb.addEventListener('keydown', this.handleKeydown.bind(this));
2117         sb.addEventListener('cbi-dropdown-close', this.handleDropdownClose.bind(this));
2118         sb.addEventListener('cbi-dropdown-select', this.handleDropdownSelect.bind(this));
2119
2120         if ('ontouchstart' in window) {
2121                 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2122                 window.addEventListener('touchstart', this.closeAllDropdowns);
2123         }
2124         else {
2125                 sb.addEventListener('mouseover', this.handleMouseover.bind(this));
2126                 sb.addEventListener('focus', this.handleFocus.bind(this));
2127
2128                 canary.addEventListener('focus', this.handleCanaryFocus.bind(this));
2129
2130                 window.addEventListener('mouseover', this.setFocus);
2131                 window.addEventListener('click', this.closeAllDropdowns);
2132         }
2133
2134         if (create) {
2135                 create.addEventListener('keydown', this.handleCreateKeydown.bind(this));
2136                 create.addEventListener('focus', this.handleCreateFocus.bind(this));
2137                 create.addEventListener('blur', this.handleCreateBlur.bind(this));
2138
2139                 var li = findParent(create, 'li');
2140
2141                 li.setAttribute('unselectable', '');
2142                 li.addEventListener('click', this.handleCreateClick.bind(this));
2143         }
2144 }
2145
2146 cbi_dropdown_init.prototype = CBIDropdown;
2147
2148 function cbi_update_table(table, data, placeholder) {
2149         var target = isElem(table) ? table : document.querySelector(table);
2150
2151         if (!isElem(target))
2152                 return;
2153
2154         target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2155                 var titles = [];
2156
2157                 thead.querySelectorAll('.th').forEach(function(th) {
2158                         titles.push(th);
2159                 });
2160
2161                 if (Array.isArray(data)) {
2162                         var n = 0, rows = target.querySelectorAll('.tr');
2163
2164                         data.forEach(function(row) {
2165                                 var trow = E('div', { 'class': 'tr' });
2166
2167                                 for (var i = 0; i < titles.length; i++) {
2168                                         var text = (titles[i].innerText || '').trim();
2169                                         var td = trow.appendChild(E('div', {
2170                                                 'class': titles[i].className,
2171                                                 'data-title': (text !== '') ? text : null
2172                                         }, row[i] || ''));
2173
2174                                         td.classList.remove('th');
2175                                         td.classList.add('td');
2176                                 }
2177
2178                                 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2179
2180                                 if (rows[n])
2181                                         target.replaceChild(trow, rows[n]);
2182                                 else
2183                                         target.appendChild(trow);
2184                         });
2185
2186                         while (rows[++n])
2187                                 target.removeChild(rows[n]);
2188
2189                         if (placeholder && target.firstElementChild === target.lastElementChild) {
2190                                 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2191                                 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2192
2193                                 td.classList.remove('th');
2194                                 td.classList.add('td');
2195                         }
2196                 }
2197                 else {
2198                         thead.parentNode.style.display = 'none';
2199
2200                         thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2201                                 if (trow !== thead) {
2202                                         var n = 0;
2203                                         trow.querySelectorAll('.th, .td').forEach(function(td) {
2204                                                 if (n < titles.length) {
2205                                                         var text = (titles[n++].innerText || '').trim();
2206                                                         if (text !== '')
2207                                                                 td.setAttribute('data-title', text);
2208                                                 }
2209                                         });
2210                                 }
2211                         });
2212
2213                         thead.parentNode.style.display = '';
2214                 }
2215         });
2216 }
2217
2218 var tooltipDiv = null, tooltipTimeout = null;
2219
2220 function showTooltip(ev) {
2221         var target = findParent(ev.target, '[data-tooltip]');
2222
2223         if (!target)
2224                 return;
2225
2226         if (tooltipTimeout !== null) {
2227                 window.clearTimeout(tooltipTimeout);
2228                 tooltipTimeout = null;
2229         }
2230
2231         var rect = target.getBoundingClientRect(),
2232             x = rect.left              + window.pageXOffset,
2233             y = rect.top + rect.height + window.pageYOffset;
2234
2235         tooltipDiv.className = 'cbi-tooltip';
2236         tooltipDiv.innerHTML = '▲ ';
2237         tooltipDiv.firstChild.data += target.getAttribute('data-tooltip');
2238
2239         if (target.hasAttribute('data-tooltip-style'))
2240                 tooltipDiv.classList.add(target.getAttribute('data-tooltip-style'));
2241
2242         if ((y + tooltipDiv.offsetHeight) > (window.innerHeight + window.pageYOffset)) {
2243                 y -= (tooltipDiv.offsetHeight + target.offsetHeight);
2244                 tooltipDiv.firstChild.data = '▼ ' + tooltipDiv.firstChild.data.substr(2);
2245         }
2246
2247         tooltipDiv.style.top = y + 'px';
2248         tooltipDiv.style.left = x + 'px';
2249         tooltipDiv.style.opacity = 1;
2250 }
2251
2252 function hideTooltip(ev) {
2253         if (ev.target === tooltipDiv || ev.relatedTarget === tooltipDiv)
2254                 return;
2255
2256         if (tooltipTimeout !== null) {
2257                 window.clearTimeout(tooltipTimeout);
2258                 tooltipTimeout = null;
2259         }
2260
2261         tooltipDiv.style.opacity = 0;
2262         tooltipTimeout = window.setTimeout(function() { tooltipDiv.removeAttribute('style'); }, 250);
2263 }
2264
2265 document.addEventListener('DOMContentLoaded', function() {
2266         tooltipDiv = document.body.appendChild(E('div', { 'class': 'cbi-tooltip' }));
2267
2268         document.addEventListener('mouseover', showTooltip, true);
2269         document.addEventListener('mouseout', hideTooltip, true);
2270         document.addEventListener('focus', showTooltip, true);
2271         document.addEventListener('blur', hideTooltip, true);
2272
2273         document.addEventListener('validation-failure', function(ev) {
2274                 if (ev.target === document.activeElement)
2275                         showTooltip(ev);
2276         });
2277
2278         document.addEventListener('validation-success', function(ev) {
2279                 if (ev.target === document.activeElement)
2280                         hideTooltip(ev);
2281         });
2282
2283         document.querySelectorAll('.table').forEach(cbi_update_table);
2284 });