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