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