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