libs/web: introduce recursive expression support for datatypes, introduce "or" and...
[project/luci.git] / libs / web / 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 <xm@subsignal.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-Z]+$/) != 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         'wpakey': function()
165         {
166                 var v = this;
167
168                 if( v.length == 64 )
169                         return (v.match(/^[a-fA-F0-9]{64}$/) != null);
170                 else
171                         return (v.length >= 8) && (v.length <= 63);
172         },
173
174         'wepkey': function()
175         {
176                 var v = this;
177
178                 if ( v.substr(0,2) == 's:' )
179                         v = v.substr(2);
180
181                 if( (v.length == 10) || (v.length == 26) )
182                         return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
183                 else
184                         return (v.length == 5) || (v.length == 13);
185         },
186
187         'uciname': function()
188         {
189                 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
190         },
191
192         'range': function(min, max)
193         {
194                 var val = parseFloat(this);
195                 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
196                         return ((val >= min) && (val <= max));
197
198                 return false;
199         },
200
201         'min': function(min)
202         {
203                 var val = parseFloat(this);
204                 if (!isNaN(min) && !isNaN(val))
205                         return (val >= min);
206
207                 return false;
208         },
209
210         'max': function(max)
211         {
212                 var val = parseFloat(this);
213                 if (!isNaN(max) && !isNaN(val))
214                         return (val <= max);
215
216                 return false;
217         },
218
219         'or': function()
220         {
221                 for (var i = 0; i < arguments.length; i += 2)
222                 {
223                         if (typeof arguments[i] != 'function')
224                         {
225                                 if (arguments[i] == this)
226                                         return true;
227                                 i--;
228                         }
229                         else if (arguments[i].apply(this, arguments[i+1]))
230                         {
231                                 return true;
232                         }
233                 }
234                 return false;
235         },
236
237         'and': function()
238         {
239                 for (var i = 0; i < arguments.length; i += 2)
240                 {
241                         if (typeof arguments[i] != 'function')
242                         {
243                                 if (arguments[i] != this)
244                                         return false;
245                                 i--;
246                         }
247                         else if (!arguments[i].apply(this, arguments[i+1]))
248                         {
249                                 return false;
250                         }
251                 }
252                 return true;
253         },
254
255         'neg': function()
256         {
257                 return cbi_validators.or.apply(
258                         this.replace(/^[ \t]*![ \t]*/, ''), arguments);
259         },
260
261         'list': function(subvalidator, subargs)
262         {
263                 if (typeof subvalidator != 'function')
264                         return false;
265
266                 var tokens = this.match(/[^ \t]+/g);
267                 for (var i = 0; i < tokens.length; i++)
268                         if (!subvalidator.apply(tokens[i], subargs))
269                                 return false;
270
271                 return true;
272         }
273 };
274
275
276 function cbi_d_add(field, dep, next) {
277         var obj = document.getElementById(field);
278         if (obj) {
279                 var entry
280                 for (var i=0; i<cbi_d.length; i++) {
281                         if (cbi_d[i].id == field) {
282                                 entry = cbi_d[i];
283                                 break;
284                         }
285                 }
286                 if (!entry) {
287                         entry = {
288                                 "node": obj,
289                                 "id": field,
290                                 "parent": obj.parentNode.id,
291                                 "next": next,
292                                 "deps": []
293                         };
294                         cbi_d.unshift(entry);
295                 }
296                 entry.deps.push(dep)
297         }
298 }
299
300 function cbi_d_checkvalue(target, ref) {
301         var t = document.getElementById(target);
302         var value;
303
304         if (!t) {
305                 var tl = document.getElementsByName(target);
306
307                 if( tl.length > 0 && tl[0].type == 'radio' )
308                         for( var i = 0; i < tl.length; i++ )
309                                 if( tl[i].checked ) {
310                                         value = tl[i].value;
311                                         break;
312                                 }
313
314                 value = value ? value : "";
315         } else if (!t.value) {
316                 value = "";
317         } else {
318                 value = t.value;
319
320                 if (t.type == "checkbox") {
321                         value = t.checked ? value : "";
322                 }
323         }
324
325         return (value == ref)
326 }
327
328 function cbi_d_check(deps) {
329         var reverse;
330         var def = false;
331         for (var i=0; i<deps.length; i++) {
332                 var istat = true;
333                 reverse = false;
334                 for (var j in deps[i]) {
335                         if (j == "!reverse") {
336                                 reverse = true;
337                         } else if (j == "!default") {
338                                 def = true;
339                                 istat = false;
340                         } else {
341                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
342                         }
343                 }
344                 if (istat) {
345                         return !reverse;
346                 }
347         }
348         return def;
349 }
350
351 function cbi_d_update() {
352         var state = false;
353         for (var i=0; i<cbi_d.length; i++) {
354                 var entry = cbi_d[i];
355                 var next  = document.getElementById(entry.next)
356                 var node  = document.getElementById(entry.id)
357                 var parent = document.getElementById(entry.parent)
358
359                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
360                         node.parentNode.removeChild(node);
361                         state = true;
362                         if( entry.parent )
363                                 cbi_c[entry.parent]--;
364                 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
365                         if (!next) {
366                                 parent.appendChild(entry.node);
367                         } else {
368                                 next.parentNode.insertBefore(entry.node, next);
369                         }
370                         state = true;
371                         if( entry.parent )
372                                 cbi_c[entry.parent]++;
373                 }
374         }
375
376         if (entry && entry.parent) {
377                 if (!cbi_t_update())
378                         cbi_tag_last(parent);
379         }
380
381         if (state) {
382                 cbi_d_update();
383         }
384 }
385
386 function cbi_bind(obj, type, callback, mode) {
387         if (!obj.addEventListener) {
388                 obj.attachEvent('on' + type,
389                         function(){
390                                 var e = window.event;
391
392                                 if (!e.target && e.srcElement)
393                                         e.target = e.srcElement;
394
395                                 return !!callback(e);
396                         }
397                 );
398         } else {
399                 obj.addEventListener(type, callback, !!mode);
400         }
401         return obj;
402 }
403
404 function cbi_combobox(id, values, def, man) {
405         var selid = "cbi.combobox." + id;
406         if (document.getElementById(selid)) {
407                 return
408         }
409
410         var obj = document.getElementById(id)
411         var sel = document.createElement("select");
412                 sel.id = selid;
413                 sel.className = 'cbi-input-select';
414
415         if (obj.nextSibling) {
416                 obj.parentNode.insertBefore(sel, obj.nextSibling);
417         } else {
418                 obj.parentNode.appendChild(sel);
419         }
420
421         var dt = obj.getAttribute('cbi_datatype');
422         var op = obj.getAttribute('cbi_optional');
423
424         if (dt)
425                 cbi_validate_field(sel, op == 'true', dt);
426
427         if (!values[obj.value]) {
428                 if (obj.value == "") {
429                         var optdef = document.createElement("option");
430                         optdef.value = "";
431                         optdef.appendChild(document.createTextNode(def));
432                         sel.appendChild(optdef);
433                 } else {
434                         var opt = document.createElement("option");
435                         opt.value = obj.value;
436                         opt.selected = "selected";
437                         opt.appendChild(document.createTextNode(obj.value));
438                         sel.appendChild(opt);
439                 }
440         }
441
442         for (var i in values) {
443                 var opt = document.createElement("option");
444                 opt.value = i;
445
446                 if (obj.value == i) {
447                         opt.selected = "selected";
448                 }
449
450                 opt.appendChild(document.createTextNode(values[i]));
451                 sel.appendChild(opt);
452         }
453
454         var optman = document.createElement("option");
455         optman.value = "";
456         optman.appendChild(document.createTextNode(man));
457         sel.appendChild(optman);
458
459         obj.style.display = "none";
460
461         cbi_bind(sel, "change", function() {
462                 if (sel.selectedIndex == sel.options.length - 1) {
463                         obj.style.display = "inline";
464                         sel.parentNode.removeChild(sel);
465                         obj.focus();
466                 } else {
467                         obj.value = sel.options[sel.selectedIndex].value;
468                 }
469
470                 try {
471                         cbi_d_update();
472                 } catch (e) {
473                         //Do nothing
474                 }
475         })
476 }
477
478 function cbi_combobox_init(id, values, def, man) {
479         var obj = document.getElementById(id);
480         cbi_bind(obj, "blur", function() {
481                 cbi_combobox(id, values, def, man)
482         });
483         cbi_combobox(id, values, def, man);
484 }
485
486 function cbi_filebrowser(id, url, defpath) {
487         var field   = document.getElementById(id);
488         var browser = window.open(
489                 url + ( field.value || defpath || '' ) + '?field=' + id,
490                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
491         );
492
493         browser.focus();
494 }
495
496 function cbi_browser_init(id, respath, url, defpath)
497 {
498         function cbi_browser_btnclick(e) {
499                 cbi_filebrowser(id, url, defpath);
500                 return false;
501         }
502
503         var field = document.getElementById(id);
504
505         var btn = document.createElement('img');
506         btn.className = 'cbi-image-button';
507         btn.src = respath + '/cbi/folder.gif';
508         field.parentNode.insertBefore(btn, field.nextSibling);
509
510         cbi_bind(btn, 'click', cbi_browser_btnclick);
511 }
512
513 function cbi_dynlist_init(name, respath, datatype, optional, choices)
514 {
515         var input0 = document.getElementsByName(name)[0];
516         var prefix = input0.name;
517         var parent = input0.parentNode;
518         var holder = input0.placeholder;
519
520         var values;
521
522         function cbi_dynlist_redraw(focus, add, del)
523         {
524                 values = [ ];
525
526                 while (parent.firstChild)
527                 {
528                         var n = parent.firstChild;
529                         var i = parseInt(n.index);
530
531                         if (i != del)
532                         {
533                                 if (n.nodeName.toLowerCase() == 'input')
534                                         values.push(n.value || '');
535                                 else if (n.nodeName.toLowerCase() == 'select')
536                                         values[values.length-1] = n.options[n.selectedIndex].value;
537                         }
538
539                         parent.removeChild(n);
540                 }
541
542                 if (add >= 0)
543                 {
544                         focus = add+1;
545                         values.splice(focus, 0, '');
546                 }
547                 else if (values.length == 0)
548                 {
549                         focus = 0;
550                         values.push('');
551                 }
552
553                 for (var i = 0; i < values.length; i++)
554                 {
555                         var t = document.createElement('input');
556                                 t.id = prefix + '.' + (i+1);
557                                 t.name = prefix;
558                                 t.value = values[i];
559                                 t.type = 'text';
560                                 t.index = i;
561                                 t.className = 'cbi-input-text';
562
563                         if (i == 0 && holder)
564                         {
565                                 t.placeholder = holder;
566                         }
567
568                         var b = document.createElement('img');
569                                 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
570                                 b.className = 'cbi-image-button';
571
572                         parent.appendChild(t);
573                         parent.appendChild(b);
574                         parent.appendChild(document.createElement('br'));
575
576                         if (datatype)
577                         {
578                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
579                         }
580
581                         if (choices)
582                         {
583                                 cbi_combobox_init(t.id, choices[0], '', choices[1]);
584                                 t.nextSibling.index = i;
585
586                                 cbi_bind(t.nextSibling, 'keydown',  cbi_dynlist_keydown);
587                                 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
588
589                                 if (i == focus || -i == focus)
590                                         t.nextSibling.focus();
591                         }
592                         else
593                         {
594                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
595                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
596
597                                 if (i == focus)
598                                 {
599                                         t.focus();
600                                 }
601                                 else if (-i == focus)
602                                 {
603                                         t.focus();
604
605                                         /* force cursor to end */
606                                         var v = t.value;
607                                         t.value = ' '
608                                         t.value = v;
609                                 }
610                         }
611
612                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
613                 }
614         }
615
616         function cbi_dynlist_keypress(ev)
617         {
618                 ev = ev ? ev : window.event;
619
620                 var se = ev.target ? ev.target : ev.srcElement;
621
622                 if (se.nodeType == 3)
623                         se = se.parentNode;
624
625                 switch (ev.keyCode)
626                 {
627                         /* backspace, delete */
628                         case 8:
629                         case 46:
630                                 if (se.value.length == 0)
631                                 {
632                                         if (ev.preventDefault)
633                                                 ev.preventDefault();
634
635                                         return false;
636                                 }
637
638                                 return true;
639
640                         /* enter, arrow up, arrow down */
641                         case 13:
642                         case 38:
643                         case 40:
644                                 if (ev.preventDefault)
645                                         ev.preventDefault();
646
647                                 return false;
648                 }
649
650                 return true;
651         }
652
653         function cbi_dynlist_keydown(ev)
654         {
655                 ev = ev ? ev : window.event;
656
657                 var se = ev.target ? ev.target : ev.srcElement;
658
659                 if (se.nodeType == 3)
660                         se = se.parentNode;
661
662                 var prev = se.previousSibling;
663                 while (prev && prev.name != name)
664                         prev = prev.previousSibling;
665
666                 var next = se.nextSibling;
667                 while (next && next.name != name)
668                         next = next.nextSibling;
669
670                 /* advance one further in combobox case */
671                 if (next && next.nextSibling.name == name)
672                         next = next.nextSibling;
673
674                 switch (ev.keyCode)
675                 {
676                         /* backspace, delete */
677                         case 8:
678                         case 46:
679                                 var del = (se.nodeName.toLowerCase() == 'select')
680                                         ? true : (se.value.length == 0);
681
682                                 if (del)
683                                 {
684                                         if (ev.preventDefault)
685                                                 ev.preventDefault();
686
687                                         var focus = se.index;
688                                         if (ev.keyCode == 8)
689                                                 focus = -focus+1;
690
691                                         cbi_dynlist_redraw(focus, -1, se.index);
692
693                                         return false;
694                                 }
695
696                                 break;
697
698                         /* enter */
699                         case 13:
700                                 cbi_dynlist_redraw(-1, se.index, -1);
701                                 break;
702
703                         /* arrow up */
704                         case 38:
705                                 if (prev)
706                                         prev.focus();
707
708                                 break;
709
710                         /* arrow down */
711                         case 40:
712                                 if (next)
713                                         next.focus();
714
715                                 break;
716                 }
717
718                 return true;
719         }
720
721         function cbi_dynlist_btnclick(ev)
722         {
723                 ev = ev ? ev : window.event;
724
725                 var se = ev.target ? ev.target : ev.srcElement;
726
727                 if (se.src.indexOf('remove') > -1)
728                 {
729                         se.previousSibling.value = '';
730
731                         cbi_dynlist_keydown({
732                                 target:  se.previousSibling,
733                                 keyCode: 8
734                         });
735                 }
736                 else
737                 {
738                         cbi_dynlist_keydown({
739                                 target:  se.previousSibling,
740                                 keyCode: 13
741                         });
742                 }
743
744                 return false;
745         }
746
747         cbi_dynlist_redraw(-1, -1, -1);
748 }
749
750 //Hijacks the CBI form to send via XHR (requires Prototype)
751 function cbi_hijack_forms(layer, win, fail, load) {
752         var forms = layer.getElementsByTagName('form');
753         for (var i=0; i<forms.length; i++) {
754                 $(forms[i]).observe('submit', function(event) {
755                         // Prevent the form from also submitting the regular way
756                         event.stop();
757
758                         // Submit via XHR
759                         event.element().request({
760                                 onSuccess: win,
761                                 onFailure: fail
762                         });
763
764                         if (load) {
765                                 load();
766                         }
767                 });
768         }
769 }
770
771
772 function cbi_t_add(section, tab) {
773         var t = document.getElementById('tab.' + section + '.' + tab);
774         var c = document.getElementById('container.' + section + '.' + tab);
775
776         if( t && c ) {
777                 cbi_t[section] = (cbi_t[section] || [ ]);
778                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
779         }
780 }
781
782 function cbi_t_switch(section, tab) {
783         if( cbi_t[section] && cbi_t[section][tab] ) {
784                 var o = cbi_t[section][tab];
785                 var h = document.getElementById('tab.' + section);
786                 for( var tid in cbi_t[section] ) {
787                         var o2 = cbi_t[section][tid];
788                         if( o.tab.id != o2.tab.id ) {
789                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
790                                 o2.container.style.display = 'none';
791                         }
792                         else {
793                                 if(h) h.value = tab;
794                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
795                                 o2.container.style.display = 'block';
796                         }
797                 }
798         }
799         return false
800 }
801
802 function cbi_t_update() {
803         var hl_tabs = [ ];
804         var updated = false;
805
806         for( var sid in cbi_t )
807                 for( var tid in cbi_t[sid] )
808                 {
809                         if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
810                                 cbi_t[sid][tid].tab.style.display = 'none';
811                         }
812                         else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
813                                 cbi_t[sid][tid].tab.style.display = '';
814
815                                 var t = cbi_t[sid][tid].tab;
816                                 t.className += ' cbi-tab-highlighted';
817                                 hl_tabs.push(t);
818                         }
819
820                         cbi_tag_last(cbi_t[sid][tid].container);
821                         updated = true;
822                 }
823
824         if( hl_tabs.length > 0 )
825                 window.setTimeout(function() {
826                         for( var i = 0; i < hl_tabs.length; i++ )
827                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
828                 }, 750);
829
830         return updated;
831 }
832
833
834 function cbi_validate_form(form, errmsg)
835 {
836         /* if triggered by a section removal or addition, don't validate */
837         if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
838                 return true;
839
840         if( form.cbi_validators )
841         {
842                 for( var i = 0; i < form.cbi_validators.length; i++ )
843                 {
844                         var validator = form.cbi_validators[i];
845                         if( !validator() && errmsg )
846                         {
847                                 alert(errmsg);
848                                 return false;
849                         }
850                 }
851         }
852
853         return true;
854 }
855
856 function cbi_validate_reset(form)
857 {
858         window.setTimeout(
859                 function() { cbi_validate_form(form, null) }, 100
860         );
861
862         return true;
863 }
864
865 function cbi_validate_compile(code)
866 {
867         var pos = 0;
868         var esc = false;
869         var depth = 0;
870         var stack = [ ];
871
872         code += ',';
873
874         for (var i = 0; i < code.length; i++)
875         {
876                 if (esc)
877                 {
878                         esc = false;
879                         continue;
880                 }
881
882                 switch (code.charCodeAt(i))
883                 {
884                 case 92:
885                         esc = true;
886                         break;
887
888                 case 40:
889                 case 44:
890                         if (depth <= 0)
891                         {
892                                 if (pos < i)
893                                 {
894                                         var label = code.substring(pos, i);
895                                                 label = label.replace(/\\(.)/g, '$1');
896                                                 label = label.replace(/^[ \t]+/g, '');
897                                                 label = label.replace(/[ \t]+$/g, '');
898
899                                         if (label && !isNaN(label))
900                                         {
901                                                 stack.push(parseFloat(label));
902                                         }
903                                         else if (label.match(/^(['"]).*\1$/))
904                                         {
905                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
906                                         }
907                                         else if (typeof cbi_validators[label] == 'function')
908                                         {
909                                                 stack.push(cbi_validators[label]);
910                                                 stack.push(null);
911                                         }
912                                         else
913                                         {
914                                                 throw "Syntax error, unhandled token '"+label+"'";
915                                         }
916                                 }
917                                 pos = i+1;
918                         }
919                         depth += (code.charCodeAt(i) == 40);
920                         break;
921
922                 case 41:
923                         if (--depth <= 0)
924                         {
925                                 if (typeof stack[stack.length-2] != 'function')
926                                         throw "Syntax error, argument list follows non-function";
927
928                                 stack[stack.length-1] =
929                                         arguments.callee(code.substring(pos, i));
930
931                                 pos = i+1;
932                         }
933                         break;
934                 }
935         }
936
937         return stack;
938 }
939
940 function cbi_validate_field(cbid, optional, type)
941 {
942         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
943         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
944
945         if (field && vstack && typeof vstack[0] == "function")
946         {
947                 var validator = function()
948                 {
949                         // is not detached
950                         if( field.form )
951                         {
952                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
953
954                                 // validate value
955                                 var value = (field.options && field.options.selectedIndex > -1)
956                                         ? field.options[field.options.selectedIndex].value : field.value;
957
958                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
959                                 {
960                                         // invalid
961                                         field.className += ' cbi-input-invalid';
962                                         return false;
963                                 }
964                         }
965
966                         return true;
967                 };
968
969                 if( ! field.form.cbi_validators )
970                         field.form.cbi_validators = [ ];
971
972                 field.form.cbi_validators.push(validator);
973
974                 cbi_bind(field, "blur",  validator);
975                 cbi_bind(field, "keyup", validator);
976
977                 if (field.nodeName == 'SELECT')
978                 {
979                         cbi_bind(field, "change", validator);
980                         cbi_bind(field, "click",  validator);
981                 }
982
983                 field.setAttribute("cbi_validate", validator);
984                 field.setAttribute("cbi_datatype", type);
985                 field.setAttribute("cbi_optional", (!!optional).toString());
986
987                 validator();
988
989                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
990                 if (fcbox)
991                         cbi_validate_field(fcbox, optional, type);
992         }
993 }
994
995 function cbi_row_swap(elem, up, store)
996 {
997         var tr = elem.parentNode;
998         while (tr && tr.nodeName.toLowerCase() != 'tr')
999                 tr = tr.parentNode;
1000
1001         if (!tr)
1002                 return false;
1003
1004         var table = tr.parentNode;
1005         while (table && table.nodeName.toLowerCase() != 'table')
1006                 table = table.parentNode;
1007
1008         if (!table)
1009                 return false;
1010
1011         var s = up ? 3 : 2;
1012         var e = up ? table.rows.length : table.rows.length - 1;
1013
1014         for (var idx = s; idx < e; idx++)
1015         {
1016                 if (table.rows[idx] == tr)
1017                 {
1018                         if (up)
1019                                 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1020                         else
1021                                 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1022
1023                         break;
1024                 }
1025         }
1026
1027         var ids = [ ];
1028         for (idx = 2; idx < table.rows.length; idx++)
1029         {
1030                 table.rows[idx].className = table.rows[idx].className.replace(
1031                         /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1032                 );
1033
1034                 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1035                         ids.push(RegExp.$1);
1036         }
1037
1038         var input = document.getElementById(store);
1039         if (input)
1040                 input.value = ids.join(' ');
1041
1042         return false;
1043 }
1044
1045 function cbi_tag_last(container)
1046 {
1047         var last;
1048
1049         for (var i = 0; i < container.childNodes.length; i++)
1050         {
1051                 var c = container.childNodes[i];
1052                 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1053                 {
1054                         c.className = c.className.replace(/ cbi-value-last$/, '');
1055                         last = c;
1056                 }
1057         }
1058
1059         if (last)
1060         {
1061                 last.className += ' cbi-value-last';
1062         }
1063 }
1064
1065 if( ! String.serialize )
1066         String.serialize = function(o)
1067         {
1068                 switch(typeof(o))
1069                 {
1070                         case 'object':
1071                                 // null
1072                                 if( o == null )
1073                                 {
1074                                         return 'null';
1075                                 }
1076
1077                                 // array
1078                                 else if( o.length )
1079                                 {
1080                                         var i, s = '';
1081
1082                                         for( var i = 0; i < o.length; i++ )
1083                                                 s += (s ? ', ' : '') + String.serialize(o[i]);
1084
1085                                         return '[ ' + s + ' ]';
1086                                 }
1087
1088                                 // object
1089                                 else
1090                                 {
1091                                         var k, s = '';
1092
1093                                         for( k in o )
1094                                                 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1095
1096                                         return '{ ' + s + ' }';
1097                                 }
1098
1099                                 break;
1100
1101                         case 'string':
1102                                 // complex string
1103                                 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1104                                         return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1105
1106                                 // simple string
1107                                 else
1108                                         return '"' + o + '"';
1109
1110                                 break;
1111
1112                         default:
1113                                 return o.toString();
1114                 }
1115         }
1116
1117
1118 if( ! String.format )
1119         String.format = function()
1120         {
1121                 if (!arguments || arguments.length < 1 || !RegExp)
1122                         return;
1123
1124                 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1125                 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1126
1127                 function esc(s, r) {
1128                         for( var i = 0; i < r.length; i += 2 )
1129                                 s = s.replace(r[i], r[i+1]);
1130                         return s;
1131                 }
1132
1133                 var str = arguments[0];
1134                 var out = '';
1135                 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1136                 var a = b = [], numSubstitutions = 0, numMatches = 0;
1137
1138                 while( a = re.exec(str) )
1139                 {
1140                         var m = a[1];
1141                         var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1142                         var pPrecision = a[6], pType = a[7];
1143
1144                         numMatches++;
1145
1146                         if (pType == '%')
1147                         {
1148                                 subst = '%';
1149                         }
1150                         else
1151                         {
1152                                 if (numSubstitutions++ < arguments.length)
1153                                 {
1154                                         var param = arguments[numSubstitutions];
1155
1156                                         var pad = '';
1157                                         if (pPad && pPad.substr(0,1) == "'")
1158                                                 pad = leftpart.substr(1,1);
1159                                         else if (pPad)
1160                                                 pad = pPad;
1161
1162                                         var justifyRight = true;
1163                                         if (pJustify && pJustify === "-")
1164                                                 justifyRight = false;
1165
1166                                         var minLength = -1;
1167                                         if (pMinLength)
1168                                                 minLength = parseInt(pMinLength);
1169
1170                                         var precision = -1;
1171                                         if (pPrecision && pType == 'f')
1172                                                 precision = parseInt(pPrecision.substring(1));
1173
1174                                         var subst = param;
1175
1176                                         switch(pType)
1177                                         {
1178                                                 case 'b':
1179                                                         subst = (parseInt(param) || 0).toString(2);
1180                                                         break;
1181
1182                                                 case 'c':
1183                                                         subst = String.fromCharCode(parseInt(param) || 0);
1184                                                         break;
1185
1186                                                 case 'd':
1187                                                         subst = (parseInt(param) || 0);
1188                                                         break;
1189
1190                                                 case 'u':
1191                                                         subst = Math.abs(parseInt(param) || 0);
1192                                                         break;
1193
1194                                                 case 'f':
1195                                                         subst = (precision > -1)
1196                                                                 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1197                                                                 : (parseFloat(param) || 0.0);
1198                                                         break;
1199
1200                                                 case 'o':
1201                                                         subst = (parseInt(param) || 0).toString(8);
1202                                                         break;
1203
1204                                                 case 's':
1205                                                         subst = param;
1206                                                         break;
1207
1208                                                 case 'x':
1209                                                         subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1210                                                         break;
1211
1212                                                 case 'X':
1213                                                         subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1214                                                         break;
1215
1216                                                 case 'h':
1217                                                         subst = esc(param, html_esc);
1218                                                         break;
1219
1220                                                 case 'q':
1221                                                         subst = esc(param, quot_esc);
1222                                                         break;
1223
1224                                                 case 'j':
1225                                                         subst = String.serialize(param);
1226                                                         break;
1227
1228                                                 case 't':
1229                                                         var td = 0;
1230                                                         var th = 0;
1231                                                         var tm = 0;
1232                                                         var ts = (param || 0);
1233
1234                                                         if (ts > 60) {
1235                                                                 tm = Math.floor(ts / 60);
1236                                                                 ts = (ts % 60);
1237                                                         }
1238
1239                                                         if (tm > 60) {
1240                                                                 th = Math.floor(tm / 60);
1241                                                                 tm = (tm % 60);
1242                                                         }
1243
1244                                                         if (th > 24) {
1245                                                                 td = Math.floor(th / 24);
1246                                                                 th = (th % 24);
1247                                                         }
1248
1249                                                         subst = (td > 0)
1250                                                                 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1251                                                                 : String.format('%dh %dm %ds', th, tm, ts);
1252
1253                                                         break;
1254
1255                                                 case 'm':
1256                                                         var mf = pMinLength ? parseInt(pMinLength) : 1000;
1257                                                         var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1258
1259                                                         var i = 0;
1260                                                         var val = parseFloat(param || 0);
1261                                                         var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1262
1263                                                         for (i = 0; (i < units.length) && (val > mf); i++)
1264                                                                 val /= mf;
1265
1266                                                         subst = val.toFixed(pr) + ' ' + units[i];
1267                                                         break;
1268                                         }
1269                                 }
1270                         }
1271
1272                         out += leftpart + subst;
1273                         str = str.substr(m.length);
1274                 }
1275
1276                 return out + str;
1277         }