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