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