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