luci-base: cbi: further refactoring
[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 ((!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.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 = {};
554
555                 for (var j = 0; j < choices[0].length; j++)
556                         options[choices[0][j]] = choices[1][j];
557
558                 cbi_dynlist_init(node, choices[2], choices[3], options);
559         }
560
561         cbi_d_update();
562 }
563
564 function cbi_bind(obj, type, callback, mode) {
565         if (!obj.addEventListener) {
566                 obj.attachEvent('on' + type,
567                         function(){
568                                 var e = window.event;
569
570                                 if (!e.target && e.srcElement)
571                                         e.target = e.srcElement;
572
573                                 return !!callback(e);
574                         }
575                 );
576         } else {
577                 obj.addEventListener(type, callback, !!mode);
578         }
579         return obj;
580 }
581
582 function cbi_combobox(id, values, def, man, focus) {
583         var selid = "cbi.combobox." + id;
584         if (document.getElementById(selid)) {
585                 return
586         }
587
588         var obj = document.getElementById(id)
589         var sel = document.createElement("select");
590                 sel.id = selid;
591                 sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
592
593         if (obj.nextSibling) {
594                 obj.parentNode.insertBefore(sel, obj.nextSibling);
595         } else {
596                 obj.parentNode.appendChild(sel);
597         }
598
599         var dt = obj.getAttribute('cbi_datatype');
600         var op = obj.getAttribute('cbi_optional');
601
602         if (dt)
603                 cbi_validate_field(sel, op == 'true', dt);
604
605         if (!values[obj.value]) {
606                 if (obj.value == "") {
607                         var optdef = document.createElement("option");
608                         optdef.value = "";
609                         optdef.appendChild(document.createTextNode(typeof(def) === 'string' ? def : cbi_strings.label.choose));
610                         sel.appendChild(optdef);
611                 } else {
612                         var opt = document.createElement("option");
613                         opt.value = obj.value;
614                         opt.selected = "selected";
615                         opt.appendChild(document.createTextNode(obj.value));
616                         sel.appendChild(opt);
617                 }
618         }
619
620         for (var i in values) {
621                 var opt = document.createElement("option");
622                 opt.value = i;
623
624                 if (obj.value == i) {
625                         opt.selected = "selected";
626                 }
627
628                 opt.appendChild(document.createTextNode(values[i]));
629                 sel.appendChild(opt);
630         }
631
632         var optman = document.createElement("option");
633         optman.value = "";
634         optman.appendChild(document.createTextNode(typeof(man) === 'string' ? man : cbi_strings.label.custom));
635         sel.appendChild(optman);
636
637         obj.style.display = "none";
638
639         cbi_bind(sel, "change", function() {
640                 if (sel.selectedIndex == sel.options.length - 1) {
641                         obj.style.display = "inline";
642                         sel.blur();
643                         sel.parentNode.removeChild(sel);
644                         obj.focus();
645                 } else {
646                         obj.value = sel.options[sel.selectedIndex].value;
647                 }
648
649                 try {
650                         cbi_d_update();
651                 } catch (e) {
652                         //Do nothing
653                 }
654         })
655
656         // Retrigger validation in select
657         if (focus) {
658                 sel.focus();
659                 sel.blur();
660         }
661 }
662
663 function cbi_combobox_init(id, values, def, man) {
664         var obj = (typeof(id) === 'string') ? document.getElementById(id) : id;
665         cbi_bind(obj, "blur", function() {
666                 cbi_combobox(obj.id, values, def, man, true);
667         });
668         cbi_combobox(obj.id, values, def, man, false);
669 }
670
671 function cbi_filebrowser(id, defpath) {
672         var field   = document.getElementById(id);
673         var browser = window.open(
674                 cbi_strings.path.browser + ( field.value || defpath || '' ) + '?field=' + id,
675                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
676         );
677
678         browser.focus();
679 }
680
681 function cbi_browser_init(id, defpath)
682 {
683         function cbi_browser_btnclick(e) {
684                 cbi_filebrowser(id, defpath);
685                 return false;
686         }
687
688         var field = document.getElementById(id);
689
690         var btn = document.createElement('img');
691         btn.className = 'cbi-image-button';
692         btn.src = cbi_strings.path.resource + '/cbi/folder.gif';
693         field.parentNode.insertBefore(btn, field.nextSibling);
694
695         cbi_bind(btn, 'click', cbi_browser_btnclick);
696 }
697
698 function cbi_dynlist_init(parent, datatype, optional, choices)
699 {
700         var prefix = parent.getAttribute('data-prefix');
701         var holder = parent.getAttribute('data-placeholder');
702
703         var values;
704
705         function cbi_dynlist_redraw(focus, add, del)
706         {
707                 values = [ ];
708
709                 while (parent.firstChild)
710                 {
711                         var n = parent.firstChild;
712                         var i = +n.index;
713
714                         if (i != del)
715                         {
716                                 if (n.nodeName.toLowerCase() == 'input')
717                                         values.push(n.value || '');
718                                 else if (n.nodeName.toLowerCase() == 'select')
719                                         values[values.length-1] = n.options[n.selectedIndex].value;
720                         }
721
722                         parent.removeChild(n);
723                 }
724
725                 if (add >= 0)
726                 {
727                         focus = add+1;
728                         values.splice(focus, 0, '');
729                 }
730                 else if (values.length == 0)
731                 {
732                         focus = 0;
733                         values.push('');
734                 }
735
736                 for (var i = 0; i < values.length; i++)
737                 {
738                         var t = document.createElement('input');
739                                 t.id = prefix + '.' + (i+1);
740                                 t.name = prefix;
741                                 t.value = values[i];
742                                 t.type = 'text';
743                                 t.index = i;
744                                 t.className = 'cbi-input-text';
745
746                         if (i == 0 && holder)
747                         {
748                                 t.placeholder = holder;
749                         }
750
751                         var b = document.createElement('img');
752                                 b.src = cbi_strings.path.resource + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
753                                 b.className = 'cbi-image-button';
754
755                         parent.appendChild(t);
756                         parent.appendChild(b);
757                         if (datatype == 'file')
758                         {
759                                 cbi_browser_init(t.id, parent.getAttribute('data-browser-path'));
760                         }
761
762                         parent.appendChild(document.createElement('br'));
763
764                         if (datatype)
765                         {
766                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
767                         }
768
769                         if (choices)
770                         {
771                                 cbi_combobox_init(t.id, choices, '', cbi_strings.label.custom);
772                                 b.index = i;
773
774                                 cbi_bind(b, 'keydown',  cbi_dynlist_keydown);
775                                 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
776
777                                 if (i == focus || -i == focus)
778                                         b.focus();
779                         }
780                         else
781                         {
782                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
783                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
784
785                                 if (i == focus)
786                                 {
787                                         t.focus();
788                                 }
789                                 else if (-i == focus)
790                                 {
791                                         t.focus();
792
793                                         /* force cursor to end */
794                                         var v = t.value;
795                                         t.value = ' '
796                                         t.value = v;
797                                 }
798                         }
799
800                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
801                 }
802         }
803
804         function cbi_dynlist_keypress(ev)
805         {
806                 ev = ev ? ev : window.event;
807
808                 var se = ev.target ? ev.target : ev.srcElement;
809
810                 if (se.nodeType == 3)
811                         se = se.parentNode;
812
813                 switch (ev.keyCode)
814                 {
815                         /* backspace, delete */
816                         case 8:
817                         case 46:
818                                 if (se.value.length == 0)
819                                 {
820                                         if (ev.preventDefault)
821                                                 ev.preventDefault();
822
823                                         return false;
824                                 }
825
826                                 return true;
827
828                         /* enter, arrow up, arrow down */
829                         case 13:
830                         case 38:
831                         case 40:
832                                 if (ev.preventDefault)
833                                         ev.preventDefault();
834
835                                 return false;
836                 }
837
838                 return true;
839         }
840
841         function cbi_dynlist_keydown(ev)
842         {
843                 ev = ev ? ev : window.event;
844
845                 var se = ev.target ? ev.target : ev.srcElement;
846
847                 if (se.nodeType == 3)
848                         se = se.parentNode;
849
850                 var prev = se.previousSibling;
851                 while (prev && prev.name != prefix)
852                         prev = prev.previousSibling;
853
854                 var next = se.nextSibling;
855                 while (next && next.name != prefix)
856                         next = next.nextSibling;
857
858                 /* advance one further in combobox case */
859                 if (next && next.nextSibling.name == prefix)
860                         next = next.nextSibling;
861
862                 switch (ev.keyCode)
863                 {
864                         /* backspace, delete */
865                         case 8:
866                         case 46:
867                                 var del = (se.nodeName.toLowerCase() == 'select')
868                                         ? true : (se.value.length == 0);
869
870                                 if (del)
871                                 {
872                                         if (ev.preventDefault)
873                                                 ev.preventDefault();
874
875                                         var focus = se.index;
876                                         if (ev.keyCode == 8)
877                                                 focus = -focus+1;
878
879                                         cbi_dynlist_redraw(focus, -1, se.index);
880
881                                         return false;
882                                 }
883
884                                 break;
885
886                         /* enter */
887                         case 13:
888                                 cbi_dynlist_redraw(-1, se.index, -1);
889                                 break;
890
891                         /* arrow up */
892                         case 38:
893                                 if (prev)
894                                         prev.focus();
895
896                                 break;
897
898                         /* arrow down */
899                         case 40:
900                                 if (next)
901                                         next.focus();
902
903                                 break;
904                 }
905
906                 return true;
907         }
908
909         function cbi_dynlist_btnclick(ev)
910         {
911                 ev = ev ? ev : window.event;
912
913                 var se = ev.target ? ev.target : ev.srcElement;
914                 var input = se.previousSibling;
915                 while (input && input.name != prefix) {
916                         input = input.previousSibling;
917                 }
918
919                 if (se.src.indexOf('remove') > -1)
920                 {
921                         input.value = '';
922
923                         cbi_dynlist_keydown({
924                                 target:  se,
925                                 keyCode: 8
926                         });
927                 }
928                 else
929                 {
930                         cbi_dynlist_keydown({
931                                 target:  se,
932                                 keyCode: 13
933                         });
934                 }
935
936                 return false;
937         }
938
939         cbi_dynlist_redraw(NaN, -1, -1);
940 }
941
942
943 function cbi_t_add(section, tab) {
944         var t = document.getElementById('tab.' + section + '.' + tab);
945         var c = document.getElementById('container.' + section + '.' + tab);
946
947         if( t && c ) {
948                 cbi_t[section] = (cbi_t[section] || [ ]);
949                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
950         }
951 }
952
953 function cbi_t_switch(section, tab) {
954         if( cbi_t[section] && cbi_t[section][tab] ) {
955                 var o = cbi_t[section][tab];
956                 var h = document.getElementById('tab.' + section);
957                 for( var tid in cbi_t[section] ) {
958                         var o2 = cbi_t[section][tid];
959                         if( o.tab.id != o2.tab.id ) {
960                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
961                                 o2.container.style.display = 'none';
962                         }
963                         else {
964                                 if(h) h.value = tab;
965                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
966                                 o2.container.style.display = 'block';
967                         }
968                 }
969         }
970         return false
971 }
972
973 function cbi_t_update() {
974         var hl_tabs = [ ];
975         var updated = false;
976
977         for( var sid in cbi_t )
978                 for( var tid in cbi_t[sid] )
979                 {
980                         var t = cbi_t[sid][tid].tab;
981                         var c = cbi_t[sid][tid].container;
982
983                         if (!c.firstElementChild) {
984                                 t.style.display = 'none';
985                         }
986                         else if (t.style.display == 'none') {
987                                 t.style.display = '';
988                                 t.className += ' cbi-tab-highlighted';
989                                 hl_tabs.push(t);
990                         }
991
992                         cbi_tag_last(c);
993                         updated = true;
994                 }
995
996         if (hl_tabs.length > 0)
997                 window.setTimeout(function() {
998                         for( var i = 0; i < hl_tabs.length; i++ )
999                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
1000                 }, 750);
1001
1002         return updated;
1003 }
1004
1005
1006 function cbi_validate_form(form, errmsg)
1007 {
1008         /* if triggered by a section removal or addition, don't validate */
1009         if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
1010                 return true;
1011
1012         if( form.cbi_validators )
1013         {
1014                 for( var i = 0; i < form.cbi_validators.length; i++ )
1015                 {
1016                         var validator = form.cbi_validators[i];
1017                         if( !validator() && errmsg )
1018                         {
1019                                 alert(errmsg);
1020                                 return false;
1021                         }
1022                 }
1023         }
1024
1025         return true;
1026 }
1027
1028 function cbi_validate_reset(form)
1029 {
1030         window.setTimeout(
1031                 function() { cbi_validate_form(form, null) }, 100
1032         );
1033
1034         return true;
1035 }
1036
1037 function cbi_validate_compile(code)
1038 {
1039         var pos = 0;
1040         var esc = false;
1041         var depth = 0;
1042         var stack = [ ];
1043
1044         code += ',';
1045
1046         for (var i = 0; i < code.length; i++)
1047         {
1048                 if (esc)
1049                 {
1050                         esc = false;
1051                         continue;
1052                 }
1053
1054                 switch (code.charCodeAt(i))
1055                 {
1056                 case 92:
1057                         esc = true;
1058                         break;
1059
1060                 case 40:
1061                 case 44:
1062                         if (depth <= 0)
1063                         {
1064                                 if (pos < i)
1065                                 {
1066                                         var label = code.substring(pos, i);
1067                                                 label = label.replace(/\\(.)/g, '$1');
1068                                                 label = label.replace(/^[ \t]+/g, '');
1069                                                 label = label.replace(/[ \t]+$/g, '');
1070
1071                                         if (label && !isNaN(label))
1072                                         {
1073                                                 stack.push(parseFloat(label));
1074                                         }
1075                                         else if (label.match(/^(['"]).*\1$/))
1076                                         {
1077                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1078                                         }
1079                                         else if (typeof cbi_validators[label] == 'function')
1080                                         {
1081                                                 stack.push(cbi_validators[label]);
1082                                                 stack.push(null);
1083                                         }
1084                                         else
1085                                         {
1086                                                 throw "Syntax error, unhandled token '"+label+"'";
1087                                         }
1088                                 }
1089                                 pos = i+1;
1090                         }
1091                         depth += (code.charCodeAt(i) == 40);
1092                         break;
1093
1094                 case 41:
1095                         if (--depth <= 0)
1096                         {
1097                                 if (typeof stack[stack.length-2] != 'function')
1098                                         throw "Syntax error, argument list follows non-function";
1099
1100                                 stack[stack.length-1] =
1101                                         arguments.callee(code.substring(pos, i));
1102
1103                                 pos = i+1;
1104                         }
1105                         break;
1106                 }
1107         }
1108
1109         return stack;
1110 }
1111
1112 function cbi_validate_field(cbid, optional, type)
1113 {
1114         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1115         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1116
1117         if (field && vstack && typeof vstack[0] == "function")
1118         {
1119                 var validator = function()
1120                 {
1121                         // is not detached
1122                         if( field.form )
1123                         {
1124                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
1125
1126                                 // validate value
1127                                 var value = (field.options && field.options.selectedIndex > -1)
1128                                         ? field.options[field.options.selectedIndex].value : field.value;
1129
1130                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1131                                 {
1132                                         // invalid
1133                                         field.className += ' cbi-input-invalid';
1134                                         return false;
1135                                 }
1136                         }
1137
1138                         return true;
1139                 };
1140
1141                 if( ! field.form.cbi_validators )
1142                         field.form.cbi_validators = [ ];
1143
1144                 field.form.cbi_validators.push(validator);
1145
1146                 cbi_bind(field, "blur",  validator);
1147                 cbi_bind(field, "keyup", validator);
1148
1149                 if (field.nodeName == 'SELECT')
1150                 {
1151                         cbi_bind(field, "change", validator);
1152                         cbi_bind(field, "click",  validator);
1153                 }
1154
1155                 field.setAttribute("cbi_validate", validator);
1156                 field.setAttribute("cbi_datatype", type);
1157                 field.setAttribute("cbi_optional", (!!optional).toString());
1158
1159                 validator();
1160
1161                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1162                 if (fcbox)
1163                         cbi_validate_field(fcbox, optional, type);
1164         }
1165 }
1166
1167 function cbi_row_swap(elem, up, store)
1168 {
1169         var tr = elem.parentNode;
1170         while (tr && tr.nodeName.toLowerCase() != 'tr')
1171                 tr = tr.parentNode;
1172
1173         if (!tr)
1174                 return false;
1175
1176         var table = tr.parentNode;
1177         while (table && table.nodeName.toLowerCase() != 'table')
1178                 table = table.parentNode;
1179
1180         if (!table)
1181                 return false;
1182
1183         var s = up ? 3 : 2;
1184         var e = up ? table.rows.length : table.rows.length - 1;
1185
1186         for (var idx = s; idx < e; idx++)
1187         {
1188                 if (table.rows[idx] == tr)
1189                 {
1190                         if (up)
1191                                 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1192                         else
1193                                 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1194
1195                         break;
1196                 }
1197         }
1198
1199         var ids = [ ];
1200         for (idx = 2; idx < table.rows.length; idx++)
1201         {
1202                 table.rows[idx].className = table.rows[idx].className.replace(
1203                         /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1204                 );
1205
1206                 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1207                         ids.push(RegExp.$1);
1208         }
1209
1210         var input = document.getElementById(store);
1211         if (input)
1212                 input.value = ids.join(' ');
1213
1214         return false;
1215 }
1216
1217 function cbi_tag_last(container)
1218 {
1219         var last;
1220
1221         for (var i = 0; i < container.childNodes.length; i++)
1222         {
1223                 var c = container.childNodes[i];
1224                 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1225                 {
1226                         c.className = c.className.replace(/ cbi-value-last$/, '');
1227                         last = c;
1228                 }
1229         }
1230
1231         if (last)
1232         {
1233                 last.className += ' cbi-value-last';
1234         }
1235 }
1236
1237 String.prototype.serialize = function()
1238 {
1239         var o = this;
1240         switch(typeof(o))
1241         {
1242                 case 'object':
1243                         // null
1244                         if( o == null )
1245                         {
1246                                 return 'null';
1247                         }
1248
1249                         // array
1250                         else if( o.length )
1251                         {
1252                                 var i, s = '';
1253
1254                                 for( var i = 0; i < o.length; i++ )
1255                                         s += (s ? ', ' : '') + String.serialize(o[i]);
1256
1257                                 return '[ ' + s + ' ]';
1258                         }
1259
1260                         // object
1261                         else
1262                         {
1263                                 var k, s = '';
1264
1265                                 for( k in o )
1266                                         s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1267
1268                                 return '{ ' + s + ' }';
1269                         }
1270
1271                         break;
1272
1273                 case 'string':
1274                         // complex string
1275                         if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1276                                 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1277
1278                         // simple string
1279                         else
1280                                 return '"' + o + '"';
1281
1282                         break;
1283
1284                 default:
1285                         return o.toString();
1286         }
1287 }
1288
1289 String.prototype.format = function()
1290 {
1291         if (!RegExp)
1292                 return;
1293
1294         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1295         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1296
1297         function esc(s, r) {
1298                 for( var i = 0; i < r.length; i += 2 )
1299                         s = s.replace(r[i], r[i+1]);
1300                 return s;
1301         }
1302
1303         var str = this;
1304         var out = '';
1305         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1306         var a = b = [], numSubstitutions = 0, numMatches = 0;
1307
1308         while( a = re.exec(str) )
1309         {
1310                 var m = a[1];
1311                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1312                 var pPrecision = a[6], pType = a[7];
1313
1314                 numMatches++;
1315
1316                 if (pType == '%')
1317                 {
1318                         subst = '%';
1319                 }
1320                 else
1321                 {
1322                         if (numSubstitutions < arguments.length)
1323                         {
1324                                 var param = arguments[numSubstitutions++];
1325
1326                                 var pad = '';
1327                                 if (pPad && pPad.substr(0,1) == "'")
1328                                         pad = leftpart.substr(1,1);
1329                                 else if (pPad)
1330                                         pad = pPad;
1331
1332                                 var justifyRight = true;
1333                                 if (pJustify && pJustify === "-")
1334                                         justifyRight = false;
1335
1336                                 var minLength = -1;
1337                                 if (pMinLength)
1338                                         minLength = +pMinLength;
1339
1340                                 var precision = -1;
1341                                 if (pPrecision && pType == 'f')
1342                                         precision = +pPrecision.substring(1);
1343
1344                                 var subst = param;
1345
1346                                 switch(pType)
1347                                 {
1348                                         case 'b':
1349                                                 subst = (+param || 0).toString(2);
1350                                                 break;
1351
1352                                         case 'c':
1353                                                 subst = String.fromCharCode(+param || 0);
1354                                                 break;
1355
1356                                         case 'd':
1357                                                 subst = (+param || 0);
1358                                                 break;
1359
1360                                         case 'u':
1361                                                 subst = Math.abs(+param || 0);
1362                                                 break;
1363
1364                                         case 'f':
1365                                                 subst = (precision > -1)
1366                                                         ? ((+param || 0.0)).toFixed(precision)
1367                                                         : (+param || 0.0);
1368                                                 break;
1369
1370                                         case 'o':
1371                                                 subst = (+param || 0).toString(8);
1372                                                 break;
1373
1374                                         case 's':
1375                                                 subst = param;
1376                                                 break;
1377
1378                                         case 'x':
1379                                                 subst = ('' + (+param || 0).toString(16)).toLowerCase();
1380                                                 break;
1381
1382                                         case 'X':
1383                                                 subst = ('' + (+param || 0).toString(16)).toUpperCase();
1384                                                 break;
1385
1386                                         case 'h':
1387                                                 subst = esc(param, html_esc);
1388                                                 break;
1389
1390                                         case 'q':
1391                                                 subst = esc(param, quot_esc);
1392                                                 break;
1393
1394                                         case 'j':
1395                                                 subst = String.serialize(param);
1396                                                 break;
1397
1398                                         case 't':
1399                                                 var td = 0;
1400                                                 var th = 0;
1401                                                 var tm = 0;
1402                                                 var ts = (param || 0);
1403
1404                                                 if (ts > 60) {
1405                                                         tm = Math.floor(ts / 60);
1406                                                         ts = (ts % 60);
1407                                                 }
1408
1409                                                 if (tm > 60) {
1410                                                         th = Math.floor(tm / 60);
1411                                                         tm = (tm % 60);
1412                                                 }
1413
1414                                                 if (th > 24) {
1415                                                         td = Math.floor(th / 24);
1416                                                         th = (th % 24);
1417                                                 }
1418
1419                                                 subst = (td > 0)
1420                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1421                                                         : String.format('%dh %dm %ds', th, tm, ts);
1422
1423                                                 break;
1424
1425                                         case 'm':
1426                                                 var mf = pMinLength ? +pMinLength : 1000;
1427                                                 var pr = pPrecision ? ~~(10 * +('0' + pPrecision)) : 2;
1428
1429                                                 var i = 0;
1430                                                 var val = (+param || 0);
1431                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1432
1433                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1434                                                         val /= mf;
1435
1436                                                 subst = val.toFixed(pr) + ' ' + units[i];
1437                                                 break;
1438                                 }
1439                         }
1440                 }
1441
1442                 out += leftpart + subst;
1443                 str = str.substr(m.length);
1444         }
1445
1446         return out + str;
1447 }
1448
1449 String.prototype.nobr = function()
1450 {
1451         return this.replace(/[\s\n]+/g, '&#160;');
1452 }
1453
1454 String.serialize = function()
1455 {
1456         var a = [ ];
1457         for (var i = 1; i < arguments.length; i++)
1458                 a.push(arguments[i]);
1459         return ''.serialize.apply(arguments[0], a);
1460 }
1461
1462 String.format = function()
1463 {
1464         var a = [ ];
1465         for (var i = 1; i < arguments.length; i++)
1466                 a.push(arguments[i]);
1467         return ''.format.apply(arguments[0], a);
1468 }
1469
1470 String.nobr = function()
1471 {
1472         var a = [ ];
1473         for (var i = 1; i < arguments.length; i++)
1474                 a.push(arguments[i]);
1475         return ''.nobr.apply(arguments[0], a);
1476 }