Fixed hotkey menu option selection issues on Chrome.
[fa-stable.git] / js / utils.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 function set_mark(img) {
12         var box = document.getElementById('ajaxmark');
13         if(box) {
14                 if(img) box.src = user.theme+'images/'+ img;
15                 box.style.visibility = img ? 'visible' : 'hidden'
16         }
17 }
18
19 function disp_msg(msg, cl) {
20         var box = document.getElementById('msgbox')
21         box.innerHTML= "<div class='"+(cl || 'err_msg')+"'>"+ msg+'</div>';
22 //      box.style.display = msg=='' ? 'none':'block';
23     if (msg!='') window.scrollTo(0,element_pos(box).y-10);
24 }
25
26 //
27 //      JsHttpRequest class extensions.
28 //
29 // Main functions for asynchronus form submitions
30 //      Trigger is the source of request and can have following forms:
31 //      - input object - all form values are also submited
32 //  - arbitrary string - POST var trigger with value 1 is added to request;
33 //              if form parameter exists also form values are submited, otherwise
34 //              request is directed to current location 
35 // 
36 JsHttpRequest.request= function(trigger, form, tout) {
37 //      if (trigger.type=='submit' && !validate(trigger)) return false;
38         tout = tout || 10000;   // default timeout value
39         document.getElementById('msgbox').innerHTML='';
40         set_mark(tout>10000 ? 'progressbar.gif' : 'ajax-loader.gif');
41         JsHttpRequest._request(trigger, form, tout, 0);
42 }
43
44 JsHttpRequest._request = function(trigger, form, tout, retry) {
45                 if (trigger.tagName=='A') {
46                         var content = {};
47                         var upload = 0;
48                         var url = trigger.href;
49                         if (trigger.id) content[trigger.id] = 1;
50                 } else {
51                 var submitObj = typeof(trigger) == "string" ? 
52                         document.getElementsByName(trigger)[0] : trigger;
53                 
54                 form = form || (submitObj && submitObj.form);
55
56                 var upload = form && form.enctype=='multipart/form-data';
57                 
58                 var url = form ? form.action : 
59                   window.location.toString();
60
61                 if (!form) form = document.forms[0]; // when trigger element is on already superseded page fragment, form is null
62
63                 var content = this.formInputs(trigger, form, upload);
64
65                 if (!form) url = url.substring(0, url.indexOf('?'));
66                 
67                 if (!submitObj) {
68                         content[trigger] = 1;
69                         }
70                 }
71                         // this is to avoid caching problems
72                 content['_random'] = Math.random()*1234567;
73         
74                 var tcheck = setTimeout(
75                         function() {
76                                 for(var id in JsHttpRequest.PENDING)  {
77                                         var call = JsHttpRequest.PENDING[id];
78                                         if (call != false) {
79                                         if (call._ldObj.xr) // needed for gecko
80                                                 call._ldObj.xr.onreadystatechange = function(){};
81                                         call.abort(); // why this doesn't kill request in firebug?
82 //                                              call._ldObj.xr.abort();
83                                                 delete JsHttpRequest.PENDING[id];
84                                         }
85                                 }
86                                 set_mark(retry ? 'ajax-loader2.gif':'warning.png' );
87                                 if(retry)
88                                         JsHttpRequest._request(trigger, form, tout, retry-1);
89                         }, tout );
90
91         JsHttpRequest.query(
92             (upload ? "form." : "")+"POST "+url, // force form loader
93                 content,
94             // Function is called when an answer arrives. 
95             function(result, errors) {
96                 // Write the answer.
97                         var newwin = 0;
98                 if (result) {
99                           for(var i in result ) { 
100                           atom = result[i];
101                           cmd = atom['n'];
102                           property = atom['p'];
103                           type = atom['c'];
104                           id = atom['t'];
105                           data = atom['data'];
106 //                              debug(cmd+':'+property+':'+type+':'+id);
107                         // seek element by id if there is no elemnt with given name
108                           objElement = document.getElementsByName(id)[0] || document.getElementById(id);
109                   if(cmd=='as') {
110                                   eval("objElement.setAttribute('"+property+"','"+data+"');");
111                           } else if(cmd=='up') {
112 //                              if(!objElement) alert('No element "'+id+'"');
113                                 if(objElement) {
114                             if (objElement.tagName == 'INPUT' || objElement.tagName == 'TEXTAREA')
115                                   objElement.value = data;
116                             else
117                                   objElement.innerHTML = data; // selector, div, span etc
118                                 }
119                           } else if(cmd=='di') { // disable/enable element
120                                   objElement.disabled = data;
121                           } else if(cmd=='fc') { // set focus
122                                   _focus = data;
123                           } else if(cmd=='js') {        // evaluate js code
124                                 __isGecko ? eval(data) : setTimeout(function(){eval(data)}, 200); // timeout required by IE7/8
125                           } else if(cmd=='rd') {        // client-side redirection
126                                   window.location = data;
127                           } else if(cmd=='pu') {        // pop-up
128                                   newwin = 1;
129                                   window.open(data,'REP_WINDOW','toolbar=no,scrollbars=yes,resizable=yes,menubar=no');
130                           } else {
131                                   errors = errors+'<br>Unknown ajax function: '+cmd;
132                         }
133                   }
134                  if(tcheck)
135                    JsHttpRequest.clearTimeout(tcheck);
136         // Write errors to the debug div.
137                   document.getElementById('msgbox').innerHTML = errors;
138                   set_mark();
139
140                   Behaviour.apply();
141
142                   if (errors.length>0)
143                         window.scrollTo(0,0);
144                         //document.getElementById('msgbox').scrollIntoView(true);
145           // Restore focus if we've just lost focus because of DOM element refresh
146                         if(!newwin) { 
147                                 setFocus();
148                         }
149                 }
150             },
151                 false  // do not disable caching
152         );
153         }
154         // collect all form input values plus inp trigger value
155         JsHttpRequest.formInputs = function(inp, objForm, upload)
156         {
157                 var submitObj = inp;
158                 var q = {};
159
160                 if (typeof(inp) == "string")
161                         submitObj = document.getElementsByName(inp)[0]||inp;
162                 
163                 objForm = objForm || (submitObj && submitObj.form);
164
165                 if (objForm)
166                 {
167                         var formElements = objForm.elements;
168                         for( var i=0; i < formElements.length; i++)
169                         {
170                           var el = formElements[i];
171                           var name = el.name;
172                                 if (!el.name) continue;
173                                 if(upload) { // for form containing file inputs collect all 
174                                         // form elements and add value of trigger submit button
175                                         // (internally form is submitted via form.submit() not button click())
176                                         if (submitObj.type=='submit' && el==submitObj)
177                                         {
178                                                 q[name] =  el.value
179                                                 continue;
180                                         }
181                                 }
182                                 if (el.type )
183                                   if( 
184                                   ((el.type == 'radio' || el.type == 'checkbox') && el.checked == false)
185                                   || (el.type == 'submit' && (!submitObj || el.name!=submitObj.name)))
186                                         continue;
187                                 if (el.disabled && el.disabled == true)
188                                         continue;
189                                 if (name)
190                                 {
191                                         if(el.type=='select-multiple')
192                                         {
193                                                 name = name.substr(0,name.length-2);
194                                                 q[name] = new Array;
195                                                 for (var j = 0; j < el.length; j++)
196                                                 {
197                                                         s = name.substring(0, name.length-2);
198                                                         if (el.options[j].selected == true)
199                                                                 q[name].push(el.options[j].value);
200                                                 }
201                                         }
202                                         else
203                                         if (el.type=='file')
204                                                 q[name] = el
205                                         else
206                                         {
207                                                 q[name] = el.value;
208                                         }
209                                 } 
210                         }
211                 }
212                 return q;
213         }
214 //
215 //      User price formatting
216 //
217 function price_format(post, num, dec, label, color) {
218         var el = label ? document.getElementById(post) : document.getElementsByName(post)[0];
219         //num = num.toString().replace(/\$|\,/g,'');
220         if(isNaN(num))
221                 num = "0";
222         sign = (num == (num = Math.abs(num)));
223         var max = dec=='max';
224         if(max) dec = num==0 ? 2 : 15 - Math.floor(Math.log(Math.abs(num)));
225         if(dec<0) dec = 2;
226         decsize = Math.pow(10, dec);
227         num = Math.floor(num*decsize+0.50000000001);
228         cents = num%decsize;
229         num = Math.floor(num/decsize).toString(); 
230         for( i=cents.toString().length; i<dec; i++){
231                 cents = "0"+cents;
232         }
233         if (max) // strip trailing 0
234                 cents = cents.toString().replace(/0+$/,'');
235         for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
236                 num = num.substring(0,num.length-(4*i+3))+user.ts+
237                         num.substring(num.length-(4*i+3));
238          num = ((sign)?'':'-') + num;
239         if(dec!=0 && (!max || cents!=0))
240                 num = num + user.ds + cents;
241         if(label)
242             el.innerHTML = num;
243         else
244             el.value = num;
245         if(color) {
246                         el.style.color = (sign) ? '' : '#FF0000';
247         }
248 }
249
250 function get_amount(doc, label) {
251             if(label)
252                         var val = document.getElementById(doc).innerHTML;
253             else
254                         var val = typeof(doc) == "string" ? 
255                         document.getElementsByName(doc)[0].value : doc.value;
256                 
257                 val = val.replace(new RegExp('\\'+user.ts, 'g'),'');
258                 val = +val.replace(new RegExp('\\'+user.ds, 'g'),'.');
259                 return isNaN(val) ? 0 : val;
260 }
261
262 function goBack(deep) {
263         if (window.opener)
264          window.close();
265         else
266          window.history.go(deep || -1);
267 }
268
269 function setFocus(name, byId) {
270
271  if(typeof(name)=='object')
272         el = name;
273  else {
274         if(!name) { // page load/ajax update
275                 if (_focus)     
276                         name = _focus;  // last focus set in onfocus handlers
277                 else 
278                         if (document.forms.length) {    // no current focus (first page display) -  set it from from last form
279                           var cur = document.getElementsByName('_focus')[document.forms.length-1];
280                           if(cur) name = cur.value;
281                         }
282           }
283           if(byId || !(el = document.getElementsByName(name)[0]))
284                 el = document.getElementById(name);
285   }
286   if(el && el.focus) {
287     // The timeout is needed to prevent unpredictable behaviour on IE & Gecko.
288     // Using tmp var prevents crash on IE5
289         
290     var tmp = function() {el.focus(); if (el.select) el.select();};
291         setTimeout(tmp, 0);
292   }
293 }
294 /*
295         Find closest element in neighbourhood and set focus.
296         dir is arrow keycode.
297 */
298 function move_focus(dir, e0, neighbours)
299 {
300         var p0 = element_pos(e0);
301         var t;
302         var l=0;
303         for(var i=0; i<neighbours.length; i++) {
304                 var e = neighbours[i];
305                 var p = element_pos(e);
306                 if (p!=null && (e.className=='menu_option' || e.className=='printlink'
307                                  || e.className == 'repclass_link' || e.className == 'repopts_link')) {
308                         if (((dir==40) && (p.y>p0.y)) || (dir==38 && (p.y<p0.y)) 
309                                 || ((dir==37) && (p.x<p0.x)) || ((dir==39 && (p.x>p0.x)))) {
310                                         var l1 = (p.y-p0.y)*(p.y-p0.y)+(p.x-p0.x)*(p.x-p0.x);
311                                         if ((l1<l) || (l==0)) {
312                                                 l = l1; t = e;
313                                         }
314                         }
315                 }
316         }
317         if (t)
318                 setFocus(t);
319         return t;
320 }
321
322 var __isGecko = navigator.userAgent.match(/gecko/i); // i.e. Gecko or KHTML, like Gecko ;)
323 //returns the absolute position of some element within document
324 function element_pos(e) {
325         var res = new Object();
326                 res.x = 0; res.y = 0;
327         if (e !== null) {
328                 res.x = e.offsetLeft;
329                 res.y = e.offsetTop;
330                 var offsetParent = e.offsetParent;
331                 var parentNode = e.parentNode;
332
333                 while (offsetParent !== null && offsetParent.style.display != 'none') {
334                         res.x += offsetParent.offsetLeft;
335                         res.y += offsetParent.offsetTop;
336                         // the second case is for IE6/7 in some doctypes
337                         if (offsetParent != document.body && offsetParent != document.documentElement) {
338                                 res.x -= offsetParent.scrollLeft;
339                                 res.y -= offsetParent.scrollTop;
340                         }
341                               //next lines are necessary to support FireFox problem with offsetParent
342                         if (__isGecko) {
343                                 while (offsetParent != parentNode && parentNode !== null) {
344                                         res.x -= parentNode.scrollLeft;
345                                         res.y -= parentNode.scrollTop;
346
347                                         parentNode = parentNode.parentNode;
348                                 }
349                         }
350                         parentNode = offsetParent.parentNode;
351                         offsetParent = offsetParent.offsetParent;
352                 }
353         }
354         // parentNode has style.display set to none
355         if (parentNode != document.documentElement) return null;
356         return res;
357 }