luci-base: cbi.js: properly round down numbers for %u and %d patterns
[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 var cbi_validators = {
27
28         'integer': function()
29         {
30                 return !!Int(this);
31         },
32
33         'uinteger': function()
34         {
35                 return (Int(this) >= 0);
36         },
37
38         'float': function()
39         {
40                 return !!Dec(this);
41         },
42
43         'ufloat': function()
44         {
45                 return (Dec(this) >= 0);
46         },
47
48         'ipaddr': function()
49         {
50                 return cbi_validators.ip4addr.apply(this) ||
51                         cbi_validators.ip6addr.apply(this);
52         },
53
54         'ip4addr': function()
55         {
56                 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
57                 {
58                         return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
59                                (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
60                                (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
61                                (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
62                                ((RegExp.$6.indexOf('.') < 0)
63                                   ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
64                                   : (cbi_validators.ip4addr.apply(RegExp.$6)))
65                         ;
66                 }
67
68                 return false;
69         },
70
71         'ip6addr': function()
72         {
73                 if( this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
74                 {
75                         if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
76                         {
77                                 var addr = RegExp.$1;
78
79                                 if( addr == '::' )
80                                 {
81                                         return true;
82                                 }
83
84                                 if( addr.indexOf('.') > 0 )
85                                 {
86                                         var off = addr.lastIndexOf(':');
87
88                                         if( !(off && cbi_validators.ip4addr.apply(addr.substr(off+1))) )
89                                                 return false;
90
91                                         addr = addr.substr(0, off) + ':0:0';
92                                 }
93
94                                 if( addr.indexOf('::') >= 0 )
95                                 {
96                                         var colons = 0;
97                                         var fill = '0';
98
99                                         for( var i = 1; i < (addr.length-1); i++ )
100                                                 if( addr.charAt(i) == ':' )
101                                                         colons++;
102
103                                         if( colons > 7 )
104                                                 return false;
105
106                                         for( var i = 0; i < (7 - colons); i++ )
107                                                 fill += ':0';
108
109                                         if (addr.match(/^(.*?)::(.*?)$/))
110                                                 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
111                                                        (RegExp.$2 ? ':' + RegExp.$2 : '');
112                                 }
113
114                                 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
115                         }
116                 }
117
118                 return false;
119         },
120
121         'port': function()
122         {
123                 var p = Int(this);
124                 return (p >= 0 && p <= 65535);
125         },
126
127         'portrange': function()
128         {
129                 if (this.match(/^(\d+)-(\d+)$/))
130                 {
131                         var p1 = +RegExp.$1;
132                         var p2 = +RegExp.$2;
133                         return (p1 <= p2 && p2 <= 65535);
134                 }
135
136                 return cbi_validators.port.apply(this);
137         },
138
139         'macaddr': function()
140         {
141                 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
142         },
143
144         'host': function(ipv4only)
145         {
146                 return cbi_validators.hostname.apply(this) ||
147                         ((ipv4only != 1) && cbi_validators.ipaddr.apply(this)) ||
148                         ((ipv4only == 1) && cb_validators.ip4addr.apply(this));
149         },
150
151         'hostname': function()
152         {
153                 if (this.length <= 253)
154                         return (this.match(/^[a-zA-Z0-9]+$/) != null ||
155                                 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
156                                  this.match(/[^0-9.]/)));
157
158                 return false;
159         },
160
161         'network': function()
162         {
163                 return cbi_validators.uciname.apply(this) ||
164                         cbi_validators.host.apply(this);
165         },
166
167         'hostport': function(ipv4only)
168         {
169                 var hp = this.split(/:/);
170
171                 if (hp.length == 2)
172                         return (cbi_validators.host.apply(hp[0], ipv4only) &&
173                                 cbi_validators.port.apply(hp[1]));
174
175                 return false;
176         },
177
178         'ip4addrport': function()
179         {
180                 var hp = this.split(/:/);
181
182                 if (hp.length == 2)
183                         return (cbi_validators.ipaddr.apply(hp[0]) &&
184                                 cbi_validators.port.apply(hp[1]));
185                 return false;
186         },
187
188         'ipaddrport': function(bracket)
189         {
190                 if (this.match(/^([^\[\]:]+):([^:]+)$/)) {
191                         var addr = RegExp.$1
192                         var port = RegExp.$2
193                         return (cbi_validators.ip4addr.apply(addr) &&
194                                 cbi_validators.port.apply(port));
195                 } else if ((bracket == 1) && (this.match(/^\[(.+)\]:([^:]+)$/))) {
196                         var addr = RegExp.$1
197                         var port = RegExp.$2
198                         return (cbi_validators.ip6addr.apply(addr) &&
199                                 cbi_validators.port.apply(port));
200                 } else if ((bracket != 1) && (this.match(/^([^\[\]]+):([^:]+)$/))) {
201                         var addr = RegExp.$1
202                         var port = RegExp.$2
203                         return (cbi_validators.ip6addr.apply(addr) &&
204                                 cbi_validators.port.apply(port));
205                 } else {
206                         return false;
207                 }
208         },
209
210         'wpakey': function()
211         {
212                 var v = this;
213
214                 if( v.length == 64 )
215                         return (v.match(/^[a-fA-F0-9]{64}$/) != null);
216                 else
217                         return (v.length >= 8) && (v.length <= 63);
218         },
219
220         'wepkey': function()
221         {
222                 var v = this;
223
224                 if ( v.substr(0,2) == 's:' )
225                         v = v.substr(2);
226
227                 if( (v.length == 10) || (v.length == 26) )
228                         return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
229                 else
230                         return (v.length == 5) || (v.length == 13);
231         },
232
233         'uciname': function()
234         {
235                 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
236         },
237
238         'range': function(min, max)
239         {
240                 var val = Dec(this);
241                 return (val >= +min && val <= +max);
242         },
243
244         'min': function(min)
245         {
246                 return (Dec(this) >= +min);
247         },
248
249         'max': function(max)
250         {
251                 return (Dec(this) <= +max);
252         },
253
254         'rangelength': function(min, max)
255         {
256                 var val = '' + this;
257                 return ((val.length >= +min) && (val.length <= +max));
258         },
259
260         'minlength': function(min)
261         {
262                 return ((''+this).length >= +min);
263         },
264
265         'maxlength': function(max)
266         {
267                 return ((''+this).length <= +max);
268         },
269
270         'or': function()
271         {
272                 for (var i = 0; i < arguments.length; i += 2)
273                 {
274                         if (typeof arguments[i] != 'function')
275                         {
276                                 if (arguments[i] == this)
277                                         return true;
278                                 i--;
279                         }
280                         else if (arguments[i].apply(this, arguments[i+1]))
281                         {
282                                 return true;
283                         }
284                 }
285                 return false;
286         },
287
288         'and': function()
289         {
290                 for (var i = 0; i < arguments.length; i += 2)
291                 {
292                         if (typeof arguments[i] != 'function')
293                         {
294                                 if (arguments[i] != this)
295                                         return false;
296                                 i--;
297                         }
298                         else if (!arguments[i].apply(this, arguments[i+1]))
299                         {
300                                 return false;
301                         }
302                 }
303                 return true;
304         },
305
306         'neg': function()
307         {
308                 return cbi_validators.or.apply(
309                         this.replace(/^[ \t]*![ \t]*/, ''), arguments);
310         },
311
312         'list': function(subvalidator, subargs)
313         {
314                 if (typeof subvalidator != 'function')
315                         return false;
316
317                 var tokens = this.match(/[^ \t]+/g);
318                 for (var i = 0; i < tokens.length; i++)
319                         if (!subvalidator.apply(tokens[i], subargs))
320                                 return false;
321
322                 return true;
323         },
324         'phonedigit': function()
325         {
326                 return (this.match(/^[0-9\*#!\.]+$/) != null);
327         },
328         'timehhmmss': function()
329         {
330                 return (this.match(/^[0-6][0-9]:[0-6][0-9]:[0-6][0-9]$/) != null);
331         },
332         'dateyyyymmdd': function()
333         {
334                 if (this == null) {
335                         return false;
336                 }
337                 if (this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)/)) {
338                         var year = RegExp.$1;
339                         var month = RegExp.$2;
340                         var day = RegExp.$2
341
342                         var days_in_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30 , 31, 30, 31 ];
343                         function is_leap_year(year) {
344                                 return ((year % 4) == 0) && ((year % 100) != 0) || ((year % 400) == 0);
345                         }
346                         function get_days_in_month(month, year) {
347                                 if ((month == 2) && is_leap_year(year)) {
348                                         return 29;
349                                 } else {
350                                         return days_in_month[month];
351                                 }
352                         }
353                         /* Firewall rules in the past don't make sense */
354                         if (year < 2015) {
355                                 return false;
356                         }
357                         if ((month <= 0) || (month > 12)) {
358                                 return false;
359                         }
360                         if ((day <= 0) || (day > get_days_in_month(month, year))) {
361                                 return false;
362                         }
363                         return true;
364
365                 } else {
366                         return false;
367                 }
368         }
369 };
370
371
372 function cbi_d_add(field, dep, index) {
373         var obj = (typeof(field) === 'string') ? document.getElementById(field) : field;
374         if (obj) {
375                 var entry
376                 for (var i=0; i<cbi_d.length; i++) {
377                         if (cbi_d[i].id == obj.id) {
378                                 entry = cbi_d[i];
379                                 break;
380                         }
381                 }
382                 if (!entry) {
383                         entry = {
384                                 "node": obj,
385                                 "id": obj.id,
386                                 "parent": obj.parentNode.id,
387                                 "deps": [],
388                                 "index": index
389                         };
390                         cbi_d.unshift(entry);
391                 }
392                 entry.deps.push(dep)
393         }
394 }
395
396 function cbi_d_checkvalue(target, ref) {
397         var t = document.getElementById(target);
398         var value;
399
400         if (!t) {
401                 var tl = document.getElementsByName(target);
402
403                 if( tl.length > 0 && (tl[0].type == 'radio' || tl[0].type == 'checkbox'))
404                         for( var i = 0; i < tl.length; i++ )
405                                 if( tl[i].checked ) {
406                                         value = tl[i].value;
407                                         break;
408                                 }
409
410                 value = value ? value : "";
411         } else if (!t.value) {
412                 value = "";
413         } else {
414                 value = t.value;
415
416                 if (t.type == "checkbox") {
417                         value = t.checked ? value : "";
418                 }
419         }
420
421         return (value == ref)
422 }
423
424 function cbi_d_check(deps) {
425         var reverse;
426         var def = false;
427         for (var i=0; i<deps.length; i++) {
428                 var istat = true;
429                 reverse = false;
430                 for (var j in deps[i]) {
431                         if (j == "!reverse") {
432                                 reverse = true;
433                         } else if (j == "!default") {
434                                 def = true;
435                                 istat = false;
436                         } else {
437                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
438                         }
439                 }
440                 if (istat) {
441                         return !reverse;
442                 }
443         }
444         return def;
445 }
446
447 function cbi_d_update() {
448         var state = false;
449         for (var i=0; i<cbi_d.length; i++) {
450                 var entry = cbi_d[i];
451                 var node  = document.getElementById(entry.id);
452                 var parent = document.getElementById(entry.parent);
453
454                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
455                         node.parentNode.removeChild(node);
456                         state = true;
457                 } else if (parent && (!node || !node.parentNode) && cbi_d_check(entry.deps)) {
458                         var next = undefined;
459
460                         for (next = parent.firstChild; next; next = next.nextSibling) {
461                                 if (next.getAttribute && parseInt(next.getAttribute('data-index'), 10) > entry.index) {
462                                         break;
463                                 }
464                         }
465
466                         if (!next) {
467                                 parent.appendChild(entry.node);
468                         } else {
469                                 parent.insertBefore(entry.node, next);
470                         }
471
472                         state = true;
473                 }
474
475                 // hide optionals widget if no choices remaining
476                 if (parent && parent.parentNode && parent.getAttribute('data-optionals'))
477                         parent.parentNode.style.display = (parent.options.length <= 1) ? 'none' : '';
478         }
479
480         if (entry && entry.parent) {
481                 if (!cbi_t_update())
482                         cbi_tag_last(parent);
483         }
484
485         if (state) {
486                 cbi_d_update();
487         }
488 }
489
490 function cbi_init() {
491         var nodes;
492
493         nodes = document.querySelectorAll('[data-strings]');
494
495         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
496                 var str = JSON.parse(node.getAttribute('data-strings'));
497                 for (var key in str) {
498                         for (var key2 in str[key]) {
499                                 var dst = cbi_strings[key] || (cbi_strings[key] = { });
500                                     dst[key2] = str[key][key2];
501                         }
502                 }
503         }
504
505         nodes = document.querySelectorAll('[data-depends]');
506
507         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
508                 var index = parseInt(node.getAttribute('data-index'), 10);
509                 var depends = JSON.parse(node.getAttribute('data-depends'));
510                 if (!isNaN(index) && depends.length > 0) {
511                         for (var alt = 0; alt < depends.length; alt++) {
512                                 cbi_d_add(node, depends[alt], index);
513                         }
514                 }
515         }
516
517         nodes = document.querySelectorAll('[data-update]');
518
519         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
520                 var events = node.getAttribute('data-update').split(' ');
521                 for (var j = 0, event; (event = events[j]) !== undefined; j++) {
522                         cbi_bind(node, event, cbi_d_update);
523                 }
524         }
525
526         nodes = document.querySelectorAll('[data-type]');
527
528         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
529                 cbi_validate_field(node, node.getAttribute('data-optional') === 'true',
530                                    node.getAttribute('data-type'));
531         }
532
533         nodes = document.querySelectorAll('[data-choices]');
534
535         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
536                 var choices = JSON.parse(node.getAttribute('data-choices'));
537                 var options = {};
538
539                 for (var j = 0; j < choices[0].length; j++)
540                         options[choices[0][j]] = choices[1][j];
541
542                 var def = (node.getAttribute('data-optional') === 'true')
543                         ? node.placeholder || '' : null;
544
545                 cbi_combobox_init(node, options, def,
546                                   node.getAttribute('data-manual'));
547         }
548
549         nodes = document.querySelectorAll('[data-dynlist]');
550
551         for (var i = 0, node; (node = nodes[i]) !== undefined; i++) {
552                 var choices = JSON.parse(node.getAttribute('data-dynlist'));
553                 var options = null;
554
555                 if (choices[0] && choices[0].length) {
556                         options = {};
557
558                         for (var j = 0; j < choices[0].length; j++)
559                                 options[choices[0][j]] = choices[1][j];
560                 }
561
562                 cbi_dynlist_init(node, choices[2], choices[3], options);
563         }
564
565         cbi_d_update();
566 }
567
568 function cbi_bind(obj, type, callback, mode) {
569         if (!obj.addEventListener) {
570                 obj.attachEvent('on' + type,
571                         function(){
572                                 var e = window.event;
573
574                                 if (!e.target && e.srcElement)
575                                         e.target = e.srcElement;
576
577                                 return !!callback(e);
578                         }
579                 );
580         } else {
581                 obj.addEventListener(type, callback, !!mode);
582         }
583         return obj;
584 }
585
586 function cbi_combobox(id, values, def, man, focus) {
587         var selid = "cbi.combobox." + id;
588         if (document.getElementById(selid)) {
589                 return
590         }
591
592         var obj = document.getElementById(id)
593         var sel = document.createElement("select");
594                 sel.id = selid;
595                 sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
596
597         if (obj.nextSibling) {
598                 obj.parentNode.insertBefore(sel, obj.nextSibling);
599         } else {
600                 obj.parentNode.appendChild(sel);
601         }
602
603         var dt = obj.getAttribute('cbi_datatype');
604         var op = obj.getAttribute('cbi_optional');
605
606         if (dt)
607                 cbi_validate_field(sel, op == 'true', dt);
608
609         if (!values[obj.value]) {
610                 if (obj.value == "") {
611                         var optdef = document.createElement("option");
612                         optdef.value = "";
613                         optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : cbi_strings.label.choose));
614                         sel.appendChild(optdef);
615                 } else {
616                         var opt = document.createElement("option");
617                         opt.value = obj.value;
618                         opt.selected = "selected";
619                         opt.appendChild(document.createTextNode(obj.value));
620                         sel.appendChild(opt);
621                 }
622         }
623
624         for (var i in values) {
625                 var opt = document.createElement("option");
626                 opt.value = i;
627
628                 if (obj.value == i) {
629                         opt.selected = "selected";
630                 }
631
632                 opt.appendChild(document.createTextNode(values[i]));
633                 sel.appendChild(opt);
634         }
635
636         var optman = document.createElement("option");
637         optman.value = "";
638         optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : cbi_strings.label.custom));
639         sel.appendChild(optman);
640
641         obj.style.display = "none";
642
643         cbi_bind(sel, "change", function() {
644                 if (sel.selectedIndex == sel.options.length - 1) {
645                         obj.style.display = "inline";
646                         sel.blur();
647                         sel.parentNode.removeChild(sel);
648                         obj.focus();
649                 } else {
650                         obj.value = sel.options[sel.selectedIndex].value;
651                 }
652
653                 try {
654                         cbi_d_update();
655                 } catch (e) {
656                         //Do nothing
657                 }
658         })
659
660         // Retrigger validation in select
661         if (focus) {
662                 sel.focus();
663                 sel.blur();
664         }
665 }
666
667 function cbi_combobox_init(id, values, def, man) {
668         var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
669         cbi_bind(obj, "blur", function() {
670                 cbi_combobox(obj.id, values, def, man, true);
671         });
672         cbi_combobox(obj.id, values, def, man, false);
673 }
674
675 function cbi_filebrowser(id, defpath) {
676         var field   = document.getElementById(id);
677         var browser = window.open(
678                 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
679                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
680         );
681
682         browser.focus();
683 }
684
685 function cbi_browser_init(id, defpath)
686 {
687         function cbi_browser_btnclick(e) {
688                 cbi_filebrowser(id, defpath);
689                 return false;
690         }
691
692         var field = document.getElementById(id);
693
694         var btn = document.createElement('img');
695         btn.className = 'cbi-image-button';
696         btn.src = cbi_strings.path.resource + '/cbi/folder.gif';
697         field.parentNode.insertBefore(btn, field.nextSibling);
698
699         cbi_bind(btn, 'click', cbi_browser_btnclick);
700 }
701
702 function cbi_dynlist_init(parent, datatype, optional, choices)
703 {
704         var prefix = parent.getAttribute('data-prefix');
705         var holder = parent.getAttribute('data-placeholder');
706
707         var values;
708
709         function cbi_dynlist_redraw(focus, add, del)
710         {
711                 values = [ ];
712
713                 while (parent.firstChild)
714                 {
715                         var n = parent.firstChild;
716                         var i = +n.index;
717
718                         if (i != del)
719                         {
720                                 if (n.nodeName.toLowerCase() == 'input')
721                                         values.push(n.value || '');
722                                 else if (n.nodeName.toLowerCase() == 'select')
723                                         values[values.length-1] = n.options[n.selectedIndex].value;
724                         }
725
726                         parent.removeChild(n);
727                 }
728
729                 if (add >= 0)
730                 {
731                         focus = add+1;
732                         values.splice(focus, 0, '');
733                 }
734                 else if (values.length == 0)
735                 {
736                         focus = 0;
737                         values.push('');
738                 }
739
740                 for (var i = 0; i < values.length; i++)
741                 {
742                         var t = document.createElement('input');
743                                 t.id = prefix + '.' + (i+1);
744                                 t.name = prefix;
745                                 t.value = values[i];
746                                 t.type = 'text';
747                                 t.index = i;
748                                 t.className = 'cbi-input-text';
749
750                         if (i == 0 && holder)
751                         {
752                                 t.placeholder = holder;
753                         }
754
755                         var b = document.createElement('img');
756                                 b.src = cbi_strings.path.resource + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
757                                 b.className = 'cbi-image-button';
758
759                         parent.appendChild(t);
760                         parent.appendChild(b);
761                         if (datatype == 'file')
762                         {
763                                 cbi_browser_init(t.id, parent.getAttribute('data-browser-path'));
764                         }
765
766                         parent.appendChild(document.createElement('br'));
767
768                         if (datatype)
769                         {
770                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
771                         }
772
773                         if (choices)
774                         {
775                                 cbi_combobox_init(t.id, choices, '', cbi_strings.label.custom);
776                                 b.index = i;
777
778                                 cbi_bind(b, 'keydown',  cbi_dynlist_keydown);
779                                 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
780
781                                 if (i == focus || -i == focus)
782                                         b.focus();
783                         }
784                         else
785                         {
786                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
787                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
788
789                                 if (i == focus)
790                                 {
791                                         t.focus();
792                                 }
793                                 else if (-i == focus)
794                                 {
795                                         t.focus();
796
797                                         /* force cursor to end */
798                                         var v = t.value;
799                                         t.value = ' '
800                                         t.value = v;
801                                 }
802                         }
803
804                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
805                 }
806         }
807
808         function cbi_dynlist_keypress(ev)
809         {
810                 ev = ev ? ev : window.event;
811
812                 var se = ev.target ? ev.target : ev.srcElement;
813
814                 if (se.nodeType == 3)
815                         se = se.parentNode;
816
817                 switch (ev.keyCode)
818                 {
819                         /* backspace, delete */
820                         case 8:
821                         case 46:
822                                 if (se.value.length == 0)
823                                 {
824                                         if (ev.preventDefault)
825                                                 ev.preventDefault();
826
827                                         return false;
828                                 }
829
830                                 return true;
831
832                         /* enter, arrow up, arrow down */
833                         case 13:
834                         case 38:
835                         case 40:
836                                 if (ev.preventDefault)
837                                         ev.preventDefault();
838
839                                 return false;
840                 }
841
842                 return true;
843         }
844
845         function cbi_dynlist_keydown(ev)
846         {
847                 ev = ev ? ev : window.event;
848
849                 var se = ev.target ? ev.target : ev.srcElement;
850
851                 if (se.nodeType == 3)
852                         se = se.parentNode;
853
854                 var prev = se.previousSibling;
855                 while (prev && prev.name != prefix)
856                         prev = prev.previousSibling;
857
858                 var next = se.nextSibling;
859                 while (next && next.name != prefix)
860                         next = next.nextSibling;
861
862                 /* advance one further in combobox case */
863                 if (next && next.nextSibling.name == prefix)
864                         next = next.nextSibling;
865
866                 switch (ev.keyCode)
867                 {
868                         /* backspace, delete */
869                         case 8:
870                         case 46:
871                                 var del = (se.nodeName.toLowerCase() == 'select')
872                                         ? true : (se.value.length == 0);
873
874                                 if (del)
875                                 {
876                                         if (ev.preventDefault)
877                                                 ev.preventDefault();
878
879                                         var focus = se.index;
880                                         if (ev.keyCode == 8)
881                                                 focus = -focus+1;
882
883                                         cbi_dynlist_redraw(focus, -1, se.index);
884
885                                         return false;
886                                 }
887
888                                 break;
889
890                         /* enter */
891                         case 13:
892                                 cbi_dynlist_redraw(-1, se.index, -1);
893                                 break;
894
895                         /* arrow up */
896                         case 38:
897                                 if (prev)
898                                         prev.focus();
899
900                                 break;
901
902                         /* arrow down */
903                         case 40:
904                                 if (next)
905                                         next.focus();
906
907                                 break;
908                 }
909
910                 return true;
911         }
912
913         function cbi_dynlist_btnclick(ev)
914         {
915                 ev = ev ? ev : window.event;
916
917                 var se = ev.target ? ev.target : ev.srcElement;
918                 var input = se.previousSibling;
919                 while (input && input.name != prefix) {
920                         input = input.previousSibling;
921                 }
922
923                 if (se.src.indexOf('remove') > -1)
924                 {
925                         input.value = '';
926
927                         cbi_dynlist_keydown({
928                                 target:  se,
929                                 keyCode: 8
930                         });
931                 }
932                 else
933                 {
934                         cbi_dynlist_keydown({
935                                 target:  se,
936                                 keyCode: 13
937                         });
938                 }
939
940                 return false;
941         }
942
943         cbi_dynlist_redraw(NaN, -1, -1);
944 }
945
946
947 function cbi_t_add(section, tab) {
948         var t = document.getElementById('tab.' + section + '.' + tab);
949         var c = document.getElementById('container.' + section + '.' + tab);
950
951         if( t && c ) {
952                 cbi_t[section] = (cbi_t[section] || [ ]);
953                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
954         }
955 }
956
957 function cbi_t_switch(section, tab) {
958         if( cbi_t[section] && cbi_t[section][tab] ) {
959                 var o = cbi_t[section][tab];
960                 var h = document.getElementById('tab.' + section);
961                 for( var tid in cbi_t[section] ) {
962                         var o2 = cbi_t[section][tid];
963                         if( o.tab.id != o2.tab.id ) {
964                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
965                                 o2.container.style.display = 'none';
966                         }
967                         else {
968                                 if(h) h.value = tab;
969                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
970                                 o2.container.style.display = 'block';
971                         }
972                 }
973         }
974         return false
975 }
976
977 function cbi_t_update() {
978         var hl_tabs = [ ];
979         var updated = false;
980
981         for( var sid in cbi_t )
982                 for( var tid in cbi_t[sid] )
983                 {
984                         var t = cbi_t[sid][tid].tab;
985                         var c = cbi_t[sid][tid].container;
986
987                         if (!c.firstElementChild) {
988                                 t.style.display = 'none';
989                         }
990                         else if (t.style.display == 'none') {
991                                 t.style.display = '';
992                                 t.className += ' cbi-tab-highlighted';
993                                 hl_tabs.push(t);
994                         }
995
996                         cbi_tag_last(c);
997                         updated = true;
998                 }
999
1000         if (hl_tabs.length > 0)
1001                 window.setTimeout(function() {
1002                         for( var i = 0; i < hl_tabs.length; i++ )
1003                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
1004                 }, 750);
1005
1006         return updated;
1007 }
1008
1009
1010 function cbi_validate_form(form, errmsg)
1011 {
1012         /* if triggered by a section removal or addition, don't validate */
1013         if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
1014                 return true;
1015
1016         if( form.cbi_validators )
1017         {
1018                 for( var i = 0; i < form.cbi_validators.length; i++ )
1019                 {
1020                         var validator = form.cbi_validators[i];
1021                         if( !validator() && errmsg )
1022                         {
1023                                 alert(errmsg);
1024                                 return false;
1025                         }
1026                 }
1027         }
1028
1029         return true;
1030 }
1031
1032 function cbi_validate_reset(form)
1033 {
1034         window.setTimeout(
1035                 function() { cbi_validate_form(form, null) }, 100
1036         );
1037
1038         return true;
1039 }
1040
1041 function cbi_validate_compile(code)
1042 {
1043         var pos = 0;
1044         var esc = false;
1045         var depth = 0;
1046         var stack = [ ];
1047
1048         code += ',';
1049
1050         for (var i = 0; i < code.length; i++)
1051         {
1052                 if (esc)
1053                 {
1054                         esc = false;
1055                         continue;
1056                 }
1057
1058                 switch (code.charCodeAt(i))
1059                 {
1060                 case 92:
1061                         esc = true;
1062                         break;
1063
1064                 case 40:
1065                 case 44:
1066                         if (depth <= 0)
1067                         {
1068                                 if (pos < i)
1069                                 {
1070                                         var label = code.substring(pos, i);
1071                                                 label = label.replace(/\\(.)/g, '$1');
1072                                                 label = label.replace(/^[ \t]+/g, '');
1073                                                 label = label.replace(/[ \t]+$/g, '');
1074
1075                                         if (label && !isNaN(label))
1076                                         {
1077                                                 stack.push(parseFloat(label));
1078                                         }
1079                                         else if (label.match(/^(['"]).*\1$/))
1080                                         {
1081                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1082                                         }
1083                                         else if (typeof cbi_validators[label] == 'function')
1084                                         {
1085                                                 stack.push(cbi_validators[label]);
1086                                                 stack.push(null);
1087                                         }
1088                                         else
1089                                         {
1090                                                 throw "Syntax error, unhandled token '"+label+"'";
1091                                         }
1092                                 }
1093                                 pos = i+1;
1094                         }
1095                         depth += (code.charCodeAt(i) == 40);
1096                         break;
1097
1098                 case 41:
1099                         if (--depth <= 0)
1100                         {
1101                                 if (typeof stack[stack.length-2] != 'function')
1102                                         throw "Syntax error, argument list follows non-function";
1103
1104                                 stack[stack.length-1] =
1105                                         arguments.callee(code.substring(pos, i));
1106
1107                                 pos = i+1;
1108                         }
1109                         break;
1110                 }
1111         }
1112
1113         return stack;
1114 }
1115
1116 function cbi_validate_field(cbid, optional, type)
1117 {
1118         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1119         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1120
1121         if (field && vstack && typeof vstack[0] == "function")
1122         {
1123                 var validator = function()
1124                 {
1125                         // is not detached
1126                         if( field.form )
1127                         {
1128                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
1129
1130                                 // validate value
1131                                 var value = (field.options && field.options.selectedIndex > -1)
1132                                         ? field.options[field.options.selectedIndex].value : field.value;
1133
1134                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1135                                 {
1136                                         // invalid
1137                                         field.className += ' cbi-input-invalid';
1138                                         return false;
1139                                 }
1140                         }
1141
1142                         return true;
1143                 };
1144
1145                 if( ! field.form.cbi_validators )
1146                         field.form.cbi_validators = [ ];
1147
1148                 field.form.cbi_validators.push(validator);
1149
1150                 cbi_bind(field, "blur",  validator);
1151                 cbi_bind(field, "keyup", validator);
1152
1153                 if (field.nodeName == 'SELECT')
1154                 {
1155                         cbi_bind(field, "change", validator);
1156                         cbi_bind(field, "click",  validator);
1157                 }
1158
1159                 field.setAttribute("cbi_validate", validator);
1160                 field.setAttribute("cbi_datatype", type);
1161                 field.setAttribute("cbi_optional", (!!optional).toString());
1162
1163                 validator();
1164
1165                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1166                 if (fcbox)
1167                         cbi_validate_field(fcbox, optional, type);
1168         }
1169 }
1170
1171 function cbi_row_swap(elem, up, store)
1172 {
1173         var tr = elem.parentNode;
1174         while (tr && tr.nodeName.toLowerCase() != 'tr')
1175                 tr = tr.parentNode;
1176
1177         if (!tr)
1178                 return false;
1179
1180         var table = tr.parentNode;
1181         while (table && table.nodeName.toLowerCase() != 'table')
1182                 table = table.parentNode;
1183
1184         if (!table)
1185                 return false;
1186
1187         var s = up ? 3 : 2;
1188         var e = up ? table.rows.length : table.rows.length - 1;
1189
1190         for (var idx = s; idx < e; idx++)
1191         {
1192                 if (table.rows[idx] == tr)
1193                 {
1194                         if (up)
1195                                 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1196                         else
1197                                 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1198
1199                         break;
1200                 }
1201         }
1202
1203         var ids = [ ];
1204         for (idx = 2; idx < table.rows.length; idx++)
1205         {
1206                 table.rows[idx].className = table.rows[idx].className.replace(
1207                         /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1208                 );
1209
1210                 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1211                         ids.push(RegExp.$1);
1212         }
1213
1214         var input = document.getElementById(store);
1215         if (input)
1216                 input.value = ids.join(' ');
1217
1218         return false;
1219 }
1220
1221 function cbi_tag_last(container)
1222 {
1223         var last;
1224
1225         for (var i = 0; i < container.childNodes.length; i++)
1226         {
1227                 var c = container.childNodes[i];
1228                 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1229                 {
1230                         c.className = c.className.replace(/ cbi-value-last$/, '');
1231                         last = c;
1232                 }
1233         }
1234
1235         if (last)
1236         {
1237                 last.className += ' cbi-value-last';
1238         }
1239 }
1240
1241 String.prototype.serialize = function()
1242 {
1243         var o = this;
1244         switch(typeof(o))
1245         {
1246                 case 'object':
1247                         // null
1248                         if( o == null )
1249                         {
1250                                 return 'null';
1251                         }
1252
1253                         // array
1254                         else if( o.length )
1255                         {
1256                                 var i, s = '';
1257
1258                                 for( var i = 0; i < o.length; i++ )
1259                                         s += (s ? ', ' : '') + String.serialize(o[i]);
1260
1261                                 return '[ ' + s + ' ]';
1262                         }
1263
1264                         // object
1265                         else
1266                         {
1267                                 var k, s = '';
1268
1269                                 for( k in o )
1270                                         s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1271
1272                                 return '{ ' + s + ' }';
1273                         }
1274
1275                         break;
1276
1277                 case 'string':
1278                         // complex string
1279                         if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1280                                 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1281
1282                         // simple string
1283                         else
1284                                 return '"' + o + '"';
1285
1286                         break;
1287
1288                 default:
1289                         return o.toString();
1290         }
1291 }
1292
1293 String.prototype.format = function()
1294 {
1295         if (!RegExp)
1296                 return;
1297
1298         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1299         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1300
1301         function esc(s, r) {
1302                 for( var i = 0; i < r.length; i += 2 )
1303                         s = s.replace(r[i], r[i+1]);
1304                 return s;
1305         }
1306
1307         var str = this;
1308         var out = '';
1309         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1310         var a = b = [], numSubstitutions = 0, numMatches = 0;
1311
1312         while (a = re.exec(str))
1313         {
1314                 var m = a[1];
1315                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1316                 var pPrecision = a[6], pType = a[7];
1317
1318                 numMatches++;
1319
1320                 if (pType == '%')
1321                 {
1322                         subst = '%';
1323                 }
1324                 else
1325                 {
1326                         if (numSubstitutions < arguments.length)
1327                         {
1328                                 var param = arguments[numSubstitutions++];
1329
1330                                 var pad = '';
1331                                 if (pPad && pPad.substr(0,1) == "'")
1332                                         pad = leftpart.substr(1,1);
1333                                 else if (pPad)
1334                                         pad = pPad;
1335                                 else
1336                                         pad = ' ';
1337
1338                                 var justifyRight = true;
1339                                 if (pJustify && pJustify === "-")
1340                                         justifyRight = false;
1341
1342                                 var minLength = -1;
1343                                 if (pMinLength)
1344                                         minLength = +pMinLength;
1345
1346                                 var precision = -1;
1347                                 if (pPrecision && pType == 'f')
1348                                         precision = +pPrecision.substring(1);
1349
1350                                 var subst = param;
1351
1352                                 switch(pType)
1353                                 {
1354                                         case 'b':
1355                                                 subst = (+param || 0).toString(2);
1356                                                 break;
1357
1358                                         case 'c':
1359                                                 subst = String.fromCharCode(+param || 0);
1360                                                 break;
1361
1362                                         case 'd':
1363                                                 subst = ~~(+param || 0);
1364                                                 break;
1365
1366                                         case 'u':
1367                                                 subst = ~~Math.abs(+param || 0);
1368                                                 break;
1369
1370                                         case 'f':
1371                                                 subst = (precision > -1)
1372                                                         ? ((+param || 0.0)).toFixed(precision)
1373                                                         : (+param || 0.0);
1374                                                 break;
1375
1376                                         case 'o':
1377                                                 subst = (+param || 0).toString(8);
1378                                                 break;
1379
1380                                         case 's':
1381                                                 subst = param;
1382                                                 break;
1383
1384                                         case 'x':
1385                                                 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1386                                                 break;
1387
1388                                         case 'X':
1389                                                 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1390                                                 break;
1391
1392                                         case 'h':
1393                                                 subst = esc(param, html_esc);
1394                                                 break;
1395
1396                                         case 'q':
1397                                                 subst = esc(param, quot_esc);
1398                                                 break;
1399
1400                                         case 'j':
1401                                                 subst = String.serialize(param);
1402                                                 break;
1403
1404                                         case 't':
1405                                                 var td = 0;
1406                                                 var th = 0;
1407                                                 var tm = 0;
1408                                                 var ts = (param || 0);
1409
1410                                                 if (ts > 60) {
1411                                                         tm = Math.floor(ts / 60);
1412                                                         ts = (ts % 60);
1413                                                 }
1414
1415                                                 if (tm > 60) {
1416                                                         th = Math.floor(tm / 60);
1417                                                         tm = (tm % 60);
1418                                                 }
1419
1420                                                 if (th > 24) {
1421                                                         td = Math.floor(th / 24);
1422                                                         th = (th % 24);
1423                                                 }
1424
1425                                                 subst = (td > 0)
1426                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1427                                                         : String.format('%dh %dm %ds', th, tm, ts);
1428
1429                                                 break;
1430
1431                                         case 'm':
1432                                                 var mf = pMinLength ? +pMinLength : 1000;
1433                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1434
1435                                                 var i = 0;
1436                                                 var val = (+param || 0);
1437                                                 var units = [ ' ', ' K', ' M', ' G', ' T', ' P', ' E' ];
1438
1439                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1440                                                         val /= mf;
1441
1442                                                 subst = (i ? val.toFixed(pr) : val) + units[i];
1443                                                 pMinLength = null;
1444                                                 break;
1445                                 }
1446                         }
1447                 }
1448
1449                 if (pMinLength) {
1450                         subst = subst.toString();
1451                         for (var i = subst.length; i < pMinLength; i++)
1452                                 if (pJustify == '-')
1453                                         subst = subst + ' ';
1454                                 else
1455                                         subst = pad + subst;
1456                 }
1457
1458                 out += leftpart + subst;
1459                 str = str.substr(m.length);
1460         }
1461
1462         return out + str;
1463 }
1464
1465 String.prototype.nobr = function()
1466 {
1467         return this.replace(/[\s\n]+/g, '&#160;');
1468 }
1469
1470 String.serialize = function()
1471 {
1472         var a = [ ];
1473         for (var i = 1; i < arguments.length; i++)
1474                 a.push(arguments[i]);
1475         return ''.serialize.apply(arguments[0], a);
1476 }
1477
1478 String.format = function()
1479 {
1480         var a = [ ];
1481         for (var i = 1; i < arguments.length; i++)
1482                 a.push(arguments[i]);
1483         return ''.format.apply(arguments[0], a);
1484 }
1485
1486 String.nobr = function()
1487 {
1488         var a = [ ];
1489         for (var i = 1; i < arguments.length; i++)
1490                 a.push(arguments[i]);
1491         return ''.nobr.apply(arguments[0], a);
1492 }