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