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