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