Javascript now works with multiple classes on elements.
[fa-stable.git] / js / inserts.js
1 /**********************************************************************
2     Copyright (C) FrontAccounting, LLC.
3         Released under the terms of the GNU General Public License, GPL,
4         as published by the Free Software Foundation, either version 3
5         of the License, or (at your option) any later version.
6     This program is distributed in the hope that it will be useful,
7     but WITHOUT ANY WARRANTY; without even the implied warranty of
8     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
9     See the License here <http://www.gnu.org/licenses/gpl-3.0.html>.
10 ***********************************************************************/
11 var _focus;
12 var _hotkeys = {
13         'alt': false,   // whether is the Alt key pressed
14         'list': false, // list of all elements with hotkey used recently
15         'focus': -1             // currently selected list element
16 };
17
18 function validate(e) {
19         if (e.name && (typeof _validate[e.name] == 'function'))
20                 return _validate[e.name](e);
21         else {
22                 var n = e.name.indexOf('[');
23                 if(n!=-1) {
24                         var key = e.name.substring(n+1, e.name.length-1);
25                         if (key.length>1 && _validate[e.name.substring(0,n)])
26                                 return _validate[e.name.substring(0,n)][key](e);
27                 }
28         }
29         return true;
30 }
31
32 function save_focus(e) {
33   _focus = e.name||e.id;
34   var h = document.getElementById('hints');
35   if (h) {
36         h.style.display = e.title && e.title.length ? 'inline' : 'none';
37         h.innerHTML = e.title ? e.title : '';
38   }
39 }
40
41 function _expand(tabobj) {
42
43   var ul = tabobj.parentNode.parentNode;
44   var alltabs=ul.getElementsByTagName("button");
45   var frm = tabobj.form;
46
47   if (ul.getAttribute("rel")){
48         for (var i=0; i<alltabs.length; i++){
49           alltabs[i].className = "ajaxbutton"  //deselect all tabs // Review CP 2014-11 This will remove all other classes from the element.
50         }
51         tabobj.className = "current";
52         JsHttpRequest.request(tabobj)
53   }
54 }
55
56 //interface for selecting a tab (plus expand corresponding content)
57 function expandtab(tabcontentid, tabnumber) {
58   var tabs = document.getElementById(tabcontentid);
59  _expand(tabs.getElementsByTagName("input")[tabnumber]);
60 }
61
62 function _set_combo_input(e) {
63                 e.setAttribute('_last', e.value);
64                 e.onblur=function() {
65                   var but_name = this.name.substring(0, this.name.length-4)+'button';
66                   var button = document.getElementsByName(but_name)[0];
67                   var select = document.getElementsByName(this.getAttribute('rel'))[0];
68                   save_focus(select);
69 // submit request if there is submit_on_change option set and
70 // search field has changed.
71
72                   if (button && (this.value != this.getAttribute('_last'))) {
73                         JsHttpRequest.request(button);
74                   } else if(string_contains(this.className, 'combo2')) {
75                                 this.style.display = 'none';
76                                 select.style.display = 'inline';
77                                 setFocus(select);
78                   }
79                   return false;
80                 };
81                 e.onkeyup = function(ev) {
82                         var select = document.getElementsByName(this.getAttribute('rel'))[0];
83                         if(select && select.selectedIndex>=0) {
84                           var len = select.length;
85                           var byid = string_contains(this.className, 'combo') || string_contains(this.className, 'combo3');
86                           var ac = this.value.toUpperCase();
87                           select.options[select.selectedIndex].selected = false;
88                           for (i = 0; i < len; i++) {
89                                 var txt = byid ? select.options[i].value : select.options[i].text;
90                                 if (string_contains(this.className, 'combo3')) {
91                                   if(txt.toUpperCase().indexOf(ac) == 0) {
92                                         select.options[i].selected = true;
93                                         break;
94                                   }
95                                 } else {
96                                   if(txt.toUpperCase().indexOf(ac) >= 0) {
97                                         select.options[i].selected = true;
98                                         break;
99                                   }
100                                 }
101                           }
102                         }
103                 };
104         e.onkeydown = function(ev) {
105                         ev = ev||window.event;
106                         key = ev.keyCode||ev.which;
107                         if(key == 13) {
108                           this.blur();
109                           return false;
110                         }
111                 }
112 }
113
114 function _update_box(s) {
115         var byid = string_contains(s.className, 'combo') || string_contains(s.className, 'combo3');
116         var rel = s.getAttribute('rel');
117         var box = document.getElementsByName(rel)[0];
118                 if(box && s.selectedIndex>=0) {
119                           var opt = s.options[s.selectedIndex];
120                                 if(box) {
121                                   var old = box.value;
122                                   box.value = byid ? opt.value : opt.text;
123                                   box.setAttribute('_last', box.value);
124                                   return old != box.value
125                                 }
126                 }
127 }
128
129 function _set_combo_select(e) {
130                 // When combo position is changed via js (eg from searchbox)
131                 // no onchange event is generated. To ensure proper change
132                 // signaling we must track selectedIndex in onblur handler.
133                 e.setAttribute('_last', e.selectedIndex);
134                 e.onblur = function() {
135                     var box = document.getElementsByName(this.getAttribute('rel'))[0];
136 //                      if(string_contains(this.className, 'combo'))
137 //                          _update_box(this);
138                         if ((this.selectedIndex != this.getAttribute('_last'))
139                                 ||((string_contains(this.className, 'combo') || string_contains(this.className, 'combo3')) && _update_box(this))
140                                 )
141                                         this.onchange();
142                 }
143                 e.onchange = function() {
144                         var s = this;
145                         this.setAttribute('_last', this.selectedIndex);
146                         if(string_contains(s.className, 'combo') || string_contains(this.className, 'combo3'))
147                             _update_box(s);
148                         if(s.selectedIndex>=0) {
149                                  var sname = '_'+s.name+'_update';
150                                  var update = document.getElementsByName(sname)[0];
151                                  if(update) {
152                                             JsHttpRequest.request(update);
153                                 }
154                         }
155                         return true;
156                 }
157                 e.onkeydown = function(event) {
158                     event = event||window.event;
159                     key = event.keyCode||event.which;
160                     var box = document.getElementsByName(this.getAttribute('rel'))[0];
161                         if(key == 8 || (key==37 && event.altKey)) {
162                                 event.returnValue = false;
163                                 return false;
164                         }
165                     if (box && (key == 32) && (this.className == 'combo2')) {
166                             this.style.display = 'none';
167                             box.style.display = 'inline';
168                                 box.value='';
169                                 setFocus(box);
170                             return false;
171                          } else {
172                                 if (key == 13 && !e.length) // prevent chrome issue (blocked cursor after CR on empty selector)
173                                         return false;
174                          }
175                 }
176 }
177
178 var _w;
179
180 function callEditor(key) {
181   var el = document.getElementsByName(editors[key][1])[0];
182   if(_w) _w.close(); // this is really necessary to have window on top in FF2 :/
183   var left = (screen.width - editors[key][2]) / 2;
184   var top = (screen.height - editors[key][3]) / 2;
185   _w = open(editors[key][0]+el.value+'&popup=1',
186           "edit","scrollbars=yes,resizable=0,width="+editors[key][2]+",height="+editors[key][3]+",left="+left+",top="+top+",screenX="+left+",screenY="+top);
187   if (_w.opener == null)
188           _w.opener = self;
189   editors._call = key; // store call point for passBack
190   _w.focus();
191 }
192
193 function passBack(value) {
194         var o = opener;
195         if(value != false) {
196                 var back = o.editors[o.editors._call]; // form input bindings
197                 var to = o.document.getElementsByName(back[1])[0];
198                 if (to) {
199                         if (to[0] != undefined)
200                                 to[0].value = value; // ugly hack to set selector to any value
201                         to.value = value;
202                         // update page after item selection
203                         o.JsHttpRequest.request('_'+to.name+'_update', to.form);
204                         o.setFocus(to.name);
205                 }
206         }
207         close();
208 }
209
210 /*
211         Normalize date format using previous input value to guess missing date elements.
212         Helps fast date input field change with only single or double numbers (for day or day-and-month fragments)
213 */
214 function fix_date(date, last)
215 {
216         var dat = last.split(user.datesep);
217         var cur = date.split(user.datesep);
218         var day, month, year;
219
220 // TODO: user.date as default?
221 // TODO: user.datesys
222         if (date == "" || date == last) // should we return an empty date or should we return last?
223                 return date;
224         if (user.datefmt == 0 || user.datefmt == 3) // set defaults
225         {
226                 day = dat[1]; month = dat[0]; year = dat[2];
227         } else if (user.datefmt == 1 || user.datefmt == 4){
228                 day = dat[0]; month = dat[1]; year = dat[2];
229         } else {
230                 day = dat[2]; month = dat[1]; year = dat[0];
231         }
232         if (cur[1] != undefined && cur[1] != "") // day or month entered, could be string 3
233         {
234                 if (user.datefmt == 0 || user.datefmt == 3 || ((user.datefmt == 2 || user.datefmt == 5) && (cur[2] == undefined || cur[2] == "")))
235                         day = cur[1];
236                 else
237                         month = cur[1];
238         }
239         if (cur[0] != undefined && cur[0] != "") // day or month entered. could be string 3
240         {
241                 if (cur[1] == undefined || cur[1] == "")
242                         day = cur[0];
243                 else if (user.datefmt == 0 || user.datefmt == 3 || ((user.datefmt == 2 || user.datefmt == 5) && (cur[2] == undefined || cur[2] == "")))
244                         month = cur[0];
245                 else if (user.datefmt == 2 || user.datefmt == 5)
246                         year = cur[0];
247                 else
248                         day = cur[0];
249         }
250         if (cur[2] != undefined && cur[2] != "") // year,
251         {
252                 if (user.datefmt == 2 || user.datefmt == 5)
253                         day = cur[2];
254                 else
255                         year = cur[2];
256         }
257         if (user.datefmt<3) {
258                 if (day<10) day = '0'+parseInt(day, 10);
259                 if (month<10) month = '0'+parseInt(month, 10);
260         }
261         if (year<100) year = year<60 ? (2000+parseInt(year,10)) : (1900+parseInt(year,10));
262
263 //      console.info(day,month,year)
264         if (user.datefmt == 0 || user.datefmt==3)
265                 return month+user.datesep+day+user.datesep+year;
266         if (user.datefmt == 1 || user.datefmt==4)
267                 return day+user.datesep+month+user.datesep+year;
268         return year+user.datesep+month+user.datesep+day;
269 }
270
271 /*
272  Behaviour definitions
273 */
274 var inserts = {
275         'input': function(e) {
276                 if(e.onfocus==undefined) {
277                         e.onfocus = function() {
278                             save_focus(this);
279                                 if (this.className == 'combo' || this.className == 'combo3')
280                                         this.select();
281                         };
282                 }
283                 if (e.className == 'combo' || e.className == 'combo2' || e.className == 'combo3') {
284                                 _set_combo_input(e);
285                 }
286                 else
287                 if(e.type == 'text' ) {
288                                 e.onkeydown = function(ev) {
289                                         ev = ev||window.event;
290                                         key = ev.keyCode||ev.which;
291                                         if(key == 13) {
292                                                 if(e.className == 'searchbox') e.onblur();
293                                                 return false;
294                                         }
295                                         return true;
296                                 }
297                         }
298         },
299         'input.combo2,input[aspect="fallback"]':
300         function(e) {
301             // this hides search button for js enabled browsers
302             e.style.display = 'none';
303         },
304         'div.js_only':
305         function(e) {
306             // this shows divs for js enabled browsers only
307             e.style.display = 'block';
308         },
309         'button': function(e) {
310                 e.onclick = function(){
311                         if (validate(e)) {
312                                 setTimeout(function() { var asp = e.getAttribute('aspect');
313                                         set_mark((asp && (asp.indexOf('process') !== -1)) ? 'progressbar.gif' : 'ajax-loader.gif');
314                                 }, 100);
315                                 return true;
316                         }
317                 },
318                 e.onkeydown = function(ev) {    // block unintentional page escape with 'history back' key pressed on buttons
319                         ev = ev||window.event;
320                         key = ev.keyCode||ev.which;
321                         if(key == 8 || (key==37 && ev.altKey)) {
322                                 ev.returnValue = false;
323                                 return false;
324                         }
325                 }
326
327         },
328 //      '.ajaxsubmit,.editbutton,.navibutton': // much slower on IE7
329         'button.ajaxsubmit,input.ajaxsubmit,input.editbutton,button.editbutton,button.navibutton':
330         function(e) {
331                         e.onclick = function() {
332                                 if (validate(e)) {
333                                         save_focus(e);
334                                         var asp = e.getAttribute('aspect')
335                                         if (asp && (asp.indexOf('process') !== -1))
336                                                 JsHttpRequest.request(this, null, 600000); // ten minutes for backup
337                                         else
338                                                 JsHttpRequest.request(this);
339                                 }
340                                 return false;
341                         }
342         },
343     '.amount': function(e) {
344                 if(e.onblur==undefined) {
345                   e.onblur = function() {
346                         var dec = this.getAttribute("dec");
347                         price_format(this.name, get_amount(this.name), dec);
348                   };
349                 }
350         },
351         '.searchbox': // emulated onchange event handling for text inputs
352                 function(e) {
353                         e.setAttribute('_last_val', e.value);
354                         e.setAttribute('autocomplete', 'off'); //must be off when calling onblur
355                         e.onblur = function() {
356                                 var val = this.getAttribute('_last_val');
357                                 if (val != this.value) {
358                                         this.setAttribute('_last_val', this.value);
359                                         JsHttpRequest.request('_'+this.name+'_changed', this.form);
360                                 }
361                         }
362         },
363         '.date':
364                 function(e) {
365                         e.setAttribute('_last_val', e.value);
366                         e.setAttribute('autocomplete', 'off');
367                         e.onblur = function() {
368                                 var val = this.getAttribute('_last_val');
369                                 if (val != this.value) {
370                                         this.value = fix_date(this.value, val);
371                                         this.setAttribute('_last_val', this.value);
372                                         if (e.className.match(/\bactive\b/))
373                                                 JsHttpRequest.request('_'+this.name+'_changed', this.form);
374                                 }
375                         }
376         },
377         'button[aspect*selector], button[aspect*abort], input[aspect*selector]': function(e) {
378                 e.onclick = function() {
379                         passBack(this.getAttribute('rel'));
380                         return false;
381                 }
382         },
383         'button[aspect=popup]': function(e) {
384                 e.onclick = function() {
385                         if(_w) _w.close(); // this is really necessary to have window on top in FF2 :/
386                          var left = (screen.width - 800)/2;
387                          var top = (screen.height - 600)/2;
388                           _w = open(document.location+'popup=1',
389                                   "edit","Scrollbars=0,resizable=0,width=800,height=600, top="+top+",left="+left+",screenX="+left+",screenY="+top);
390                           if (_w.opener == null)
391                                   _w.opener = self;
392                         //  editors._call = key; // store call point for passBack
393 //                        _w.moveTo(50, 50);
394                           _w.focus();
395                         return false;
396                 }
397         },
398         'select': function(e) {
399                 if(e.onfocus==undefined) {
400                         e.onfocus = function() {
401                             save_focus(this);
402                         };
403                 }
404                 var c = e.className;
405                 if (string_contains(c, 'combo') || string_contains(c, 'combo2') || string_contains(c, 'combo3'))
406                         _set_combo_select(e);
407                 else {
408                         e.onkeydown = function(ev) {    // block unintentional page escape with 'history back' key pressed on buttons
409                                 ev = ev||window.event;
410                                 key = ev.keyCode||ev.which;
411                                 if(key == 8 || (key=37 && ev.altKey)) {
412                                         ev.returnValue = false;
413                                         return false;
414                                 }
415                         }
416                 }
417         },
418         'a.printlink':  function(l) {
419                 l.onclick = function() {
420                     save_focus(this);
421                         JsHttpRequest.request(this, null, 60000);
422                         return false;
423                 }
424         },
425         'a.repopts_link':       function(l) {
426                 l.onclick = function() {
427                     save_focus(this);
428                     var replinks = document.getElementsBySelector('a.repopts_link');
429                                 for(var i in replinks)
430                                         replinks[i].style.fontWeight = replinks[i]==this ? 'bold' : 'normal';
431                         JsHttpRequest.request(this, null);
432                         return false;
433                 }
434         },
435         'a': function(e) { // traverse menu
436                 e.onkeydown = function(ev) {
437                         ev = ev||window.event;
438                         key = ev.keyCode||ev.which;
439                         if(key==37 || key==38 || key==39 || key==40) {
440                                         move_focus(key, e, document.links);
441                                         ev.returnValue = false;
442                                         return false;
443                         }
444                 }
445                 // prevent unneeded transaction entry abortion
446                 if (e.className == 'shortcut'
447                  || e.className == 'menu_option'
448                  || e.className == 'menu_tab'
449                  || e.className == 'selected')
450                         e.onclick = function(ev) {
451                                 if (_validate._processing
452                                  && _validate._modified
453                                  && !confirm(_validate._processing)) {
454                                         ev.returnValue = false;
455                                         return false;
456                                 }
457                                 if (_hotkeys.alt)       // ommit Chrome accesskeys
458                                         return false;
459                                 window.location = e.href;
460                         }
461         },
462         'ul.ajaxtabs':  function(ul) {
463             var ulist=ul.getElementsByTagName("li");
464             for (var x=0; x<ulist.length; x++){ //loop through each LI e
465                 var tab=ulist[x].getElementsByTagName("button")[0];
466 //              if(tab.onclick==undefined) {
467 // ?  var modifiedurl=ulistlink.getAttribute("href").replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/")
468                     var url = tab.form.action
469                     tab.onclick=function(){
470                     if (!_hotkeys.alt && !tab.disabled)
471                                 _expand(this);
472                         return false;
473                     }
474                 }
475 //          }
476         },
477         'textarea': function(e) {
478                 if(e.onfocus==undefined) {
479                         e.onfocus = function() {
480                             save_focus(this);
481                         };
482                 }
483         }
484 /*      'tr.editrow': function(e) {
485                         e.onkeydown = function(ev) {
486                         ev = ev||window.event;
487                         key = ev.keyCode||ev.which;
488                         if(key == 13) {
489                           // Find & click additem/update button
490
491                         } else  if(key == 27) {
492                           return false;
493                         }
494                 }
495
496         },
497 *//*    '#msgbox': function(e) {
498         // this is to avoid changing div height after ajax update in IE7
499           e.style.display = e.innerHTML.length ? 'block' : 'none';
500         }
501 *//* TODO
502         'a.date_picker':  function(e) {
503             // this un-hides data picker for js enabled browsers
504             e.href = date_picker(this.getAttribute('rel'));
505             e.style.display = '';
506             e.tabindex = -1; // skip in tabbing order
507         }
508 */
509 };
510
511 function stopEv(ev) {
512                         if(ev.preventDefault) {
513                                 ev.preventDefault();
514                                 ev.stopPropagation();
515                         } else {
516                                 ev.returnValue = false;
517                                 ev.cancelBubble = true;
518                                 window.keycode = 0;
519                         }
520                         return false;
521 }
522 /*
523         Modified accesskey system. While Alt key is pressed letter keys moves
524         focus to next marked link. Alt key release activates focused link.
525 */
526 function setHotKeys() {
527         document.onkeydown = function(ev) {
528                 ev = ev||window.event;
529                 key = ev.keyCode||ev.which;
530                 if (key == 18 && !ev.ctrlKey) { // start selection, skip Win AltGr
531                         _hotkeys.alt = true;
532                         _hotkeys.focus = -1;
533                         return stopEv(ev);
534                 }
535                 else if (ev.altKey && !ev.ctrlKey && ((key>47 && key<58) || (key>64 && key<91))) {
536                         key = String.fromCharCode(key);
537                         var n = _hotkeys.focus;
538                         var l = document.getElementsBySelector('[accesskey='+key+']');
539                         var cnt = l.length;
540                         _hotkeys.list = l;
541                         for (var i=0; i<cnt; i++) {
542                                 n = (n+1)%cnt;
543                                 // check also if the link is visible
544                                 if (l[n].accessKey==key && (l[n].offsetWidth || l[n].offsetHeight)) {
545                                         _hotkeys.focus = n;
546             // The timeout is needed to prevent unpredictable behaviour on IE.
547                                         var tmp = function() {l[_hotkeys.focus].focus();};
548                                         setTimeout(tmp, 0);
549                                         break;
550                                 }
551                         }
552                         return stopEv(ev);
553                 }
554                 if((ev.ctrlKey && key == 13) || key == 27) {
555                         _hotkeys.alt = false; // cancel link selection
556                         _hotkeys.focus = -1;
557                         ev.cancelBubble = true;
558                         if(ev.stopPropagation) ev.stopPropagation();
559                         // activate submit/escape form
560                         for(var j=0; j<this.forms.length; j++) {
561                                 var form = this.forms[j];
562                                 for (var i=0; i<form.elements.length; i++){
563                                         var el = form.elements[i];
564                                         var asp = el.getAttribute('aspect');
565
566                                         if (!string_contains(el.className, 'editbutton') && (asp && asp.indexOf('selector') !== -1) && (key==13 || key==27)) {
567                                                 passBack(key==13 ? el.getAttribute('rel') : false);
568                                                 ev.returnValue = false;
569                                                 return false;
570                                         }
571                                         if (((asp && asp.indexOf('default') !== -1) && key==13)||((asp && asp.indexOf('cancel') !== -1) && key==27)) {
572                                                 if (validate(el)) {
573                                                         if (asp.indexOf('nonajax') !== -1)
574                                                                 el.click();
575                                                         else
576                                                         if (asp.indexOf('process') !== -1)
577                                                                 JsHttpRequest.request(el, null, 600000);
578                                                         else
579                                                                 JsHttpRequest.request(el);
580                                                 }
581                                                 ev.returnValue = false;
582                                                 return false;
583                                         }
584                                 }
585                         }
586                         ev.returnValue = false;
587                         return false;
588                 }
589                 if (editors!=='undefined' && editors[key]) {
590                         callEditor(key);
591                         return stopEv(ev); // prevent default binding
592                 }
593                 return true;
594         };
595         document.onkeyup = function(ev) {
596                 ev = ev||window.event;
597                 key = ev.keyCode||ev.which;
598
599                 if (_hotkeys.alt==true) {
600                         if (key == 18) {
601                                 _hotkeys.alt = false;
602                                 if (_hotkeys.focus >= 0) {
603                                         var link = _hotkeys.list[_hotkeys.focus];
604                                         if(link.onclick)
605                                                 link.onclick();
606                                         else
607                                                 if (link.target=='_blank') {
608                                                         window.open(link.href,'','toolbar=no,scrollbar=no,resizable=yes,menubar=no,width=900,height=500');
609                                                         openWindow(link.href,'_blank');
610                                                 } else
611                                                         window.location = link.href;
612                                 }
613                         return stopEv(ev);
614                         }
615                 }
616                 return true;
617         }
618 }
619
620 Behaviour.register(inserts);
621
622 Behaviour.addLoadEvent(setFocus);
623 Behaviour.addLoadEvent(setHotKeys);