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

Revision 2403, 16.3 KB checked in by amuller, 14 years ago (diff)

Ticket #1022 - Melhorias adicionais, por questões de legibilidade

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        //Create XMLHTTP object Method
291        cConnector.prototype.createXMLHTTP = function ()
292        {
293                try
294                {
295                        this.oxmlhttp = new XMLHttpRequest();
296                        this.oxmlhttp.overrideMimeType('text/xml');
297                }
298                catch (e)
299                {
300                        try
301                        {
302                                this.oxmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
303                        }
304                        catch (e1)
305                        {
306                                try
307                                {
308                                        this.oxmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
309                                }
310                                catch (e2)
311                                {
312                                        this.oxmlhttp = null;
313                                }
314                        }
315                }
316
317        }
318
319        // Request Constructor Connector
320        cConnector.prototype.newRequest = function (id, target, method, handler, data)
321        {
322                var params = data;
323                this.tid = id;
324                if (this.requests[id]) {
325                        return false;
326                }
327
328                this.createXMLHTTP();
329                var oxmlhttp = this.oxmlhttp;
330                var _thisObject = this;
331
332                if (! oxmlhttp)
333                        return false;
334
335                this.requests[id] = oxmlhttp;
336                this.buildBar();
337                this.showProgressBar();
338
339                var sub_handler = function ()
340                {
341                        var progressBar = _thisObject.progressBar;
342
343                        try
344                        {
345                                if (oxmlhttp.readyState == 4 )
346                                {
347
348                                        switch (oxmlhttp.status)
349                                        {
350
351                                                case 200:
352                                                        if (typeof(handler) == 'function')
353                                                        {
354                                                                _thisObject.hideProgressBar();
355                                                                var data = _thisObject.unserialize(oxmlhttp.responseText);
356                                                                if ( typeof data == 'undefined' )
357                                                                        data = oxmlhttp.responseText;
358                                                                // Verify user session
359                                                                if(!_thisObject.verify_session(data)){
360                                                                        delete _thisObject.requests[id];
361                                                                        _thisObject.requests[id] = null;
362                                                                        return false;
363                                                                }
364                                                                if(debug_controller) {
365                                                                        document.getElementById("debug_controller").innerHTML += oxmlhttp.responseText;
366                                                                        document.getElementById("debug_controller").innerHTML += "<br>-------------------------------------------------------------------------------------<br>";
367                                                                }
368                                                                handler(data);
369                                                                _thisObject.addToCache(params?id+"&"+params:id,data);
370                                                                delete _thisObject.requests[id];
371                                                                _thisObject.requests[id] = null;
372                                                        }
373
374                                                        break;
375
376                                                case 404:
377
378                                                        alert(get_lang('Page Not Found!'));
379                                                        break;
380
381                                                default:
382                                        }
383                                }
384                        }
385                        catch (e)
386                        {
387                                _thisObject.hideProgressBar();
388                                if(debug_controller)
389                                        alert(e+"\n"+oxmlhttp.responseText);
390                                // View Exception in Javascript Console
391                                throw(e);
392                        }
393
394                }
395
396                try
397                {
398
399                        if (method == '' || method == 'GET')
400                        {
401                                oxmlhttp.open("GET",target,true);
402                                if (typeof(handler) == 'function')
403                                {
404                                        oxmlhttp.onreadystatechange =  sub_handler;
405                                        oxmlhttp.send(null);
406                                }
407
408                        }
409                        else if (method == 'POST')
410                        {
411                                oxmlhttp.open("POST",target, true);
412                                oxmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
413                                if (typeof(handler) == 'function')
414                                {
415                                        oxmlhttp.onreadystatechange = sub_handler;
416                                        oxmlhttp.send(data);
417                                }
418
419                        }
420                }
421                catch(e)
422                {
423                        _thisObject.hideProgressBar();
424                        if(debug_controller)
425                                alert(e);
426                        // View Exception in Javascript Console
427                        throw(e);
428                }
429
430                return true;
431        }
432        // Cancel Request Connector
433        cConnector.prototype.cancelRequest = function (){
434                if (!this.requests[this.tid]){
435                        return false;
436                }
437                this.oxmlhttp.onreadystatechange = null;
438                this.requests[this.tid].abort();
439                this.hideProgressBar();
440        }
441//------------------------------------  END: Functions for Connector HTTPRequest  -------------------------------------------------//
442
443//      ----------------------------------- BEGIN: Functions for build Bar Progress ---------------------------------------------------------//
444        cConnector.prototype.hideProgressBar = function ()
445        {
446                var div = document.getElementById('divProgressBar');
447                div.style.visibility = 'hidden';
448                this.isVisibleBar = false;
449        }
450
451        cConnector.prototype.showProgressBar = function(){
452                var div = document.getElementById('divProgressBar');
453                div.style.visibility = 'visible';
454
455                this.isVisibleBar = true;
456        }
457
458        cConnector.prototype.loadAllScripts = function(scripts) {
459                for(var i = 0; i < scripts.length; i++){
460                        this.loadScript(scripts[i]);
461                }
462        }
463
464        cConnector.prototype.loadScript = function(scriptPath)  {
465        if (document.getElementById('uploadscript_'+scriptPath)) {
466                return;
467        }
468                var head = document.getElementsByTagName("head")[0];
469                var script = document.createElement("SCRIPT");
470                script.id = 'uploadscript_'+scriptPath;
471                script.type = 'text/javascript';
472
473                if(is_ie) {
474
475                        this.oxmlhttp.open("GET", "js/"+scriptPath+".js?"+this.updateVersion, false);
476                        this.oxmlhttp.setRequestHeader('Content-Type','text/plain');
477                        this.oxmlhttp.send(null);
478                        if(this.oxmlhttp.status != 0 && this.oxmlhttp.status != 200 ||  this.oxmlhttp.status == 0 && this.oxmlhttp.responseText.length == 0)
479                                throw new Error("Error " + this.oxmlhttp.status + "("+this.oxmlhttp.statusText+") when loading script file '"+scriptPath+"'");
480                        script.text = this.oxmlhttp.responseText;
481                }
482                else {
483                        script.src =  "js/"+scriptPath+".js?"+this.updateVersion;
484                }
485
486                head.appendChild(script);
487                return;
488        }
489//------------------------------------  END: Functions for Progress Bar  -------------------------------------------------//
490        // Default Controller File
491        var URL_DEFAULT = URL_SERVER+'/controller.php?action=';
492        // connector object
493        var _onmouseup = document.onmouseup;
494        var isExecuteForm = false;
495        var id = null;
496
497        cConnector.prototype.queryConnectorCache = function(url,handler){
498                if (this.connectorCache.valid[url])
499                {
500                        handler(this.connectorCache.result[url]);
501                        return true;
502                }
503                else
504                        return false;
505        }
506        cConnector.prototype.purgeCache= function(){
507                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
508                        return false;
509                var i;
510                for (i=0; i<= this.expurgatedCache.length; i++)
511                {
512                        this.connectorCache.valid[this.expurgatedCache[i]] = false;
513                        try {
514                        delete this.connectorCache.result[this.expurgatedCache[i]];
515                        }
516                        catch (e) { };
517                }
518        }
519        cConnector.prototype.cacheNextRequest = function(expiration){
520                if (typeof(expiration) == 'undefined')
521                        expiration=0;
522                this.cacheRequest=expiration;
523        }
524
525        cConnector.prototype.addToCache = function(id,data){
526                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
527                        return false;
528                var func = id.substr(id.lastIndexOf('.')+1);
529                if (func.indexOf('&') > 0)
530                        func = func.substr(0,func.indexOf('&'));
531                switch (this.cacheRequest){
532                        // functions that enters in cache and never expires
533                        case 0:
534                                data.cacheHit = true;
535                                this.connectorCache.valid[id] = true;
536                                this.connectorCache.result[id] = data;
537                                break;
538                        case 1:
539                        // function that needs expire
540                                this.connectorCache.valid[id] = true;
541                                this.connectorCache.result[id] = data;
542                                var i = this.expurgatedCache.length;
543                                this.expurgatedCache[i+1] = id;
544                                break;
545                        default:
546                        // no cache
547                                break;
548                }
549        }
550
551        //      Function executes AJAX
552        //      cExecute (url, handler, params)
553        //      url: 'module.class.method'
554        //  handle: function handle() receive response.
555        //  params: parameters for POST method
556        //      form: form element (for upload files)
557        function cExecute(url, handler, params, form) {
558                if(isExecuteForm){
559                        isExecuteForm = false;
560                        document.onmouseup = _onmouseup;
561                }
562                if(form) {
563                        cExecuteForm(url, form);
564                        return;
565                }
566                url = URL_DEFAULT + url;
567
568                if (expresso.connector.queryConnectorCache(params?url+"&"+params:url,handler))
569                        return;
570
571                if(params)
572                        method = "POST";
573                else
574                        method = "GET";
575
576                id = url;
577                expresso.connector.newRequest(id, url, method, handler, params);
578        }
579
580// This function executes submit values to Controller (POST)
581        // The return is void.
582        //      cExecuteForm (url, form)
583        //      url: 'module.class.method'
584        //      form: form element (for upload files)
585        function cExecuteForm(url, form, handler,id){
586                expresso.connector.buildBar();
587                isExecuteForm = true;
588
589                document.onmouseup = alertBut;
590
591                expresso.connector.showProgressBar();
592                if(! (divUpload = document.getElementById('divUpload'))) {
593                        divUpload               = document.createElement('DIV');
594                        divUpload.id    = 'divUpload';
595                        document.body.appendChild(divUpload);
596                }
597
598                if(! (el = document.getElementById('_action'))) {
599                        el                      = document.createElement('input');
600                        el.type = 'hidden';
601                        el.id           = '_action';
602                        el.name = '_action';
603                        form.appendChild(el);
604                }
605
606                var divFiles = document.getElementById("divFiles_"+id);
607                if (divFiles && divFiles.firstChild) {
608                        el                      = document.createElement('input');
609                        el.type = 'hidden';
610                        el.name = 'countFiles';
611                        var countDivFiles = 0;
612                        try{
613                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
614                                }
615                        catch (e) { var countDivFiles = 0; };
616                        el.value        = countDivFiles ;
617                        form.appendChild(el);
618                }
619
620                form._action.value = url;
621                // Connector Bug fixing: Encapsulating returned handler function
622                handlerExecuteForm = handler;
623                var form_handler = function (data){
624                        handlerExecuteForm(data);
625                        handlerExecuteForm = null;
626                }
627                divUpload.innerHTML= "<iframe onload=\"cExecute('$this.functions.getReturnExecuteForm',"+form_handler+");\"  style='display:"+(debug_controller ? "" : "none")+";width:"+(debug_controller ? 400 : 0)+";height:"+(debug_controller ? 400 : 0)+";' name='uploadFile'></iframe>";
628                form.action = URL_SERVER + "/controller.php";
629                form.target ="uploadFile";
630                form.submit();
631                // Connector Bug fixing: Exclude '_action' element after cExecuteForm execution
632                if(el && el.id == '_action'){
633                        el.parentNode.removeChild(el);
634                }
635        }
636
637
638        function alertBut(e) {
639                if(!e)
640                        e = window.event;
641
642            if(_onmouseup)
643                        _onmouseup(e);
644
645                if(isExecuteForm) {
646                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
647                        expresso.connector.hideProgressBar();
648                        isExecuteForm = false;
649                        delete expresso.connector.requests[id];
650                                expresso.connector.requests[id] = null;
651                        stop();
652                        return;
653                }
654                else
655                        return false;
656            }
657        }
658
659function expressoAjax(){
660        this.connector = new cConnector();
661
662}
663expressoAjax.prototype.require = function (module){
664        expresso.connector.loadScript(module);
665}
666var expresso = new expressoAjax();
Note: See TracBrowser for help on using the repository browser.