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