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 return (/^-?\d+$/.test(x) ? +x : NaN);
23 return (/^-?\d+(?:\.\d+)?$/.test(x) ? +x : NaN);
27 if (!x.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/))
30 if (RegExp.$1 > 255 || RegExp.$2 > 255 || RegExp.$3 > 255 || RegExp.$4 > 255)
33 return [ +RegExp.$1, +RegExp.$2, +RegExp.$3, +RegExp.$4 ];
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);
43 x = v6 + ':' + (v4[0] * 256 + v4[1]).toString(16)
44 + ':' + (v4[2] * 256 + v4[3]).toString(16);
47 if (!x.match(/^[a-fA-F0-9:]+$/))
50 var prefix_suffix = x.split(/::/);
52 if (prefix_suffix.length > 2)
55 var prefix = (prefix_suffix[0] || '0').split(/:/);
56 var suffix = prefix_suffix.length > 1 ? (prefix_suffix[1] || '0').split(/:/) : [];
58 if (suffix.length ? (prefix.length + suffix.length > 7) : (prefix.length > 8))
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)
70 for (i = 0; i < (8 - prefix.length - suffix.length); i++)
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)
82 var cbi_validators = {
89 'uinteger': function()
91 return (Int(this) >= 0);
101 return (Dec(this) >= 0);
106 return cbi_validators.ip4addr.apply(this) ||
107 cbi_validators.ip6addr.apply(this);
110 'ip4addr': function()
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)));
116 'ip6addr': function()
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));
122 'ip4prefix': function()
124 return !isNaN(this) && this >= 0 && this <= 32;
127 'ip6prefix': function()
129 return !isNaN(this) && this >= 0 && this <= 128;
134 return cbi_validators.cidr4.apply(this) ||
135 cbi_validators.cidr6.apply(this);
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]));
146 var m = this.match(/^([0-9a-fA-F:.]+)\/(\d{1,3})$/);
147 return !!(m && IPv6(m[1]) && cbi_validators.ip6prefix.apply(m[2]));
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]));
158 var m = this.match(/^([0-9a-fA-F:.]+)\/([0-9a-fA-F:.]+)$/);
159 return !!(m && IPv6(m[1]) && IPv6(m[2]));
162 'ip6hostid': function()
164 if (this == "eui64" || this == "random")
168 return !(!v6 || v6[0] || v6[1] || v6[2] || v6[3]);
173 return cbi_validators.ipmask4.apply(this) ||
174 cbi_validators.ipmask6.apply(this);
177 'ipmask4': function()
179 return cbi_validators.cidr4.apply(this) ||
180 cbi_validators.ipnet4.apply(this) ||
181 cbi_validators.ip4addr.apply(this);
184 'ipmask6': function()
186 return cbi_validators.cidr6.apply(this) ||
187 cbi_validators.ipnet6.apply(this) ||
188 cbi_validators.ip6addr.apply(this);
194 return (p >= 0 && p <= 65535);
197 'portrange': function()
199 if (this.match(/^(\d+)-(\d+)$/))
203 return (p1 <= p2 && p2 <= 65535);
206 return cbi_validators.port.apply(this);
209 'macaddr': function()
211 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
214 'host': function(ipv4only)
216 return cbi_validators.hostname.apply(this) ||
217 ((ipv4only != 1) && cbi_validators.ipaddr.apply(this)) ||
218 ((ipv4only == 1) && cbi_validators.ip4addr.apply(this));
221 'hostname': function(strict)
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(/^_/));
232 'network': function()
234 return cbi_validators.uciname.apply(this) ||
235 cbi_validators.host.apply(this);
238 'hostport': function(ipv4only)
240 var hp = this.split(/:/);
243 return (cbi_validators.host.apply(hp[0], ipv4only) &&
244 cbi_validators.port.apply(hp[1]));
249 'ip4addrport': function()
251 var hp = this.split(/:/);
254 return (cbi_validators.ipaddr.apply(hp[0]) &&
255 cbi_validators.port.apply(hp[1]));
259 'ipaddrport': function(bracket)
261 if (this.match(/^([^\[\]:]+):([^:]+)$/)) {
264 return (cbi_validators.ip4addr.apply(addr) &&
265 cbi_validators.port.apply(port));
266 } else if ((bracket == 1) && (this.match(/^\[(.+)\]:([^:]+)$/))) {
269 return (cbi_validators.ip6addr.apply(addr) &&
270 cbi_validators.port.apply(port));
271 } else if ((bracket != 1) && (this.match(/^([^\[\]]+):([^:]+)$/))) {
274 return (cbi_validators.ip6addr.apply(addr) &&
275 cbi_validators.port.apply(port));
286 return (v.match(/^[a-fA-F0-9]{64}$/) != null);
288 return (v.length >= 8) && (v.length <= 63);
295 if ( v.substr(0,2) == 's:' )
298 if( (v.length == 10) || (v.length == 26) )
299 return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
301 return (v.length == 5) || (v.length == 13);
304 'uciname': function()
306 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
309 'range': function(min, max)
312 return (val >= +min && val <= +max);
317 return (Dec(this) >= +min);
322 return (Dec(this) <= +max);
325 'rangelength': function(min, max)
328 return ((val.length >= +min) && (val.length <= +max));
331 'minlength': function(min)
333 return ((''+this).length >= +min);
336 'maxlength': function(max)
338 return ((''+this).length <= +max);
343 for (var i = 0; i < arguments.length; i += 2)
345 if (typeof arguments[i] != 'function')
347 if (arguments[i] == this)
351 else if (arguments[i].apply(this, arguments[i+1]))
361 for (var i = 0; i < arguments.length; i += 2)
363 if (typeof arguments[i] != 'function')
365 if (arguments[i] != this)
369 else if (!arguments[i].apply(this, arguments[i+1]))
379 return cbi_validators.or.apply(
380 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
383 'list': function(subvalidator, subargs)
385 if (typeof subvalidator != 'function')
388 var tokens = this.match(/[^ \t]+/g);
389 for (var i = 0; i < tokens.length; i++)
390 if (!subvalidator.apply(tokens[i], subargs))
395 'phonedigit': function()
397 return (this.match(/^[0-9\*#!\.]+$/) != null);
399 'timehhmmss': function()
401 return (this.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/) != null);
403 'dateyyyymmdd': function()
408 if (this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
409 var year = RegExp.$1;
410 var month = RegExp.$2;
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);
417 function get_days_in_month(month, year) {
418 if ((month == 2) && is_leap_year(year)) {
421 return days_in_month[month];
424 /* Firewall rules in the past don't make sense */
428 if ((month <= 0) || (month > 12)) {
431 if ((day <= 0) || (day > get_days_in_month(month, year))) {
443 function cbi_d_add(field, dep, index) {
444 var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
447 for (var i=0; i<cbi_d.length; i++) {
448 if (cbi_d[i].id == obj.id) {
457 "parent": obj.parentNode.id,
461 cbi_d.unshift(entry);
467 function cbi_d_checkvalue(target, ref) {
468 var t = document.getElementById(target);
472 var tl = document.getElementsByName(target);
474 if( tl.length > 0 && (tl[0].type == 'radio' || tl[0].type == 'checkbox'))
475 for( var i = 0; i < tl.length; i++ )
476 if( tl[i].checked ) {
481 value = value ? value : "";
482 } else if (!t.value) {
487 if (t.type == "checkbox") {
488 value = t.checked ? value : "";
492 return (value == ref)
495 function cbi_d_check(deps) {
498 for (var i=0; i<deps.length; i++) {
501 for (var j in deps[i]) {
502 if (j == "!reverse") {
504 } else if (j == "!default") {
508 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
512 if (istat ^ reverse) {
519 function cbi_d_update() {
521 for (var i=0; i<cbi_d.length; i++) {
522 var entry = cbi_d[i];
523 var node = document.getElementById(entry.id);
524 var parent = document.getElementById(entry.parent);
526 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
527 node.parentNode.removeChild(node);
529 } else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
530 var next = undefined;
532 for (next = parent.firstChild; next; next = next.nextSibling) {
533 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index) {
539 parent.appendChild(entry.node);
541 parent.insertBefore(entry.node, next);
547 // hide optionals widget if no choices remaining
548 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
549 parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
552 if (entry && entry.parent) {
554 cbi_tag_last(parent);
562 function cbi_init() {
565 nodes = document.querySelectorAll('[data-strings]');
567 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
568 var str = JSON.parse(node.getAttribute('data-strings'));
569 for (var key in str) {
570 for (var key2 in str[key]) {
571 var dst = cbi_strings[key] || (cbi_strings[key] = { });
572 dst[key2] = str[key][key2];
577 nodes = document.querySelectorAll('[data-depends]');
579 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
580 var index = parseInt(node.getAttribute('data-index'), 10);
581 var depends = JSON.parse(node.getAttribute('data-depends'));
582 if (!isNaN(index) && depends.length > 0) {
583 for (var alt = 0; alt < depends.length; alt++) {
584 cbi_d_add(node, depends[alt], index);
589 nodes = document.querySelectorAll('[data-update]');
591 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
592 var events = node.getAttribute('data-update').split(' ');
593 for (var j = 0, event; (event = events[j]) !== undefined; j++) {
594 cbi_bind(node, event, cbi_d_update);
598 nodes = document.querySelectorAll('[data-choices]');
600 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
601 var choices = JSON.parse(node.getAttribute('data-choices'));
604 for (var j = 0; j < choices[0].length; j++)
605 options[choices[0][j]] = choices[1][j];
607 var def = (node.getAttribute('data-optional') === 'true')
608 ? node.placeholder || '' : null;
610 cbi_combobox_init(node, options, def,
611 node.getAttribute('data-manual'));
614 nodes = document.querySelectorAll('[data-dynlist]');
616 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
617 var choices = JSON.parse(node.getAttribute('data-dynlist'));
620 if (choices[0] && choices[0].length) {
623 for (var j = 0; j < choices[0].length; j++)
624 options[choices[0][j]] = choices[1][j];
627 cbi_dynlist_init(node, choices[2], choices[3], options);
630 nodes = document.querySelectorAll('[data-type]');
632 for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
633 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
634 node.getAttribute('data-type'));
640 function cbi_bind(obj, type, callback, mode) {
641 if (!obj.addEventListener) {
642 obj.attachEvent('on' + type,
644 var e = window.event;
646 if (!e.target && e.srcElement)
647 e.target = e.srcElement;
649 return !!callback(e);
653 obj.addEventListener(type, callback, !!mode);
658 function cbi_combobox(id, values, def, man, focus) {
659 var selid = "cbi.combobox." + id;
660 if (document.getElementById(selid)) {
664 var obj = document.getElementById(id)
665 var sel = document.createElement("select");
667 sel.index = obj.index;
668 sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
670 if (obj.nextSibling) {
671 obj.parentNode.insertBefore(sel, obj.nextSibling);
673 obj.parentNode.appendChild(sel);
676 var dt = obj.getAttribute('cbi_datatype');
677 var op = obj.getAttribute('cbi_optional');
679 if (!values[obj.value]) {
680 if (obj.value == "") {
681 var optdef = document.createElement("option");
683 optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : cbi_strings.label.choose));
684 sel.appendChild(optdef);
686 var opt = document.createElement("option");
687 opt.value = obj.value;
688 opt.selected = "selected";
689 opt.appendChild(document.createTextNode(obj.value));
690 sel.appendChild(opt);
694 for (var i in values) {
695 var opt = document.createElement("option");
698 if (obj.value == i) {
699 opt.selected = "selected";
702 opt.appendChild(document.createTextNode(values[i]));
703 sel.appendChild(opt);
706 var optman = document.createElement("option");
708 optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : cbi_strings.label.custom));
709 sel.appendChild(optman);
711 obj.style.display = "none";
714 cbi_validate_field(sel, op == 'true', dt);
716 cbi_bind(sel, "change", function() {
717 if (sel.selectedIndex == sel.options.length - 1) {
718 obj.style.display = "inline";
720 sel.parentNode.removeChild(sel);
723 obj.value = sel.options[sel.selectedIndex].value;
733 // Retrigger validation in select
740 function cbi_combobox_init(id, values, def, man) {
741 var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
742 cbi_bind(obj, "blur", function() {
743 cbi_combobox(obj.id, values, def, man, true);
745 cbi_combobox(obj.id, values, def, man, false);
748 function cbi_filebrowser(id, defpath) {
749 var field = document.getElementById(id);
750 var browser = window.open(
751 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
752 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
758 function cbi_browser_init(id, resource, defpath)
760 function cbi_browser_btnclick(e) {
761 cbi_filebrowser(id, defpath);
765 var field = document.getElementById(id);
767 var btn = document.createElement('img');
768 btn.className = 'cbi-image-button';
769 btn.src = (resource || cbi_strings.path.resource) + '/cbi/folder.gif';
770 field.parentNode.insertBefore(btn, field.nextSibling);
772 cbi_bind(btn, 'click', cbi_browser_btnclick);
775 function cbi_dynlist_init(parent, datatype, optional, choices)
777 var prefix = parent.getAttribute('data-prefix');
778 var holder = parent.getAttribute('data-placeholder');
782 function cbi_dynlist_redraw(focus, add, del)
786 while (parent.firstChild)
788 var n = parent.firstChild;
793 if (n.nodeName.toLowerCase() == 'input')
794 values.push(n.value || '');
795 else if (n.nodeName.toLowerCase() == 'select')
796 values[values.length-1] = n.options[n.selectedIndex].value;
799 parent.removeChild(n);
805 values.splice(focus, 0, '');
807 else if (values.length == 0)
813 for (var i = 0; i < values.length; i++)
815 var t = document.createElement('input');
816 t.id = prefix + '.' + (i+1);
821 t.className = 'cbi-input-text';
823 if (i == 0 && holder)
825 t.placeholder = holder;
828 var b = document.createElement('img');
829 b.src = cbi_strings.path.resource + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
830 b.className = 'cbi-image-button';
832 parent.appendChild(t);
833 parent.appendChild(b);
834 if (datatype == 'file')
836 cbi_browser_init(t.id, null, parent.getAttribute('data-browser-path'));
839 parent.appendChild(document.createElement('br'));
843 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
848 cbi_combobox_init(t.id, choices, '', cbi_strings.label.custom);
851 cbi_bind(b, 'keydown', cbi_dynlist_keydown);
852 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
854 if (i == focus || -i == focus)
859 cbi_bind(t, 'keydown', cbi_dynlist_keydown);
860 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
866 else if (-i == focus)
870 /* force cursor to end */
877 cbi_bind(b, 'click', cbi_dynlist_btnclick);
881 function cbi_dynlist_keypress(ev)
883 ev = ev ? ev : window.event;
885 var se = ev.target ? ev.target : ev.srcElement;
887 if (se.nodeType == 3)
892 /* backspace, delete */
895 if (se.value.length == 0)
897 if (ev.preventDefault)
905 /* enter, arrow up, arrow down */
909 if (ev.preventDefault)
918 function cbi_dynlist_keydown(ev)
920 ev = ev ? ev : window.event;
922 var se = ev.target ? ev.target : ev.srcElement;
924 if (se.nodeType == 3)
927 var prev = se.previousSibling;
928 while (prev && prev.name != prefix)
929 prev = prev.previousSibling;
931 var next = se.nextSibling;
932 while (next && next.name != prefix)
933 next = next.nextSibling;
935 /* advance one further in combobox case */
936 if (next && next.nextSibling.name == prefix)
937 next = next.nextSibling;
941 /* backspace, delete */
944 var del = (se.nodeName.toLowerCase() == 'select')
945 ? true : (se.value.length == 0);
949 if (ev.preventDefault)
952 var focus = se.index;
956 cbi_dynlist_redraw(focus, -1, se.index);
965 cbi_dynlist_redraw(-1, se.index, -1);
986 function cbi_dynlist_btnclick(ev)
988 ev = ev ? ev : window.event;
990 var se = ev.target ? ev.target : ev.srcElement;
991 var input = se.previousSibling;
992 while (input && input.name != prefix) {
993 input = input.previousSibling;
996 if (se.src.indexOf('remove') > -1)
1000 cbi_dynlist_keydown({
1007 cbi_dynlist_keydown({
1016 cbi_dynlist_redraw(NaN, -1, -1);
1020 function cbi_t_add(section, tab) {
1021 var t = document.getElementById('tab.' + section + '.' + tab);
1022 var c = document.getElementById('container.' + section + '.' + tab);
1025 cbi_t[section] = (cbi_t[section] || [ ]);
1026 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
1030 function cbi_t_switch(section, tab) {
1031 if( cbi_t[section] && cbi_t[section][tab] ) {
1032 var o = cbi_t[section][tab];
1033 var h = document.getElementById('tab.' + section);
1034 for( var tid in cbi_t[section] ) {
1035 var o2 = cbi_t[section][tid];
1036 if( o.tab.id != o2.tab.id ) {
1037 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
1038 o2.container.style.display = 'none';
1041 if(h) h.value = tab;
1042 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
1043 o2.container.style.display = 'block';
1050 function cbi_t_update() {
1052 var updated = false;
1054 for( var sid in cbi_t )
1055 for( var tid in cbi_t[sid] )
1057 var t = cbi_t[sid][tid].tab;
1058 var c = cbi_t[sid][tid].container;
1060 if (!c.firstElementChild) {
1061 t.style.display = 'none';
1063 else if (t.style.display == 'none') {
1064 t.style.display = '';
1065 t.className += ' cbi-tab-highlighted';
1073 if (hl_tabs.length > 0)
1074 window.setTimeout(function() {
1075 for( var i = 0; i < hl_tabs.length; i++ )
1076 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
1083 function cbi_validate_form(form, errmsg)
1085 /* if triggered by a section removal or addition, don't validate */
1086 if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
1089 if( form.cbi_validators )
1091 for( var i = 0; i < form.cbi_validators.length; i++ )
1093 var validator = form.cbi_validators[i];
1094 if( !validator() && errmsg )
1105 function cbi_validate_reset(form)
1108 function() { cbi_validate_form(form, null) }, 100
1114 function cbi_validate_compile(code)
1123 for (var i = 0; i < code.length; i++)
1131 switch (code.charCodeAt(i))
1143 var label = code.substring(pos, i);
1144 label = label.replace(/\\(.)/g, '$1');
1145 label = label.replace(/^[ \t]+/g, '');
1146 label = label.replace(/[ \t]+$/g, '');
1148 if (label && !isNaN(label))
1150 stack.push(parseFloat(label));
1152 else if (label.match(/^(['"]).*\1$/))
1154 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1156 else if (typeof cbi_validators[label] == 'function')
1158 stack.push(cbi_validators[label]);
1163 throw "Syntax error, unhandled token '"+label+"'";
1168 depth += (code.charCodeAt(i) == 40);
1174 if (typeof stack[stack.length-2] != 'function')
1175 throw "Syntax error, argument list follows non-function";
1177 stack[stack.length-1] =
1178 arguments.callee(code.substring(pos, i));
1189 function cbi_validate_field(cbid, optional, type)
1191 var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1192 var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1194 if (field && vstack && typeof vstack[0] == "function")
1196 var validator = function()
1201 field.className = field.className.replace(/ cbi-input-invalid/g, '');
1204 var value = (field.options && field.options.selectedIndex > -1)
1205 ? field.options[field.options.selectedIndex].value : field.value;
1207 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1210 field.className += ' cbi-input-invalid';
1218 if( ! field.form.cbi_validators )
1219 field.form.cbi_validators = [ ];
1221 field.form.cbi_validators.push(validator);
1223 cbi_bind(field, "blur", validator);
1224 cbi_bind(field, "keyup", validator);
1226 if (field.nodeName == 'SELECT')
1228 cbi_bind(field, "change", validator);
1229 cbi_bind(field, "click", validator);
1232 field.setAttribute("cbi_validate", validator);
1233 field.setAttribute("cbi_datatype", type);
1234 field.setAttribute("cbi_optional", (!!optional).toString());
1238 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1240 cbi_validate_field(fcbox, optional, type);
1244 function cbi_row_swap(elem, up, store)
1246 var tr = elem.parentNode;
1248 while (tr && !tr.classList.contains('cbi-section-table-row'))
1255 var prev = tr.previousElementSibling;
1257 if (prev && prev.classList.contains('cbi-section-table-row'))
1258 tr.parentNode.insertBefore(tr, prev);
1263 var next = tr.nextElementSibling ? tr.nextElementSibling.nextElementSibling : null;
1265 if (next && next.classList.contains('cbi-section-table-row'))
1266 tr.parentNode.insertBefore(tr, next);
1268 tr.parentNode.appendChild(tr);
1275 for (var i = 0, n = 0; i < tr.parentNode.childNodes.length; i++) {
1276 var node = tr.parentNode.childNodes[i];
1277 if (node.classList && node.classList.contains('cbi-section-table-row')) {
1278 node.classList.remove('cbi-rowstyle-1');
1279 node.classList.remove('cbi-rowstyle-2');
1280 node.classList.add((n++ % 2) ? 'cbi-rowstyle-2' : 'cbi-rowstyle-1');
1282 if (/-([^\-]+)$/.test(node.id))
1283 ids.push(RegExp.$1);
1287 var input = document.getElementById(store);
1289 input.value = ids.join(' ');
1294 function cbi_tag_last(container)
1298 for (var i = 0; i < container.childNodes.length; i++)
1300 var c = container.childNodes[i];
1301 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1303 c.className = c.className.replace(/ cbi-value-last$/, '');
1310 last.className += ' cbi-value-last';
1314 String.prototype.format = function()
1319 var html_esc = [/&/g, '&', /"/g, '"', /'/g, ''', /</g, '<', />/g, '>'];
1320 var quot_esc = [/"/g, '"', /'/g, '''];
1322 function esc(s, r) {
1323 if (typeof(s) !== 'string' && !(s instanceof String))
1326 for( var i = 0; i < r.length; i += 2 )
1327 s = s.replace(r[i], r[i+1]);
1333 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1334 var a = b = [], numSubstitutions = 0, numMatches = 0;
1336 while (a = re.exec(str))
1339 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1340 var pPrecision = a[6], pType = a[7];
1350 if (numSubstitutions < arguments.length)
1352 var param = arguments[numSubstitutions++];
1355 if (pPad && pPad.substr(0,1) == "'")
1356 pad = leftpart.substr(1,1);
1362 var justifyRight = true;
1363 if (pJustify && pJustify === "-")
1364 justifyRight = false;
1368 minLength = +pMinLength;
1371 if (pPrecision && pType == 'f')
1372 precision = +pPrecision.substring(1);
1379 subst = (+param || 0).toString(2);
1383 subst = String.fromCharCode(+param || 0);
1387 subst = ~~(+param || 0);
1391 subst = ~~Math.abs(+param || 0);
1395 subst = (precision > -1)
1396 ? ((+param || 0.0)).toFixed(precision)
1401 subst = (+param || 0).toString(8);
1409 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1413 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1417 subst = esc(param, html_esc);
1421 subst = esc(param, quot_esc);
1428 var ts = (param || 0);
1431 tm = Math.floor(ts / 60);
1436 th = Math.floor(tm / 60);
1441 td = Math.floor(th / 24);
1446 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1447 : String.format('%dh %dm %ds', th, tm, ts);
1452 var mf = pMinLength ? +pMinLength : 1000;
1453 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1456 var val = (+param || 0);
1457 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1459 for (i = 0; (i < units.length) && (val > mf); i++)
1462 subst = (i ? val.toFixed(pr) : val) + units[i];
1470 subst = subst.toString();
1471 for (var i = subst.length; i < pMinLength; i++)
1472 if (pJustify == '-')
1473 subst = subst + ' ';
1475 subst = pad + subst;
1478 out += leftpart + subst;
1479 str = str.substr(m.length);
1485 String.prototype.nobr = function()
1487 return this.replace(/[\s\n]+/g, ' ');
1490 String.format = function()
1493 for (var i = 1; i < arguments.length; i++)
1494 a.push(arguments[i]);
1495 return ''.format.apply(arguments[0], a);
1498 String.nobr = function()
1501 for (var i = 1; i < arguments.length; i++)
1502 a.push(arguments[i]);
1503 return ''.nobr.apply(arguments[0], a);
1507 var dummyElem, domParser;
1511 return (typeof(e) === 'object' && e !== null && 'nodeType' in e);
1519 domParser = domParser || new DOMParser();
1520 elem = domParser.parseFromString(s, 'text/html').body.firstChild;
1526 dummyElem = dummyElem || document.createElement('div');
1527 dummyElem.innerHTML = s;
1528 elem = dummyElem.firstChild;
1533 return elem || null;
1538 var html = arguments[0],
1539 attr = (arguments[1] instanceof Object && !Array.isArray(arguments[1])) ? arguments[1] : null,
1540 data = attr ? arguments[2] : arguments[1],
1545 else if (html.charCodeAt(0) === 60)
1546 elem = toElem(html);
1548 elem = document.createElement(html);
1554 for (var key in attr)
1555 if (attr.hasOwnProperty(key))
1556 elem.setAttribute(key, attr[key]);
1558 if (typeof(data) === 'function')
1562 elem.appendChild(data);
1564 else if (Array.isArray(data)) {
1565 for (var i = 0; i < data.length; i++)
1566 if (isElem(data[i]))
1567 elem.appendChild(data[i]);
1569 elem.appendChild(document.createTextNode('' + data[i]));
1571 else if (data !== null && data !== undefined) {
1572 elem.innerHTML = '' + data;