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