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