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