2 LuCI - Lua Configuration Interface
4 Copyright 2008 Steven Barth <steven@midlink.org>
5 Copyright 2008-2012 Jo-Philipp Wich <jow@openwrt.org>
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
11 http://www.apache.org/licenses/LICENSE-2.0
16 var cbi_strings = { path: {}, label: {} };
19 if (s === null || s.length === 0)
22 var hash = (s.length >>> 0),
23 len = (s.length >>> 2),
27 hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0;
28 tmp = ((((s.charCodeAt(off + 3) << 8) + s.charCodeAt(off + 2)) << 11) ^ hash) >>> 0;
29 hash = ((hash << 16) ^ tmp) >>> 0;
34 switch ((s.length & 3) >>> 0) {
36 hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0;
37 hash = (hash ^ (hash << 16)) >>> 0;
38 hash = (hash ^ (s.charCodeAt(off + 2) << 18)) >>> 0;
43 hash += ((s.charCodeAt(off + 1) << 8) + s.charCodeAt(off)) >>> 0;
44 hash = (hash ^ (hash << 11)) >>> 0;
49 hash += s.charCodeAt(off);
50 hash = (hash ^ (hash << 10)) >>> 0;
55 hash = (hash ^ (hash << 3)) >>> 0;
57 hash = (hash ^ (hash << 4)) >>> 0;
59 hash = (hash ^ (hash << 25)) >>> 0;
62 return (0x100000000 + hash).toString(16).substr(1);
66 return (window.TR && TR[sfh(s)]) || s;
70 return (/^-?\d+$/.test(x) ? +x : NaN);
74 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
78 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
81 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
84 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
88 if (x.match(/^([a-fA-F0-9:]+):(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/)) {
89 var v6 = RegExp.$1, v4 = IPv4(RegExp.$2);
94 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
95 + ':' + (v4[2] * 256 + v4[3]).toString(16);
98 if (!x.match(/^[a-fA-F0-9:]+$/))
101 var prefix_suffix = x.split(/::/);
103 if (prefix_suffix.length > 2)
106 var prefix = (prefix_suffix[0] || '0').split(/:/);
107 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
109 if (suffix.length ? (prefix.length + suffix.length > 7)
110 : ((prefix_suffix.length < 2 && prefix.length < 8) || prefix.length > 8))
116 for (i = 0, word = parseInt(prefix[0], 16); i < prefix.length; word = parseInt(prefix[++i], 16))
117 if (prefix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
122 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
125 for (i = 0, word = parseInt(suffix[0], 16); i < suffix.length; word = parseInt(suffix[++i], 16))
126 if (suffix[i].length <= 4 && !isNaN(word) && word <= 0xFFFF)
134 var cbi_validators = {
136 'integer': function()
141 'uinteger': function()
143 return (Int(this) >= 0);
153 return (Dec(this) >= 0);
158 return cbi_validators.ip4addr.apply(this) ||
159 cbi_validators.ip6addr.apply(this);
162 'ip4addr': function()
164 var m = this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?:\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|\/(\d{1,2}))?$/);
165 return !!(m && IPv4(m[1]) && (m[2] ? IPv4(m[2]) : (m[3] ? cbi_validators.ip4prefix.apply(m[3]) : true)));
168 'ip6addr': function()
170 var m = this.match(/^([0-9a-fA-F:.]+)(?:\/(\d{1,3}))?$/);
171 return !!(m && IPv6(m[1]) && (m[2] ? cbi_validators.ip6prefix.apply(m[2]) : true));
174 'ip4prefix': function()
176 return !isNaN(this) && this >= 0 && this <= 32;
179 'ip6prefix': function()
181 return !isNaN(this) && this >= 0 && this <= 128;
186 return cbi_validators.cidr4.apply(this) ||
187 cbi_validators.cidr6.apply(this);
192 var m = this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,2})$/);
193 return !!(m && IPv4(m[1]) && cbi_validators.ip4prefix.apply(m[2]));
198 var m = this.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
199 return !!(m && IPv6(m[1]) && cbi_validators.ip6prefix.apply(m[2]));
204 var m = this.match(/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/);
205 return !!(m && IPv4(m[1]) && IPv4(m[2]));
210 var m = this.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
211 return !!(m && IPv6(m[1]) && IPv6(m[2]));
214 'ip6hostid': function()
216 if (this == "eui64" || this == "random")
220 return !(!v6 || v6[0] || v6[1] || v6[2] || v6[3]);
225 return cbi_validators.ipmask4.apply(this) ||
226 cbi_validators.ipmask6.apply(this);
229 'ipmask4': function()
231 return cbi_validators.cidr4.apply(this) ||
232 cbi_validators.ipnet4.apply(this) ||
233 cbi_validators.ip4addr.apply(this);
236 'ipmask6': function()
238 return cbi_validators.cidr6.apply(this) ||
239 cbi_validators.ipnet6.apply(this) ||
240 cbi_validators.ip6addr.apply(this);
246 return (p >= 0 && p <= 65535);
249 'portrange': function()
251 if (this.match(/^(\d+)-(\d+)$/))
255 return (p1 <= p2 && p2 <= 65535);
258 return cbi_validators.port.apply(this);
261 'macaddr': function()
263 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
266 'host': function(ipv4only)
268 return cbi_validators.hostname.apply(this) ||
269 ((ipv4only != 1) && cbi_validators.ipaddr.apply(this)) ||
270 ((ipv4only == 1) && cbi_validators.ip4addr.apply(this));
273 'hostname': function(strict)
275 if (this.length <= 253)
276 return (this.match(/^[a-zA-Z0-9_]+$/) != null ||
277 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
278 this.match(/[^0-9.]/))) &&
279 (!strict || !this.match(/^_/));
284 'network': function()
286 return cbi_validators.uciname.apply(this) ||
287 cbi_validators.host.apply(this);
290 'hostport': function(ipv4only)
292 var hp = this.split(/:/);
295 return (cbi_validators.host.apply(hp[0], ipv4only) &&
296 cbi_validators.port.apply(hp[1]));
301 'ip4addrport': function()
303 var hp = this.split(/:/);
306 return (cbi_validators.ipaddr.apply(hp[0]) &&
307 cbi_validators.port.apply(hp[1]));
311 'ipaddrport': function(bracket)
313 if (this.match(/^([^\[\]:]+):([^:]+)$/)) {
316 return (cbi_validators.ip4addr.apply(addr) &&
317 cbi_validators.port.apply(port));
318 } else if ((bracket == 1) && (this.match(/^\[(.+)\]:([^:]+)$/))) {
321 return (cbi_validators.ip6addr.apply(addr) &&
322 cbi_validators.port.apply(port));
323 } else if ((bracket != 1) && (this.match(/^([^\[\]]+):([^:]+)$/))) {
326 return (cbi_validators.ip6addr.apply(addr) &&
327 cbi_validators.port.apply(port));
338 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
340 return (v.length >= 8) && (v.length <= 63);
347 if ( v.substr(0,2) == 's:' )
350 if( (v.length == 10) || (v.length == 26) )
351 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
353 return (v.length == 5) || (v.length == 13);
356 'uciname': function()
358 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
361 'range': function(min, max)
364 return (val >= +min && val <= +max);
369 return (Dec(this) >= +min);
374 return (Dec(this) <= +max);
377 'rangelength': function(min, max)
380 return ((val.length >= +min) && (val.length <= +max));
383 'minlength': function(min)
385 return ((''+this).length >= +min);
388 'maxlength': function(max)
390 return ((''+this).length <= +max);
395 for (var i = 0; i < arguments.length; i += 2)
397 if (typeof arguments[i] != 'function')
399 if (arguments[i] == this)
403 else if (arguments[i].apply(this, arguments[i+1]))
413 for (var i = 0; i < arguments.length; i += 2)
415 if (typeof arguments[i] != 'function')
417 if (arguments[i] != this)
421 else if (!arguments[i].apply(this, arguments[i+1]))
431 return cbi_validators.or.apply(
432 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
435 'list': function(subvalidator, subargs)
437 if (typeof subvalidator != 'function')
440 var tokens = this.match(/[^ \t]+/g);
441 for (var i = 0; i < tokens.length; i++)
442 if (!subvalidator.apply(tokens[i], subargs))
447 'phonedigit': function()
449 return (this.match(/^[0-9\*#!\.]+$/) != null);
451 'timehhmmss': function()
453 return (this.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/) != null);
455 'dateyyyymmdd': function()
460 if (this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
461 var year = RegExp.$1;
462 var month = RegExp.$2;
465 var days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30 , 31, 30, 31 ];
466 function is_leap_year(year) {
467 return ((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0);
469 function get_days_in_month(month, year) {
470 if ((month == 2) && is_leap_year(year)) {
473 return days_in_month[month];
476 /* Firewall rules in the past don't make sense */
480 if ((month <= 0) || (month > 12)) {
483 if ((day <= 0) || (day > get_days_in_month(month, year))) {
495 function cbi_d_add(field, dep, index) {
496 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
499 for (var i=0; i<cbi_d.length; i++) {
500 if (cbi_d[i].id == obj.id) {
509 "parent": obj.parentNode.id,
513 cbi_d.unshift(entry);
519 function cbi_d_checkvalue(target, ref) {
521 query = 'input[id="'+target+'"], input[name="'+target+'"], ' +
522 'select[id="'+target+'"], select[name="'+target+'"]';
524 document.querySelectorAll(query).forEach(function(i) {
525 if (value === null && ((i.type !== 'radio' && i.type !== 'checkbox') || i.checked === true))
529 return (((value !== null) ? value : "") == ref);
532 function cbi_d_check(deps) {
535 for (var i=0; i<deps.length; i++) {
538 for (var j in deps[i]) {
539 if (j == "!reverse") {
541 } else if (j == "!default") {
545 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
549 if (istat ^ reverse) {
556 function cbi_d_update() {
558 for (var i=0; i<cbi_d.length; i++) {
559 var entry = cbi_d[i];
560 var node = document.getElementById(entry.id);
561 var parent = document.getElementById(entry.parent);
563 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
564 node.parentNode.removeChild(node);
567 else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
568 var next = undefined;
570 for (next = parent.firstChild; next; next = next.nextSibling) {
571 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index)
576 parent.appendChild(entry.node);
578 parent.insertBefore(entry.node, next);
583 // hide optionals widget if no choices remaining
584 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
585 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
588 if (entry && entry.parent) {
590 cbi_tag_last(parent);
597 function cbi_init() {
600 nodes = document.querySelectorAll('[data-strings]');
602 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
603 var str = JSON.parse(node.getAttribute('data-strings'));
604 for (var key in str) {
605 for (var key2 in str[key]) {
606 var dst = cbi_strings[key] || (cbi_strings[key] = { });
607 dst[key2] = str[key][key2];
612 nodes = document.querySelectorAll('[data-depends]');
614 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
615 var index = parseInt(node.getAttribute('data-index'), 10);
616 var depends = JSON.parse(node.getAttribute('data-depends'));
617 if (!isNaN(index) && depends.length > 0) {
618 for (var alt = 0; alt < depends.length; alt++)
619 cbi_d_add(node, depends[alt], index);
623 nodes = document.querySelectorAll('[data-update]');
625 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
626 var events = node.getAttribute('data-update').split(' ');
627 for (var j = 0, event; (event = events[j]) !== undefined; j++)
628 cbi_bind(node, event, cbi_d_update);
631 nodes = document.querySelectorAll('[data-choices]');
633 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
634 var choices = JSON.parse(node.getAttribute('data-choices'));
637 for (var j = 0; j < choices[0].length; j++)
638 options[choices[0][j]] = choices[1][j];
640 var def = (node.getAttribute('data-optional') === 'true')
641 ? node.placeholder || '' : null;
643 cbi_combobox_init(node, options, def,
644 node.getAttribute('data-manual'));
647 nodes = document.querySelectorAll('[data-dynlist]');
649 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
650 var choices = JSON.parse(node.getAttribute('data-dynlist'));
653 if (choices[0] && choices[0].length) {
656 for (var j = 0; j < choices[0].length; j++)
657 options[choices[0][j]] = choices[1][j];
660 cbi_dynlist_init(node, choices[2], choices[3], options);
663 nodes = document.querySelectorAll('[data-type]');
665 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
666 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
667 node.getAttribute('data-type'));
670 document.querySelectorAll('.cbi-dropdown').forEach(function(s) {
671 cbi_dropdown_init(s);
674 document.querySelectorAll('.cbi-tooltip:not(:empty)').forEach(function(s) {
675 s.parentNode.classList.add('cbi-tooltip-container');
678 document.querySelectorAll('.cbi-section-remove > input[name^="cbi.rts"]').forEach(function(i) {
679 var handler = function(ev) {
680 var bits = this.name.split(/\./),
681 section = document.getElementById('cbi-' + bits[2] + '-' + bits[3]);
683 section.style.opacity = (ev.type === 'mouseover') ? 0.5 : '';
686 i.addEventListener('mouseover', handler);
687 i.addEventListener('mouseout', handler);
693 function cbi_bind(obj, type, callback, mode) {
694 if (!obj.addEventListener) {
695 obj.attachEvent('on' + type,
697 var e = window.event;
699 if (!e.target && e.srcElement)
700 e.target = e.srcElement;
702 return !!callback(e);
706 obj.addEventListener(type, callback, !!mode);
711 function cbi_combobox(id, values, def, man, focus) {
712 var selid = "cbi.combobox." + id;
713 if (document.getElementById(selid)) {
717 var obj = document.getElementById(id)
718 var sel = document.createElement("select");
720 sel.index = obj.index;
721 sel.classList.remove('cbi-input-text');
722 sel.classList.add('cbi-input-select');
725 obj.parentNode.insertBefore(sel, obj.nextSibling);
727 obj.parentNode.appendChild(sel);
729 var dt = obj.getAttribute('cbi_datatype');
730 var op = obj.getAttribute('cbi_optional');
732 if (!values[obj.value]) {
733 if (obj.value == "") {
734 var optdef = document.createElement("option");
736 optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : _('-- Please choose --')));
737 sel.appendChild(optdef);
740 var opt = document.createElement("option");
741 opt.value = obj.value;
742 opt.selected = "selected";
743 opt.appendChild(document.createTextNode(obj.value));
744 sel.appendChild(opt);
748 for (var i in values) {
749 var opt = document.createElement("option");
753 opt.selected = "selected";
755 opt.appendChild(document.createTextNode(values[i]));
756 sel.appendChild(opt);
759 var optman = document.createElement("option");
761 optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : _('-- custom --')));
762 sel.appendChild(optman);
764 obj.style.display = "none";
767 cbi_validate_field(sel, op == 'true', dt);
769 cbi_bind(sel, "change", function() {
770 if (sel.selectedIndex == sel.options.length - 1) {
771 obj.style.display = "inline";
773 sel.parentNode.removeChild(sel);
777 obj.value = sel.options[sel.selectedIndex].value;
787 // Retrigger validation in select
794 function cbi_combobox_init(id, values, def, man) {
795 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
796 cbi_bind(obj, "blur", function() {
797 cbi_combobox(obj.id, values, def, man, true);
799 cbi_combobox(obj.id, values, def, man, false);
802 function cbi_filebrowser(id, defpath) {
803 var field = document.getElementById(id);
804 var browser = window.open(
805 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
806 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
812 function cbi_browser_init(id, resource, defpath)
814 function cbi_browser_btnclick(e) {
815 cbi_filebrowser(id, defpath);
819 var field = document.getElementById(id);
821 var btn = document.createElement('img');
822 btn.className = 'cbi-image-button';
823 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
824 field.parentNode.insertBefore(btn, field.nextSibling);
826 cbi_bind(btn, 'click', cbi_browser_btnclick);
829 function cbi_dynlist_init(parent, datatype, optional, choices)
831 var prefix = parent.getAttribute('data-prefix');
832 var holder = parent.getAttribute('data-placeholder');
836 function cbi_dynlist_redraw(focus, add, del)
840 while (parent.firstChild) {
841 var n = parent.firstChild;
845 if (matchesElem(n, 'input'))
846 values.push(n.value || '');
847 else if (matchesElem(n, 'select'))
848 values[values.length-1] = n.options[n.selectedIndex].value;
851 parent.removeChild(n);
856 values.splice(focus, 0, '');
858 else if (values.length == 0) {
863 for (var i = 0; i < values.length; i++) {
864 var t = document.createElement('input');
865 t.id = prefix + '.' + (i+1);
870 t.className = 'cbi-input-text';
872 if (i == 0 && holder)
873 t.placeholder = holder;
876 class: 'cbi-button cbi-button-' + ((i+1) < values.length ? 'remove' : 'add')
877 }, (i+1) < values.length ? '×' : '+');
879 parent.appendChild(t);
880 parent.appendChild(b);
882 if (datatype == 'file')
883 cbi_browser_init(t.id, null, parent.getAttribute('data-browser-path'));
885 parent.appendChild(document.createElement('br'));
888 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
891 cbi_combobox_init(t.id, choices, '', _('-- custom --'));
894 cbi_bind(b, 'keydown', cbi_dynlist_keydown);
895 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
897 if (i == focus || -i == focus)
901 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
902 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
907 else if (-i == focus) {
910 /* force cursor to end */
917 cbi_bind(b, 'click', cbi_dynlist_btnclick);
921 function cbi_dynlist_keypress(ev)
923 ev = ev ? ev : window.event;
925 var se = ev.target ? ev.target : ev.srcElement;
927 if (se.nodeType == 3)
930 switch (ev.keyCode) {
931 /* backspace, delete */
934 if (se.value.length == 0) {
935 if (ev.preventDefault)
943 /* enter, arrow up, arrow down */
947 if (ev.preventDefault)
956 function cbi_dynlist_keydown(ev)
958 ev = ev ? ev : window.event;
960 var se = ev.target ? ev.target : ev.srcElement;
962 if (se.nodeType == 3)
965 var prev = se.previousSibling;
966 while (prev && prev.name != prefix)
967 prev = prev.previousSibling;
969 var next = se.nextSibling;
970 while (next && next.name != prefix)
971 next = next.nextSibling;
973 /* advance one further in combobox case */
974 if (next && next.nextSibling.name == prefix)
975 next = next.nextSibling;
977 switch (ev.keyCode) {
978 /* backspace, delete */
981 var del = (matchesElem(se, 'select'))
982 ? true : (se.value.length == 0);
985 if (ev.preventDefault)
988 var focus = se.index;
992 cbi_dynlist_redraw(focus, -1, se.index);
1001 cbi_dynlist_redraw(-1, se.index, -1);
1022 function cbi_dynlist_btnclick(ev)
1024 ev = ev ? ev : window.event;
1026 var se = ev.target ? ev.target : ev.srcElement;
1027 var input = se.previousSibling;
1028 while (input && input.name != prefix)
1029 input = input.previousSibling;
1031 if (se.classList.contains('cbi-button-remove')) {
1034 cbi_dynlist_keydown({
1040 cbi_dynlist_keydown({
1049 cbi_dynlist_redraw(NaN, -1, -1);
1053 function cbi_t_add(section, tab) {
1054 var t = document.getElementById('tab.' + section + '.' + tab);
1055 var c = document.getElementById('container.' + section + '.' + tab);
1058 cbi_t[section] = (cbi_t[section] || [ ]);
1059 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1063 function cbi_t_switch(section, tab) {
1064 if (cbi_t[section] && cbi_t[section][tab]) {
1065 var o = cbi_t[section][tab];
1066 var h = document.getElementById('tab.' + section);
1068 for (var tid in cbi_t[section]) {
1069 var o2 = cbi_t[section][tid];
1071 if (o.tab.id != o2.tab.id) {
1072 o2.tab.classList.remove('cbi-tab');
1073 o2.tab.classList.add('cbi-tab-disabled');
1074 o2.container.style.display = 'none';
1080 o2.tab.classList.remove('cbi-tab-disabled');
1081 o2.tab.classList.add('cbi-tab');
1082 o2.container.style.display = 'block';
1090 function cbi_t_update() {
1092 var updated = false;
1094 for (var sid in cbi_t)
1095 for (var tid in cbi_t[sid]) {
1096 var t = cbi_t[sid][tid].tab;
1097 var c = cbi_t[sid][tid].container;
1099 if (!c.firstElementChild) {
1100 t.style.display = 'none';
1102 else if (t.style.display == 'none') {
1103 t.style.display = '';
1104 t.classList.add('cbi-tab-highlighted');
1112 if (hl_tabs.length > 0)
1113 window.setTimeout(function() {
1114 for (var i = 0; i < hl_tabs.length; i++)
1115 hl_tabs[i].classList.remove('cbi-tab-highlighted');
1122 function cbi_validate_form(form, errmsg)
1124 /* if triggered by a section removal or addition, don't validate */
1125 if (form.cbi_state == 'add-section' || form.cbi_state == 'del-section')
1128 if (form.cbi_validators) {
1129 for (var i = 0; i < form.cbi_validators.length; i++) {
1130 var validator = form.cbi_validators[i];
1132 if (!validator() && errmsg) {
1142 function cbi_validate_reset(form)
1145 function() { cbi_validate_form(form, null) }, 100
1151 function cbi_validate_compile(code)
1160 for (var i = 0; i < code.length; i++) {
1166 switch (code.charCodeAt(i))
1176 var label = code.substring(pos, i);
1177 label = label.replace(/\\(.)/g, '$1');
1178 label = label.replace(/^[ \t]+/g, '');
1179 label = label.replace(/[ \t]+$/g, '');
1181 if (label && !isNaN(label)) {
1182 stack.push(parseFloat(label));
1184 else if (label.match(/^(['"]).*\1$/)) {
1185 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1187 else if (typeof cbi_validators[label] == 'function') {
1188 stack.push(cbi_validators[label]);
1192 throw "Syntax error, unhandled token '"+label+"'";
1199 depth += (code.charCodeAt(i) == 40);
1204 if (typeof stack[stack.length-2] != 'function')
1205 throw "Syntax error, argument list follows non-function";
1207 stack[stack.length-1] =
1208 arguments.callee(code.substring(pos, i));
1220 function cbi_validate_field(cbid, optional, type)
1222 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1223 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1225 if (field && vstack && typeof vstack[0] == "function") {
1226 var validator = function()
1230 field.classList.remove('cbi-input-invalid');
1233 var value = (field.options && field.options.selectedIndex > -1)
1234 ? field.options[field.options.selectedIndex].value : field.value;
1236 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1]))) {
1238 field.classList.add('cbi-input-invalid');
1246 if (!field.form.cbi_validators)
1247 field.form.cbi_validators = [ ];
1249 field.form.cbi_validators.push(validator);
1251 cbi_bind(field, "blur", validator);
1252 cbi_bind(field, "keyup", validator);
1254 if (matchesElem(field, 'select')) {
1255 cbi_bind(field, "change", validator);
1256 cbi_bind(field, "click", validator);
1259 field.setAttribute("cbi_validate", validator);
1260 field.setAttribute("cbi_datatype", type);
1261 field.setAttribute("cbi_optional", (!!optional).toString());
1265 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1267 cbi_validate_field(fcbox, optional, type);
1271 function cbi_row_swap(elem, up, store)
1273 var tr = findParent(elem.parentNode, '.cbi-section-table-row');
1278 tr.classList.remove('flash');
1281 var prev = tr.previousElementSibling;
1283 if (prev && prev.classList.contains('cbi-section-table-row'))
1284 tr.parentNode.insertBefore(tr, prev);
1289 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1291 if (next && next.classList.contains('cbi-section-table-row'))
1292 tr.parentNode.insertBefore(tr, next);
1294 tr.parentNode.appendChild(tr);
1301 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1302 var node = tr.parentNode.childNodes[i];
1303 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1304 node.classList.remove('cbi-rowstyle-1');
1305 node.classList.remove('cbi-rowstyle-2');
1306 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1308 if (/-([^\-]+)$/.test(node.id))
1309 ids.push(RegExp.$1);
1313 var input = document.getElementById(store);
1315 input.value = ids.join(' ');
1317 window.scrollTo(0, tr.offsetTop);
1318 void tr.offsetWidth;
1319 tr.classList.add('flash');
1324 function cbi_tag_last(container)
1328 for (var i = 0; i < container.childNodes.length; i++) {
1329 var c = container.childNodes[i];
1330 if (matchesElem(c, 'div')) {
1331 c.classList.remove('cbi-value-last');
1337 last.classList.add('cbi-value-last');
1340 function cbi_submit(elem, name, value, action)
1342 var form = elem.form || findParent(elem, 'form');
1348 form.action = action;
1351 var hidden = form.querySelector('input[type="hidden"][name="%s"]'.format(name)) ||
1352 E('input', { type: 'hidden', name: name });
1354 hidden.value = value || '1';
1355 form.appendChild(hidden);
1362 String.prototype.format = function()
1367 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1368 var quot_esc = [/"/g, '"', /'/g, '''];
1370 function esc(s, r) {
1371 if (typeof(s) !== 'string' && !(s instanceof String))
1374 for (var i = 0; i < r.length; i += 2)
1375 s = s.replace(r[i], r[i+1]);
1382 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1383 var a = b = [], numSubstitutions = 0, numMatches = 0;
1385 while (a = re.exec(str)) {
1387 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1388 var pPrecision = a[6], pType = a[7];
1396 if (numSubstitutions < arguments.length) {
1397 var param = arguments[numSubstitutions++];
1400 if (pPad && pPad.substr(0,1) == "'")
1401 pad = leftpart.substr(1,1);
1407 var justifyRight = true;
1408 if (pJustify && pJustify === "-")
1409 justifyRight = false;
1413 minLength = +pMinLength;
1416 if (pPrecision && pType == 'f')
1417 precision = +pPrecision.substring(1);
1423 subst = (+param || 0).toString(2);
1427 subst = String.fromCharCode(+param || 0);
1431 subst = ~~(+param || 0);
1435 subst = ~~Math.abs(+param || 0);
1439 subst = (precision > -1)
1440 ? ((+param || 0.0)).toFixed(precision)
1445 subst = (+param || 0).toString(8);
1453 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1457 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1461 subst = esc(param, html_esc);
1465 subst = esc(param, quot_esc);
1472 var ts = (param || 0);
1475 tm = Math.floor(ts / 60);
1480 th = Math.floor(tm / 60);
1485 td = Math.floor(th / 24);
1490 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1491 : String.format('%dh %dm %ds', th, tm, ts);
1496 var mf = pMinLength ? +pMinLength : 1000;
1497 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1500 var val = (+param || 0);
1501 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1503 for (i = 0; (i < units.length) && (val > mf); i++)
1506 subst = (i ? val.toFixed(pr) : val) + units[i];
1514 subst = subst.toString();
1515 for (var i = subst.length; i < pMinLength; i++)
1516 if (pJustify == '-')
1517 subst = subst + ' ';
1519 subst = pad + subst;
1522 out += leftpart + subst;
1523 str = str.substr(m.length);
1529 String.prototype.nobr = function()
1531 return this.replace(/[\s\n]+/g, ' ');
1534 String.format = function()
1538 for (var i = 1; i < arguments.length; i++)
1539 a.push(arguments[i]);
1541 return ''.format.apply(arguments[0], a);
1544 String.nobr = function()
1548 for (var i = 1; i < arguments.length; i++)
1549 a.push(arguments[i]);
1551 return ''.nobr.apply(arguments[0], a);
1554 if (window.NodeList && !NodeList.prototype.forEach) {
1555 NodeList.prototype.forEach = function (callback, thisArg) {
1556 thisArg = thisArg || window;
1557 for (var i = 0; i < this.length; i++) {
1558 callback.call(thisArg, this[i], i, this);
1564 var dummyElem, domParser;
1568 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1576 domParser = domParser || new DOMParser();
1577 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1583 dummyElem = dummyElem || document.createElement('div');
1584 dummyElem.innerHTML = s;
1585 elem = dummyElem.firstChild;
1590 return elem || null;
1593 function matchesElem(node, selector)
1595 return ((node.matches && node.matches(selector)) ||
1596 (node.msMatchesSelector && node.msMatchesSelector(selector)));
1599 function findParent(node, selector)
1602 if (matchesElem(node, selector))
1605 node = node.parentNode;
1612 var html = arguments[0],
1613 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1614 data = attr ? arguments[2] : arguments[1],
1619 else if (html.charCodeAt(0) === 60)
1620 elem = toElem(html);
1622 elem = document.createElement(html);
1628 for (var key in attr)
1629 if (attr.hasOwnProperty(key) && attr[key] !== null && attr[key] !== undefined)
1630 elem.setAttribute(key, attr[key]);
1632 if (typeof(data) === 'function')
1636 elem.appendChild(data);
1638 else if (Array.isArray(data)) {
1639 for (var i = 0; i < data.length; i++)
1640 if (isElem(data[i]))
1641 elem.appendChild(data[i]);
1643 elem.appendChild(document.createTextNode('' + data[i]));
1645 else if (data !== null && data !== undefined) {
1646 elem.innerHTML = '' + data;
1652 if (typeof(window.CustomEvent) !== 'function') {
1653 function CustomEvent(event, params) {
1654 params = params || { bubbles: false, cancelable: false, detail: undefined };
1655 var evt = document.createEvent('CustomEvent');
1656 evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
1660 CustomEvent.prototype = window.Event.prototype;
1661 window.CustomEvent = CustomEvent;
1665 openDropdown: function(sb) {
1666 var st = window.getComputedStyle(sb, null),
1667 ul = sb.querySelector('ul'),
1668 li = ul.querySelectorAll('li'),
1669 sel = ul.querySelector('[selected]'),
1670 rect = sb.getBoundingClientRect(),
1671 h = sb.clientHeight - parseFloat(st.paddingTop) - parseFloat(st.paddingBottom),
1672 mh = this.dropdown_items * h,
1673 eh = Math.min(mh, li.length * h);
1675 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1676 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1679 ul.style.maxHeight = mh + 'px';
1680 sb.setAttribute('open', '');
1682 ul.scrollTop = sel ? Math.max(sel.offsetTop - sel.offsetHeight, 0) : 0;
1683 ul.querySelectorAll('[selected] input[type="checkbox"]').forEach(function(c) {
1687 ul.style.top = ul.style.bottom = '';
1688 ul.style[((sb.getBoundingClientRect().top + eh) > window.innerHeight) ? 'bottom' : 'top'] = rect.height + 'px';
1689 ul.classList.add('dropdown');
1691 var pv = ul.cloneNode(true);
1692 pv.classList.remove('dropdown');
1693 pv.classList.add('preview');
1695 sb.insertBefore(pv, ul.nextElementSibling);
1697 li.forEach(function(l) {
1698 l.setAttribute('tabindex', 0);
1701 sb.lastElementChild.setAttribute('tabindex', 0);
1703 this.setFocus(sb, sel || li[0], true);
1706 closeDropdown: function(sb, no_focus) {
1707 if (!sb.hasAttribute('open'))
1710 var pv = sb.querySelector('ul.preview'),
1711 ul = sb.querySelector('ul.dropdown'),
1712 li = ul.querySelectorAll('li');
1714 li.forEach(function(l) { l.removeAttribute('tabindex'); });
1715 sb.lastElementChild.removeAttribute('tabindex');
1718 sb.removeAttribute('open');
1719 sb.style.width = sb.style.height = '';
1721 ul.classList.remove('dropdown');
1724 this.setFocus(sb, sb);
1726 this.saveValues(sb, ul);
1729 toggleItem: function(sb, li, force_state) {
1730 if (li.hasAttribute('unselectable'))
1734 var cbox = li.querySelector('input[type="checkbox"]'),
1735 items = li.parentNode.querySelectorAll('li'),
1736 label = sb.querySelector('ul.preview'),
1737 sel = li.parentNode.querySelectorAll('[selected]').length,
1738 more = sb.querySelector('.more'),
1739 ndisplay = this.display_items,
1742 if (li.hasAttribute('selected')) {
1743 if (force_state !== true) {
1744 if (sel > 1 || this.optional) {
1745 li.removeAttribute('selected');
1746 cbox.checked = cbox.disabled = false;
1750 cbox.disabled = true;
1755 if (force_state !== false) {
1756 li.setAttribute('selected', '');
1757 cbox.checked = true;
1758 cbox.disabled = false;
1763 while (label.firstElementChild)
1764 label.removeChild(label.firstElementChild);
1766 for (var i = 0; i < items.length; i++) {
1767 items[i].removeAttribute('display');
1768 if (items[i].hasAttribute('selected')) {
1769 if (ndisplay-- > 0) {
1770 items[i].setAttribute('display', n++);
1771 label.appendChild(items[i].cloneNode(true));
1773 var c = items[i].querySelector('input[type="checkbox"]');
1775 c.disabled = (sel == 1 && !this.optional);
1780 sb.setAttribute('more', '');
1782 sb.removeAttribute('more');
1784 if (ndisplay === this.display_items)
1785 sb.setAttribute('empty', '');
1787 sb.removeAttribute('empty');
1789 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1792 var sel = li.parentNode.querySelector('[selected]');
1794 sel.removeAttribute('display');
1795 sel.removeAttribute('selected');
1798 li.setAttribute('display', 0);
1799 li.setAttribute('selected', '');
1801 this.closeDropdown(sb, true);
1804 this.saveValues(sb, li.parentNode);
1807 transformItem: function(sb, li) {
1808 var cbox = E('form', {}, E('input', { type: 'checkbox', tabindex: -1, onclick: 'event.preventDefault()' })),
1811 while (li.firstChild)
1812 label.appendChild(li.firstChild);
1814 li.appendChild(cbox);
1815 li.appendChild(label);
1818 saveValues: function(sb, ul) {
1819 var sel = ul.querySelectorAll('[selected]'),
1820 div = sb.lastElementChild;
1822 while (div.lastElementChild)
1823 div.removeChild(div.lastElementChild);
1825 sel.forEach(function (s) {
1826 div.appendChild(E('input', {
1828 name: s.hasAttribute('name') ? s.getAttribute('name') : (sb.getAttribute('name') || ''),
1829 value: s.hasAttribute('data-value') ? s.getAttribute('data-value') : s.innerText
1836 setFocus: function(sb, elem, scroll) {
1837 if (sb && sb.hasAttribute && sb.hasAttribute('locked-in'))
1840 document.querySelectorAll('.focus').forEach(function(e) {
1841 if (!matchesElem(e, 'input')) {
1842 e.classList.remove('focus');
1849 elem.classList.add('focus');
1852 elem.parentNode.scrollTop = elem.offsetTop - elem.parentNode.offsetTop;
1856 createItems: function(sb, value) {
1858 val = (value || '').trim().split(/\s+/),
1859 ul = sb.querySelector('ul');
1862 val.length = Math.min(val.length, 1);
1864 val.forEach(function(item) {
1865 var new_item = null;
1867 ul.childNodes.forEach(function(li) {
1868 if (li.getAttribute && li.getAttribute('data-value') === item)
1874 tpl = sb.querySelector(sbox.template);
1877 markup = (tpl.textContent || tpl.innerHTML || tpl.firstChild.data).replace(/^<!--|-->$/, '').trim();
1879 markup = '<li data-value="{{value}}">{{value}}</li>';
1881 new_item = E(markup.replace(/{{value}}/g, item));
1884 sbox.transformItem(sb, new_item);
1887 var old = ul.querySelector('li[created]');
1889 ul.removeChild(old);
1891 new_item.setAttribute('created', '');
1894 new_item = ul.insertBefore(new_item, ul.lastElementChild);
1897 sbox.toggleItem(sb, new_item, true);
1898 sbox.setFocus(sb, new_item, true);
1902 closeAllDropdowns: function() {
1903 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
1904 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
1909 function cbi_dropdown_init(sb) {
1910 if (!(this instanceof cbi_dropdown_init))
1911 return new cbi_dropdown_init(sb);
1913 this.multi = sb.hasAttribute('multiple');
1914 this.optional = sb.hasAttribute('optional');
1915 this.placeholder = sb.getAttribute('placeholder') || '---';
1916 this.display_items = parseInt(sb.getAttribute('display-items') || 3);
1917 this.dropdown_items = parseInt(sb.getAttribute('dropdown-items') || 5);
1918 this.create = sb.getAttribute('item-create') || '.create-item-input';
1919 this.template = sb.getAttribute('item-template') || 'script[type="item-template"]';
1922 ul = sb.querySelector('ul'),
1923 items = ul.querySelectorAll('li'),
1924 more = sb.appendChild(E('span', { class: 'more', tabindex: -1 }, '···')),
1925 open = sb.appendChild(E('span', { class: 'open', tabindex: -1 }, '▾')),
1926 canary = sb.appendChild(E('div')),
1927 create = sb.querySelector(this.create),
1928 ndisplay = this.display_items,
1932 for (var i = 0; i < items.length; i++) {
1933 sbox.transformItem(sb, items[i]);
1935 if (items[i].hasAttribute('selected') && ndisplay-- > 0)
1936 items[i].setAttribute('display', n++);
1940 var sel = sb.querySelectorAll('[selected]');
1942 sel.forEach(function(s) {
1943 s.removeAttribute('selected');
1946 var s = sel[0] || items[0];
1948 s.setAttribute('selected', '');
1949 s.setAttribute('display', n++);
1954 if (this.optional && !ul.querySelector('li[data-value=""]')) {
1955 var placeholder = E('li', { placeholder: '' }, this.placeholder);
1956 ul.firstChild ? ul.insertBefore(placeholder, ul.firstChild) : ul.appendChild(placeholder);
1960 sbox.saveValues(sb, ul);
1962 ul.setAttribute('tabindex', -1);
1963 sb.setAttribute('tabindex', 0);
1966 sb.setAttribute('more', '')
1968 sb.removeAttribute('more');
1970 if (ndisplay === this.display_items)
1971 sb.setAttribute('empty', '')
1973 sb.removeAttribute('empty');
1975 more.innerHTML = (ndisplay === this.display_items) ? this.placeholder : '···';
1978 sb.addEventListener('click', function(ev) {
1979 if (!this.hasAttribute('open')) {
1980 if (!matchesElem(ev.target, 'input'))
1981 sbox.openDropdown(this);
1984 var li = findParent(ev.target, 'li');
1985 if (li && li.parentNode.classList.contains('dropdown'))
1986 sbox.toggleItem(this, li);
1989 ev.preventDefault();
1990 ev.stopPropagation();
1993 sb.addEventListener('keydown', function(ev) {
1994 if (matchesElem(ev.target, 'input'))
1997 if (!this.hasAttribute('open')) {
1998 switch (ev.keyCode) {
2003 sbox.openDropdown(this);
2004 ev.preventDefault();
2009 var active = findParent(document.activeElement, 'li');
2011 switch (ev.keyCode) {
2013 sbox.closeDropdown(this);
2018 if (!active.hasAttribute('selected'))
2019 sbox.toggleItem(this, active);
2020 sbox.closeDropdown(this);
2021 ev.preventDefault();
2027 sbox.toggleItem(this, active);
2028 ev.preventDefault();
2033 if (active && active.previousElementSibling) {
2034 sbox.setFocus(this, active.previousElementSibling);
2035 ev.preventDefault();
2040 if (active && active.nextElementSibling) {
2041 sbox.setFocus(this, active.nextElementSibling);
2042 ev.preventDefault();
2049 sb.addEventListener('cbi-dropdown-close', function(ev) {
2050 sbox.closeDropdown(this, true);
2053 if ('ontouchstart' in window) {
2054 sb.addEventListener('touchstart', function(ev) { ev.stopPropagation(); });
2055 window.addEventListener('touchstart', sbox.closeAllDropdowns);
2058 sb.addEventListener('mouseover', function(ev) {
2059 if (!this.hasAttribute('open'))
2062 var li = findParent(ev.target, 'li');
2064 if (li.parentNode.classList.contains('dropdown'))
2065 sbox.setFocus(this, li);
2067 ev.stopPropagation();
2071 sb.addEventListener('focus', function(ev) {
2072 document.querySelectorAll('.cbi-dropdown[open]').forEach(function(s) {
2073 if (s !== this || this.hasAttribute('open'))
2074 s.dispatchEvent(new CustomEvent('cbi-dropdown-close', {}));
2078 canary.addEventListener('focus', function(ev) {
2079 sbox.closeDropdown(this.parentNode);
2082 window.addEventListener('mouseover', sbox.setFocus);
2083 window.addEventListener('click', sbox.closeAllDropdowns);
2087 create.addEventListener('keydown', function(ev) {
2088 switch (ev.keyCode) {
2090 ev.preventDefault();
2092 if (this.classList.contains('cbi-input-invalid'))
2095 sbox.createItems(sb, this.value);
2102 create.addEventListener('focus', function(ev) {
2103 var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2104 if (cbox) cbox.checked = true;
2105 sb.setAttribute('locked-in', '');
2108 create.addEventListener('blur', function(ev) {
2109 var cbox = findParent(this, 'li').querySelector('input[type="checkbox"]');
2110 if (cbox) cbox.checked = false;
2111 sb.removeAttribute('locked-in');
2114 var li = findParent(create, 'li');
2116 li.setAttribute('unselectable', '');
2117 li.addEventListener('click', function(ev) {
2118 this.querySelector(sbox.create).focus();
2123 cbi_dropdown_init.prototype = CBIDropdown;
2125 function cbi_update_table(table, data, placeholder) {
2126 var target = isElem(table) ? table : document.querySelector(table);
2128 if (!isElem(target))
2131 target.querySelectorAll('.tr.table-titles, .cbi-section-table-titles').forEach(function(thead) {
2134 thead.querySelectorAll('.th').forEach(function(th) {
2138 if (Array.isArray(data)) {
2139 var n = 0, rows = target.querySelectorAll('.tr');
2141 data.forEach(function(row) {
2142 var trow = E('div', { 'class': 'tr' });
2144 for (var i = 0; i < titles.length; i++) {
2145 var text = (titles[i].innerText || '').trim();
2146 var td = trow.appendChild(E('div', {
2147 'class': titles[i].className,
2148 'data-title': (text !== '') ? text : null
2151 td.classList.remove('th');
2152 td.classList.add('td');
2155 trow.classList.add('cbi-rowstyle-%d'.format((n++ % 2) ? 2 : 1));
2158 target.replaceChild(trow, rows[n]);
2160 target.appendChild(trow);
2164 target.removeChild(rows[n]);
2166 if (placeholder && target.firstElementChild === target.lastElementChild) {
2167 var trow = target.appendChild(E('div', { 'class': 'tr placeholder' }));
2168 var td = trow.appendChild(E('div', { 'class': titles[0].className }, placeholder));
2170 td.classList.remove('th');
2171 td.classList.add('td');
2175 thead.parentNode.style.display = 'none';
2177 thead.parentNode.querySelectorAll('.tr, .cbi-section-table-row').forEach(function(trow) {
2178 if (trow !== thead) {
2180 trow.querySelectorAll('.th, .td').forEach(function(td) {
2181 if (n < titles.length) {
2182 var text = (titles[n++].innerText || '').trim();
2184 td.setAttribute('data-title', text);
2190 thead.parentNode.style.display = '';
2195 var tooltipDiv = null, tooltipTimeout = null;
2197 function showTooltip(ev) {
2198 if (!matchesElem(ev.target, '[data-tooltip]'))
2201 if (tooltipTimeout !== null) {
2202 window.clearTimeout(tooltipTimeout);
2203 tooltipTimeout = null;
2206 var rect = ev.target.getBoundingClientRect(),
2207 x = rect.left + window.pageXOffset,
2208 y = rect.top + rect.height + window.pageYOffset;
2210 tooltipDiv.className = 'cbi-tooltip';
2211 tooltipDiv.innerHTML = '▲ ';
2212 tooltipDiv.firstChild.data += ev.target.getAttribute('data-tooltip');
2214 if (ev.target.hasAttribute('data-tooltip-style'))
2215 tooltipDiv.classList.add(ev.target.getAttribute('data-tooltip-style'));
2217 if ((y + tooltipDiv.offsetHeight) > (window.innerHeight + window.pageYOffset)) {
2218 y -= (tooltipDiv.offsetHeight + ev.target.offsetHeight);
2219 tooltipDiv.firstChild.data = '▼ ' + tooltipDiv.firstChild.data.substr(2);
2222 tooltipDiv.style.top = y + 'px';
2223 tooltipDiv.style.left = x + 'px';
2224 tooltipDiv.style.opacity = 1;
2227 function hideTooltip(ev) {
2228 if (ev.target === tooltipDiv || ev.relatedTarget === tooltipDiv)
2231 if (tooltipTimeout !== null) {
2232 window.clearTimeout(tooltipTimeout);
2233 tooltipTimeout = null;
2236 tooltipDiv.style.opacity = 0;
2237 tooltipTimeout = window.setTimeout(function() { tooltipDiv.removeAttribute('style'); }, 250);
2240 document.addEventListener('DOMContentLoaded', function() {
2241 tooltipDiv = document.body.appendChild(E('div', { 'class': 'cbi-tooltip' }));
2243 document.addEventListener('mouseover', showTooltip, true);
2244 document.addEventListener('mouseout', hideTooltip, true);
2245 document.addEventListener('focus', showTooltip, true);
2246 document.addEventListener('blur', hideTooltip, true);
2248 document.querySelectorAll('.table').forEach(cbi_update_table);