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