source: trunk/phpgwapi/js/expressoAjax/expressoAjax.js @ 2618

Revision 2618, 13.6 KB checked in by amuller, 14 years ago (diff)

Ticket #911 - Usando xconnector e transformando lang para API

Line 
1var debug_controller =false;
2var files = new Array();
3var progressBar;
4var handlerExecuteForm = null;
5
6  if (document.all)
7        {
8                navigator.userAgent.toLowerCase().indexOf('msie 5') != -1 ? is_ie5 = true : is_ie5 = false;
9                is_ie = true;
10                is_moz1_6 = false;
11                is_mozilla = false;
12                is_ns4 = false;
13        }
14        else if (document.getElementById)
15        {
16                navigator.userAgent.toLowerCase().match('mozilla.*rv[:]1\.6.*gecko') ? is_moz1_6 = true : is_moz1_6 = false;
17                is_ie = false;
18                is_ie5 = false;
19                is_mozilla = true;
20                is_ns4 = false;
21        }
22        else if (document.layers)
23        {
24                is_ie = false;
25                is_ie5 = false;
26                is_moz1_6 = false;
27                is_mozilla = false;
28                is_ns4 = true;
29        }
30
31/****************************************** Connector Class *************************************************/
32        // Constructor
33        function cConnector()
34        {
35                this.requests = new Array();
36                this.hold_session = false;
37                this.oxmlhttp = null;
38                this.isVisibleBar = false;
39                this.tid = 0;
40                this.progressBar = null;
41                this.oldX = 0;
42                this.oldY = 0;
43                this.updateVersion = "";
44                this.cacheRequest = null;
45                this.connectorCache = {
46                                'valid' : [],
47                                'result' : []
48                };
49                this.expurgatedCache = new Array(); // Data to purge from cache
50
51        };
52        cConnector.prototype.verify_session = function(data) {
53                if(data && data.nosession){
54                        // If hold session is setted, dont reload the page ...
55                        if(expresso.connector.hold_session) {
56                                if(typeof(write_msg) == "function" && typeof(get_lang) == "function")
57                                        write_msg(get_lang("your session could not be verified."));
58                                else
59                                        alert("your session could not be verified.");
60                        }
61                        else
62                                window.location.reload();
63                        return false;
64                }
65                else
66                        return true;
67        };
68        cConnector.prototype.buildBar = function()
69                {
70                        var div = document.getElementById('divProgressBar');
71
72                        if(! div) {
73                                div = document.createElement("DIV");
74                                div.style.visibility    = "hidden";
75                                div.style.width = "103px";
76                                div.id = 'divProgressBar';
77                                div.align = "center";
78                                var loadingTitle = document.getElementById('txt_loading');
79                                div.innerHTML = '&nbsp;&nbsp;<font face="Verdana" size="2" color="WHITE">'+loadingTitle.value+'...</font>&nbsp;';
80                                div.style.background = "#cc4444";
81                                div.style.position = 'fixed';
82                                div.style.top = '0px';
83                                div.style.right = '0px';
84                                document.body.appendChild(div);
85
86                                if(is_ie) {
87                                        var elem = document.all[div.id];
88                                        elem.style.position="absolute";
89                                        var root = document.body;
90                                        var posX = elem.offsetLeft-root.scrollLeft;
91                                        var posY = elem.offsetTop-root.scrollTop;
92                                        root.onscroll = function() {
93                                                elem.style.right = '0px';
94                                                elem.style.top = (posY + root.scrollTop) + "px";
95                                        };
96                                }
97
98                                if(debug_controller) {
99                                        div = document.createElement("DIV");
100                                        div.style.width = "800px";
101                                        div.style.height= "400px";
102                                        div.id = "debug_controller";
103                                        div.align='right';
104                                        document.body.appendChild(div);
105                                }
106                        }
107        };
108//------------------------------------ BEGIN: Functions for Connector HTTPRequest  -------------------------------------------------//
109        // Serialize Data Method
110        cConnector.prototype.serialize = function(data)
111        {       var _thisObject = this;
112                var f = function(data)
113                {
114                        var str_data;
115
116                        if (data == null ||
117                                (typeof(data) == 'string' && data == ''))
118                        {
119                                str_data = 'N;';
120                        }
121
122                        else switch(typeof(data))
123                        {
124                                case 'object':
125                                        var arrayCount = 0;
126
127                                        str_data = '';
128
129                                        for (i in data)
130                                        {
131                                                if (i == 'length')
132                                                {
133                                                        continue;
134                                                }
135
136                                                arrayCount++;
137                                                switch (typeof(i))
138                                                {
139                                                        case 'number':
140                                                                str_data += 'i:' + i + ';' + f(data[i]);
141                                                                break;
142
143                                                        case 'string':
144                                                                str_data += 's:' + i.length + ':"' + i + '";' + f(data[i]);
145                                                                break;
146
147                                                        default:
148                                                                showMessage(Element('cc_msg_err_serialize_data_unknown').value);
149                                                                break;
150                                                };
151                                        }
152
153                                        if (!arrayCount)
154                                        {
155                                                str_data = 'N;';
156                                        }
157                                        else
158                                        {
159                                                str_data = 'a:' + arrayCount + ':{' + str_data + '}';
160                                        }
161
162                                        break;
163
164                                case 'string':
165                                        str_data = 's:' + data.length + ':"' + data + '";';
166                                        break;
167
168                                case 'number':
169                                        str_data = 'i:' + data + ';';
170                                        break;
171
172                                case 'boolean':
173                                        str_data = 'b:' + (data ? '1' : '0') + ';';
174                                        break;
175
176                                default:
177                                        showMessage(Element('cc_msg_err_serialize_data_unknown').value);
178                                        return null;
179                        };
180
181                        return str_data;
182                };
183
184                return f(data);
185        };
186
187
188        //Unserialize Data Method
189        cConnector.prototype.unserialize = function(str)
190        {
191
192                _thisObject = this;
193                var matchB = function (str, iniPos)
194                {
195                        var nOpen, nClose = iniPos;
196                        do
197                        {
198                                nOpen = str.indexOf('{', nClose+1);
199                                nClose = str.indexOf('}', nClose+1);
200
201                                if (nOpen == -1)
202                                {
203                                        return nClose;
204                                }
205                                if (nOpen < nClose )
206                                {
207                                        nClose = matchB(str, nOpen);
208                                }
209                        } while (nOpen < nClose);
210
211                        return nClose;
212                };
213
214                var f = function (str)
215                {
216                        switch (str.toString().charAt(0))
217                        {
218                                case 'a':
219
220                                        var data = new Array();
221                                        var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
222                                        var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
223
224                                        for (var i = 0; i < n; i++)
225                                        {
226                                                var pos = 0;
227
228                                                /* Process Index */
229                                                var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
230                                                var index = f(indexStr);
231                                                pos = arrayContent.indexOf(';', pos)+1;
232
233                                                /* Process Content */
234                                                var part = null;
235                                                switch (arrayContent.charAt(pos))
236                                                {
237                                                        case 'a':
238                                                                var pos_ = matchB(arrayContent, arrayContent.indexOf('{', pos))+1;
239                                                                part = arrayContent.substring(pos, pos_);
240                                                                pos = pos_;
241                                                                data[index] = f(part);
242                                                                break;
243
244                                                        case 's':
245                                                                var pval = arrayContent.indexOf(':', pos+2);
246                                                                var val  = parseInt(arrayContent.substring(pos+2, pval));
247                                                                pos = pval + val + 4;
248                                                                data[index] = arrayContent.substr(pval+2, val);
249                                                                break;
250
251                                                        default:
252                                                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
253                                                                pos = arrayContent.indexOf(';', pos)+1;
254                                                                data[index] = f(part);
255                                                                break;
256                                                }
257                                                arrayContent = arrayContent.substr(pos);
258                                        }
259                                        break;
260
261                                case 's':
262                                        var pos = str.indexOf(':', 2);
263                                        var val = parseInt(str.substring(2,pos));
264                                        var data = str.substr(pos+2, val);
265                                        str = str.substr(pos + 4 + val);
266                                        break;
267
268                                case 'i':
269                                case 'd':
270                                        var pos = str.indexOf(';');
271                                        var data = parseInt(str.substring(2,pos));
272                                        str = str.substr(pos + 1);
273                                        break;
274
275                                case 'N':
276                                        var data = null;
277                                        str = str.substr(str.indexOf(';') + 1);
278                                        break;
279
280                                case 'b':
281                                        var data = str.charAt(2) == '1' ? true : false;
282                                        break;
283                        };
284                        return data;
285                };
286
287                return f(str);
288        };
289
290        // Request Constructor Connector
291        cConnector.prototype.newRequest = function (id, target, method, handler, data)
292        {
293                _connector.go( {
294                        "access" : target,
295                        "handler" : function( data )
296                        {
297                                handler( expresso.connector.unserialize( data ) );
298                        }
299                } );
300        };
301        // Cancel Request Connector
302        cConnector.prototype.cancelRequest = function (){
303                return false;
304        };
305//------------------------------------  END: Functions for Connector HTTPRequest  -------------------------------------------------//
306
307//      ----------------------------------- BEGIN: Functions for build Bar Progress ---------------------------------------------------------//
308        cConnector.prototype.hideProgressBar = function ()
309        {
310                var div = document.getElementById('divProgressBar');
311                div.style.visibility = 'hidden';
312                this.isVisibleBar = false;
313        };
314
315        cConnector.prototype.showProgressBar = function(){
316                var div = document.getElementById('divProgressBar');
317                div.style.visibility = 'visible';
318
319                this.isVisibleBar = true;
320        };
321
322        cConnector.prototype.loadAllScripts = function(scripts) {
323                for(var i = 0; i < scripts.length; i++){
324                        this.loadScript(scripts[i]);
325                }
326        };
327
328        cConnector.prototype.loadScript = function(scriptPath)  {
329        if (document.getElementById('uploadscript_'+scriptPath)) {
330                return;
331        }
332                var head = document.getElementsByTagName("head")[0];
333                var script = document.createElement("SCRIPT");
334                script.id = 'uploadscript_'+scriptPath;
335                script.type = 'text/javascript';
336
337                if(is_ie) {
338
339                        this.oxmlhttp.open("GET", URL_SERVER + "/expressoMail1_2/js/"+scriptPath+".js?"+this.updateVersion, false);
340                        this.oxmlhttp.setRequestHeader('Content-Type','text/plain');
341                        this.oxmlhttp.send(null);
342                        if(this.oxmlhttp.status != 0 && this.oxmlhttp.status != 200 ||  this.oxmlhttp.status == 0 && this.oxmlhttp.responseText.length == 0)
343                                throw new Error("Error " + this.oxmlhttp.status + "("+this.oxmlhttp.statusText+") when loading script file '"+scriptPath+"'");
344                        script.text = this.oxmlhttp.responseText;
345                }
346                else {
347                        script.src =  URL_SERVER + "/expressoMail1_2/js/"+scriptPath+".js?"+this.updateVersion;
348                }
349
350                head.appendChild(script);
351                return;
352        };
353//------------------------------------  END: Functions for Progress Bar  -------------------------------------------------//
354        // Default Controller File
355        var URL_DEFAULT = URL_SERVER + "/controller.php?menuaction=";
356        // connector object
357        var _onmouseup = document.onmouseup;
358        var isExecuteForm = false;
359        var id = null;
360
361        cConnector.prototype.queryConnectorCache = function(url,handler){
362                if (this.connectorCache.valid[url])
363                {
364                        handler(this.connectorCache.result[url]);
365                        return true;
366                }
367                else
368                        return false;
369        };
370        cConnector.prototype.purgeCache= function(){
371                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
372                        return false;
373                var i;
374                for (i=0; i<= this.expurgatedCache.length; i++)
375                {
376                        this.connectorCache.valid[this.expurgatedCache[i]] = false;
377                        try {
378                        delete this.connectorCache.result[this.expurgatedCache[i]];
379                        }
380                        catch (e) { };
381                }
382        };
383        cConnector.prototype.cacheNextRequest = function(expiration){
384                if (typeof(expiration) == 'undefined')
385                        expiration=0;
386                this.cacheRequest=expiration;
387        };
388
389        cConnector.prototype.addToCache = function(id,data){
390                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
391                        return false;
392                var func = id.substr(id.lastIndexOf('.')+1);
393                if (func.indexOf('&') > 0)
394                        func = func.substr(0,func.indexOf('&'));
395                switch (this.cacheRequest){
396                        // functions that enters in cache and never expires
397                        case 0:
398                                data.cacheHit = true;
399                                this.connectorCache.valid[id] = true;
400                                this.connectorCache.result[id] = data;
401                                break;
402                        case 1:
403                        // function that needs expire
404                                this.connectorCache.valid[id] = true;
405                                this.connectorCache.result[id] = data;
406                                var i = this.expurgatedCache.length;
407                                this.expurgatedCache[i+1] = id;
408                                break;
409                        default:
410                        // no cache
411                                break;
412                }
413        };
414
415        //      Function executes AJAX
416        //      cExecute (url, handler, params)
417        //      url: 'module.class.method'
418        //  handle: function handle() receive response.
419        //  params: parameters for POST method
420        //      form: form element (for upload files)
421        function cExecute(url, handler, params, form) {
422                if(isExecuteForm){
423                        isExecuteForm = false;
424                        document.onmouseup = _onmouseup;
425                }
426                if(form) {
427                        cExecuteForm(url, form);
428                        return;
429                }
430                //url = URL_DEFAULT + url;
431
432                if (expresso.connector.queryConnectorCache(params?url+"&"+params:url,handler))
433                        return;
434
435                if(params)
436                        method = "POST";
437                else
438                        method = "GET";
439
440                id = url;
441                expresso.connector.newRequest(id, url, method, handler, params);
442        };
443
444// This function executes submit values to Controller (POST)
445        // The return is void.
446        //      cExecuteForm (url, form)
447        //      url: 'module.class.method'
448        //      form: form element (for upload files)
449        function cExecuteForm(url, form, handler,id){
450                expresso.connector.buildBar();
451                isExecuteForm = true;
452
453                document.onmouseup = alertBut;
454
455                expresso.connector.showProgressBar();
456                if(! (divUpload = document.getElementById('divUpload'))) {
457                        divUpload               = document.createElement('DIV');
458                        divUpload.id    = 'divUpload';
459                        document.body.appendChild(divUpload);
460                }
461
462                if(! (el = document.getElementById('_action'))) {
463                        el                      = document.createElement('input');
464                        el.type = 'hidden';
465                        el.id           = '_action';
466                        el.name = '_action';
467                        form.appendChild(el);
468                }
469
470                var divFiles = document.getElementById("divFiles_"+id);
471                if (divFiles && divFiles.firstChild) {
472                        el                      = document.createElement('input');
473                        el.type = 'hidden';
474                        el.name = 'countFiles';
475                        var countDivFiles = 0;
476                        try{
477                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
478                                }
479                        catch (e) { var countDivFiles = 0; };
480                        el.value        = countDivFiles ;
481                        form.appendChild(el);
482                }
483
484                form._action.value = url;
485                // Connector Bug fixing: Encapsulating returned handler function
486                handlerExecuteForm = handler;
487                var form_handler = function (data){
488                        handlerExecuteForm(data);
489                        handlerExecuteForm = null;
490                };
491                divUpload.innerHTML= "<iframe onload=\"cExecute('expressoMail1_2.functions.getReturnExecuteForm',"+form_handler+");\"  style='display:"+(debug_controller ? "" : "none")+";width:"+(debug_controller ? 400 : 0)+";height:"+(debug_controller ? 400 : 0)+";' name='uploadFile'></iframe>";
492                form.action = URL_DEFAULT + url;
493                form.target ="uploadFile";
494                form.submit();
495                // Connector Bug fixing: Exclude '_action' element after cExecuteForm execution
496                if(el && el.id == '_action'){
497                        el.parentNode.removeChild(el);
498                }
499        };
500
501
502        function alertBut(e) {
503                if(!e)
504                        e = window.event;
505
506            if(_onmouseup)
507                        _onmouseup(e);
508
509                if(isExecuteForm) {
510                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
511                        expresso.connector.hideProgressBar();
512                        isExecuteForm = false;
513                        delete expresso.connector.requests[id];
514                                expresso.connector.requests[id] = null;
515                        stop();
516                        return;
517                }
518                else
519                        return false;
520            }
521        };
522
523function expressoAjax(){
524        this.connector = new cConnector();
525
526};
527expressoAjax.prototype.require = function (module){
528        expresso.connector.loadScript(module);
529};
530var expresso = new expressoAjax();
Note: See TracBrowser for help on using the repository browser.