fca82d03c069af2f8e1acaf82ab34caaeafd560d
[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(cmd=='as') {
60                                   eval("objElement.setAttribute('"+property+"',"+data+");");
61                           } else if(cmd=='up') {
62 //                              if(!objElement) debug('No element "'+id+'"');
63                             if (objElement.tagName == 'INPUT' || objElement.tagName == 'TEXTAREA')
64                                   objElement.value = data;
65                             else
66                                   objElement.innerHTML = data; // selector, div, span etc
67                           } else if(cmd=='di') { // disable/enable element
68                                   objElement.disabled = data;
69                           } else if(cmd=='fc') { // set focus
70                                   _focus = data;
71                           } else if(cmd=='js') {        // evaluate js code
72                                   eval(data);
73                           } else if(cmd=='rd') {        // client-side redirection
74                                   window.location = data;
75                           } else if(cmd=='pu') {        // pop-up
76                                   newwin = 1;
77                                   window.open(data,'REP_WINDOW','toolbar=no,scrollbar=no,resizable=yes,menubar=no');
78                           } else {
79                                   errors = errors+'<br>Unknown ajax function: '+cmd;
80                         }
81                   }
82
83         // Write errors to the debug div.
84                   document.getElementById('msgbox').innerHTML = errors;
85                   var mark = document.getElementById('ajaxmark');
86                   if(mark) mark.style.visibility = 'hidden';
87
88                   Behaviour.apply();
89
90                   if (errors.length>0)
91                         window.scrollTo(0,0);
92                         //document.getElementById('msgbox').scrollIntoView(true);
93           // Restore focus if we've just lost focus because of DOM element refresh
94                         if(!newwin) { 
95                                 setFocus();
96                         }
97                 }
98             },
99             false  // do not disable caching
100         );
101     }
102         // collect all form input values plus inp trigger value
103         JsHttpRequest.formInputs = function(inp, objForm, upload)
104         {
105                 var submitObj = inp;
106                 var q = {};
107
108                 if (typeof(inp) == "string")
109                         submitObj = document.getElementsByName(inp)[0];
110                 else
111                         submitObj = inp;
112                 
113                 objForm = objForm || (submitObj && submitObj.form);
114
115                 if (objForm)
116                 {
117                         var formElements = objForm.elements;
118                         for( var i=0; i < formElements.length; i++)
119                         {
120                           var el = formElements[i];
121                           var name = el.name;
122                                 if (!el.name) continue;
123                                 if(upload) { // for form containing file inputs collect all 
124                                         // form elements and add value of trigger submit button
125                                         // (internally form is submitted via form.submit() not button click())
126                                         q[name] = submitObj.type=='submit' && el==submitObj ? el.value : el;
127                                         continue;
128                                 }
129                                 if (el.type )
130                                   if( 
131                                   ((el.type == 'radio' || el.type == 'checkbox') && el.checked == false)
132                                   || (el.type == 'submit' && (!submitObj || el.name!=submitObj.name)))
133                                         continue;
134                                 if (el.disabled && el.disabled == true)
135                                         continue;
136                                 if (name)
137                                 {
138                                         if(el.type=='select-multiple')
139                                         {
140                                                 for (var j = 0; j < el.length; j++)
141                                                 {
142                                                         if (el.options[j].selected == true)
143                                                                 q[name] = el.options[j].value;
144                                                 }
145                                         }
146                                         else
147                                         {
148                                                 q[name] = el.value;
149                                         }
150                                 } 
151                         }
152                 }
153                 return q;
154         }
155 //
156 //      User price formatting
157 //
158 function price_format(post, num, dec, label, color) {
159         var el = label ? document.getElementById(post) : document.getElementsByName(post)[0];
160         //num = num.toString().replace(/\$|\,/g,'');
161         if(isNaN(num))
162                 num = "0";
163         sign = (num == (num = Math.abs(num)));
164         if(dec<0) dec = 2;
165         decsize = Math.pow(10, dec);
166         num = Math.floor(num*decsize+0.50000000001);
167         cents = num%decsize;
168         num = Math.floor(num/decsize).toString();
169         for( i=cents.toString().length; i<dec; i++){
170                 cents = "0" + cents;
171         }
172         for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
173                 num = num.substring(0,num.length-(4*i+3))+user.ts+
174                         num.substring(num.length-(4*i+3));
175          num = ((sign)?'':'-') + num;
176          if(dec!=0) num = num + user.ds + cents;
177         if(label)
178             el.innerHTML = num;
179         else
180             el.value = num;
181         if(color) {
182                         el.style.color = (sign) ? '' : '#FF0000';
183         }
184 }
185
186 function get_amount(doc, label) {
187             if(label)
188                 var val = document.getElementById(doc).innerHTML;
189             else
190                 var val = document.getElementsByName(doc)[0].value;
191                 val = val.replace(new RegExp('\\'+user.ts, 'g'),'');
192                 val = val.replace(new RegExp('\\'+user.ds, 'g'),'.');
193                 return 1*val;
194 }
195
196 function goBack() {
197         if (window.history.length <= 1)
198          window.close();
199         else
200          window.history.go(-1);
201 }
202
203 function setFocus(name, byId) {
204   if(document.location.pathname.indexOf('index.php') != -1) {
205         // this is application menu page - set focus on first link
206         // var el = document.getElementById('msgbox');
207         // TODO find first link after msgbox and set focus
208   }
209   if(!name) {
210         if (_focus)     
211                 name = _focus;  // last focus set in onfocus handlers
212         else 
213          if (document.forms.length) {   // no current focus (first page display) -  set it from from last form
214           var cur = document.getElementsByName('_focus')[document.forms.length-1];
215           if(cur) name = cur.value;
216         }
217   }
218   if(byId)
219         el = document.getElementById(name);
220   else
221         el = document.getElementsByName(name)[0];
222
223   if(el && el.focus) {
224     // The timeout is needed to prevent unpredictable behaviour on IE & Gecko.
225     // Using tmp var prevents crash on IE5
226         
227     var tmp = function() {el.focus(); if (el.select) el.select();};
228         setTimeout(tmp, 0);
229   }
230 }