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