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