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