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