655ddbf53a9dede39e3c591cbd03e52a3a09cda7
[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         '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 = '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
509 function cbi_combobox_init(id, values, def, man) {
510         var obj = document.getElementById(id);
511         cbi_bind(obj, "blur", function() {
512                 cbi_combobox(id, values, def, man)
513         });
514         cbi_combobox(id, values, def, man);
515 }
516
517 function cbi_filebrowser(id, url, defpath) {
518         var field   = document.getElementById(id);
519         var browser = window.open(
520                 url + ( field.value || defpath || '' ) + '?field=' + id,
521                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
522         );
523
524         browser.focus();
525 }
526
527 function cbi_browser_init(id, respath, url, defpath)
528 {
529         function cbi_browser_btnclick(e) {
530                 cbi_filebrowser(id, url, defpath);
531                 return false;
532         }
533
534         var field = document.getElementById(id);
535
536         var btn = document.createElement('img');
537         btn.className = 'cbi-image-button';
538         btn.src = respath + '/cbi/folder.gif';
539         field.parentNode.insertBefore(btn, field.nextSibling);
540
541         cbi_bind(btn, 'click', cbi_browser_btnclick);
542 }
543
544 function cbi_dynlist_init(name, respath, datatype, optional, choices)
545 {
546         var input0 = document.getElementsByName(name)[0];
547         var prefix = input0.name;
548         var parent = input0.parentNode;
549         var holder = input0.placeholder;
550
551         var values;
552
553         function cbi_dynlist_redraw(focus, add, del)
554         {
555                 values = [ ];
556
557                 while (parent.firstChild)
558                 {
559                         var n = parent.firstChild;
560                         var i = parseInt(n.index);
561
562                         if (i != del)
563                         {
564                                 if (n.nodeName.toLowerCase() == 'input')
565                                         values.push(n.value || '');
566                                 else if (n.nodeName.toLowerCase() == 'select')
567                                         values[values.length-1] = n.options[n.selectedIndex].value;
568                         }
569
570                         parent.removeChild(n);
571                 }
572
573                 if (add >= 0)
574                 {
575                         focus = add+1;
576                         values.splice(focus, 0, '');
577                 }
578                 else if (values.length == 0)
579                 {
580                         focus = 0;
581                         values.push('');
582                 }
583
584                 for (var i = 0; i < values.length; i++)
585                 {
586                         var t = document.createElement('input');
587                                 t.id = prefix + '.' + (i+1);
588                                 t.name = prefix;
589                                 t.value = values[i];
590                                 t.type = 'text';
591                                 t.index = i;
592                                 t.className = 'cbi-input-text';
593
594                         if (i == 0 && holder)
595                         {
596                                 t.placeholder = holder;
597                         }
598
599                         var b = document.createElement('img');
600                                 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
601                                 b.className = 'cbi-image-button';
602
603                         parent.appendChild(t);
604                         parent.appendChild(b);
605                         parent.appendChild(document.createElement('br'));
606
607                         if (datatype)
608                         {
609                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
610                         }
611
612                         if (choices)
613                         {
614                                 cbi_combobox_init(t.id, choices[0], '', choices[1]);
615                                 t.nextSibling.index = i;
616
617                                 cbi_bind(t.nextSibling, 'keydown',  cbi_dynlist_keydown);
618                                 cbi_bind(t.nextSibling, 'keypress', cbi_dynlist_keypress);
619
620                                 if (i == focus || -i == focus)
621                                         t.nextSibling.focus();
622                         }
623                         else
624                         {
625                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
626                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
627
628                                 if (i == focus)
629                                 {
630                                         t.focus();
631                                 }
632                                 else if (-i == focus)
633                                 {
634                                         t.focus();
635
636                                         /* force cursor to end */
637                                         var v = t.value;
638                                         t.value = ' '
639                                         t.value = v;
640                                 }
641                         }
642
643                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
644                 }
645         }
646
647         function cbi_dynlist_keypress(ev)
648         {
649                 ev = ev ? ev : window.event;
650
651                 var se = ev.target ? ev.target : ev.srcElement;
652
653                 if (se.nodeType == 3)
654                         se = se.parentNode;
655
656                 switch (ev.keyCode)
657                 {
658                         /* backspace, delete */
659                         case 8:
660                         case 46:
661                                 if (se.value.length == 0)
662                                 {
663                                         if (ev.preventDefault)
664                                                 ev.preventDefault();
665
666                                         return false;
667                                 }
668
669                                 return true;
670
671                         /* enter, arrow up, arrow down */
672                         case 13:
673                         case 38:
674                         case 40:
675                                 if (ev.preventDefault)
676                                         ev.preventDefault();
677
678                                 return false;
679                 }
680
681                 return true;
682         }
683
684         function cbi_dynlist_keydown(ev)
685         {
686                 ev = ev ? ev : window.event;
687
688                 var se = ev.target ? ev.target : ev.srcElement;
689
690                 if (se.nodeType == 3)
691                         se = se.parentNode;
692
693                 var prev = se.previousSibling;
694                 while (prev && prev.name != name)
695                         prev = prev.previousSibling;
696
697                 var next = se.nextSibling;
698                 while (next && next.name != name)
699                         next = next.nextSibling;
700
701                 /* advance one further in combobox case */
702                 if (next && next.nextSibling.name == name)
703                         next = next.nextSibling;
704
705                 switch (ev.keyCode)
706                 {
707                         /* backspace, delete */
708                         case 8:
709                         case 46:
710                                 var del = (se.nodeName.toLowerCase() == 'select')
711                                         ? true : (se.value.length == 0);
712
713                                 if (del)
714                                 {
715                                         if (ev.preventDefault)
716                                                 ev.preventDefault();
717
718                                         var focus = se.index;
719                                         if (ev.keyCode == 8)
720                                                 focus = -focus+1;
721
722                                         cbi_dynlist_redraw(focus, -1, se.index);
723
724                                         return false;
725                                 }
726
727                                 break;
728
729                         /* enter */
730                         case 13:
731                                 cbi_dynlist_redraw(-1, se.index, -1);
732                                 break;
733
734                         /* arrow up */
735                         case 38:
736                                 if (prev)
737                                         prev.focus();
738
739                                 break;
740
741                         /* arrow down */
742                         case 40:
743                                 if (next)
744                                         next.focus();
745
746                                 break;
747                 }
748
749                 return true;
750         }
751
752         function cbi_dynlist_btnclick(ev)
753         {
754                 ev = ev ? ev : window.event;
755
756                 var se = ev.target ? ev.target : ev.srcElement;
757
758                 if (se.src.indexOf('remove') > -1)
759                 {
760                         se.previousSibling.value = '';
761
762                         cbi_dynlist_keydown({
763                                 target:  se.previousSibling,
764                                 keyCode: 8
765                         });
766                 }
767                 else
768                 {
769                         cbi_dynlist_keydown({
770                                 target:  se.previousSibling,
771                                 keyCode: 13
772                         });
773                 }
774
775                 return false;
776         }
777
778         cbi_dynlist_redraw(NaN, -1, -1);
779 }
780
781 //Hijacks the CBI form to send via XHR (requires Prototype)
782 function cbi_hijack_forms(layer, win, fail, load) {
783         var forms = layer.getElementsByTagName('form');
784         for (var i=0; i<forms.length; i++) {
785                 $(forms[i]).observe('submit', function(event) {
786                         // Prevent the form from also submitting the regular way
787                         event.stop();
788
789                         // Submit via XHR
790                         event.element().request({
791                                 onSuccess: win,
792                                 onFailure: fail
793                         });
794
795                         if (load) {
796                                 load();
797                         }
798                 });
799         }
800 }
801
802
803 function cbi_t_add(section, tab) {
804         var t = document.getElementById('tab.' + section + '.' + tab);
805         var c = document.getElementById('container.' + section + '.' + tab);
806
807         if( t && c ) {
808                 cbi_t[section] = (cbi_t[section] || [ ]);
809                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
810         }
811 }
812
813 function cbi_t_switch(section, tab) {
814         if( cbi_t[section] && cbi_t[section][tab] ) {
815                 var o = cbi_t[section][tab];
816                 var h = document.getElementById('tab.' + section);
817                 for( var tid in cbi_t[section] ) {
818                         var o2 = cbi_t[section][tid];
819                         if( o.tab.id != o2.tab.id ) {
820                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
821                                 o2.container.style.display = 'none';
822                         }
823                         else {
824                                 if(h) h.value = tab;
825                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
826                                 o2.container.style.display = 'block';
827                         }
828                 }
829         }
830         return false
831 }
832
833 function cbi_t_update() {
834         var hl_tabs = [ ];
835         var updated = false;
836
837         for( var sid in cbi_t )
838                 for( var tid in cbi_t[sid] )
839                 {
840                         if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
841                                 cbi_t[sid][tid].tab.style.display = 'none';
842                         }
843                         else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
844                                 cbi_t[sid][tid].tab.style.display = '';
845
846                                 var t = cbi_t[sid][tid].tab;
847                                 t.className += ' cbi-tab-highlighted';
848                                 hl_tabs.push(t);
849                         }
850
851                         cbi_tag_last(cbi_t[sid][tid].container);
852                         updated = true;
853                 }
854
855         if( hl_tabs.length > 0 )
856                 window.setTimeout(function() {
857                         for( var i = 0; i < hl_tabs.length; i++ )
858                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
859                 }, 750);
860
861         return updated;
862 }
863
864
865 function cbi_validate_form(form, errmsg)
866 {
867         /* if triggered by a section removal or addition, don't validate */
868         if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
869                 return true;
870
871         if( form.cbi_validators )
872         {
873                 for( var i = 0; i < form.cbi_validators.length; i++ )
874                 {
875                         var validator = form.cbi_validators[i];
876                         if( !validator() && errmsg )
877                         {
878                                 alert(errmsg);
879                                 return false;
880                         }
881                 }
882         }
883
884         return true;
885 }
886
887 function cbi_validate_reset(form)
888 {
889         window.setTimeout(
890                 function() { cbi_validate_form(form, null) }, 100
891         );
892
893         return true;
894 }
895
896 function cbi_validate_compile(code)
897 {
898         var pos = 0;
899         var esc = false;
900         var depth = 0;
901         var stack = [ ];
902
903         code += ',';
904
905         for (var i = 0; i < code.length; i++)
906         {
907                 if (esc)
908                 {
909                         esc = false;
910                         continue;
911                 }
912
913                 switch (code.charCodeAt(i))
914                 {
915                 case 92:
916                         esc = true;
917                         break;
918
919                 case 40:
920                 case 44:
921                         if (depth <= 0)
922                         {
923                                 if (pos < i)
924                                 {
925                                         var label = code.substring(pos, i);
926                                                 label = label.replace(/\\(.)/g, '$1');
927                                                 label = label.replace(/^[ \t]+/g, '');
928                                                 label = label.replace(/[ \t]+$/g, '');
929
930                                         if (label && !isNaN(label))
931                                         {
932                                                 stack.push(parseFloat(label));
933                                         }
934                                         else if (label.match(/^(['"]).*\1$/))
935                                         {
936                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
937                                         }
938                                         else if (typeof cbi_validators[label] == 'function')
939                                         {
940                                                 stack.push(cbi_validators[label]);
941                                                 stack.push(null);
942                                         }
943                                         else
944                                         {
945                                                 throw "Syntax error, unhandled token '"+label+"'";
946                                         }
947                                 }
948                                 pos = i+1;
949                         }
950                         depth += (code.charCodeAt(i) == 40);
951                         break;
952
953                 case 41:
954                         if (--depth <= 0)
955                         {
956                                 if (typeof stack[stack.length-2] != 'function')
957                                         throw "Syntax error, argument list follows non-function";
958
959                                 stack[stack.length-1] =
960                                         arguments.callee(code.substring(pos, i));
961
962                                 pos = i+1;
963                         }
964                         break;
965                 }
966         }
967
968         return stack;
969 }
970
971 function cbi_validate_field(cbid, optional, type)
972 {
973         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
974         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
975
976         if (field && vstack && typeof vstack[0] == "function")
977         {
978                 var validator = function()
979                 {
980                         // is not detached
981                         if( field.form )
982                         {
983                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
984
985                                 // validate value
986                                 var value = (field.options && field.options.selectedIndex > -1)
987                                         ? field.options[field.options.selectedIndex].value : field.value;
988
989                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
990                                 {
991                                         // invalid
992                                         field.className += ' cbi-input-invalid';
993                                         return false;
994                                 }
995                         }
996
997                         return true;
998                 };
999
1000                 if( ! field.form.cbi_validators )
1001                         field.form.cbi_validators = [ ];
1002
1003                 field.form.cbi_validators.push(validator);
1004
1005                 cbi_bind(field, "blur",  validator);
1006                 cbi_bind(field, "keyup", validator);
1007
1008                 if (field.nodeName == 'SELECT')
1009                 {
1010                         cbi_bind(field, "change", validator);
1011                         cbi_bind(field, "click",  validator);
1012                 }
1013
1014                 field.setAttribute("cbi_validate", validator);
1015                 field.setAttribute("cbi_datatype", type);
1016                 field.setAttribute("cbi_optional", (!!optional).toString());
1017
1018                 validator();
1019
1020                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1021                 if (fcbox)
1022                         cbi_validate_field(fcbox, optional, type);
1023         }
1024 }
1025
1026 function cbi_row_swap(elem, up, store)
1027 {
1028         var tr = elem.parentNode;
1029         while (tr && tr.nodeName.toLowerCase() != 'tr')
1030                 tr = tr.parentNode;
1031
1032         if (!tr)
1033                 return false;
1034
1035         var table = tr.parentNode;
1036         while (table && table.nodeName.toLowerCase() != 'table')
1037                 table = table.parentNode;
1038
1039         if (!table)
1040                 return false;
1041
1042         var s = up ? 3 : 2;
1043         var e = up ? table.rows.length : table.rows.length - 1;
1044
1045         for (var idx = s; idx < e; idx++)
1046         {
1047                 if (table.rows[idx] == tr)
1048                 {
1049                         if (up)
1050                                 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1051                         else
1052                                 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1053
1054                         break;
1055                 }
1056         }
1057
1058         var ids = [ ];
1059         for (idx = 2; idx < table.rows.length; idx++)
1060         {
1061                 table.rows[idx].className = table.rows[idx].className.replace(
1062                         /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1063                 );
1064
1065                 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1066                         ids.push(RegExp.$1);
1067         }
1068
1069         var input = document.getElementById(store);
1070         if (input)
1071                 input.value = ids.join(' ');
1072
1073         return false;
1074 }
1075
1076 function cbi_tag_last(container)
1077 {
1078         var last;
1079
1080         for (var i = 0; i < container.childNodes.length; i++)
1081         {
1082                 var c = container.childNodes[i];
1083                 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1084                 {
1085                         c.className = c.className.replace(/ cbi-value-last$/, '');
1086                         last = c;
1087                 }
1088         }
1089
1090         if (last)
1091         {
1092                 last.className += ' cbi-value-last';
1093         }
1094 }
1095
1096 if( ! String.serialize )
1097         String.serialize = function(o)
1098         {
1099                 switch(typeof(o))
1100                 {
1101                         case 'object':
1102                                 // null
1103                                 if( o == null )
1104                                 {
1105                                         return 'null';
1106                                 }
1107
1108                                 // array
1109                                 else if( o.length )
1110                                 {
1111                                         var i, s = '';
1112
1113                                         for( var i = 0; i < o.length; i++ )
1114                                                 s += (s ? ', ' : '') + String.serialize(o[i]);
1115
1116                                         return '[ ' + s + ' ]';
1117                                 }
1118
1119                                 // object
1120                                 else
1121                                 {
1122                                         var k, s = '';
1123
1124                                         for( k in o )
1125                                                 s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1126
1127                                         return '{ ' + s + ' }';
1128                                 }
1129
1130                                 break;
1131
1132                         case 'string':
1133                                 // complex string
1134                                 if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1135                                         return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1136
1137                                 // simple string
1138                                 else
1139                                         return '"' + o + '"';
1140
1141                                 break;
1142
1143                         default:
1144                                 return o.toString();
1145                 }
1146         }
1147
1148
1149 if( ! String.format )
1150         String.format = function()
1151         {
1152                 if (!arguments || arguments.length < 1 || !RegExp)
1153                         return;
1154
1155                 var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1156                 var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1157
1158                 function esc(s, r) {
1159                         for( var i = 0; i < r.length; i += 2 )
1160                                 s = s.replace(r[i], r[i+1]);
1161                         return s;
1162                 }
1163
1164                 var str = arguments[0];
1165                 var out = '';
1166                 var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1167                 var a = b = [], numSubstitutions = 0, numMatches = 0;
1168
1169                 while( a = re.exec(str) )
1170                 {
1171                         var m = a[1];
1172                         var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1173                         var pPrecision = a[6], pType = a[7];
1174
1175                         numMatches++;
1176
1177                         if (pType == '%')
1178                         {
1179                                 subst = '%';
1180                         }
1181                         else
1182                         {
1183                                 if (numSubstitutions++ < arguments.length)
1184                                 {
1185                                         var param = arguments[numSubstitutions];
1186
1187                                         var pad = '';
1188                                         if (pPad && pPad.substr(0,1) == "'")
1189                                                 pad = leftpart.substr(1,1);
1190                                         else if (pPad)
1191                                                 pad = pPad;
1192
1193                                         var justifyRight = true;
1194                                         if (pJustify && pJustify === "-")
1195                                                 justifyRight = false;
1196
1197                                         var minLength = -1;
1198                                         if (pMinLength)
1199                                                 minLength = parseInt(pMinLength);
1200
1201                                         var precision = -1;
1202                                         if (pPrecision && pType == 'f')
1203                                                 precision = parseInt(pPrecision.substring(1));
1204
1205                                         var subst = param;
1206
1207                                         switch(pType)
1208                                         {
1209                                                 case 'b':
1210                                                         subst = (parseInt(param) || 0).toString(2);
1211                                                         break;
1212
1213                                                 case 'c':
1214                                                         subst = String.fromCharCode(parseInt(param) || 0);
1215                                                         break;
1216
1217                                                 case 'd':
1218                                                         subst = (parseInt(param) || 0);
1219                                                         break;
1220
1221                                                 case 'u':
1222                                                         subst = Math.abs(parseInt(param) || 0);
1223                                                         break;
1224
1225                                                 case 'f':
1226                                                         subst = (precision > -1)
1227                                                                 ? ((parseFloat(param) || 0.0)).toFixed(precision)
1228                                                                 : (parseFloat(param) || 0.0);
1229                                                         break;
1230
1231                                                 case 'o':
1232                                                         subst = (parseInt(param) || 0).toString(8);
1233                                                         break;
1234
1235                                                 case 's':
1236                                                         subst = param;
1237                                                         break;
1238
1239                                                 case 'x':
1240                                                         subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1241                                                         break;
1242
1243                                                 case 'X':
1244                                                         subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1245                                                         break;
1246
1247                                                 case 'h':
1248                                                         subst = esc(param, html_esc);
1249                                                         break;
1250
1251                                                 case 'q':
1252                                                         subst = esc(param, quot_esc);
1253                                                         break;
1254
1255                                                 case 'j':
1256                                                         subst = String.serialize(param);
1257                                                         break;
1258
1259                                                 case 't':
1260                                                         var td = 0;
1261                                                         var th = 0;
1262                                                         var tm = 0;
1263                                                         var ts = (param || 0);
1264
1265                                                         if (ts > 60) {
1266                                                                 tm = Math.floor(ts / 60);
1267                                                                 ts = (ts % 60);
1268                                                         }
1269
1270                                                         if (tm > 60) {
1271                                                                 th = Math.floor(tm / 60);
1272                                                                 tm = (tm % 60);
1273                                                         }
1274
1275                                                         if (th > 24) {
1276                                                                 td = Math.floor(th / 24);
1277                                                                 th = (th % 24);
1278                                                         }
1279
1280                                                         subst = (td > 0)
1281                                                                 ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1282                                                                 : String.format('%dh %dm %ds', th, tm, ts);
1283
1284                                                         break;
1285
1286                                                 case 'm':
1287                                                         var mf = pMinLength ? parseInt(pMinLength) : 1000;
1288                                                         var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1289
1290                                                         var i = 0;
1291                                                         var val = parseFloat(param || 0);
1292                                                         var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1293
1294                                                         for (i = 0; (i < units.length) && (val > mf); i++)
1295                                                                 val /= mf;
1296
1297                                                         subst = val.toFixed(pr) + ' ' + units[i];
1298                                                         break;
1299                                         }
1300                                 }
1301                         }
1302
1303                         out += leftpart + subst;
1304                         str = str.substr(m.length);
1305                 }
1306
1307                 return out + str;
1308         }