modules/luci-base: Fix ipaddrport validator to support ipv6
[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()
143         {
144                 return cbi_validators.hostname.apply(this) ||
145                         cbi_validators.ipaddr.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()
165         {
166                 var hp = this.split(/:/);
167
168                 if (hp.length == 2)
169                         return (cbi_validators.host.apply(hp[0]) &&
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                         if( entry.parent )
478                                 cbi_c[entry.parent]--;
479                 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
480                         if (!next) {
481                                 parent.appendChild(entry.node);
482                         } else {
483                                 next.parentNode.insertBefore(entry.node, next);
484                         }
485                         state = true;
486                         if( entry.parent )
487                                 cbi_c[entry.parent]++;
488                 }
489         }
490
491         if (entry && entry.parent) {
492                 if (!cbi_t_update())
493                         cbi_tag_last(parent);
494         }
495
496         if (state) {
497                 cbi_d_update();
498         }
499 }
500
501 function cbi_bind(obj, type, callback, mode) {
502         if (!obj.addEventListener) {
503                 obj.attachEvent('on' + type,
504                         function(){
505                                 var e = window.event;
506
507                                 if (!e.target && e.srcElement)
508                                         e.target = e.srcElement;
509
510                                 return !!callback(e);
511                         }
512                 );
513         } else {
514                 obj.addEventListener(type, callback, !!mode);
515         }
516         return obj;
517 }
518
519 function cbi_combobox(id, values, def, man) {
520         var selid = "cbi.combobox." + id;
521         if (document.getElementById(selid)) {
522                 return
523         }
524
525         var obj = document.getElementById(id)
526         var sel = document.createElement("select");
527                 sel.id = selid;
528                 sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
529
530         if (obj.nextSibling) {
531                 obj.parentNode.insertBefore(sel, obj.nextSibling);
532         } else {
533                 obj.parentNode.appendChild(sel);
534         }
535
536         var dt = obj.getAttribute('cbi_datatype');
537         var op = obj.getAttribute('cbi_optional');
538
539         if (dt)
540                 cbi_validate_field(sel, op == 'true', dt);
541
542         if (!values[obj.value]) {
543                 if (obj.value == "") {
544                         var optdef = document.createElement("option");
545                         optdef.value = "";
546                         optdef.appendChild(document.createTextNode(def));
547                         sel.appendChild(optdef);
548                 } else {
549                         var opt = document.createElement("option");
550                         opt.value = obj.value;
551                         opt.selected = "selected";
552                         opt.appendChild(document.createTextNode(obj.value));
553                         sel.appendChild(opt);
554                 }
555         }
556
557         for (var i in values) {
558                 var opt = document.createElement("option");
559                 opt.value = i;
560
561                 if (obj.value == i) {
562                         opt.selected = "selected";
563                 }
564
565                 opt.appendChild(document.createTextNode(values[i]));
566                 sel.appendChild(opt);
567         }
568
569         var optman = document.createElement("option");
570         optman.value = "";
571         optman.appendChild(document.createTextNode(man));
572         sel.appendChild(optman);
573
574         obj.style.display = "none";
575
576         cbi_bind(sel, "change", function() {
577                 if (sel.selectedIndex == sel.options.length - 1) {
578                         obj.style.display = "inline";
579                         sel.parentNode.removeChild(sel);
580                         obj.focus();
581                 } else {
582                         obj.value = sel.options[sel.selectedIndex].value;
583                 }
584
585                 try {
586                         cbi_d_update();
587                 } catch (e) {
588                         //Do nothing
589                 }
590         })
591
592         // Retrigger validation in select
593         sel.focus();
594         sel.blur();
595 }
596
597 function cbi_combobox_init(id, values, def, man) {
598         var obj = document.getElementById(id);
599         cbi_bind(obj, "blur", function() {
600                 cbi_combobox(id, values, def, man)
601         });
602         cbi_combobox(id, values, def, man);
603 }
604
605 function cbi_filebrowser(id, url, defpath) {
606         var field   = document.getElementById(id);
607         var browser = window.open(
608                 url + ( field.value || defpath || '' ) + '?field=' + id,
609                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
610         );
611
612         browser.focus();
613 }
614
615 function cbi_browser_init(id, respath, url, defpath)
616 {
617         function cbi_browser_btnclick(e) {
618                 cbi_filebrowser(id, url, defpath);
619                 return false;
620         }
621
622         var field = document.getElementById(id);
623
624         var btn = document.createElement('img');
625         btn.className = 'cbi-image-button';
626         btn.src = respath + '/cbi/folder.gif';
627         field.parentNode.insertBefore(btn, field.nextSibling);
628
629         cbi_bind(btn, 'click', cbi_browser_btnclick);
630 }
631
632 function cbi_dynlist_init(name, respath, datatype, optional, url, defpath, choices)
633 {
634         var input0 = document.getElementsByName(name)[0];
635         var prefix = input0.name;
636         var parent = input0.parentNode;
637         var holder = input0.placeholder;
638
639         var values;
640
641         function cbi_dynlist_redraw(focus, add, del)
642         {
643                 values = [ ];
644
645                 while (parent.firstChild)
646                 {
647                         var n = parent.firstChild;
648                         var i = parseInt(n.index);
649
650                         if (i != del)
651                         {
652                                 if (n.nodeName.toLowerCase() == 'input')
653                                         values.push(n.value || '');
654                                 else if (n.nodeName.toLowerCase() == 'select')
655                                         values[values.length-1] = n.options[n.selectedIndex].value;
656                         }
657
658                         parent.removeChild(n);
659                 }
660
661                 if (add >= 0)
662                 {
663                         focus = add+1;
664                         values.splice(focus, 0, '');
665                 }
666                 else if (values.length == 0)
667                 {
668                         focus = 0;
669                         values.push('');
670                 }
671
672                 for (var i = 0; i < values.length; i++)
673                 {
674                         var t = document.createElement('input');
675                                 t.id = prefix + '.' + (i+1);
676                                 t.name = prefix;
677                                 t.value = values[i];
678                                 t.type = 'text';
679                                 t.index = i;
680                                 t.className = 'cbi-input-text';
681
682                         if (i == 0 && holder)
683                         {
684                                 t.placeholder = holder;
685                         }
686
687                         var b = document.createElement('img');
688                                 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
689                                 b.className = 'cbi-image-button';
690
691                         parent.appendChild(t);
692                         parent.appendChild(b);
693                         if (datatype == 'file')
694                         {
695                                 cbi_browser_init(t.id, respath, url, defpath);
696                         }
697
698                         parent.appendChild(document.createElement('br'));
699
700                         if (datatype)
701                         {
702                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
703                         }
704
705                         if (choices)
706                         {
707                                 cbi_combobox_init(t.id, choices[0], '', choices[1]);
708                                 b.index = i;
709
710                                 cbi_bind(b, 'keydown',  cbi_dynlist_keydown);
711                                 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
712
713                                 if (i == focus || -i == focus)
714                                         b.focus();
715                         }
716                         else
717                         {
718                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
719                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
720
721                                 if (i == focus)
722                                 {
723                                         t.focus();
724                                 }
725                                 else if (-i == focus)
726                                 {
727                                         t.focus();
728
729                                         /* force cursor to end */
730                                         var v = t.value;
731                                         t.value = ' '
732                                         t.value = v;
733                                 }
734                         }
735
736                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
737                 }
738         }
739
740         function cbi_dynlist_keypress(ev)
741         {
742                 ev = ev ? ev : window.event;
743
744                 var se = ev.target ? ev.target : ev.srcElement;
745
746                 if (se.nodeType == 3)
747                         se = se.parentNode;
748
749                 switch (ev.keyCode)
750                 {
751                         /* backspace, delete */
752                         case 8:
753                         case 46:
754                                 if (se.value.length == 0)
755                                 {
756                                         if (ev.preventDefault)
757                                                 ev.preventDefault();
758
759                                         return false;
760                                 }
761
762                                 return true;
763
764                         /* enter, arrow up, arrow down */
765                         case 13:
766                         case 38:
767                         case 40:
768                                 if (ev.preventDefault)
769                                         ev.preventDefault();
770
771                                 return false;
772                 }
773
774                 return true;
775         }
776
777         function cbi_dynlist_keydown(ev)
778         {
779                 ev = ev ? ev : window.event;
780
781                 var se = ev.target ? ev.target : ev.srcElement;
782
783                 if (se.nodeType == 3)
784                         se = se.parentNode;
785
786                 var prev = se.previousSibling;
787                 while (prev && prev.name != name)
788                         prev = prev.previousSibling;
789
790                 var next = se.nextSibling;
791                 while (next && next.name != name)
792                         next = next.nextSibling;
793
794                 /* advance one further in combobox case */
795                 if (next && next.nextSibling.name == name)
796                         next = next.nextSibling;
797
798                 switch (ev.keyCode)
799                 {
800                         /* backspace, delete */
801                         case 8:
802                         case 46:
803                                 var del = (se.nodeName.toLowerCase() == 'select')
804                                         ? true : (se.value.length == 0);
805
806                                 if (del)
807                                 {
808                                         if (ev.preventDefault)
809                                                 ev.preventDefault();
810
811                                         var focus = se.index;
812                                         if (ev.keyCode == 8)
813                                                 focus = -focus+1;
814
815                                         cbi_dynlist_redraw(focus, -1, se.index);
816
817                                         return false;
818                                 }
819
820                                 break;
821
822                         /* enter */
823                         case 13:
824                                 cbi_dynlist_redraw(-1, se.index, -1);
825                                 break;
826
827                         /* arrow up */
828                         case 38:
829                                 if (prev)
830                                         prev.focus();
831
832                                 break;
833
834                         /* arrow down */
835                         case 40:
836                                 if (next)
837                                         next.focus();
838
839                                 break;
840                 }
841
842                 return true;
843         }
844
845         function cbi_dynlist_btnclick(ev)
846         {
847                 ev = ev ? ev : window.event;
848
849                 var se = ev.target ? ev.target : ev.srcElement;
850                 var input = se.previousSibling;
851                 while (input && input.name != name) {
852                         input = input.previousSibling;
853                 }
854
855                 if (se.src.indexOf('remove') > -1)
856                 {
857                         input.value = '';
858
859                         cbi_dynlist_keydown({
860                                 target:  input,
861                                 keyCode: 8
862                         });
863                 }
864                 else
865                 {
866                         cbi_dynlist_keydown({
867                                 target:  input,
868                                 keyCode: 13
869                         });
870                 }
871
872                 return false;
873         }
874
875         cbi_dynlist_redraw(NaN, -1, -1);
876 }
877
878 //Hijacks the CBI form to send via XHR (requires Prototype)
879 function cbi_hijack_forms(layer, win, fail, load) {
880         var forms = layer.getElementsByTagName('form');
881         for (var i=0; i<forms.length; i++) {
882                 $(forms[i]).observe('submit', function(event) {
883                         // Prevent the form from also submitting the regular way
884                         event.stop();
885
886                         // Submit via XHR
887                         event.element().request({
888                                 onSuccess: win,
889                                 onFailure: fail
890                         });
891
892                         if (load) {
893                                 load();
894                         }
895                 });
896         }
897 }
898
899
900 function cbi_t_add(section, tab) {
901         var t = document.getElementById('tab.' + section + '.' + tab);
902         var c = document.getElementById('container.' + section + '.' + tab);
903
904         if( t && c ) {
905                 cbi_t[section] = (cbi_t[section] || [ ]);
906                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
907         }
908 }
909
910 function cbi_t_switch(section, tab) {
911         if( cbi_t[section] && cbi_t[section][tab] ) {
912                 var o = cbi_t[section][tab];
913                 var h = document.getElementById('tab.' + section);
914                 for( var tid in cbi_t[section] ) {
915                         var o2 = cbi_t[section][tid];
916                         if( o.tab.id != o2.tab.id ) {
917                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
918                                 o2.container.style.display = 'none';
919                         }
920                         else {
921                                 if(h) h.value = tab;
922                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
923                                 o2.container.style.display = 'block';
924                         }
925                 }
926         }
927         return false
928 }
929
930 function cbi_t_update() {
931         var hl_tabs = [ ];
932         var updated = false;
933
934         for( var sid in cbi_t )
935                 for( var tid in cbi_t[sid] )
936                 {
937                         if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
938                                 cbi_t[sid][tid].tab.style.display = 'none';
939                         }
940                         else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
941                                 cbi_t[sid][tid].tab.style.display = '';
942
943                                 var t = cbi_t[sid][tid].tab;
944                                 t.className += ' cbi-tab-highlighted';
945                                 hl_tabs.push(t);
946                         }
947
948                         cbi_tag_last(cbi_t[sid][tid].container);
949                         updated = true;
950                 }
951
952         if( hl_tabs.length > 0 )
953                 window.setTimeout(function() {
954                         for( var i = 0; i < hl_tabs.length; i++ )
955                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
956                 }, 750);
957
958         return updated;
959 }
960
961
962 function cbi_validate_form(form, errmsg)
963 {
964         /* if triggered by a section removal or addition, don't validate */
965         if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
966                 return true;
967
968         if( form.cbi_validators )
969         {
970                 for( var i = 0; i < form.cbi_validators.length; i++ )
971                 {
972                         var validator = form.cbi_validators[i];
973                         if( !validator() && errmsg )
974                         {
975                                 alert(errmsg);
976                                 return false;
977                         }
978                 }
979         }
980
981         return true;
982 }
983
984 function cbi_validate_reset(form)
985 {
986         window.setTimeout(
987                 function() { cbi_validate_form(form, null) }, 100
988         );
989
990         return true;
991 }
992
993 function cbi_validate_compile(code)
994 {
995         var pos = 0;
996         var esc = false;
997         var depth = 0;
998         var stack = [ ];
999
1000         code += ',';
1001
1002         for (var i = 0; i < code.length; i++)
1003         {
1004                 if (esc)
1005                 {
1006                         esc = false;
1007                         continue;
1008                 }
1009
1010                 switch (code.charCodeAt(i))
1011                 {
1012                 case 92:
1013                         esc = true;
1014                         break;
1015
1016                 case 40:
1017                 case 44:
1018                         if (depth <= 0)
1019                         {
1020                                 if (pos < i)
1021                                 {
1022                                         var label = code.substring(pos, i);
1023                                                 label = label.replace(/\\(.)/g, '$1');
1024                                                 label = label.replace(/^[ \t]+/g, '');
1025                                                 label = label.replace(/[ \t]+$/g, '');
1026
1027                                         if (label && !isNaN(label))
1028                                         {
1029                                                 stack.push(parseFloat(label));
1030                                         }
1031                                         else if (label.match(/^(['"]).*\1$/))
1032                                         {
1033                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
1034                                         }
1035                                         else if (typeof cbi_validators[label] == 'function')
1036                                         {
1037                                                 stack.push(cbi_validators[label]);
1038                                                 stack.push(null);
1039                                         }
1040                                         else
1041                                         {
1042                                                 throw "Syntax error, unhandled token '"+label+"'";
1043                                         }
1044                                 }
1045                                 pos = i+1;
1046                         }
1047                         depth += (code.charCodeAt(i) == 40);
1048                         break;
1049
1050                 case 41:
1051                         if (--depth <= 0)
1052                         {
1053                                 if (typeof stack[stack.length-2] != 'function')
1054                                         throw "Syntax error, argument list follows non-function";
1055
1056                                 stack[stack.length-1] =
1057                                         arguments.callee(code.substring(pos, i));
1058
1059                                 pos = i+1;
1060                         }
1061                         break;
1062                 }
1063         }
1064
1065         return stack;
1066 }
1067
1068 function cbi_validate_field(cbid, optional, type)
1069 {
1070         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1071         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1072
1073         if (field && vstack && typeof vstack[0] == "function")
1074         {
1075                 var validator = function()
1076                 {
1077                         // is not detached
1078                         if( field.form )
1079                         {
1080                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
1081
1082                                 // validate value
1083                                 var value = (field.options && field.options.selectedIndex > -1)
1084                                         ? field.options[field.options.selectedIndex].value : field.value;
1085
1086                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1087                                 {
1088                                         // invalid
1089                                         field.className += ' cbi-input-invalid';
1090                                         return false;
1091                                 }
1092                         }
1093
1094                         return true;
1095                 };
1096
1097                 if( ! field.form.cbi_validators )
1098                         field.form.cbi_validators = [ ];
1099
1100                 field.form.cbi_validators.push(validator);
1101
1102                 cbi_bind(field, "blur",  validator);
1103                 cbi_bind(field, "keyup", validator);
1104
1105                 if (field.nodeName == 'SELECT')
1106                 {
1107                         cbi_bind(field, "change", validator);
1108                         cbi_bind(field, "click",  validator);
1109                 }
1110
1111                 field.setAttribute("cbi_validate", validator);
1112                 field.setAttribute("cbi_datatype", type);
1113                 field.setAttribute("cbi_optional", (!!optional).toString());
1114
1115                 validator();
1116
1117                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1118                 if (fcbox)
1119                         cbi_validate_field(fcbox, optional, type);
1120         }
1121 }
1122
1123 function cbi_row_swap(elem, up, store)
1124 {
1125         var tr = elem.parentNode;
1126         while (tr && tr.nodeName.toLowerCase() != 'tr')
1127                 tr = tr.parentNode;
1128
1129         if (!tr)
1130                 return false;
1131
1132         var table = tr.parentNode;
1133         while (table && table.nodeName.toLowerCase() != 'table')
1134                 table = table.parentNode;
1135
1136         if (!table)
1137                 return false;
1138
1139         var s = up ? 3 : 2;
1140         var e = up ? table.rows.length : table.rows.length - 1;
1141
1142         for (var idx = s; idx < e; idx++)
1143         {
1144                 if (table.rows[idx] == tr)
1145                 {
1146                         if (up)
1147                                 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1148                         else
1149                                 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1150
1151                         break;
1152                 }
1153         }
1154
1155         var ids = [ ];
1156         for (idx = 2; idx < table.rows.length; idx++)
1157         {
1158                 table.rows[idx].className = table.rows[idx].className.replace(
1159                         /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1160                 );
1161
1162                 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1163                         ids.push(RegExp.$1);
1164         }
1165
1166         var input = document.getElementById(store);
1167         if (input)
1168                 input.value = ids.join(' ');
1169
1170         return false;
1171 }
1172
1173 function cbi_tag_last(container)
1174 {
1175         var last;
1176
1177         for (var i = 0; i < container.childNodes.length; i++)
1178         {
1179                 var c = container.childNodes[i];
1180                 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1181                 {
1182                         c.className = c.className.replace(/ cbi-value-last$/, '');
1183                         last = c;
1184                 }
1185         }
1186
1187         if (last)
1188         {
1189                 last.className += ' cbi-value-last';
1190         }
1191 }
1192
1193 String.prototype.serialize = function()
1194 {
1195         var o = this;
1196         switch(typeof(o))
1197         {
1198                 case 'object':
1199                         // null
1200                         if( o == null )
1201                         {
1202                                 return 'null';
1203                         }
1204
1205                         // array
1206                         else if( o.length )
1207                         {
1208                                 var i, s = '';
1209
1210                                 for( var i = 0; i < o.length; i++ )
1211                                         s += (s ? ', ' : '') + String.serialize(o[i]);
1212
1213                                 return '[ ' + s + ' ]';
1214                         }
1215
1216                         // object
1217                         else
1218                         {
1219                                 var k, s = '';
1220
1221                                 for( k in o )
1222                                         s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1223
1224                                 return '{ ' + s + ' }';
1225                         }
1226
1227                         break;
1228
1229                 case 'string':
1230                         // complex string
1231                         if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1232                                 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1233
1234                         // simple string
1235                         else
1236                                 return '"' + o + '"';
1237
1238                         break;
1239
1240                 default:
1241                         return o.toString();
1242         }
1243 }
1244
1245 String.prototype.format = function()
1246 {
1247         if (!RegExp)
1248                 return;
1249
1250         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1251         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1252
1253         function esc(s, r) {
1254                 for( var i = 0; i < r.length; i += 2 )
1255                         s = s.replace(r[i], r[i+1]);
1256                 return s;
1257         }
1258
1259         var str = this;
1260         var out = '';
1261         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1262         var a = b = [], numSubstitutions = 0, numMatches = 0;
1263
1264         while( a = re.exec(str) )
1265         {
1266                 var m = a[1];
1267                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1268                 var pPrecision = a[6], pType = a[7];
1269
1270                 numMatches++;
1271
1272                 if (pType == '%')
1273                 {
1274                         subst = '%';
1275                 }
1276                 else
1277                 {
1278                         if (numSubstitutions < arguments.length)
1279                         {
1280                                 var param = arguments[numSubstitutions++];
1281
1282                                 var pad = '';
1283                                 if (pPad && pPad.substr(0,1) == "'")
1284                                         pad = leftpart.substr(1,1);
1285                                 else if (pPad)
1286                                         pad = pPad;
1287
1288                                 var justifyRight = true;
1289                                 if (pJustify && pJustify === "-")
1290                                         justifyRight = false;
1291
1292                                 var minLength = -1;
1293                                 if (pMinLength)
1294                                         minLength = parseInt(pMinLength);
1295
1296                                 var precision = -1;
1297                                 if (pPrecision && pType == 'f')
1298                                         precision = parseInt(pPrecision.substring(1));
1299
1300                                 var subst = param;
1301
1302                                 switch(pType)
1303                                 {
1304                                         case 'b':
1305                                                 subst = (parseInt(param) || 0).toString(2);
1306                                                 break;
1307
1308                                         case 'c':
1309                                                 subst = String.fromCharCode(parseInt(param) || 0);
1310                                                 break;
1311
1312                                         case 'd':
1313                                                 subst = (parseInt(param) || 0);
1314                                                 break;
1315
1316                                         case 'u':
1317                                                 subst = Math.abs(parseInt(param) || 0);
1318                                                 break;
1319
1320                                         case 'f':
1321                                                 subst = (precision > -1)
1322                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
1323                                                         : (parseFloat(param) || 0.0);
1324                                                 break;
1325
1326                                         case 'o':
1327                                                 subst = (parseInt(param) || 0).toString(8);
1328                                                 break;
1329
1330                                         case 's':
1331                                                 subst = param;
1332                                                 break;
1333
1334                                         case 'x':
1335                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1336                                                 break;
1337
1338                                         case 'X':
1339                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1340                                                 break;
1341
1342                                         case 'h':
1343                                                 subst = esc(param, html_esc);
1344                                                 break;
1345
1346                                         case 'q':
1347                                                 subst = esc(param, quot_esc);
1348                                                 break;
1349
1350                                         case 'j':
1351                                                 subst = String.serialize(param);
1352                                                 break;
1353
1354                                         case 't':
1355                                                 var td = 0;
1356                                                 var th = 0;
1357                                                 var tm = 0;
1358                                                 var ts = (param || 0);
1359
1360                                                 if (ts > 60) {
1361                                                         tm = Math.floor(ts / 60);
1362                                                         ts = (ts % 60);
1363                                                 }
1364
1365                                                 if (tm > 60) {
1366                                                         th = Math.floor(tm / 60);
1367                                                         tm = (tm % 60);
1368                                                 }
1369
1370                                                 if (th > 24) {
1371                                                         td = Math.floor(th / 24);
1372                                                         th = (th % 24);
1373                                                 }
1374
1375                                                 subst = (td > 0)
1376                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1377                                                         : String.format('%dh %dm %ds', th, tm, ts);
1378
1379                                                 break;
1380
1381                                         case 'm':
1382                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1383                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1384
1385                                                 var i = 0;
1386                                                 var val = parseFloat(param || 0);
1387                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1388
1389                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1390                                                         val /= mf;
1391
1392                                                 subst = val.toFixed(pr) + ' ' + units[i];
1393                                                 break;
1394                                 }
1395                         }
1396                 }
1397
1398                 out += leftpart + subst;
1399                 str = str.substr(m.length);
1400         }
1401
1402         return out + str;
1403 }
1404
1405 String.prototype.nobr = function()
1406 {
1407         return this.replace(/[\s\n]+/g, '&#160;');
1408 }
1409
1410 String.serialize = function()
1411 {
1412         var a = [ ];
1413         for (var i = 1; i < arguments.length; i++)
1414                 a.push(arguments[i]);
1415         return ''.serialize.apply(arguments[0], a);
1416 }
1417
1418 String.format = function()
1419 {
1420         var a = [ ];
1421         for (var i = 1; i < arguments.length; i++)
1422                 a.push(arguments[i]);
1423         return ''.format.apply(arguments[0], a);
1424 }
1425
1426 String.nobr = function()
1427 {
1428         var a = [ ];
1429         for (var i = 1; i < arguments.length; i++)
1430                 a.push(arguments[i]);
1431         return ''.nobr.apply(arguments[0], a);
1432 }