]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/javascript/yui/build/connection/connection.js
Release 6.5.0
[Github/sugarcrm.git] / include / javascript / yui / build / connection / connection.js
1 /*
2 Copyright (c) 2011, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 2.9.0
6 */
7 /**
8  * The Connection Manager provides a simplified interface to the XMLHttpRequest
9  * object.  It handles cross-browser instantiantion of XMLHttpRequest, negotiates the
10  * interactive states and server response, returning the results to a pre-defined
11  * callback you create.
12  *
13  * @namespace YAHOO.util
14  * @module connection
15  * @requires yahoo
16  * @requires event
17  */
18
19 /**
20  * The Connection Manager singleton provides methods for creating and managing
21  * asynchronous transactions.
22  *
23  * @class YAHOO.util.Connect
24  */
25
26 YAHOO.util.Connect =
27 {
28   /**
29    * @description Array of MSFT ActiveX ids for XMLHttpRequest.
30    * @property _msxml_progid
31    * @private
32    * @static
33    * @type array
34    */
35     _msxml_progid:[
36         'Microsoft.XMLHTTP',
37         'MSXML2.XMLHTTP.3.0',
38         'MSXML2.XMLHTTP'
39         ],
40
41   /**
42    * @description Object literal of HTTP header(s)
43    * @property _http_header
44    * @private
45    * @static
46    * @type object
47    */
48     _http_headers:{},
49
50   /**
51    * @description Determines if HTTP headers are set.
52    * @property _has_http_headers
53    * @private
54    * @static
55    * @type boolean
56    */
57     _has_http_headers:false,
58
59  /**
60   * @description Determines if a default header of
61   * Content-Type of 'application/x-www-form-urlencoded'
62   * will be added to any client HTTP headers sent for POST
63   * transactions.
64   * @property _use_default_post_header
65   * @private
66   * @static
67   * @type boolean
68   */
69     _use_default_post_header:true,
70
71  /**
72   * @description The default header used for POST transactions.
73   * @property _default_post_header
74   * @private
75   * @static
76   * @type boolean
77   */
78     _default_post_header:'application/x-www-form-urlencoded; charset=UTF-8',
79
80  /**
81   * @description The default header used for transactions involving the
82   * use of HTML forms.
83   * @property _default_form_header
84   * @private
85   * @static
86   * @type boolean
87   */
88     _default_form_header:'application/x-www-form-urlencoded',
89
90  /**
91   * @description Determines if a default header of
92   * 'X-Requested-With: XMLHttpRequest'
93   * will be added to each transaction.
94   * @property _use_default_xhr_header
95   * @private
96   * @static
97   * @type boolean
98   */
99     _use_default_xhr_header:true,
100
101  /**
102   * @description The default header value for the label
103   * "X-Requested-With".  This is sent with each
104   * transaction, by default, to identify the
105   * request as being made by YUI Connection Manager.
106   * @property _default_xhr_header
107   * @private
108   * @static
109   * @type boolean
110   */
111     _default_xhr_header:'XMLHttpRequest',
112
113  /**
114   * @description Determines if custom, default headers
115   * are set for each transaction.
116   * @property _has_default_header
117   * @private
118   * @static
119   * @type boolean
120   */
121     _has_default_headers:true,
122
123  /**
124    * @description Property modified by setForm() to determine if the data
125    * should be submitted as an HTML form.
126    * @property _isFormSubmit
127    * @private
128    * @static
129    * @type boolean
130    */
131         _isFormSubmit:false,
132
133  /**
134   * @description Determines if custom, default headers
135   * are set for each transaction.
136   * @property _has_default_header
137   * @private
138   * @static
139   * @type boolean
140   */
141     _default_headers:{},
142
143  /**
144   * @description Collection of polling references to the polling mechanism in handleReadyState.
145   * @property _poll
146   * @private
147   * @static
148   * @type object
149   */
150     _poll:{},
151
152  /**
153   * @description Queue of timeout values for each transaction callback with a defined timeout value.
154   * @property _timeOut
155   * @private
156   * @static
157   * @type object
158   */
159     _timeOut:{},
160
161   /**
162    * @description The polling frequency, in milliseconds, for HandleReadyState.
163    * when attempting to determine a transaction's XHR readyState.
164    * The default is 50 milliseconds.
165    * @property _polling_interval
166    * @private
167    * @static
168    * @type int
169    */
170      _polling_interval:50,
171
172   /**
173    * @description A transaction counter that increments the transaction id for each transaction.
174    * @property _transaction_id
175    * @private
176    * @static
177    * @type int
178    */
179      _transaction_id:0,
180
181   /**
182    * @description Custom event that fires at the start of a transaction
183    * @property startEvent
184    * @private
185    * @static
186    * @type CustomEvent
187    */
188     startEvent: new YAHOO.util.CustomEvent('start'),
189
190   /**
191    * @description Custom event that fires when a transaction response has completed.
192    * @property completeEvent
193    * @private
194    * @static
195    * @type CustomEvent
196    */
197     completeEvent: new YAHOO.util.CustomEvent('complete'),
198
199   /**
200    * @description Custom event that fires when handleTransactionResponse() determines a
201    * response in the HTTP 2xx range.
202    * @property successEvent
203    * @private
204    * @static
205    * @type CustomEvent
206    */
207     successEvent: new YAHOO.util.CustomEvent('success'),
208
209   /**
210    * @description Custom event that fires when handleTransactionResponse() determines a
211    * response in the HTTP 4xx/5xx range.
212    * @property failureEvent
213    * @private
214    * @static
215    * @type CustomEvent
216    */
217     failureEvent: new YAHOO.util.CustomEvent('failure'),
218
219   /**
220    * @description Custom event that fires when a transaction is successfully aborted.
221    * @property abortEvent
222    * @private
223    * @static
224    * @type CustomEvent
225    */
226     abortEvent: new YAHOO.util.CustomEvent('abort'),
227
228   /**
229    * @description A reference table that maps callback custom events members to its specific
230    * event name.
231    * @property _customEvents
232    * @private
233    * @static
234    * @type object
235    */
236     _customEvents:
237     {
238         onStart:['startEvent', 'start'],
239         onComplete:['completeEvent', 'complete'],
240         onSuccess:['successEvent', 'success'],
241         onFailure:['failureEvent', 'failure'],
242         onUpload:['uploadEvent', 'upload'],
243         onAbort:['abortEvent', 'abort']
244     },
245
246   /**
247    * @description Member to add an ActiveX id to the existing xml_progid array.
248    * In the event(unlikely) a new ActiveX id is introduced, it can be added
249    * without internal code modifications.
250    * @method setProgId
251    * @public
252    * @static
253    * @param {string} id The ActiveX id to be added to initialize the XHR object.
254    * @return void
255    */
256     setProgId:function(id)
257     {
258         this._msxml_progid.unshift(id);
259     },
260
261   /**
262    * @description Member to override the default POST header.
263    * @method setDefaultPostHeader
264    * @public
265    * @static
266    * @param {boolean} b Set and use default header - true or false .
267    * @return void
268    */
269     setDefaultPostHeader:function(b)
270     {
271         if(typeof b == 'string'){
272             this._default_post_header = b;
273                         this._use_default_post_header = true;
274
275         }
276         else if(typeof b == 'boolean'){
277             this._use_default_post_header = b;
278         }
279     },
280
281   /**
282    * @description Member to override the default transaction header..
283    * @method setDefaultXhrHeader
284    * @public
285    * @static
286    * @param {boolean} b Set and use default header - true or false .
287    * @return void
288    */
289     setDefaultXhrHeader:function(b)
290     {
291         if(typeof b == 'string'){
292             this._default_xhr_header = b;
293         }
294         else{
295             this._use_default_xhr_header = b;
296         }
297     },
298
299   /**
300    * @description Member to modify the default polling interval.
301    * @method setPollingInterval
302    * @public
303    * @static
304    * @param {int} i The polling interval in milliseconds.
305    * @return void
306    */
307     setPollingInterval:function(i)
308     {
309         if(typeof i == 'number' && isFinite(i)){
310             this._polling_interval = i;
311         }
312     },
313
314   /**
315    * @description Instantiates a XMLHttpRequest object and returns an object with two properties:
316    * the XMLHttpRequest instance and the transaction id.
317    * @method createXhrObject
318    * @private
319    * @static
320    * @param {int} transactionId Property containing the transaction id for this transaction.
321    * @return object
322    */
323     createXhrObject:function(transactionId)
324     {
325         var obj,http,i;
326         try
327         {
328             // Instantiates XMLHttpRequest in non-IE browsers and assigns to http.
329             http = new XMLHttpRequest();
330             //  Object literal with http and tId properties
331             obj = { conn:http, tId:transactionId, xhr: true };
332         }
333         catch(e)
334         {
335             for(i=0; i<this._msxml_progid.length; ++i){
336                 try
337                 {
338                     // Instantiates XMLHttpRequest for IE and assign to http
339                     http = new ActiveXObject(this._msxml_progid[i]);
340                     //  Object literal with conn and tId properties
341                     obj = { conn:http, tId:transactionId, xhr: true };
342                     break;
343                 }
344                 catch(e1){}
345             }
346         }
347         finally
348         {
349             return obj;
350         }
351     },
352
353   /**
354    * @description This method is called by asyncRequest to create a
355    * valid connection object for the transaction.  It also passes a
356    * transaction id and increments the transaction id counter.
357    * @method getConnectionObject
358    * @private
359    * @static
360    * @return {object}
361    */
362     getConnectionObject:function(t)
363     {
364         var o, tId = this._transaction_id;
365
366         try
367         {
368             if(!t){
369                 o = this.createXhrObject(tId);
370             }
371             else{
372                 o = {tId:tId};
373                 if(t==='xdr'){
374                     o.conn = this._transport;
375                     o.xdr = true;
376                 }
377                 else if(t==='upload'){
378                     o.upload = true;
379                 }
380             }
381
382             if(o){
383                 this._transaction_id++;
384             }
385         }
386         catch(e){}
387         return o;
388     },
389
390   /**
391    * @description Method for initiating an asynchronous request via the XHR object.
392    * @method asyncRequest
393    * @public
394    * @static
395    * @param {string} method HTTP transaction method
396    * @param {string} uri Fully qualified path of resource
397    * @param {callback} callback User-defined callback function or object
398    * @param {string} postData POST body
399    * @return {object} Returns the connection object
400    */
401     asyncRequest:function(method, uri, callback, postData)
402     {
403         var args = callback&&callback.argument?callback.argument:null,
404             YCM = this,
405             o, t;
406
407         if(this._isFileUpload){
408             t = 'upload';
409         }
410         else if(callback && callback.xdr){
411             t = 'xdr';
412         }
413
414         o = this.getConnectionObject(t);
415         if(!o){
416             return null;
417         }
418         else{
419
420             // Intialize any transaction-specific custom events, if provided.
421             if(callback && callback.customevents){
422                 this.initCustomEvents(o, callback);
423             }
424
425             if(this._isFormSubmit){
426                 if(this._isFileUpload){
427                     window.setTimeout(function(){YCM.uploadFile(o, callback, uri, postData);}, 10);
428                     return o;
429                 }
430
431                 // If the specified HTTP method is GET, setForm() will return an
432                 // encoded string that is concatenated to the uri to
433                 // create a querystring.
434                 if(method.toUpperCase() == 'GET'){
435                     if(this._sFormData.length !== 0){
436                         // If the URI already contains a querystring, append an ampersand
437                         // and then concatenate _sFormData to the URI.
438                         uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
439                     }
440                 }
441                 else if(method.toUpperCase() == 'POST'){
442                     // If POST data exist in addition to the HTML form data,
443                     // it will be concatenated to the form data.
444                     postData = postData?this._sFormData + "&" + postData:this._sFormData;
445                 }
446             }
447
448             if(method.toUpperCase() == 'GET' && (callback && callback.cache === false)){
449                 // If callback.cache is defined and set to false, a
450                 // timestamp value will be added to the querystring.
451                 uri += ((uri.indexOf('?') == -1)?'?':'&') + "rnd=" + new Date().valueOf().toString();
452             }
453
454             // Each transaction will automatically include a custom header of
455             // "X-Requested-With: XMLHttpRequest" to identify the request as
456             // having originated from Connection Manager.
457             if(this._use_default_xhr_header){
458                 if(!this._default_headers['X-Requested-With']){
459                     this.initHeader('X-Requested-With', this._default_xhr_header, true);
460                 }
461             }
462
463             //If the transaction method is POST and the POST header value is set to true
464             //or a custom value, initalize the Content-Type header to this value.
465             if((method.toUpperCase() === 'POST' && this._use_default_post_header) && this._isFormSubmit === false){
466                 this.initHeader('Content-Type', this._default_post_header);
467             }
468
469             if(o.xdr){
470                 this.xdr(o, method, uri, callback, postData);
471                 return o;
472             }
473
474             o.conn.open(method, uri, true);
475             //Initialize all default and custom HTTP headers,
476             if(this._has_default_headers || this._has_http_headers){
477                 this.setHeader(o);
478             }
479
480             this.handleReadyState(o, callback);
481             o.conn.send(postData || '');
482
483             // Reset the HTML form data and state properties as
484             // soon as the data are submitted.
485             if(this._isFormSubmit === true){
486                 this.resetFormState();
487             }
488
489             // Fire global custom event -- startEvent
490             this.startEvent.fire(o, args);
491
492             if(o.startEvent){
493                 // Fire transaction custom event -- startEvent
494                 o.startEvent.fire(o, args);
495             }
496
497             return o;
498         }
499     },
500
501   /**
502    * @description This method creates and subscribes custom events,
503    * specific to each transaction
504    * @method initCustomEvents
505    * @private
506    * @static
507    * @param {object} o The connection object
508    * @param {callback} callback The user-defined callback object
509    * @return {void}
510    */
511     initCustomEvents:function(o, callback)
512     {
513         var prop;
514         // Enumerate through callback.customevents members and bind/subscribe
515         // events that match in the _customEvents table.
516         for(prop in callback.customevents){
517             if(this._customEvents[prop][0]){
518                 // Create the custom event
519                 o[this._customEvents[prop][0]] = new YAHOO.util.CustomEvent(this._customEvents[prop][1], (callback.scope)?callback.scope:null);
520
521                 // Subscribe the custom event
522                 o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]);
523             }
524         }
525     },
526
527   /**
528    * @description This method serves as a timer that polls the XHR object's readyState
529    * property during a transaction, instead of binding a callback to the
530    * onreadystatechange event.  Upon readyState 4, handleTransactionResponse
531    * will process the response, and the timer will be cleared.
532    * @method handleReadyState
533    * @private
534    * @static
535    * @param {object} o The connection object
536    * @param {callback} callback The user-defined callback object
537    * @return {void}
538    */
539
540     handleReadyState:function(o, callback)
541
542     {
543         var oConn = this,
544             args = (callback && callback.argument)?callback.argument:null;
545
546         if(callback && callback.timeout){
547             this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
548         }
549
550         this._poll[o.tId] = window.setInterval(
551             function(){
552                 if(o.conn && o.conn.readyState === 4){
553
554                     // Clear the polling interval for the transaction
555                     // and remove the reference from _poll.
556                     window.clearInterval(oConn._poll[o.tId]);
557                     delete oConn._poll[o.tId];
558
559                     if(callback && callback.timeout){
560                         window.clearTimeout(oConn._timeOut[o.tId]);
561                         delete oConn._timeOut[o.tId];
562                     }
563
564                     // Fire global custom event -- completeEvent
565                     oConn.completeEvent.fire(o, args);
566
567                     if(o.completeEvent){
568                         // Fire transaction custom event -- completeEvent
569                         o.completeEvent.fire(o, args);
570                     }
571
572                     oConn.handleTransactionResponse(o, callback);
573                 }
574             }
575         ,this._polling_interval);
576     },
577
578   /**
579    * @description This method attempts to interpret the server response and
580    * determine whether the transaction was successful, or if an error or
581    * exception was encountered.
582    * @method handleTransactionResponse
583    * @private
584    * @static
585    * @param {object} o The connection object
586    * @param {object} callback The user-defined callback object
587    * @param {boolean} isAbort Determines if the transaction was terminated via abort().
588    * @return {void}
589    */
590     handleTransactionResponse:function(o, callback, isAbort)
591     {
592         var httpStatus, responseObject,
593             args = (callback && callback.argument)?callback.argument:null,
594             xdrS = (o.r && o.r.statusText === 'xdr:success')?true:false,
595             xdrF = (o.r && o.r.statusText === 'xdr:failure')?true:false,
596             xdrA = isAbort;
597
598         try
599         {
600             if((o.conn.status !== undefined && o.conn.status !== 0) || xdrS){
601                 // XDR requests will not have HTTP status defined. The
602                 // statusText property will define the response status
603                 // set by the Flash transport.
604                 httpStatus = o.conn.status;
605             }
606             else if(xdrF && !xdrA){
607                 // Set XDR transaction failure to a status of 0, which
608                 // resolves as an HTTP failure, instead of an exception.
609                 httpStatus = 0;
610             }
611             else{
612                 httpStatus = 13030;
613             }
614         }
615         catch(e){
616
617              // 13030 is a custom code to indicate the condition -- in Mozilla/FF --
618              // when the XHR object's status and statusText properties are
619              // unavailable, and a query attempt throws an exception.
620             httpStatus = 13030;
621         }
622
623         if((httpStatus >= 200 && httpStatus < 300) || httpStatus === 1223 || xdrS){
624             responseObject = o.xdr ? o.r : this.createResponseObject(o, args);
625             if(callback && callback.success){
626                 if(!callback.scope){
627                     callback.success(responseObject);
628                 }
629                 else{
630                     // If a scope property is defined, the callback will be fired from
631                     // the context of the object.
632                     callback.success.apply(callback.scope, [responseObject]);
633                 }
634             }
635
636             // Fire global custom event -- successEvent
637             this.successEvent.fire(responseObject);
638
639             if(o.successEvent){
640                 // Fire transaction custom event -- successEvent
641                 o.successEvent.fire(responseObject);
642             }
643         }
644         else{
645             switch(httpStatus){
646                 // The following cases are wininet.dll error codes that may be encountered.
647                 case 12002: // Server timeout
648                 case 12029: // 12029 to 12031 correspond to dropped connections.
649                 case 12030:
650                 case 12031:
651                 case 12152: // Connection closed by server.
652                 case 13030: // See above comments for variable status.
653                     // XDR transactions will not resolve to this case, since the
654                     // response object is already built in the xdr response.
655                     responseObject = this.createExceptionObject(o.tId, args, (isAbort?isAbort:false));
656                     if(callback && callback.failure){
657                         if(!callback.scope){
658                             callback.failure(responseObject);
659                         }
660                         else{
661                             callback.failure.apply(callback.scope, [responseObject]);
662                         }
663                     }
664
665                     break;
666                 default:
667                     responseObject = (o.xdr) ? o.response : this.createResponseObject(o, args);
668                     if(callback && callback.failure){
669                         if(!callback.scope){
670                             callback.failure(responseObject);
671                         }
672                         else{
673                             callback.failure.apply(callback.scope, [responseObject]);
674                         }
675                     }
676             }
677
678             // Fire global custom event -- failureEvent
679             this.failureEvent.fire(responseObject);
680
681             if(o.failureEvent){
682                 // Fire transaction custom event -- failureEvent
683                 o.failureEvent.fire(responseObject);
684             }
685
686         }
687
688         this.releaseObject(o);
689         responseObject = null;
690     },
691
692   /**
693    * @description This method evaluates the server response, creates and returns the results via
694    * its properties.  Success and failure cases will differ in the response
695    * object's property values.
696    * @method createResponseObject
697    * @private
698    * @static
699    * @param {object} o The connection object
700    * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
701    * @return {object}
702    */
703     createResponseObject:function(o, callbackArg)
704     {
705         var obj = {}, headerObj = {},
706             i, headerStr, header, delimitPos;
707
708         try
709         {
710             headerStr = o.conn.getAllResponseHeaders();
711             header = headerStr.split('\n');
712             for(i=0; i<header.length; i++){
713                 delimitPos = header[i].indexOf(':');
714                 if(delimitPos != -1){
715                     headerObj[header[i].substring(0,delimitPos)] = YAHOO.lang.trim(header[i].substring(delimitPos+2));
716                 }
717             }
718         }
719         catch(e){}
720
721         obj.tId = o.tId;
722         // Normalize IE's response to HTTP 204 when Win error 1223.
723         obj.status = (o.conn.status == 1223)?204:o.conn.status;
724         // Normalize IE's statusText to "No Content" instead of "Unknown".
725         obj.statusText = (o.conn.status == 1223)?"No Content":o.conn.statusText;
726         obj.getResponseHeader = headerObj;
727         obj.getAllResponseHeaders = headerStr;
728         obj.responseText = o.conn.responseText;
729         obj.responseXML = o.conn.responseXML;
730
731         if(callbackArg){
732             obj.argument = callbackArg;
733         }
734
735         return obj;
736     },
737
738   /**
739    * @description If a transaction cannot be completed due to dropped or closed connections,
740    * there may be not be enough information to build a full response object.
741    * The failure callback will be fired and this specific condition can be identified
742    * by a status property value of 0.
743    *
744    * If an abort was successful, the status property will report a value of -1.
745    *
746    * @method createExceptionObject
747    * @private
748    * @static
749    * @param {int} tId The Transaction Id
750    * @param {callbackArg} callbackArg The user-defined argument or arguments to be passed to the callback
751    * @param {boolean} isAbort Determines if the exception case is caused by a transaction abort
752    * @return {object}
753    */
754     createExceptionObject:function(tId, callbackArg, isAbort)
755     {
756         var COMM_CODE = 0,
757             COMM_ERROR = 'communication failure',
758             ABORT_CODE = -1,
759             ABORT_ERROR = 'transaction aborted',
760             obj = {};
761
762         obj.tId = tId;
763         if(isAbort){
764             obj.status = ABORT_CODE;
765             obj.statusText = ABORT_ERROR;
766         }
767         else{
768             obj.status = COMM_CODE;
769             obj.statusText = COMM_ERROR;
770         }
771
772         if(callbackArg){
773             obj.argument = callbackArg;
774         }
775
776         return obj;
777     },
778
779   /**
780    * @description Method that initializes the custom HTTP headers for the each transaction.
781    * @method initHeader
782    * @public
783    * @static
784    * @param {string} label The HTTP header label
785    * @param {string} value The HTTP header value
786    * @param {string} isDefault Determines if the specific header is a default header
787    * automatically sent with each transaction.
788    * @return {void}
789    */
790     initHeader:function(label, value, isDefault)
791     {
792         var headerObj = (isDefault)?this._default_headers:this._http_headers;
793
794         headerObj[label] = value;
795         if(isDefault){
796             this._has_default_headers = true;
797         }
798         else{
799             this._has_http_headers = true;
800         }
801     },
802
803
804   /**
805    * @description Accessor that sets the HTTP headers for each transaction.
806    * @method setHeader
807    * @private
808    * @static
809    * @param {object} o The connection object for the transaction.
810    * @return {void}
811    */
812     setHeader:function(o)
813     {
814         var prop;
815         if(this._has_default_headers){
816             for(prop in this._default_headers){
817                 if(YAHOO.lang.hasOwnProperty(this._default_headers, prop)){
818                     o.conn.setRequestHeader(prop, this._default_headers[prop]);
819                 }
820             }
821         }
822
823         if(this._has_http_headers){
824             for(prop in this._http_headers){
825                 if(YAHOO.lang.hasOwnProperty(this._http_headers, prop)){
826                     o.conn.setRequestHeader(prop, this._http_headers[prop]);
827                 }
828             }
829
830             this._http_headers = {};
831             this._has_http_headers = false;
832         }
833     },
834
835   /**
836    * @description Resets the default HTTP headers object
837    * @method resetDefaultHeaders
838    * @public
839    * @static
840    * @return {void}
841    */
842     resetDefaultHeaders:function(){
843         this._default_headers = {};
844         this._has_default_headers = false;
845     },
846
847   /**
848    * @description Method to terminate a transaction, if it has not reached readyState 4.
849    * @method abort
850    * @public
851    * @static
852    * @param {object} o The connection object returned by asyncRequest.
853    * @param {object} callback  User-defined callback object.
854    * @param {string} isTimeout boolean to indicate if abort resulted from a callback timeout.
855    * @return {boolean}
856    */
857     abort:function(o, callback, isTimeout)
858     {
859         var abortStatus,
860             args = (callback && callback.argument)?callback.argument:null;
861             o = o || {};
862
863         if(o.conn){
864             if(o.xhr){
865                 if(this.isCallInProgress(o)){
866                     // Issue abort request
867                     o.conn.abort();
868
869                     window.clearInterval(this._poll[o.tId]);
870                     delete this._poll[o.tId];
871
872                     if(isTimeout){
873                         window.clearTimeout(this._timeOut[o.tId]);
874                         delete this._timeOut[o.tId];
875                     }
876
877                     abortStatus = true;
878                 }
879             }
880             else if(o.xdr){
881                 o.conn.abort(o.tId);
882                 abortStatus = true;
883             }
884         }
885         else if(o.upload){
886             var frameId = 'yuiIO' + o.tId;
887             var io = document.getElementById(frameId);
888
889             if(io){
890                 // Remove all listeners on the iframe prior to
891                 // its destruction.
892                 YAHOO.util.Event.removeListener(io, "load");
893                 // Destroy the iframe facilitating the transaction.
894                 document.body.removeChild(io);
895
896                 if(isTimeout){
897                     window.clearTimeout(this._timeOut[o.tId]);
898                     delete this._timeOut[o.tId];
899                 }
900
901                 abortStatus = true;
902             }
903         }
904         else{
905             abortStatus = false;
906         }
907
908         if(abortStatus === true){
909             // Fire global custom event -- abortEvent
910             this.abortEvent.fire(o, args);
911
912             if(o.abortEvent){
913                 // Fire transaction custom event -- abortEvent
914                 o.abortEvent.fire(o, args);
915             }
916
917             this.handleTransactionResponse(o, callback, true);
918         }
919
920         return abortStatus;
921     },
922
923   /**
924    * @description Determines if the transaction is still being processed.
925    * @method isCallInProgress
926    * @public
927    * @static
928    * @param {object} o The connection object returned by asyncRequest
929    * @return {boolean}
930    */
931     isCallInProgress:function(o)
932     {
933         o = o || {};
934         // if the XHR object assigned to the transaction has not been dereferenced,
935         // then check its readyState status.  Otherwise, return false.
936         if(o.xhr && o.conn){
937             return o.conn.readyState !== 4 && o.conn.readyState !== 0;
938         }
939         else if(o.xdr && o.conn){
940             return o.conn.isCallInProgress(o.tId);
941         }
942         else if(o.upload === true){
943             return document.getElementById('yuiIO' + o.tId)?true:false;
944         }
945         else{
946             return false;
947         }
948     },
949
950   /**
951    * @description Dereference the XHR instance and the connection object after the transaction is completed.
952    * @method releaseObject
953    * @private
954    * @static
955    * @param {object} o The connection object
956    * @return {void}
957    */
958     releaseObject:function(o)
959     {
960         if(o && o.conn){
961             //dereference the XHR instance.
962             o.conn = null;
963
964
965             //dereference the connection object.
966             o = null;
967         }
968     }
969 };
970
971 /**
972   * @for YAHOO.util.Connect
973   */
974 (function() {
975         var YCM = YAHOO.util.Connect, _fn = {};
976
977    /**
978     * @description This method creates and instantiates the Flash transport.
979     * @method _swf
980     * @private
981     * @static
982     * @param {string} URI to connection.swf.
983     * @return {void}
984     */
985         function _swf(uri) {
986                 var o = '<object id="YUIConnectionSwf" type="application/x-shockwave-flash" data="' +
987                                 uri + '" width="0" height="0">' +
988                                 '<param name="movie" value="' + uri + '">' +
989                                 '<param name="allowScriptAccess" value="always">' +
990                                 '</object>',
991                     c = document.createElement('div');
992
993                 document.body.appendChild(c);
994                 c.innerHTML = o;
995         }
996
997    /**
998     * @description This method calls the public method on the
999     * Flash transport to start the XDR transaction.  It is analogous
1000     * to Connection Manager's asyncRequest method.
1001     * @method xdr
1002     * @private
1003     * @static
1004     * @param {object} The transaction object.
1005     * @param {string} HTTP request method.
1006     * @param {string} URI for the transaction.
1007     * @param {object} The transaction's callback object.
1008     * @param {object} The JSON object used as HTTP POST data.
1009     * @return {void}
1010     */
1011         function _xdr(o, m, u, c, d) {
1012                 _fn[parseInt(o.tId)] = { 'o':o, 'c':c };
1013                 if (d) {
1014                         c.method = m;
1015                         c.data = d;
1016                 }
1017
1018                 o.conn.send(u, c, o.tId);
1019         }
1020
1021    /**
1022     * @description This method instantiates the Flash transport and
1023     * establishes a static reference to it, used for all XDR requests.
1024     * @method transport
1025     * @public
1026     * @static
1027     * @param {string} URI to connection.swf.
1028     * @return {void}
1029     */
1030         function _init(uri) {
1031                 _swf(uri);
1032                 YCM._transport = document.getElementById('YUIConnectionSwf');
1033         }
1034
1035         function _xdrReady() {
1036                 YCM.xdrReadyEvent.fire();
1037         }
1038
1039    /**
1040     * @description This method fires the global and transaction start
1041     * events.
1042     * @method _xdrStart
1043     * @private
1044     * @static
1045     * @param {object} The transaction object.
1046     * @param {string} The transaction's callback object.
1047     * @return {void}
1048     */
1049         function _xdrStart(o, cb) {
1050                 if (o) {
1051                         // Fire global custom event -- startEvent
1052                         YCM.startEvent.fire(o, cb.argument);
1053
1054                         if(o.startEvent){
1055                                 // Fire transaction custom event -- startEvent
1056                                 o.startEvent.fire(o, cb.argument);
1057                         }
1058                 }
1059         }
1060
1061    /**
1062     * @description This method is the initial response handler
1063     * for XDR transactions.  The Flash transport calls this
1064     * function and sends the response payload.
1065     * @method handleXdrResponse
1066     * @private
1067     * @static
1068     * @param {object} The response object sent from the Flash transport.
1069     * @return {void}
1070     */
1071         function _handleXdrResponse(r) {
1072                 var o = _fn[r.tId].o,
1073                         cb = _fn[r.tId].c;
1074
1075                 if (r.statusText === 'xdr:start') {
1076                         _xdrStart(o, cb);
1077                         return;
1078                 }
1079
1080                 r.responseText = decodeURI(r.responseText);
1081                 o.r = r;
1082                 if (cb.argument) {
1083                         o.r.argument = cb.argument;
1084                 }
1085
1086                 this.handleTransactionResponse(o, cb, r.statusText === 'xdr:abort' ? true : false);
1087                 delete _fn[r.tId];
1088         }
1089
1090         // Bind the functions to Connection Manager as static fields.
1091         YCM.xdr = _xdr;
1092         YCM.swf = _swf;
1093         YCM.transport = _init;
1094         YCM.xdrReadyEvent = new YAHOO.util.CustomEvent('xdrReady');
1095         YCM.xdrReady = _xdrReady;
1096         YCM.handleXdrResponse = _handleXdrResponse;
1097 })();
1098
1099 /**
1100   * @for YAHOO.util.Connect
1101   */
1102 (function(){
1103         var YCM = YAHOO.util.Connect,
1104                 YE = YAHOO.util.Event,
1105                 dM = document.documentMode ? document.documentMode : false;
1106
1107    /**
1108         * @description Property modified by setForm() to determine if a file(s)
1109         * upload is expected.
1110         * @property _isFileUpload
1111         * @private
1112         * @static
1113         * @type boolean
1114         */
1115         YCM._isFileUpload = false;
1116
1117    /**
1118         * @description Property modified by setForm() to set a reference to the HTML
1119         * form node if the desired action is file upload.
1120         * @property _formNode
1121         * @private
1122         * @static
1123         * @type object
1124         */
1125         YCM._formNode = null;
1126
1127    /**
1128         * @description Property modified by setForm() to set the HTML form data
1129         * for each transaction.
1130         * @property _sFormData
1131         * @private
1132         * @static
1133         * @type string
1134         */
1135         YCM._sFormData = null;
1136
1137    /**
1138         * @description Tracks the name-value pair of the "clicked" submit button if multiple submit
1139         * buttons are present in an HTML form; and, if YAHOO.util.Event is available.
1140         * @property _submitElementValue
1141         * @private
1142         * @static
1143         * @type string
1144         */
1145         YCM._submitElementValue = null;
1146
1147    /**
1148     * @description Custom event that fires when handleTransactionResponse() determines a
1149     * response in the HTTP 4xx/5xx range.
1150     * @property failureEvent
1151     * @private
1152     * @static
1153     * @type CustomEvent
1154     */
1155         YCM.uploadEvent = new YAHOO.util.CustomEvent('upload');
1156
1157    /**
1158         * @description Determines whether YAHOO.util.Event is available and returns true or false.
1159         * If true, an event listener is bound at the document level to trap click events that
1160         * resolve to a target type of "Submit".  This listener will enable setForm() to determine
1161         * the clicked "Submit" value in a multi-Submit button, HTML form.
1162         * @property _hasSubmitListener
1163         * @private
1164         * @static
1165         */
1166         YCM._hasSubmitListener = function() {
1167                 if(YE){
1168                         YE.addListener(
1169                                 document,
1170                                 'click',
1171                                 function(e){
1172                                         var obj = YE.getTarget(e),
1173                                                 name = obj.nodeName.toLowerCase();
1174
1175                                         if((name === 'input' || name === 'button') && (obj.type && obj.type.toLowerCase() == 'submit')){
1176                                                 YCM._submitElementValue = encodeURIComponent(obj.name) + "=" + encodeURIComponent(obj.value);
1177                                         }
1178                                 });
1179                         return true;
1180                 }
1181                 return false;
1182         }();
1183
1184   /**
1185    * @description This method assembles the form label and value pairs and
1186    * constructs an encoded string.
1187    * asyncRequest() will automatically initialize the transaction with a
1188    * a HTTP header Content-Type of application/x-www-form-urlencoded.
1189    * @method setForm
1190    * @public
1191    * @static
1192    * @param {string || object} form id or name attribute, or form object.
1193    * @param {boolean} optional enable file upload.
1194    * @param {boolean} optional enable file upload over SSL in IE only.
1195    * @return {string} string of the HTML form field name and value pairs..
1196    */
1197         function _setForm(formId, isUpload, secureUri)
1198         {
1199                 var oForm, oElement, oName, oValue, oDisabled,
1200                         hasSubmit = false,
1201                         data = [], item = 0,
1202                         i,len,j,jlen,opt;
1203
1204                 this.resetFormState();
1205
1206                 if(typeof formId == 'string'){
1207                         // Determine if the argument is a form id or a form name.
1208                         // Note form name usage is deprecated by supported
1209                         // here for legacy reasons.
1210                         oForm = (document.getElementById(formId) || document.forms[formId]);
1211                 }
1212                 else if(typeof formId == 'object'){
1213                         // Treat argument as an HTML form object.
1214                         oForm = formId;
1215                 }
1216                 else{
1217                         return;
1218                 }
1219
1220                 // If the isUpload argument is true, setForm will call createFrame to initialize
1221                 // an iframe as the form target.
1222                 //
1223                 // The argument secureURI is also required by IE in SSL environments
1224                 // where the secureURI string is a fully qualified HTTP path, used to set the source
1225                 // of the iframe, to a stub resource in the same domain.
1226                 if(isUpload){
1227
1228                         // Create iframe in preparation for file upload.
1229                         this.createFrame(secureUri?secureUri:null);
1230
1231                         // Set form reference and file upload properties to true.
1232                         this._isFormSubmit = true;
1233                         this._isFileUpload = true;
1234                         this._formNode = oForm;
1235
1236                         return;
1237                 }
1238
1239                 // Iterate over the form elements collection to construct the
1240                 // label-value pairs.
1241                 for (i=0,len=oForm.elements.length; i<len; ++i){
1242                         oElement  = oForm.elements[i];
1243                         oDisabled = oElement.disabled;
1244                         oName     = oElement.name;
1245
1246                         // Do not submit fields that are disabled or
1247                         // do not have a name attribute value.
1248                         if(!oDisabled && oName)
1249                         {
1250                                 oName  = encodeURIComponent(oName)+'=';
1251                                 oValue = encodeURIComponent(oElement.value);
1252
1253                                 switch(oElement.type)
1254                                 {
1255                                         // Safari, Opera, FF all default opt.value from .text if
1256                                         // value attribute not specified in markup
1257                                         case 'select-one':
1258                                                 if (oElement.selectedIndex > -1) {
1259                                                         opt = oElement.options[oElement.selectedIndex];
1260                                                         data[item++] = oName + encodeURIComponent(
1261                                                                 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1262                                                 }
1263                                                 break;
1264                                         case 'select-multiple':
1265                                                 if (oElement.selectedIndex > -1) {
1266                                                         for(j=oElement.selectedIndex, jlen=oElement.options.length; j<jlen; ++j){
1267                                                                 opt = oElement.options[j];
1268                                                                 if (opt.selected) {
1269                                                                         data[item++] = oName + encodeURIComponent(
1270                                                                                 (opt.attributes.value && opt.attributes.value.specified) ? opt.value : opt.text);
1271                                                                 }
1272                                                         }
1273                                                 }
1274                                                 break;
1275                                         case 'radio':
1276                                         case 'checkbox':
1277                                                 if(oElement.checked){
1278                                                         data[item++] = oName + oValue;
1279                                                 }
1280                                                 break;
1281                                         case 'file':
1282                                                 // stub case as XMLHttpRequest will only send the file path as a string.
1283                                         case undefined:
1284                                                 // stub case for fieldset element which returns undefined.
1285                                         case 'reset':
1286                                                 // stub case for input type reset button.
1287                                         case 'button':
1288                                                 // stub case for input type button elements.
1289                                                 break;
1290                                         case 'submit':
1291                                                 if(hasSubmit === false){
1292                                                         if(this._hasSubmitListener && this._submitElementValue){
1293                                                                 data[item++] = this._submitElementValue;
1294                                                         }
1295                                                         hasSubmit = true;
1296                                                 }
1297                                                 break;
1298                                         default:
1299                                                 data[item++] = oName + oValue;
1300                                 }
1301                         }
1302                 }
1303
1304                 this._isFormSubmit = true;
1305                 this._sFormData = data.join('&');
1306
1307
1308                 this.initHeader('Content-Type', this._default_form_header);
1309
1310                 return this._sFormData;
1311         }
1312
1313    /**
1314     * @description Resets HTML form properties when an HTML form or HTML form
1315     * with file upload transaction is sent.
1316     * @method resetFormState
1317     * @private
1318     * @static
1319     * @return {void}
1320     */
1321         function _resetFormState(){
1322                 this._isFormSubmit = false;
1323                 this._isFileUpload = false;
1324                 this._formNode = null;
1325                 this._sFormData = "";
1326         }
1327
1328
1329    /**
1330     * @description Creates an iframe to be used for form file uploads.  It is remove from the
1331     * document upon completion of the upload transaction.
1332     * @method createFrame
1333     * @private
1334     * @static
1335     * @param {string} optional qualified path of iframe resource for SSL in IE.
1336     * @return {void}
1337     */
1338         function _createFrame(secureUri){
1339
1340                 // IE does not allow the setting of id and name attributes as object
1341                 // properties via createElement().  A different iframe creation
1342                 // pattern is required for IE.
1343                 var frameId = 'yuiIO' + this._transaction_id,
1344                         ie9 = (dM === 9) ? true : false,
1345                         io;
1346
1347                 if(YAHOO.env.ua.ie && !ie9){
1348                         io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
1349
1350                         // IE will throw a security exception in an SSL environment if the
1351                         // iframe source is undefined.
1352                         if(typeof secureUri == 'boolean'){
1353                                 io.src = 'javascript:false';
1354                         }
1355                 }
1356                 else{
1357                         io = document.createElement('iframe');
1358                         io.id = frameId;
1359                         io.name = frameId;
1360                 }
1361
1362                 io.style.position = 'absolute';
1363                 io.style.top = '-1000px';
1364                 io.style.left = '-1000px';
1365
1366                 document.body.appendChild(io);
1367         }
1368
1369    /**
1370     * @description Parses the POST data and creates hidden form elements
1371     * for each key-value, and appends them to the HTML form object.
1372     * @method appendPostData
1373     * @private
1374     * @static
1375     * @param {string} postData The HTTP POST data
1376     * @return {array} formElements Collection of hidden fields.
1377     */
1378         function _appendPostData(postData){
1379                 var formElements = [],
1380                         postMessage = postData.split('&'),
1381                         i, delimitPos;
1382
1383                 for(i=0; i < postMessage.length; i++){
1384                         delimitPos = postMessage[i].indexOf('=');
1385                         if(delimitPos != -1){
1386                                 formElements[i] = document.createElement('input');
1387                                 formElements[i].type = 'hidden';
1388                                 formElements[i].name = decodeURIComponent(postMessage[i].substring(0,delimitPos));
1389                                 formElements[i].value = decodeURIComponent(postMessage[i].substring(delimitPos+1));
1390                                 this._formNode.appendChild(formElements[i]);
1391                         }
1392                 }
1393
1394                 return formElements;
1395         }
1396
1397    /**
1398     * @description Uploads HTML form, inclusive of files/attachments, using the
1399     * iframe created in createFrame to facilitate the transaction.
1400     * @method uploadFile
1401     * @private
1402     * @static
1403     * @param {int} id The transaction id.
1404     * @param {object} callback User-defined callback object.
1405     * @param {string} uri Fully qualified path of resource.
1406     * @param {string} postData POST data to be submitted in addition to HTML form.
1407     * @return {void}
1408     */
1409         function _uploadFile(o, callback, uri, postData){
1410                 // Each iframe has an id prefix of "yuiIO" followed
1411                 // by the unique transaction id.
1412                 var frameId = 'yuiIO' + o.tId,
1413                     uploadEncoding = 'multipart/form-data',
1414                     io = document.getElementById(frameId),
1415                     ie8 = (dM >= 8) ? true : false,
1416                     oConn = this,
1417                         args = (callback && callback.argument)?callback.argument:null,
1418             oElements,i,prop,obj, rawFormAttributes, uploadCallback;
1419
1420                 // Track original HTML form attribute values.
1421                 rawFormAttributes = {
1422                         action:this._formNode.getAttribute('action'),
1423                         method:this._formNode.getAttribute('method'),
1424                         target:this._formNode.getAttribute('target')
1425                 };
1426
1427                 // Initialize the HTML form properties in case they are
1428                 // not defined in the HTML form.
1429                 this._formNode.setAttribute('action', uri);
1430                 this._formNode.setAttribute('method', 'POST');
1431                 this._formNode.setAttribute('target', frameId);
1432
1433                 if(YAHOO.env.ua.ie && !ie8){
1434                         // IE does not respect property enctype for HTML forms.
1435                         // Instead it uses the property - "encoding".
1436                         this._formNode.setAttribute('encoding', uploadEncoding);
1437                 }
1438                 else{
1439                         this._formNode.setAttribute('enctype', uploadEncoding);
1440                 }
1441
1442                 if(postData){
1443                         oElements = this.appendPostData(postData);
1444                 }
1445
1446                 // Start file upload.
1447                 this._formNode.submit();
1448
1449                 // Fire global custom event -- startEvent
1450                 this.startEvent.fire(o, args);
1451
1452                 if(o.startEvent){
1453                         // Fire transaction custom event -- startEvent
1454                         o.startEvent.fire(o, args);
1455                 }
1456
1457                 // Start polling if a callback is present and the timeout
1458                 // property has been defined.
1459                 if(callback && callback.timeout){
1460                         this._timeOut[o.tId] = window.setTimeout(function(){ oConn.abort(o, callback, true); }, callback.timeout);
1461                 }
1462
1463                 // Remove HTML elements created by appendPostData
1464                 if(oElements && oElements.length > 0){
1465                         for(i=0; i < oElements.length; i++){
1466                                 this._formNode.removeChild(oElements[i]);
1467                         }
1468                 }
1469
1470                 // Restore HTML form attributes to their original
1471                 // values prior to file upload.
1472                 for(prop in rawFormAttributes){
1473                         if(YAHOO.lang.hasOwnProperty(rawFormAttributes, prop)){
1474                                 if(rawFormAttributes[prop]){
1475                                         this._formNode.setAttribute(prop, rawFormAttributes[prop]);
1476                                 }
1477                                 else{
1478                                         this._formNode.removeAttribute(prop);
1479                                 }
1480                         }
1481                 }
1482
1483                 // Reset HTML form state properties.
1484                 this.resetFormState();
1485
1486                 // Create the upload callback handler that fires when the iframe
1487                 // receives the load event.  Subsequently, the event handler is detached
1488                 // and the iframe removed from the document.
1489                 uploadCallback = function() {
1490                         var body, pre, text;
1491
1492                         if(callback && callback.timeout){
1493                                 window.clearTimeout(oConn._timeOut[o.tId]);
1494                                 delete oConn._timeOut[o.tId];
1495                         }
1496
1497                         // Fire global custom event -- completeEvent
1498                         oConn.completeEvent.fire(o, args);
1499
1500                         if(o.completeEvent){
1501                                 // Fire transaction custom event -- completeEvent
1502                                 o.completeEvent.fire(o, args);
1503                         }
1504
1505                         obj = {
1506                             tId : o.tId,
1507                             argument : args
1508             };
1509
1510                         try
1511                         {
1512                                 body = io.contentWindow.document.getElementsByTagName('body')[0];
1513                                 pre = io.contentWindow.document.getElementsByTagName('pre')[0];
1514
1515                                 if (body) {
1516                                         if (pre) {
1517                                                 text = pre.textContent?pre.textContent:pre.innerText;
1518                                         }
1519                                         else {
1520                                                 text = body.textContent?body.textContent:body.innerText;
1521                                         }
1522                                 }
1523                                 obj.responseText = text;
1524                                 // responseText and responseXML will be populated with the same data from the iframe.
1525                                 // Since the HTTP headers cannot be read from the iframe
1526                                 obj.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
1527                         }
1528                         catch(e){}
1529
1530                         if(callback && callback.upload){
1531                                 if(!callback.scope){
1532                                         callback.upload(obj);
1533                                 }
1534                                 else{
1535                                         callback.upload.apply(callback.scope, [obj]);
1536                                 }
1537                         }
1538
1539                         // Fire global custom event -- uploadEvent
1540                         oConn.uploadEvent.fire(obj);
1541
1542                         if(o.uploadEvent){
1543                                 // Fire transaction custom event -- uploadEvent
1544                                 o.uploadEvent.fire(obj);
1545                         }
1546
1547                         YE.removeListener(io, "load", uploadCallback);
1548
1549                         setTimeout(
1550                                 function(){
1551                                         document.body.removeChild(io);
1552                                         oConn.releaseObject(o);
1553                                 }, 100);
1554                 };
1555
1556                 // Bind the onload handler to the iframe to detect the file upload response.
1557                 YE.addListener(io, "load", uploadCallback);
1558         }
1559
1560         YCM.setForm = _setForm;
1561         YCM.resetFormState = _resetFormState;
1562         YCM.createFrame = _createFrame;
1563         YCM.appendPostData = _appendPostData;
1564         YCM.uploadFile = _uploadFile;
1565 })();
1566
1567 YAHOO.register("connection", YAHOO.util.Connect, {version: "2.9.0", build: "2800"});