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