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