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