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