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