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