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