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