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