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