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