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