Small fix to avoid ajax hangups after nonexistent element update.
[fa-stable.git] / js / utils.js
1 //
2 //      JsHttpRequest class extensions.
3 //
4 // Main functions for asynchronus form submitions
5 //      Trigger is the source of request and can have following forms:
6 //      - input object - all form values are also submited
7 //  - arbitrary string - POST var trigger with value 1 is added to request;
8 //              if form parameter exists also form values are submited, otherwise
9 //              request is directed to current location 
10 // 
11     JsHttpRequest.request= function(trigger, form) {
12                 var mark = document.getElementById('ajaxmark');
13                 if(mark) mark.style.visibility = 'visible';
14                 if (trigger.tagName=='A') {
15                         var content = {};
16                         var upload = 0;
17                         var url = trigger.href;
18                         if (trigger.id) content[trigger.id] = 1;
19                 } else {
20                 var submitObj = typeof(trigger) == "string" ? 
21                         document.getElementsByName(trigger)[0] : trigger;
22                 
23                 form = form || (submitObj && submitObj.form);
24
25                 var upload = form && form.enctype=='multipart/form-data';
26                 
27                 var url = form ? form.action : 
28                   window.location.toString();
29
30                 var content = this.formInputs(trigger, form, upload);
31
32                 if (!form) url = url.substring(0, url.indexOf('?'));
33                 
34                 if (!submitObj) 
35                         content[trigger] = 1;
36                         
37                 }
38                         // this is to avoid caching problems
39                 content['_random'] = Math.random()*1234567;
40
41         JsHttpRequest.query(
42             (upload ? "form." : "")+"POST "+url, // force form loader
43                 content,
44             // Function is called when an answer arrives. 
45             function(result, errors) {
46                 // Write the answer.
47                         var newwin = 0;
48                 if (result) {
49                           for(var i in result ) { 
50                           atom = result[i];
51                           cmd = atom['n'];
52                           property = atom['p'];
53                           type = atom['c'];
54                           id = atom['t'];
55                           data = atom['data'];
56 //                              debug(cmd+':'+property+':'+type+':'+id);
57                         // seek element by id if there is no elemnt with given name
58                           objElement = document.getElementsByName(id)[0] || document.getElementById(id);
59                           if(!objElement) continue;
60                   if(cmd=='as') {
61                                   eval("objElement.setAttribute('"+property+"',"+data+");");
62                           } else if(cmd=='up') {
63 //                              if(!objElement) debug('No element "'+id+'"');
64                             if (objElement.tagName == 'INPUT' || objElement.tagName == 'TEXTAREA')
65                                   objElement.value = data;
66                             else
67                                   objElement.innerHTML = data; // selector, div, span etc
68                           } else if(cmd=='di') { // disable/enable element
69                                   objElement.disabled = data;
70                           } else if(cmd=='fc') { // set focus
71                                   _focus = data;
72                           } else if(cmd=='js') {        // evaluate js code
73                                   eval(data);
74                           } else if(cmd=='rd') {        // client-side redirection
75                                   window.location = data;
76                           } else if(cmd=='pu') {        // pop-up
77                                   newwin = 1;
78                                   window.open(data,'REP_WINDOW','toolbar=no,scrollbar=no,resizable=yes,menubar=no');
79                           } else {
80                                   errors = errors+'<br>Unknown ajax function: '+cmd;
81                         }
82                   }
83
84         // Write errors to the debug div.
85                   document.getElementById('msgbox').innerHTML = errors;
86                   var mark = document.getElementById('ajaxmark');
87                   if(mark) mark.style.visibility = 'hidden';
88
89                   Behaviour.apply();
90
91                   if (errors.length>0)
92                         window.scrollTo(0,0);
93                         //document.getElementById('msgbox').scrollIntoView(true);
94           // Restore focus if we've just lost focus because of DOM element refresh
95                         if(!newwin) { 
96                                 setFocus();
97                         }
98                 }
99             },
100             false  // do not disable caching
101         );
102     }
103         // collect all form input values plus inp trigger value
104         JsHttpRequest.formInputs = function(inp, objForm, upload)
105         {
106                 var submitObj = inp;
107                 var q = {};
108
109                 if (typeof(inp) == "string")
110                         submitObj = document.getElementsByName(inp)[0];
111                 else
112                         submitObj = inp;
113                 
114                 objForm = objForm || (submitObj && submitObj.form);
115
116                 if (objForm)
117                 {
118                         var formElements = objForm.elements;
119                         for( var i=0; i < formElements.length; i++)
120                         {
121                           var el = formElements[i];
122                           var name = el.name;
123                                 if (!el.name) continue;
124                                 if(upload) { // for form containing file inputs collect all 
125                                         // form elements and add value of trigger submit button
126                                         // (internally form is submitted via form.submit() not button click())
127                                         q[name] = submitObj.type=='submit' && el==submitObj ? el.value : el;
128                                         continue;
129                                 }
130                                 if (el.type )
131                                   if( 
132                                   ((el.type == 'radio' || el.type == 'checkbox') && el.checked == false)
133                                   || (el.type == 'submit' && (!submitObj || el.name!=submitObj.name)))
134                                         continue;
135                                 if (el.disabled && el.disabled == true)
136                                         continue;
137                                 if (name)
138                                 {
139                                         if(el.type=='select-multiple')
140                                         {
141                                                 for (var j = 0; j < el.length; j++)
142                                                 {
143                                                         if (el.options[j].selected == true)
144                                                                 q[name] = el.options[j].value;
145                                                 }
146                                         }
147                                         else
148                                         {
149                                                 q[name] = el.value;
150                                         }
151                                 } 
152                         }
153                 }
154                 return q;
155         }
156 //
157 //      User price formatting
158 //
159 function price_format(post, num, dec, label, color) {
160         var el = label ? document.getElementById(post) : document.getElementsByName(post)[0];
161         //num = num.toString().replace(/\$|\,/g,'');
162         if(isNaN(num))
163                 num = "0";
164         sign = (num == (num = Math.abs(num)));
165         if(dec<0) dec = 2;
166         decsize = Math.pow(10, dec);
167         num = Math.floor(num*decsize+0.50000000001);
168         cents = num%decsize;
169         num = Math.floor(num/decsize).toString();
170         for( i=cents.toString().length; i<dec; i++){
171                 cents = "0" + cents;
172         }
173         for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
174                 num = num.substring(0,num.length-(4*i+3))+user.ts+
175                         num.substring(num.length-(4*i+3));
176          num = ((sign)?'':'-') + num;
177          if(dec!=0) num = num + user.ds + cents;
178         if(label)
179             el.innerHTML = num;
180         else
181             el.value = num;
182         if(color) {
183                         el.style.color = (sign) ? '' : '#FF0000';
184         }
185 }
186
187 function get_amount(doc, label) {
188             if(label)
189                 var val = document.getElementById(doc).innerHTML;
190             else
191                 var val = document.getElementsByName(doc)[0].value;
192                 val = val.replace(new RegExp('\\'+user.ts, 'g'),'');
193                 val = val.replace(new RegExp('\\'+user.ds, 'g'),'.');
194                 return 1*val;
195 }
196
197 function goBack() {
198         if (window.history.length <= 1)
199          window.close();
200         else
201          window.history.go(-1);
202 }
203
204 function setFocus(name, byId) {
205   if(document.location.pathname.indexOf('index.php') != -1) {
206         // this is application menu page - set focus on first link
207         // var el = document.getElementById('msgbox');
208         // TODO find first link after msgbox and set focus
209   }
210   if(!name) {
211         if (_focus)     
212                 name = _focus;  // last focus set in onfocus handlers
213         else 
214          if (document.forms.length) {   // no current focus (first page display) -  set it from from last form
215           var cur = document.getElementsByName('_focus')[document.forms.length-1];
216           if(cur) name = cur.value;
217         }
218   }
219   if(byId)
220         el = document.getElementById(name);
221   else
222         el = document.getElementsByName(name)[0];
223
224   if(el && el.focus) {
225     // The timeout is needed to prevent unpredictable behaviour on IE & Gecko.
226     // Using tmp var prevents crash on IE5
227         
228     var tmp = function() {el.focus(); if (el.select) el.select();};
229         setTimeout(tmp, 0);
230   }
231 }