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