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