Merge pull request #2193 from rosysong/freespace
[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                 }
515                 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
516                         var next = undefined;
517
518                         for (next = parent.firstChild; next; next = next.nextSibling) {
519                                 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
520                                         break;
521                         }
522
523                         if (!next)
524                                 parent.appendChild(entry.node);
525                         else
526                                 parent.insertBefore(entry.node, next);
527
528                         state = true;
529                 }
530
531                 // hide optionals widget if no choices remaining
532                 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
533                         parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
534         }
535
536         if (entry && entry.parent) {
537                 if (!cbi_t_update())
538                         cbi_tag_last(parent);
539         }
540
541         if (state)
542                 cbi_d_update();
543 }
544
545 function cbi_init() {
546         var nodes;
547
548         nodes = document.querySelectorAll('[data-strings]');
549
550         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
551                 var str = JSON.parse(node.getAttribute('data-strings'));
552                 for (var key in str) {
553                         for (var key2 in str[key]) {
554                                 var dst = cbi_strings[key] || (cbi_strings[key] = { });
555                                     dst[key2] = str[key][key2];
556                         }
557                 }
558         }
559
560         nodes = document.querySelectorAll('[data-depends]');
561
562         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
563                 var index = parseInt(node.getAttribute('data-index'), 10);
564                 var depends = JSON.parse(node.getAttribute('data-depends'));
565                 if (!isNaN(index) && depends.length > 0) {
566                         for (var alt = 0; alt < depends.length; alt++)
567                                 cbi_d_add(node, depends[alt], index);
568                 }
569         }
570
571         nodes = document.querySelectorAll('[data-update]');
572
573         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
574                 var events = node.getAttribute('data-update').split(' ');
575                 for (var j = 0, event; (event = events[j]) !== undefined; j++)
576                         cbi_bind(node, event, cbi_d_update);
577         }
578
579         nodes = document.querySelectorAll('[data-choices]');
580
581         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
582                 var choices = JSON.parse(node.getAttribute('data-choices'));
583                 var options = {};
584
585                 for (var j = 0; j < choices[0].length; j++)
586                         options[choices[0][j]] = choices[1][j];
587
588                 var def = (node.getAttribute('data-optional') === 'true')
589                         ? node.placeholder || '' : null;
590
591                 cbi_combobox_init(node, options, def,
592                                   node.getAttribute('data-manual'));
593         }
594
595         nodes = document.querySelectorAll('[data-dynlist]');
596
597         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
598                 var choices = JSON.parse(node.getAttribute('data-dynlist'));
599                 var options = null;
600
601                 if (choices[0] && choices[0].length) {
602                         options = {};
603
604                         for (var j = 0; j < choices[0].length; j++)
605                                 options[choices[0][j]] = choices[1][j];
606                 }
607
608                 cbi_dynlist_init(node, choices[2], choices[3], options);
609         }
610
611         nodes = document.querySelectorAll('[data-type]');
612
613         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
614                 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
615                                    node.getAttribute('data-type'));
616         }
617
618         document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
619                 cbi_dropdown_init(s);
620         });
621
622         document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
623                 s.parentNode.classList.add('cbi-tooltip-container');
624         });
625
626         document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
627                 var handler = function(ev) {
628                         var bits = this.name.split(/\./),
629                             section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
630
631                     section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
632                 };
633
634                 i.addEventListener('mouseover', handler);
635                 i.addEventListener('mouseout', handler);
636         });
637
638         cbi_d_update();
639 }
640
641 function cbi_bind(obj, type, callback, mode) {
642         if (!obj.addEventListener) {
643                 obj.attachEvent('on' + type,
644                         function(){
645                                 var e = window.event;
646
647                                 if (!e.target && e.srcElement)
648                                         e.target = e.srcElement;
649
650                                 return !!callback(e);
651                         }
652                 );
653         } else {
654                 obj.addEventListener(type, callback, !!mode);
655         }
656         return obj;
657 }
658
659 function cbi_combobox(id, values, def, man, focus) {
660         var selid = "cbi.combobox." + id;
661         if (document.getElementById(selid)) {
662                 return
663         }
664
665         var obj = document.getElementById(id)
666         var sel = document.createElement("select");
667                 sel.id = selid;
668                 sel.index = obj.index;
669                 sel.classList.remove('cbi-input-text');
670                 sel.classList.add('cbi-input-select');
671
672         if (obj.nextSibling)
673                 obj.parentNode.insertBefore(sel, obj.nextSibling);
674         else
675                 obj.parentNode.appendChild(sel);
676
677         var dt = obj.getAttribute('cbi_datatype');
678         var op = obj.getAttribute('cbi_optional');
679
680         if (!values[obj.value]) {
681                 if (obj.value == "") {
682                         var optdef = document.createElement("option");
683                         optdef.value = "";
684                         optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : cbi_strings.label.choose));
685                         sel.appendChild(optdef);
686                 }
687                 else {
688                         var opt = document.createElement("option");
689                         opt.value = obj.value;
690                         opt.selected = "selected";
691                         opt.appendChild(document.createTextNode(obj.value));
692                         sel.appendChild(opt);
693                 }
694         }
695
696         for (var i in values) {
697                 var opt = document.createElement("option");
698                 opt.value = i;
699
700                 if (obj.value == i)
701                         opt.selected = "selected";
702
703                 opt.appendChild(document.createTextNode(values[i]));
704                 sel.appendChild(opt);
705         }
706
707         var optman = document.createElement("option");
708         optman.value = "";
709         optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : cbi_strings.label.custom));
710         sel.appendChild(optman);
711
712         obj.style.display = "none";
713
714         if (dt)
715                 cbi_validate_field(sel, op == 'true', dt);
716
717         cbi_bind(sel, "change", function() {
718                 if (sel.selectedIndex == sel.options.length - 1) {
719                         obj.style.display = "inline";
720                         sel.blur();
721                         sel.parentNode.removeChild(sel);
722                         obj.focus();
723                 }
724                 else {
725                         obj.value = sel.options[sel.selectedIndex].value;
726                 }
727
728                 try {
729                         cbi_d_update();
730                 } catch (e) {
731                         //Do nothing
732                 }
733         })
734
735         // Retrigger validation in select
736         if (focus) {
737                 sel.focus();
738                 sel.blur();
739         }
740 }
741
742 function cbi_combobox_init(id, values, def, man) {
743         var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
744         cbi_bind(obj, "blur", function() {
745                 cbi_combobox(obj.id, values, def, man, true);
746         });
747         cbi_combobox(obj.id, values, def, man, false);
748 }
749
750 function cbi_filebrowser(id, defpath) {
751         var field   = document.getElementById(id);
752         var browser = window.open(
753                 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
754                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
755         );
756
757         browser.focus();
758 }
759
760 function cbi_browser_init(id, resource, defpath)
761 {
762         function cbi_browser_btnclick(e) {
763                 cbi_filebrowser(id, defpath);
764                 return false;
765         }
766
767         var field = document.getElementById(id);
768
769         var btn = document.createElement('img');
770         btn.className = 'cbi-image-button';
771         btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
772         field.parentNode.insertBefore(btn, field.nextSibling);
773
774         cbi_bind(btn, 'click', cbi_browser_btnclick);
775 }
776
777 function cbi_dynlist_init(parent, datatype, optional, choices)
778 {
779         var prefix = parent.getAttribute('data-prefix');
780         var holder = parent.getAttribute('data-placeholder');
781
782         var values;
783
784         function cbi_dynlist_redraw(focus, add, del)
785         {
786                 values = [ ];
787
788                 while (parent.firstChild) {
789                         var n = parent.firstChild;
790                         var i = +n.index;
791
792                         if (i != del) {
793                                 if (matchesElem(n, 'input'))
794                                         values.push(n.value || '');
795                                 else if (matchesElem(n, 'select'))
796                                         values[values.length-1] = n.options[n.selectedIndex].value;
797                         }
798
799                         parent.removeChild(n);
800                 }
801
802                 if (add >= 0) {
803                         focus = add+1;
804                         values.splice(focus, 0, '');
805                 }
806                 else if (values.length == 0) {
807                         focus = 0;
808                         values.push('');
809                 }
810
811                 for (var i = 0; i < values.length; i++) {
812                         var t = document.createElement('input');
813                                 t.id = prefix + '.' + (i+1);
814                                 t.name = prefix;
815                                 t.value = values[i];
816                                 t.type = 'text';
817                                 t.index = i;
818                                 t.className = 'cbi-input-text';
819
820                         if (i == 0 && holder)
821                                 t.placeholder = holder;
822
823                         var b = E('div', {
824                                 class: 'cbi-button cbi-button-' + ((i+1) < values.length ? 'remove' : 'add')
825                         }, (i+1) < values.length ? '×' : '+');
826
827                         parent.appendChild(t);
828                         parent.appendChild(b);
829
830                         if (datatype == 'file')
831                                 cbi_browser_init(t.id, null, parent.getAttribute('data-browser-path'));
832
833                         parent.appendChild(document.createElement('br'));
834
835                         if (datatype)
836                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
837
838                         if (choices) {
839                                 cbi_combobox_init(t.id, choices, '', cbi_strings.label.custom);
840                                 b.index = i;
841
842                                 cbi_bind(b, 'keydown',  cbi_dynlist_keydown);
843                                 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
844
845                                 if (i == focus || -i == focus)
846                                         b.focus();
847                         }
848                         else {
849                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
850                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
851
852                                 if (i == focus) {
853                                         t.focus();
854                                 }
855                                 else if (-i == focus) {
856                                         t.focus();
857
858                                         /* force cursor to end */
859                                         var v = t.value;
860                                         t.value = ' '
861                                         t.value = v;
862                                 }
863                         }
864
865                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
866                 }
867         }
868
869         function cbi_dynlist_keypress(ev)
870         {
871                 ev = ev ? ev : window.event;
872
873                 var se = ev.target ? ev.target : ev.srcElement;
874
875                 if (se.nodeType == 3)
876                         se = se.parentNode;
877
878                 switch (ev.keyCode) {
879                         /* backspace, delete */
880                         case 8:
881                         case 46:
882                                 if (se.value.length == 0) {
883                                         if (ev.preventDefault)
884                                                 ev.preventDefault();
885
886                                         return false;
887                                 }
888
889                                 return true;
890
891                         /* enter, arrow up, arrow down */
892                         case 13:
893                         case 38:
894                         case 40:
895                                 if (ev.preventDefault)
896                                         ev.preventDefault();
897
898                                 return false;
899                 }
900
901                 return true;
902         }
903
904         function cbi_dynlist_keydown(ev)
905         {
906                 ev = ev ? ev : window.event;
907
908                 var se = ev.target ? ev.target : ev.srcElement;
909
910                 if (se.nodeType == 3)
911                         se = se.parentNode;
912
913                 var prev = se.previousSibling;
914                 while (prev && prev.name != prefix)
915                         prev = prev.previousSibling;
916
917                 var next = se.nextSibling;
918                 while (next && next.name != prefix)
919                         next = next.nextSibling;
920
921                 /* advance one further in combobox case */
922                 if (next && next.nextSibling.name == prefix)
923                         next = next.nextSibling;
924
925                 switch (ev.keyCode) {
926                         /* backspace, delete */
927                         case 8:
928                         case 46:
929                                 var del = (matchesElem(se, 'select'))
930                                         ? true : (se.value.length == 0);
931
932                                 if (del) {
933                                         if (ev.preventDefault)
934                                                 ev.preventDefault();
935
936                                         var focus = se.index;
937                                         if (ev.keyCode == 8)
938                                                 focus = -focus+1;
939
940                                         cbi_dynlist_redraw(focus, -1, se.index);
941
942                                         return false;
943                                 }
944
945                                 break;
946
947                         /* enter */
948                         case 13:
949                                 cbi_dynlist_redraw(-1, se.index, -1);
950                                 break;
951
952                         /* arrow up */
953                         case 38:
954                                 if (prev)
955                                         prev.focus();
956
957                                 break;
958
959                         /* arrow down */
960                         case 40:
961                                 if (next)
962                                         next.focus();
963
964                                 break;
965                 }
966
967                 return true;
968         }
969
970         function cbi_dynlist_btnclick(ev)
971         {
972                 ev = ev ? ev : window.event;
973
974                 var se = ev.target ? ev.target : ev.srcElement;
975                 var input = se.previousSibling;
976                 while (input && input.name != prefix)
977                         input = input.previousSibling;
978
979                 if (se.classList.contains('cbi-button-remove')) {
980                         input.value = '';
981
982                         cbi_dynlist_keydown({
983                                 target:  input,
984                                 keyCode: 8
985                         });
986                 }
987                 else {
988                         cbi_dynlist_keydown({
989                                 target:  input,
990                                 keyCode: 13
991                         });
992                 }
993
994                 return false;
995         }
996
997         cbi_dynlist_redraw(NaN, -1, -1);
998 }
999
1000
1001 function cbi_t_add(section, tab) {
1002         var t = document.getElementById('tab.' + section + '.' + tab);
1003         var c = document.getElementById('container.' + section + '.' + tab);
1004
1005         if (t && c) {
1006                 cbi_t[section] = (cbi_t[section] || [ ]);
1007                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1008         }
1009 }
1010
1011 function cbi_t_switch(section, tab) {
1012         if (cbi_t[section] && cbi_t[section][tab]) {
1013                 var o = cbi_t[section][tab];
1014                 var h = document.getElementById('tab.' + section);
1015
1016                 for (var tid in cbi_t[section]) {
1017                         var o2 = cbi_t[section][tid];
1018
1019                         if (o.tab.id != o2.tab.id) {
1020                                 o2.tab.classList.remove('cbi-tab');
1021                                 o2.tab.classList.add('cbi-tab-disabled');
1022                                 o2.container.style.display = 'none';
1023                         }
1024                         else {
1025                                 if(h)
1026                                         h.value = tab;
1027
1028                                 o2.tab.classList.remove('cbi-tab-disabled');
1029                                 o2.tab.classList.add('cbi-tab');
1030                                 o2.container.style.display = 'block';
1031                         }
1032                 }
1033         }
1034
1035         return false;
1036 }
1037
1038 function cbi_t_update() {
1039         var hl_tabs = [ ];
1040         var updated = false;
1041
1042         for (var sid in cbi_t)
1043                 for (var tid in cbi_t[sid]) {
1044                         var t = cbi_t[sid][tid].tab;
1045                         var c = cbi_t[sid][tid].container;
1046
1047                         if (!c.firstElementChild) {
1048                                 t.style.display = 'none';
1049                         }
1050                         else if (t.style.display == 'none') {
1051                                 t.style.display = '';
1052                                 t.classList.add('cbi-tab-highlighted');
1053                                 hl_tabs.push(t);
1054                         }
1055
1056                         cbi_tag_last(c);
1057                         updated = true;
1058                 }
1059
1060         if (hl_tabs.length > 0)
1061                 window.setTimeout(function() {
1062                         for (var i = 0; i < hl_tabs.length; i++)
1063                                 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1064                 }, 750);
1065
1066         return updated;
1067 }
1068
1069
1070 function cbi_validate_form(form, errmsg)
1071 {
1072         /* if triggered by a section removal or addition, don't validate */
1073         if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1074                 return true;
1075
1076         if (form.cbi_validators) {
1077                 for (var i = 0; i < form.cbi_validators.length; i++) {
1078                         var validator = form.cbi_validators[i];
1079
1080                         if (!validator() && errmsg) {
1081                                 alert(errmsg);
1082                                 return false;
1083                         }
1084                 }
1085         }
1086
1087         return true;
1088 }
1089
1090 function cbi_validate_reset(form)
1091 {
1092         window.setTimeout(
1093                 function() { cbi_validate_form(form, null) }, 100
1094         );
1095
1096         return true;
1097 }
1098
1099 function cbi_validate_compile(code)
1100 {
1101         var pos = 0;
1102         var esc = false;
1103         var depth = 0;
1104         var stack = [ ];
1105
1106         code += ',';
1107
1108         for (var i = 0; i < code.length; i++) {
1109                 if (esc) {
1110                         esc = false;
1111                         continue;
1112                 }
1113
1114                 switch (code.charCodeAt(i))
1115                 {
1116                 case 92:
1117                         esc = true;
1118                         break;
1119
1120                 case 40:
1121                 case 44:
1122                         if (depth <= 0) {
1123                                 if (pos < i) {
1124                                         var label = code.substring(pos, i);
1125                                                 label = label.replace(/\\(.)/g, '$1');
1126                                                 label = label.replace(/^[ \t]+/g, '');
1127                                                 label = label.replace(/[ \t]+$/g, '');
1128
1129                                         if (label && !isNaN(label)) {
1130                                                 stack.push(parseFloat(label));
1131                                         }
1132                                         else if (label.match(/^(['"]).*\1$/)) {
1133                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1134                                         }
1135                                         else if (typeof cbi_validators[label] == 'function') {
1136                                                 stack.push(cbi_validators[label]);
1137                                                 stack.push(null);
1138                                         }
1139                                         else {
1140                                                 throw "Syntax error, unhandled token '"+label+"'";
1141                                         }
1142                                 }
1143
1144                                 pos = i+1;
1145                         }
1146
1147                         depth += (code.charCodeAt(i) == 40);
1148                         break;
1149
1150                 case 41:
1151                         if (--depth <= 0) {
1152                                 if (typeof stack[stack.length-2] != 'function')
1153                                         throw "Syntax error, argument list follows non-function";
1154
1155                                 stack[stack.length-1] =
1156                                         arguments.callee(code.substring(pos, i));
1157
1158                                 pos = i+1;
1159                         }
1160
1161                         break;
1162                 }
1163         }
1164
1165         return stack;
1166 }
1167
1168 function cbi_validate_field(cbid, optional, type)
1169 {
1170         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1171         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1172
1173         if (field && vstack && typeof vstack[0] == "function") {
1174                 var validator = function()
1175                 {
1176                         // is not detached
1177                         if (field.form) {
1178                                 field.classList.remove('cbi-input-invalid');
1179
1180                                 // validate value
1181                                 var value = (field.options && field.options.selectedIndex > -1)
1182                                         ? field.options[field.options.selectedIndex].value : field.value;
1183
1184                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1]))) {
1185                                         // invalid
1186                                         field.classList.add('cbi-input-invalid');
1187                                         return false;
1188                                 }
1189                         }
1190
1191                         return true;
1192                 };
1193
1194                 if (!field.form.cbi_validators)
1195                         field.form.cbi_validators = [ ];
1196
1197                 field.form.cbi_validators.push(validator);
1198
1199                 cbi_bind(field, "blur",  validator);
1200                 cbi_bind(field, "keyup", validator);
1201
1202                 if (matchesElem(field, 'select')) {
1203                         cbi_bind(field, "change", validator);
1204                         cbi_bind(field, "click",  validator);
1205                 }
1206
1207                 field.setAttribute("cbi_validate", validator);
1208                 field.setAttribute("cbi_datatype", type);
1209                 field.setAttribute("cbi_optional", (!!optional).toString());
1210
1211                 validator();
1212
1213                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1214                 if (fcbox)
1215                         cbi_validate_field(fcbox, optional, type);
1216         }
1217 }
1218
1219 function cbi_row_swap(elem, up, store)
1220 {
1221         var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1222
1223         if (!tr)
1224                 return false;
1225
1226         tr.classList.remove('flash');
1227
1228         if (up) {
1229                 var prev = tr.previousElementSibling;
1230
1231                 if (prev && prev.classList.contains('cbi-section-table-row'))
1232                         tr.parentNode.insertBefore(tr, prev);
1233                 else
1234                         return;
1235         }
1236         else {
1237                 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1238
1239                 if (next && next.classList.contains('cbi-section-table-row'))
1240                         tr.parentNode.insertBefore(tr, next);
1241                 else if (!next)
1242                         tr.parentNode.appendChild(tr);
1243                 else
1244                         return;
1245         }
1246
1247         var ids = [ ];
1248
1249         for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1250                 var node = tr.parentNode.childNodes[i];
1251                 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1252                         node.classList.remove('cbi-rowstyle-1');
1253                         node.classList.remove('cbi-rowstyle-2');
1254                         node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1255
1256                         if (/-([^\-]+)$/.test(node.id))
1257                                 ids.push(RegExp.$1);
1258                 }
1259         }
1260
1261         var input = document.getElementById(store);
1262         if (input)
1263                 input.value = ids.join(' ');
1264
1265         window.scrollTo(0, tr.offsetTop);
1266         void tr.offsetWidth;
1267         tr.classList.add('flash');
1268
1269         return false;
1270 }
1271
1272 function cbi_tag_last(container)
1273 {
1274         var last;
1275
1276         for (var i = 0; i < container.childNodes.length; i++) {
1277                 var c = container.childNodes[i];
1278                 if (matchesElem(c, 'div')) {
1279                         c.classList.remove('cbi-value-last');
1280                         last = c;
1281                 }
1282         }
1283
1284         if (last)
1285                 last.classList.add('cbi-value-last');
1286 }
1287
1288 function cbi_submit(elem, name, value, action)
1289 {
1290         var form = elem.form || findParent(elem, 'form');
1291
1292         if (!form)
1293                 return false;
1294
1295         if (action)
1296                 form.action = action;
1297
1298         if (name) {
1299                 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1300                         E('input', { type: 'hidden', name: name });
1301
1302                 hidden.value = value || '1';
1303                 form.appendChild(hidden);
1304         }
1305
1306         form.submit();
1307         return true;
1308 }
1309
1310 String.prototype.format = function()
1311 {
1312         if (!RegExp)
1313                 return;
1314
1315         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1316         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1317
1318         function esc(s, r) {
1319                 if (typeof(s) !== 'string' && !(s instanceof String))
1320                         return '';
1321
1322                 for (var i = 0; i < r.length; i += 2)
1323                         s = s.replace(r[i], r[i+1]);
1324
1325                 return s;
1326         }
1327
1328         var str = this;
1329         var out = '';
1330         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1331         var a = b = [], numSubstitutions = 0, numMatches = 0;
1332
1333         while (a = re.exec(str)) {
1334                 var m = a[1];
1335                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1336                 var pPrecision = a[6], pType = a[7];
1337
1338                 numMatches++;
1339
1340                 if (pType == '%') {
1341                         subst = '%';
1342                 }
1343                 else {
1344                         if (numSubstitutions < arguments.length) {
1345                                 var param = arguments[numSubstitutions++];
1346
1347                                 var pad = '';
1348                                 if (pPad && pPad.substr(0,1) == "'")
1349                                         pad = leftpart.substr(1,1);
1350                                 else if (pPad)
1351                                         pad = pPad;
1352                                 else
1353                                         pad = ' ';
1354
1355                                 var justifyRight = true;
1356                                 if (pJustify && pJustify === "-")
1357                                         justifyRight = false;
1358
1359                                 var minLength = -1;
1360                                 if (pMinLength)
1361                                         minLength = +pMinLength;
1362
1363                                 var precision = -1;
1364                                 if (pPrecision && pType == 'f')
1365                                         precision = +pPrecision.substring(1);
1366
1367                                 var subst = param;
1368
1369                                 switch(pType) {
1370                                         case 'b':
1371                                                 subst = (+param || 0).toString(2);
1372                                                 break;
1373
1374                                         case 'c':
1375                                                 subst = String.fromCharCode(+param || 0);
1376                                                 break;
1377
1378                                         case 'd':
1379                                                 subst = ~~(+param || 0);
1380                                                 break;
1381
1382                                         case 'u':
1383                                                 subst = ~~Math.abs(+param || 0);
1384                                                 break;
1385
1386                                         case 'f':
1387                                                 subst = (precision > -1)
1388                                                         ? ((+param || 0.0)).toFixed(precision)
1389                                                         : (+param || 0.0);
1390                                                 break;
1391
1392                                         case 'o':
1393                                                 subst = (+param || 0).toString(8);
1394                                                 break;
1395
1396                                         case 's':
1397                                                 subst = param;
1398                                                 break;
1399
1400                                         case 'x':
1401                                                 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1402                                                 break;
1403
1404                                         case 'X':
1405                                                 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1406                                                 break;
1407
1408                                         case 'h':
1409                                                 subst = esc(param, html_esc);
1410                                                 break;
1411
1412                                         case 'q':
1413                                                 subst = esc(param, quot_esc);
1414                                                 break;
1415
1416                                         case 't':
1417                                                 var td = 0;
1418                                                 var th = 0;
1419                                                 var tm = 0;
1420                                                 var ts = (param || 0);
1421
1422                                                 if (ts > 60) {
1423                                                         tm = Math.floor(ts / 60);
1424                                                         ts = (ts % 60);
1425                                                 }
1426
1427                                                 if (tm > 60) {
1428                                                         th = Math.floor(tm / 60);
1429                                                         tm = (tm % 60);
1430                                                 }
1431
1432                                                 if (th > 24) {
1433                                                         td = Math.floor(th / 24);
1434                                                         th = (th % 24);
1435                                                 }
1436
1437                                                 subst = (td > 0)
1438                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1439                                                         : String.format('%dh %dm %ds', th, tm, ts);
1440
1441                                                 break;
1442
1443                                         case 'm':
1444                                                 var mf = pMinLength ? +pMinLength : 1000;
1445                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1446
1447                                                 var i = 0;
1448                                                 var val = (+param || 0);
1449                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1450
1451                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1452                                                         val /= mf;
1453
1454                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
1455                                                 pMinLength = null;
1456                                                 break;
1457                                 }
1458                         }
1459                 }
1460
1461                 if (pMinLength) {
1462                         subst = subst.toString();
1463                         for (var i = subst.length; i < pMinLength; i++)
1464                                 if (pJustify == '-')
1465                                         subst = subst + ' ';
1466                                 else
1467                                         subst = pad + subst;
1468                 }
1469
1470                 out += leftpart + subst;
1471                 str = str.substr(m.length);
1472         }
1473
1474         return out + str;
1475 }
1476
1477 String.prototype.nobr = function()
1478 {
1479         return this.replace(/[\s\n]+/g, '&#160;');
1480 }
1481
1482 String.format = function()
1483 {
1484         var a = [ ];
1485
1486         for (var i = 1; i < arguments.length; i++)
1487                 a.push(arguments[i]);
1488
1489         return ''.format.apply(arguments[0], a);
1490 }
1491
1492 String.nobr = function()
1493 {
1494         var a = [ ];
1495
1496         for (var i = 1; i < arguments.length; i++)
1497                 a.push(arguments[i]);
1498
1499         return ''.nobr.apply(arguments[0], a);
1500 }
1501
1502 if (window.NodeList && !NodeList.prototype.forEach) {
1503         NodeList.prototype.forEach = function (callback, thisArg) {
1504                 thisArg = thisArg || window;
1505                 for (var i = 0; i < this.length; i++) {
1506                         callback.call(thisArg, this[i], i, this);
1507                 }
1508         };
1509 }
1510
1511
1512 var dummyElem, domParser;
1513
1514 function isElem(e)
1515 {
1516         return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1517 }
1518
1519 function toElem(s)
1520 {
1521         var elem;
1522
1523         try {
1524                 domParser = domParser || new DOMParser();
1525                 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1526         }
1527         catch(e) {}
1528
1529         if (!elem) {
1530                 try {
1531                         dummyElem = dummyElem || document.createElement('div');
1532                         dummyElem.innerHTML = s;
1533                         elem = dummyElem.firstChild;
1534                 }
1535                 catch (e) {}
1536         }
1537
1538         return elem || null;
1539 }
1540
1541 function matchesElem(node, selector)
1542 {
1543         return ((node.matches && node.matches(selector)) ||
1544                 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1545 }
1546
1547 function findParent(node, selector)
1548 {
1549         while (node)
1550                 if (matchesElem(node, selector))
1551                         return node;
1552                 else
1553                         node = node.parentNode;
1554
1555         return null;
1556 }
1557
1558 function E()
1559 {
1560         var html = arguments[0],
1561             attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1562             data = attr ? arguments[2] : arguments[1],
1563             elem;
1564
1565         if (isElem(html))
1566                 elem = html;
1567         else if (html.charCodeAt(0) === 60)
1568                 elem = toElem(html);
1569         else
1570                 elem = document.createElement(html);
1571
1572         if (!elem)
1573                 return null;
1574
1575         if (attr)
1576                 for (var key in attr)
1577                         if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1578                                 elem.setAttribute(key, attr[key]);
1579
1580         if (typeof(data) === 'function')
1581                 data = data(elem);
1582
1583         if (isElem(data)) {
1584                 elem.appendChild(data);
1585         }
1586         else if (Array.isArray(data)) {
1587                 for (var i = 0; i < data.length; i++)
1588                         if (isElem(data[i]))
1589                                 elem.appendChild(data[i]);
1590                         else
1591                                 elem.appendChild(document.createTextNode('' + data[i]));
1592         }
1593         else if (data !== null && data !== undefined) {
1594                 elem.innerHTML = '' + data;
1595         }
1596
1597         return elem;
1598 }
1599
1600 if (typeof(window.CustomEvent) !== 'function') {
1601         function CustomEvent(event, params) {
1602                 params = params || { bubbles: false, cancelable: false, detail: undefined };
1603                 var evt = document.createEvent('CustomEvent');
1604                     evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1605                 return evt;
1606         }
1607
1608         CustomEvent.prototype = window.Event.prototype;
1609         window.CustomEvent = CustomEvent;
1610 }
1611
1612 CBIDropdown = {
1613         openDropdown: function(sb) {
1614                 var st = window.getComputedStyle(sb, null),
1615                     ul = sb.querySelector('ul'),
1616                     li = ul.querySelectorAll('li'),
1617                     sel = ul.querySelector('[selected]'),
1618                     rect = sb.getBoundingClientRect(),
1619                     h = sb.clientHeight - parseFloat(st.paddingTop) - parseFloat(st.paddingBottom),
1620                     mh = this.dropdown_items * h,
1621                     eh = Math.min(mh, li.length * h);
1622
1623                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1624                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1625                 });
1626
1627                 ul.style.maxHeight = mh + 'px';
1628                 sb.setAttribute('open', '');
1629
1630                 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1631                 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1632                         c.checked = true;
1633                 });
1634
1635                 ul.style.top = ul.style.bottom = '';
1636                 ul.style[((sb.getBoundingClientRect().top + eh) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1637                 ul.classList.add('dropdown');
1638
1639                 var pv = ul.cloneNode(true);
1640                     pv.classList.remove('dropdown');
1641                     pv.classList.add('preview');
1642
1643                 sb.insertBefore(pv, ul.nextElementSibling);
1644
1645                 li.forEach(function(l) {
1646                         l.setAttribute('tabindex', 0);
1647                 });
1648
1649                 sb.lastElementChild.setAttribute('tabindex', 0);
1650
1651                 this.setFocus(sb, sel || li[0], true);
1652         },
1653
1654         closeDropdown: function(sb, no_focus) {
1655                 if (!sb.hasAttribute('open'))
1656                         return;
1657
1658                 var pv = sb.querySelector('ul.preview'),
1659                     ul = sb.querySelector('ul.dropdown'),
1660                     li = ul.querySelectorAll('li');
1661
1662                 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1663                 sb.lastElementChild.removeAttribute('tabindex');
1664
1665                 sb.removeChild(pv);
1666                 sb.removeAttribute('open');
1667                 sb.style.width = sb.style.height = '';
1668
1669                 ul.classList.remove('dropdown');
1670
1671                 if (!no_focus)
1672                         this.setFocus(sb, sb);
1673
1674                 this.saveValues(sb, ul);
1675         },
1676
1677         toggleItem: function(sb, li, force_state) {
1678                 if (li.hasAttribute('unselectable'))
1679                         return;
1680
1681                 if (this.multi) {
1682                         var cbox = li.querySelector('input[type="checkbox"]'),
1683                             items = li.parentNode.querySelectorAll('li'),
1684                             label = sb.querySelector('ul.preview'),
1685                             sel = li.parentNode.querySelectorAll('[selected]').length,
1686                             more = sb.querySelector('.more'),
1687                             ndisplay = this.display_items,
1688                             n = 0;
1689
1690                         if (li.hasAttribute('selected')) {
1691                                 if (force_state !== true) {
1692                                         if (sel > 1 || this.optional) {
1693                                                 li.removeAttribute('selected');
1694                                                 cbox.checked = cbox.disabled = false;
1695                                                 sel--;
1696                                         }
1697                                         else {
1698                                                 cbox.disabled = true;
1699                                         }
1700                                 }
1701                         }
1702                         else {
1703                                 if (force_state !== false) {
1704                                         li.setAttribute('selected', '');
1705                                         cbox.checked = true;
1706                                         cbox.disabled = false;
1707                                         sel++;
1708                                 }
1709                         }
1710
1711                         while (label.firstElementChild)
1712                                 label.removeChild(label.firstElementChild);
1713
1714                         for (var i = 0; i < items.length; i++) {
1715                                 items[i].removeAttribute('display');
1716                                 if (items[i].hasAttribute('selected')) {
1717                                         if (ndisplay-- > 0) {
1718                                                 items[i].setAttribute('display', n++);
1719                                                 label.appendChild(items[i].cloneNode(true));
1720                                         }
1721                                         var c = items[i].querySelector('input[type="checkbox"]');
1722                                         if (c)
1723                                                 c.disabled = (sel == 1 && !this.optional);
1724                                 }
1725                         }
1726
1727                         if (ndisplay < 0)
1728                                 sb.setAttribute('more', '');
1729                         else
1730                                 sb.removeAttribute('more');
1731
1732                         if (ndisplay === this.display_items)
1733                                 sb.setAttribute('empty', '');
1734                         else
1735                                 sb.removeAttribute('empty');
1736
1737                         more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1738                 }
1739                 else {
1740                         var sel = li.parentNode.querySelector('[selected]');
1741                         if (sel) {
1742                                 sel.removeAttribute('display');
1743                                 sel.removeAttribute('selected');
1744                         }
1745
1746                         li.setAttribute('display', 0);
1747                         li.setAttribute('selected', '');
1748
1749                         this.closeDropdown(sb, true);
1750                 }
1751
1752                 this.saveValues(sb, li.parentNode);
1753         },
1754
1755         transformItem: function(sb, li) {
1756                 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1757                     label = E('label');
1758
1759                 while (li.firstChild)
1760                         label.appendChild(li.firstChild);
1761
1762                 li.appendChild(cbox);
1763                 li.appendChild(label);
1764         },
1765
1766         saveValues: function(sb, ul) {
1767                 var sel = ul.querySelectorAll('[selected]'),
1768                     div = sb.lastElementChild;
1769
1770                 while (div.lastElementChild)
1771                         div.removeChild(div.lastElementChild);
1772
1773                 sel.forEach(function (s) {
1774                         div.appendChild(E('input', {
1775                                 type: 'hidden',
1776                                 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1777                                 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText
1778                         }));
1779                 });
1780
1781                 cbi_d_update();
1782         },
1783
1784         setFocus: function(sb, elem, scroll) {
1785                 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1786                         return;
1787
1788                 document.querySelectorAll('.focus').forEach(function(e) {
1789                         if (!matchesElem(e, 'input')) {
1790                                 e.classList.remove('focus');
1791                                 e.blur();
1792                         }
1793                 });
1794
1795                 if (elem) {
1796                         elem.focus();
1797                         elem.classList.add('focus');
1798
1799                         if (scroll)
1800                                 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1801                 }
1802         },
1803
1804         createItems: function(sb, value) {
1805                 var sbox = this,
1806                     val = (value || '').trim().split(/\s+/),
1807                     ul = sb.querySelector('ul');
1808
1809                 if (!sbox.multi)
1810                         val.length = Math.min(val.length, 1);
1811
1812                 val.forEach(function(item) {
1813                         var new_item = null;
1814
1815                         ul.childNodes.forEach(function(li) {
1816                                 if (li.getAttribute && li.getAttribute('data-value') === item)
1817                                         new_item = li;
1818                         });
1819
1820                         if (!new_item) {
1821                                 var markup,
1822                                     tpl = sb.querySelector(sbox.template);
1823
1824                                 if (tpl)
1825                                         markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1826                                 else
1827                                         markup = '<li data-value="{{value}}">{{value}}</li>';
1828
1829                                 new_item = E(markup.replace(/{{value}}/g, item));
1830
1831                                 if (sbox.multi) {
1832                                         sbox.transformItem(sb, new_item);
1833                                 }
1834                                 else {
1835                                         var old = ul.querySelector('li[created]');
1836                                         if (old)
1837                                                 ul.removeChild(old);
1838
1839                                         new_item.setAttribute('created', '');
1840                                 }
1841
1842                                 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1843                         }
1844
1845                         sbox.toggleItem(sb, new_item, true);
1846                         sbox.setFocus(sb, new_item, true);
1847                 });
1848         },
1849
1850         closeAllDropdowns: function() {
1851                 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1852                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1853                 });
1854         }
1855 };
1856
1857 function cbi_dropdown_init(sb) {
1858         if (!(this instanceof cbi_dropdown_init))
1859                 return new cbi_dropdown_init(sb);
1860
1861         this.multi = sb.hasAttribute('multiple');
1862         this.optional = sb.hasAttribute('optional');
1863         this.placeholder = sb.getAttribute('placeholder') || '---';
1864         this.display_items = parseInt(sb.getAttribute('display-items') || 3);
1865         this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
1866         this.create = sb.getAttribute('item-create') || '.create-item-input';
1867         this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
1868
1869         var sbox = this,
1870             ul = sb.querySelector('ul'),
1871             items = ul.querySelectorAll('li'),
1872             more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
1873             open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, 'â–¾')),
1874             canary = sb.appendChild(E('div')),
1875             create = sb.querySelector(this.create),
1876             ndisplay = this.display_items,
1877             n = 0;
1878
1879         if (this.multi) {
1880                 for (var i = 0; i < items.length; i++) {
1881                         sbox.transformItem(sb, items[i]);
1882
1883                         if (items[i].hasAttribute('selected') && ndisplay-- > 0)
1884                                 items[i].setAttribute('display', n++);
1885                 }
1886         }
1887         else {
1888                 var sel = sb.querySelectorAll('[selected]');
1889
1890                 sel.forEach(function(s) {
1891                         s.removeAttribute('selected');
1892                 });
1893
1894                 var s = sel[0] || items[0];
1895                 if (s) {
1896                         s.setAttribute('selected', '');
1897                         s.setAttribute('display', n++);
1898                 }
1899
1900                 ndisplay--;
1901
1902                 if (this.optional && !ul.querySelector('li[data-value=""]')) {
1903                         var placeholder = E('li', { placeholder: '' }, this.placeholder);
1904                         ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
1905                 }
1906         }
1907
1908         sbox.saveValues(sb, ul);
1909
1910         ul.setAttribute('tabindex', -1);
1911         sb.setAttribute('tabindex', 0);
1912
1913         if (ndisplay < 0)
1914                 sb.setAttribute('more', '')
1915         else
1916                 sb.removeAttribute('more');
1917
1918         if (ndisplay === this.display_items)
1919                 sb.setAttribute('empty', '')
1920         else
1921                 sb.removeAttribute('empty');
1922
1923         more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1924
1925
1926         sb.addEventListener('click', function(ev) {
1927                 if (!this.hasAttribute('open')) {
1928                         if (!matchesElem(ev.target, 'input'))
1929                                 sbox.openDropdown(this);
1930                 }
1931                 else {
1932                         var li = findParent(ev.target, 'li');
1933                         if (li && li.parentNode.classList.contains('dropdown'))
1934                                 sbox.toggleItem(this, li);
1935                 }
1936
1937                 ev.preventDefault();
1938                 ev.stopPropagation();
1939         });
1940
1941         sb.addEventListener('keydown', function(ev) {
1942                 if (matchesElem(ev.target, 'input'))
1943                         return;
1944
1945                 if (!this.hasAttribute('open')) {
1946                         switch (ev.keyCode) {
1947                         case 37:
1948                         case 38:
1949                         case 39:
1950                         case 40:
1951                                 sbox.openDropdown(this);
1952                                 ev.preventDefault();
1953                         }
1954                 }
1955                 else
1956                 {
1957                         var active = findParent(document.activeElement, 'li');
1958
1959                         switch (ev.keyCode) {
1960                         case 27:
1961                                 sbox.closeDropdown(this);
1962                                 break;
1963
1964                         case 13:
1965                                 if (active) {
1966                                         if (!active.hasAttribute('selected'))
1967                                                 sbox.toggleItem(this, active);
1968                                         sbox.closeDropdown(this);
1969                                         ev.preventDefault();
1970                                 }
1971                                 break;
1972
1973                         case 32:
1974                                 if (active) {
1975                                         sbox.toggleItem(this, active);
1976                                         ev.preventDefault();
1977                                 }
1978                                 break;
1979
1980                         case 38:
1981                                 if (active && active.previousElementSibling) {
1982                                         sbox.setFocus(this, active.previousElementSibling);
1983                                         ev.preventDefault();
1984                                 }
1985                                 break;
1986
1987                         case 40:
1988                                 if (active && active.nextElementSibling) {
1989                                         sbox.setFocus(this, active.nextElementSibling);
1990                                         ev.preventDefault();
1991                                 }
1992                                 break;
1993                         }
1994                 }
1995         });
1996
1997         sb.addEventListener('cbi-dropdown-close', function(ev) {
1998                 sbox.closeDropdown(this, true);
1999         });
2000
2001         if ('ontouchstart' in window) {
2002                 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2003                 window.addEventListener('touchstart', sbox.closeAllDropdowns);
2004         }
2005         else {
2006                 sb.addEventListener('mouseover', function(ev) {
2007                         if (!this.hasAttribute('open'))
2008                                 return;
2009
2010                         var li = findParent(ev.target, 'li');
2011                         if (li) {
2012                                 if (li.parentNode.classList.contains('dropdown'))
2013                                         sbox.setFocus(this, li);
2014
2015                                 ev.stopPropagation();
2016                         }
2017                 });
2018
2019                 sb.addEventListener('focus', function(ev) {
2020                         document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
2021                                 if (s !== this || this.hasAttribute('open'))
2022                                         s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2023                         });
2024                 });
2025
2026                 canary.addEventListener('focus', function(ev) {
2027                         sbox.closeDropdown(this.parentNode);
2028                 });
2029
2030                 window.addEventListener('mouseover', sbox.setFocus);
2031                 window.addEventListener('click', sbox.closeAllDropdowns);
2032         }
2033
2034         if (create) {
2035                 create.addEventListener('keydown', function(ev) {
2036                         switch (ev.keyCode) {
2037                         case 13:
2038                                 ev.preventDefault();
2039
2040                                 if (this.classList.contains('cbi-input-invalid'))
2041                                         return;
2042
2043                                 sbox.createItems(sb, this.value);
2044                                 this.value = '';
2045                                 this.blur();
2046                                 break;
2047                         }
2048                 });
2049
2050                 create.addEventListener('focus', function(ev) {
2051                         var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2052                         if (cbox) cbox.checked = true;
2053                         sb.setAttribute('locked-in', '');
2054                 });
2055
2056                 create.addEventListener('blur', function(ev) {
2057                         var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2058                         if (cbox) cbox.checked = false;
2059                         sb.removeAttribute('locked-in');
2060                 });
2061
2062                 var li = findParent(create, 'li');
2063
2064                 li.setAttribute('unselectable', '');
2065                 li.addEventListener('click', function(ev) {
2066                         this.querySelector(sbox.create).focus();
2067                 });
2068         }
2069 }
2070
2071 cbi_dropdown_init.prototype = CBIDropdown;
2072
2073 function cbi_update_table(table, data, placeholder) {
2074         var target = isElem(table) ? table : document.querySelector(table);
2075
2076         if (!isElem(target))
2077                 return;
2078
2079         target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2080                 var titles = [];
2081
2082                 thead.querySelectorAll('.th').forEach(function(th) {
2083                         titles.push(th);
2084                 });
2085
2086                 if (Array.isArray(data)) {
2087                         var n = 0, rows = target.querySelectorAll('.tr');
2088
2089                         data.forEach(function(row) {
2090                                 var trow = E('div', { 'class': 'tr' });
2091
2092                                 for (var i = 0; i < titles.length; i++) {
2093                                         var text = (titles[i].innerText || '').trim();
2094                                         var td = trow.appendChild(E('div', {
2095                                                 'class': titles[i].className,
2096                                                 'data-title': (text !== '') ? text : null
2097                                         }, row[i] || ''));
2098
2099                                         td.classList.remove('th');
2100                                         td.classList.add('td');
2101                                 }
2102
2103                                 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2104
2105                                 if (rows[n])
2106                                         target.replaceChild(trow, rows[n]);
2107                                 else
2108                                         target.appendChild(trow);
2109                         });
2110
2111                         while (rows[++n])
2112                                 target.removeChild(rows[n]);
2113
2114                         if (placeholder && target.firstElementChild === target.lastElementChild) {
2115                                 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2116                                 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2117
2118                                 td.classList.remove('th');
2119                                 td.classList.add('td');
2120                         }
2121                 }
2122                 else {
2123                         thead.parentNode.style.display = 'none';
2124
2125                         thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2126                                 if (trow !== thead) {
2127                                         var n = 0;
2128                                         trow.querySelectorAll('.th, .td').forEach(function(td) {
2129                                                 if (n < titles.length) {
2130                                                         var text = (titles[n++].innerText || '').trim();
2131                                                         if (text !== '')
2132                                                                 td.setAttribute('data-title', text);
2133                                                 }
2134                                         });
2135                                 }
2136                         });
2137
2138                         thead.parentNode.style.display = '';
2139                 }
2140         });
2141 }
2142
2143 document.addEventListener('DOMContentLoaded', function() {
2144         document.querySelectorAll('.table').forEach(cbi_update_table);
2145 });