]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/yui3/build/event/event-base.js
Release 6.5.0
[Github/sugarcrm.git] / jssource / src_files / include / javascript / yui3 / build / event / event-base.js
1 /*
2 Copyright (c) 2010, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.com/yui/license.html
5 version: 3.3.0
6 build: 3167
7 */
8 var GLOBAL_ENV = YUI.Env;
9
10 if (!GLOBAL_ENV._ready) {
11     GLOBAL_ENV._ready = function() {
12         GLOBAL_ENV.DOMReady = true;
13         GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
14     };
15
16     // if (!YUI.UA.ie) {
17         GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready);
18     // }
19 }
20
21 YUI.add('event-base', function(Y) {
22
23 /*
24  * DOM event listener abstraction layer
25  * @module event
26  * @submodule event-base
27  */
28
29 /**
30  * The domready event fires at the moment the browser's DOM is
31  * usable. In most cases, this is before images are fully
32  * downloaded, allowing you to provide a more responsive user
33  * interface.
34  *
35  * In YUI 3, domready subscribers will be notified immediately if
36  * that moment has already passed when the subscription is created.
37  *
38  * One exception is if the yui.js file is dynamically injected into
39  * the page.  If this is done, you must tell the YUI instance that
40  * you did this in order for DOMReady (and window load events) to
41  * fire normally.  That configuration option is 'injected' -- set
42  * it to true if the yui.js script is not included inline.
43  *
44  * This method is part of the 'event-ready' module, which is a
45  * submodule of 'event'.
46  *
47  * @event domready
48  * @for YUI
49  */
50 Y.publish('domready', {
51     fireOnce: true,
52     async: true
53 });
54
55 if (GLOBAL_ENV.DOMReady) {
56     Y.fire('domready');
57 } else {
58     Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready');
59 }
60
61 /**
62  * Custom event engine, DOM event listener abstraction layer, synthetic DOM
63  * events.
64  * @module event
65  * @submodule event-base
66  */
67
68 /**
69  * Wraps a DOM event, properties requiring browser abstraction are
70  * fixed here.  Provids a security layer when required.
71  * @class DOMEventFacade
72  * @param ev {Event} the DOM event
73  * @param currentTarget {HTMLElement} the element the listener was attached to
74  * @param wrapper {Event.Custom} the custom event wrapper for this DOM event
75  */
76
77     var ua = Y.UA,
78
79     EMPTY = {},
80
81     /**
82      * webkit key remapping required for Safari < 3.1
83      * @property webkitKeymap
84      * @private
85      */
86     webkitKeymap = {
87         63232: 38, // up
88         63233: 40, // down
89         63234: 37, // left
90         63235: 39, // right
91         63276: 33, // page up
92         63277: 34, // page down
93         25:     9, // SHIFT-TAB (Safari provides a different key code in
94                    // this case, even though the shiftKey modifier is set)
95         63272: 46, // delete
96         63273: 36, // home
97         63275: 35  // end
98     },
99
100     /**
101      * Returns a wrapped node.  Intended to be used on event targets,
102      * so it will return the node's parent if the target is a text
103      * node.
104      *
105      * If accessing a property of the node throws an error, this is
106      * probably the anonymous div wrapper Gecko adds inside text
107      * nodes.  This likely will only occur when attempting to access
108      * the relatedTarget.  In this case, we now return null because
109      * the anonymous div is completely useless and we do not know
110      * what the related target was because we can't even get to
111      * the element's parent node.
112      *
113      * @method resolve
114      * @private
115      */
116     resolve = function(n) {
117         if (!n) {
118             return n;
119         }
120         try {
121             if (n && 3 == n.nodeType) {
122                 n = n.parentNode;
123             }
124         } catch(e) {
125             return null;
126         }
127
128         return Y.one(n);
129     },
130
131     DOMEventFacade = function(ev, currentTarget, wrapper) {
132         this._event = ev;
133         this._currentTarget = currentTarget;
134         this._wrapper = wrapper || EMPTY;
135
136         // if not lazy init
137         this.init();
138     };
139
140 Y.extend(DOMEventFacade, Object, {
141
142     init: function() {
143
144         var e = this._event,
145             overrides = this._wrapper.overrides,
146             x = e.pageX,
147             y = e.pageY,
148             c,
149             currentTarget = this._currentTarget;
150
151         this.altKey   = e.altKey;
152         this.ctrlKey  = e.ctrlKey;
153         this.metaKey  = e.metaKey;
154         this.shiftKey = e.shiftKey;
155         this.type     = (overrides && overrides.type) || e.type;
156         this.clientX  = e.clientX;
157         this.clientY  = e.clientY;
158
159         this.pageX = x;
160         this.pageY = y;
161
162         c = e.keyCode || e.charCode;
163
164         if (ua.webkit && (c in webkitKeymap)) {
165             c = webkitKeymap[c];
166         }
167
168         this.keyCode = c;
169         this.charCode = c;
170         this.which = e.which || e.charCode || c;
171         // this.button = e.button;
172         this.button = this.which;
173
174         this.target = resolve(e.target);
175         this.currentTarget = resolve(currentTarget);
176         this.relatedTarget = resolve(e.relatedTarget);
177
178         if (e.type == "mousewheel" || e.type == "DOMMouseScroll") {
179             this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1);
180         }
181
182         if (this._touch) {
183             this._touch(e, currentTarget, this._wrapper);
184         }
185     },
186
187     stopPropagation: function() {
188         this._event.stopPropagation();
189         this._wrapper.stopped = 1;
190         this.stopped = 1;
191     },
192
193     stopImmediatePropagation: function() {
194         var e = this._event;
195         if (e.stopImmediatePropagation) {
196             e.stopImmediatePropagation();
197         } else {
198             this.stopPropagation();
199         }
200         this._wrapper.stopped = 2;
201         this.stopped = 2;
202     },
203
204     preventDefault: function(returnValue) {
205         var e = this._event;
206         e.preventDefault();
207         e.returnValue = returnValue || false;
208         this._wrapper.prevented = 1;
209         this.prevented = 1;
210     },
211
212     halt: function(immediate) {
213         if (immediate) {
214             this.stopImmediatePropagation();
215         } else {
216             this.stopPropagation();
217         }
218
219         this.preventDefault();
220     }
221
222 });
223
224 DOMEventFacade.resolve = resolve;
225 Y.DOM2EventFacade = DOMEventFacade;
226 Y.DOMEventFacade = DOMEventFacade;
227
228     /**
229      * The native event
230      * @property _event
231      */
232
233     /**
234      * The X location of the event on the page (including scroll)
235      * @property pageX
236      * @type int
237      */
238
239     /**
240      * The Y location of the event on the page (including scroll)
241      * @property pageY
242      * @type int
243      */
244
245     /**
246      * The keyCode for key events.  Uses charCode if keyCode is not available
247      * @property keyCode
248      * @type int
249      */
250
251     /**
252      * The charCode for key events.  Same as keyCode
253      * @property charCode
254      * @type int
255      */
256
257     /**
258      * The button that was pushed.
259      * @property button
260      * @type int
261      */
262
263     /**
264      * The button that was pushed.  Same as button.
265      * @property which
266      * @type int
267      */
268
269     /**
270      * Node reference for the targeted element
271      * @propery target
272      * @type Node
273      */
274
275     /**
276      * Node reference for the element that the listener was attached to.
277      * @propery currentTarget
278      * @type Node
279      */
280
281     /**
282      * Node reference to the relatedTarget
283      * @propery relatedTarget
284      * @type Node
285      */
286
287     /**
288      * Number representing the direction and velocity of the movement of the mousewheel.
289      * Negative is down, the higher the number, the faster.  Applies to the mousewheel event.
290      * @property wheelDelta
291      * @type int
292      */
293
294     /**
295      * Stops the propagation to the next bubble target
296      * @method stopPropagation
297      */
298
299     /**
300      * Stops the propagation to the next bubble target and
301      * prevents any additional listeners from being exectued
302      * on the current target.
303      * @method stopImmediatePropagation
304      */
305
306     /**
307      * Prevents the event's default behavior
308      * @method preventDefault
309      * @param returnValue {string} sets the returnValue of the event to this value
310      * (rather than the default false value).  This can be used to add a customized
311      * confirmation query to the beforeunload event).
312      */
313
314     /**
315      * Stops the event propagation and prevents the default
316      * event behavior.
317      * @method halt
318      * @param immediate {boolean} if true additional listeners
319      * on the current target will not be executed
320      */
321 (function() {
322 /**
323  * DOM event listener abstraction layer
324  * @module event
325  * @submodule event-base
326  */
327
328 /**
329  * The event utility provides functions to add and remove event listeners,
330  * event cleansing.  It also tries to automatically remove listeners it
331  * registers during the unload event.
332  *
333  * @class Event
334  * @static
335  */
336
337 Y.Env.evt.dom_wrappers = {};
338 Y.Env.evt.dom_map = {};
339
340 var _eventenv = Y.Env.evt,
341     config = Y.config,
342     win = config.win,
343     add = YUI.Env.add,
344     remove = YUI.Env.remove,
345
346     onLoad = function() {
347         YUI.Env.windowLoaded = true;
348         Y.Event._load();
349         remove(win, "load", onLoad);
350     },
351
352     onUnload = function() {
353         Y.Event._unload();
354     },
355
356     EVENT_READY = 'domready',
357
358     COMPAT_ARG = '~yui|2|compat~',
359
360     shouldIterate = function(o) {
361         try {
362             return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) &&
363                     !o.tagName && !o.alert);
364         } catch(ex) {
365             return false;
366         }
367
368     },
369
370 Event = function() {
371
372     /**
373      * True after the onload event has fired
374      * @property _loadComplete
375      * @type boolean
376      * @static
377      * @private
378      */
379     var _loadComplete =  false,
380
381     /**
382      * The number of times to poll after window.onload.  This number is
383      * increased if additional late-bound handlers are requested after
384      * the page load.
385      * @property _retryCount
386      * @static
387      * @private
388      */
389     _retryCount = 0,
390
391     /**
392      * onAvailable listeners
393      * @property _avail
394      * @static
395      * @private
396      */
397     _avail = [],
398
399     /**
400      * Custom event wrappers for DOM events.  Key is
401      * 'event:' + Element uid stamp + event type
402      * @property _wrappers
403      * @type Y.Event.Custom
404      * @static
405      * @private
406      */
407     _wrappers = _eventenv.dom_wrappers,
408
409     _windowLoadKey = null,
410
411     /**
412      * Custom event wrapper map DOM events.  Key is
413      * Element uid stamp.  Each item is a hash of custom event
414      * wrappers as provided in the _wrappers collection.  This
415      * provides the infrastructure for getListeners.
416      * @property _el_events
417      * @static
418      * @private
419      */
420     _el_events = _eventenv.dom_map;
421
422     return {
423
424         /**
425          * The number of times we should look for elements that are not
426          * in the DOM at the time the event is requested after the document
427          * has been loaded.  The default is 1000@amp;40 ms, so it will poll
428          * for 40 seconds or until all outstanding handlers are bound
429          * (whichever comes first).
430          * @property POLL_RETRYS
431          * @type int
432          * @static
433          * @final
434          */
435         POLL_RETRYS: 1000,
436
437         /**
438          * The poll interval in milliseconds
439          * @property POLL_INTERVAL
440          * @type int
441          * @static
442          * @final
443          */
444         POLL_INTERVAL: 40,
445
446         /**
447          * addListener/removeListener can throw errors in unexpected scenarios.
448          * These errors are suppressed, the method returns false, and this property
449          * is set
450          * @property lastError
451          * @static
452          * @type Error
453          */
454         lastError: null,
455
456
457         /**
458          * poll handle
459          * @property _interval
460          * @static
461          * @private
462          */
463         _interval: null,
464
465         /**
466          * document readystate poll handle
467          * @property _dri
468          * @static
469          * @private
470          */
471          _dri: null,
472
473         /**
474          * True when the document is initially usable
475          * @property DOMReady
476          * @type boolean
477          * @static
478          */
479         DOMReady: false,
480
481         /**
482          * @method startInterval
483          * @static
484          * @private
485          */
486         startInterval: function() {
487             if (!Event._interval) {
488 Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL);
489             }
490         },
491
492         /**
493          * Executes the supplied callback when the item with the supplied
494          * id is found.  This is meant to be used to execute behavior as
495          * soon as possible as the page loads.  If you use this after the
496          * initial page load it will poll for a fixed time for the element.
497          * The number of times it will poll and the frequency are
498          * configurable.  By default it will poll for 10 seconds.
499          *
500          * <p>The callback is executed with a single parameter:
501          * the custom object parameter, if provided.</p>
502          *
503          * @method onAvailable
504          *
505          * @param {string||string[]}   id the id of the element, or an array
506          * of ids to look for.
507          * @param {function} fn what to execute when the element is found.
508          * @param {object}   p_obj an optional object to be passed back as
509          *                   a parameter to fn.
510          * @param {boolean|object}  p_override If set to true, fn will execute
511          *                   in the context of p_obj, if set to an object it
512          *                   will execute in the context of that object
513          * @param checkContent {boolean} check child node readiness (onContentReady)
514          * @static
515          * @deprecated Use Y.on("available")
516          */
517         // @TODO fix arguments
518         onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) {
519
520             var a = Y.Array(id), i, availHandle;
521
522
523             for (i=0; i<a.length; i=i+1) {
524                 _avail.push({
525                     id:         a[i],
526                     fn:         fn,
527                     obj:        p_obj,
528                     override:   p_override,
529                     checkReady: checkContent,
530                     compat:     compat
531                 });
532             }
533             _retryCount = this.POLL_RETRYS;
534
535             // We want the first test to be immediate, but async
536             setTimeout(Event._poll, 0);
537
538             availHandle = new Y.EventHandle({
539
540                 _delete: function() {
541                     // set by the event system for lazy DOM listeners
542                     if (availHandle.handle) {
543                         availHandle.handle.detach();
544                         return;
545                     }
546
547                     var i, j;
548
549                     // otherwise try to remove the onAvailable listener(s)
550                     for (i = 0; i < a.length; i++) {
551                         for (j = 0; j < _avail.length; j++) {
552                             if (a[i] === _avail[j].id) {
553                                 _avail.splice(j, 1);
554                             }
555                         }
556                     }
557                 }
558
559             });
560
561             return availHandle;
562         },
563
564         /**
565          * Works the same way as onAvailable, but additionally checks the
566          * state of sibling elements to determine if the content of the
567          * available element is safe to modify.
568          *
569          * <p>The callback is executed with a single parameter:
570          * the custom object parameter, if provided.</p>
571          *
572          * @method onContentReady
573          *
574          * @param {string}   id the id of the element to look for.
575          * @param {function} fn what to execute when the element is ready.
576          * @param {object}   obj an optional object to be passed back as
577          *                   a parameter to fn.
578          * @param {boolean|object}  override If set to true, fn will execute
579          *                   in the context of p_obj.  If an object, fn will
580          *                   exectute in the context of that object
581          *
582          * @static
583          * @deprecated Use Y.on("contentready")
584          */
585         // @TODO fix arguments
586         onContentReady: function(id, fn, obj, override, compat) {
587             return Event.onAvailable(id, fn, obj, override, true, compat);
588         },
589
590         /**
591          * Adds an event listener
592          *
593          * @method attach
594          *
595          * @param {String}   type     The type of event to append
596          * @param {Function} fn        The method the event invokes
597          * @param {String|HTMLElement|Array|NodeList} el An id, an element
598          *  reference, or a collection of ids and/or elements to assign the
599          *  listener to.
600          * @param {Object}   context optional context object
601          * @param {Boolean|object}  args 0..n arguments to pass to the callback
602          * @return {EventHandle} an object to that can be used to detach the listener
603          *
604          * @static
605          */
606
607         attach: function(type, fn, el, context) {
608             return Event._attach(Y.Array(arguments, 0, true));
609         },
610
611         _createWrapper: function (el, type, capture, compat, facade) {
612
613             var cewrapper,
614                 ek  = Y.stamp(el),
615                 key = 'event:' + ek + type;
616
617             if (false === facade) {
618                 key += 'native';
619             }
620             if (capture) {
621                 key += 'capture';
622             }
623
624
625             cewrapper = _wrappers[key];
626
627
628             if (!cewrapper) {
629                 // create CE wrapper
630                 cewrapper = Y.publish(key, {
631                     silent: true,
632                     bubbles: false,
633                     contextFn: function() {
634                         if (compat) {
635                             return cewrapper.el;
636                         } else {
637                             cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el);
638                             return cewrapper.nodeRef;
639                         }
640                     }
641                 });
642
643                 cewrapper.overrides = {};
644
645                 // for later removeListener calls
646                 cewrapper.el = el;
647                 cewrapper.key = key;
648                 cewrapper.domkey = ek;
649                 cewrapper.type = type;
650                 cewrapper.fn = function(e) {
651                     cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade))));
652                 };
653                 cewrapper.capture = capture;
654
655                 if (el == win && type == "load") {
656                     // window load happens once
657                     cewrapper.fireOnce = true;
658                     _windowLoadKey = key;
659                 }
660
661                 _wrappers[key] = cewrapper;
662                 _el_events[ek] = _el_events[ek] || {};
663                 _el_events[ek][key] = cewrapper;
664
665                 add(el, type, cewrapper.fn, capture);
666             }
667
668             return cewrapper;
669
670         },
671
672         _attach: function(args, conf) {
673
674             var compat,
675                 handles, oEl, cewrapper, context,
676                 fireNow = false, ret,
677                 type = args[0],
678                 fn = args[1],
679                 el = args[2] || win,
680                 facade = conf && conf.facade,
681                 capture = conf && conf.capture,
682                 overrides = conf && conf.overrides;
683
684             if (args[args.length-1] === COMPAT_ARG) {
685                 compat = true;
686                 // trimmedArgs.pop();
687             }
688
689             if (!fn || !fn.call) {
690 // throw new TypeError(type + " attach call failed, callback undefined");
691                 return false;
692             }
693
694             // The el argument can be an array of elements or element ids.
695             if (shouldIterate(el)) {
696
697                 handles=[];
698
699                 Y.each(el, function(v, k) {
700                     args[2] = v;
701                     handles.push(Event._attach(args, conf));
702                 });
703
704                 // return (handles.length === 1) ? handles[0] : handles;
705                 return new Y.EventHandle(handles);
706
707             // If the el argument is a string, we assume it is
708             // actually the id of the element.  If the page is loaded
709             // we convert el to the actual element, otherwise we
710             // defer attaching the event until the element is
711             // ready
712             } else if (Y.Lang.isString(el)) {
713
714                 // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el);
715
716                 if (compat) {
717                     oEl = Y.DOM.byId(el);
718                 } else {
719
720                     oEl = Y.Selector.query(el);
721
722                     switch (oEl.length) {
723                         case 0:
724                             oEl = null;
725                             break;
726                         case 1:
727                             oEl = oEl[0];
728                             break;
729                         default:
730                             args[2] = oEl;
731                             return Event._attach(args, conf);
732                     }
733                 }
734
735                 if (oEl) {
736
737                     el = oEl;
738
739                 // Not found = defer adding the event until the element is available
740                 } else {
741
742                     ret = Event.onAvailable(el, function() {
743
744                         ret.handle = Event._attach(args, conf);
745
746                     }, Event, true, false, compat);
747
748                     return ret;
749
750                 }
751             }
752
753             // Element should be an html element or node
754             if (!el) {
755                 return false;
756             }
757
758             if (Y.Node && Y.instanceOf(el, Y.Node)) {
759                 el = Y.Node.getDOMNode(el);
760             }
761
762             cewrapper = Event._createWrapper(el, type, capture, compat, facade);
763             if (overrides) {
764                 Y.mix(cewrapper.overrides, overrides);
765             }
766
767             if (el == win && type == "load") {
768
769                 // if the load is complete, fire immediately.
770                 // all subscribers, including the current one
771                 // will be notified.
772                 if (YUI.Env.windowLoaded) {
773                     fireNow = true;
774                 }
775             }
776
777             if (compat) {
778                 args.pop();
779             }
780
781             context = args[3];
782
783             // set context to the Node if not specified
784             // ret = cewrapper.on.apply(cewrapper, trimmedArgs);
785             ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null);
786
787             if (fireNow) {
788                 cewrapper.fire();
789             }
790
791             return ret;
792
793         },
794
795         /**
796          * Removes an event listener.  Supports the signature the event was bound
797          * with, but the preferred way to remove listeners is using the handle
798          * that is returned when using Y.on
799          *
800          * @method detach
801          *
802          * @param {String} type the type of event to remove.
803          * @param {Function} fn the method the event invokes.  If fn is
804          * undefined, then all event handlers for the type of event are
805          * removed.
806          * @param {String|HTMLElement|Array|NodeList|EventHandle} el An
807          * event handle, an id, an element reference, or a collection
808          * of ids and/or elements to remove the listener from.
809          * @return {boolean} true if the unbind was successful, false otherwise.
810          * @static
811          */
812         detach: function(type, fn, el, obj) {
813
814             var args=Y.Array(arguments, 0, true), compat, l, ok, i,
815                 id, ce;
816
817             if (args[args.length-1] === COMPAT_ARG) {
818                 compat = true;
819                 // args.pop();
820             }
821
822             if (type && type.detach) {
823                 return type.detach();
824             }
825
826             // The el argument can be a string
827             if (typeof el == "string") {
828
829                 // el = (compat) ? Y.DOM.byId(el) : Y.all(el);
830                 if (compat) {
831                     el = Y.DOM.byId(el);
832                 } else {
833                     el = Y.Selector.query(el);
834                     l = el.length;
835                     if (l < 1) {
836                         el = null;
837                     } else if (l == 1) {
838                         el = el[0];
839                     }
840                 }
841                 // return Event.detach.apply(Event, args);
842             }
843
844             if (!el) {
845                 return false;
846             }
847
848             if (el.detach) {
849                 args.splice(2, 1);
850                 return el.detach.apply(el, args);
851             // The el argument can be an array of elements or element ids.
852             } else if (shouldIterate(el)) {
853                 ok = true;
854                 for (i=0, l=el.length; i<l; ++i) {
855                     args[2] = el[i];
856                     ok = ( Y.Event.detach.apply(Y.Event, args) && ok );
857                 }
858
859                 return ok;
860             }
861
862             if (!type || !fn || !fn.call) {
863                 return Event.purgeElement(el, false, type);
864             }
865
866             id = 'event:' + Y.stamp(el) + type;
867             ce = _wrappers[id];
868
869             if (ce) {
870                 return ce.detach(fn);
871             } else {
872                 return false;
873             }
874
875         },
876
877         /**
878          * Finds the event in the window object, the caller's arguments, or
879          * in the arguments of another method in the callstack.  This is
880          * executed automatically for events registered through the event
881          * manager, so the implementer should not normally need to execute
882          * this function at all.
883          * @method getEvent
884          * @param {Event} e the event parameter from the handler
885          * @param {HTMLElement} el the element the listener was attached to
886          * @return {Event} the event
887          * @static
888          */
889         getEvent: function(e, el, noFacade) {
890             var ev = e || win.event;
891
892             return (noFacade) ? ev :
893                 new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]);
894         },
895
896         /**
897          * Generates an unique ID for the element if it does not already
898          * have one.
899          * @method generateId
900          * @param el the element to create the id for
901          * @return {string} the resulting id of the element
902          * @static
903          */
904         generateId: function(el) {
905             return Y.DOM.generateID(el);
906         },
907
908         /**
909          * We want to be able to use getElementsByTagName as a collection
910          * to attach a group of events to.  Unfortunately, different
911          * browsers return different types of collections.  This function
912          * tests to determine if the object is array-like.  It will also
913          * fail if the object is an array, but is empty.
914          * @method _isValidCollection
915          * @param o the object to test
916          * @return {boolean} true if the object is array-like and populated
917          * @deprecated was not meant to be used directly
918          * @static
919          * @private
920          */
921         _isValidCollection: shouldIterate,
922
923         /**
924          * hook up any deferred listeners
925          * @method _load
926          * @static
927          * @private
928          */
929         _load: function(e) {
930             if (!_loadComplete) {
931                 _loadComplete = true;
932
933                 // Just in case DOMReady did not go off for some reason
934                 // E._ready();
935                 if (Y.fire) {
936                     Y.fire(EVENT_READY);
937                 }
938
939                 // Available elements may not have been detected before the
940                 // window load event fires. Try to find them now so that the
941                 // the user is more likely to get the onAvailable notifications
942                 // before the window load notification
943                 Event._poll();
944             }
945         },
946
947         /**
948          * Polling function that runs before the onload event fires,
949          * attempting to attach to DOM Nodes as soon as they are
950          * available
951          * @method _poll
952          * @static
953          * @private
954          */
955         _poll: function() {
956             if (Event.locked) {
957                 return;
958             }
959
960             if (Y.UA.ie && !YUI.Env.DOMReady) {
961                 // Hold off if DOMReady has not fired and check current
962                 // readyState to protect against the IE operation aborted
963                 // issue.
964                 Event.startInterval();
965                 return;
966             }
967
968             Event.locked = true;
969
970             // keep trying until after the page is loaded.  We need to
971             // check the page load state prior to trying to bind the
972             // elements so that we can be certain all elements have been
973             // tested appropriately
974             var i, len, item, el, notAvail, executeItem,
975                 tryAgain = !_loadComplete;
976
977             if (!tryAgain) {
978                 tryAgain = (_retryCount > 0);
979             }
980
981             // onAvailable
982             notAvail = [];
983
984             executeItem = function (el, item) {
985                 var context, ov = item.override;
986                 if (item.compat) {
987                     if (item.override) {
988                         if (ov === true) {
989                             context = item.obj;
990                         } else {
991                             context = ov;
992                         }
993                     } else {
994                         context = el;
995                     }
996                     item.fn.call(context, item.obj);
997                 } else {
998                     context = item.obj || Y.one(el);
999                     item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []);
1000                 }
1001             };
1002
1003             // onAvailable
1004             for (i=0,len=_avail.length; i<len; ++i) {
1005                 item = _avail[i];
1006                 if (item && !item.checkReady) {
1007
1008                     // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1009                     el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1010
1011                     if (el) {
1012                         executeItem(el, item);
1013                         _avail[i] = null;
1014                     } else {
1015                         notAvail.push(item);
1016                     }
1017                 }
1018             }
1019
1020             // onContentReady
1021             for (i=0,len=_avail.length; i<len; ++i) {
1022                 item = _avail[i];
1023                 if (item && item.checkReady) {
1024
1025                     // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id);
1026                     el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true);
1027
1028                     if (el) {
1029                         // The element is available, but not necessarily ready
1030                         // @todo should we test parentNode.nextSibling?
1031                         if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) {
1032                             executeItem(el, item);
1033                             _avail[i] = null;
1034                         }
1035                     } else {
1036                         notAvail.push(item);
1037                     }
1038                 }
1039             }
1040
1041             _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1;
1042
1043             if (tryAgain) {
1044                 // we may need to strip the nulled out items here
1045                 Event.startInterval();
1046             } else {
1047                 clearInterval(Event._interval);
1048                 Event._interval = null;
1049             }
1050
1051             Event.locked = false;
1052
1053             return;
1054
1055         },
1056
1057         /**
1058          * Removes all listeners attached to the given element via addListener.
1059          * Optionally, the node's children can also be purged.
1060          * Optionally, you can specify a specific type of event to remove.
1061          * @method purgeElement
1062          * @param {HTMLElement} el the element to purge
1063          * @param {boolean} recurse recursively purge this element's children
1064          * as well.  Use with caution.
1065          * @param {string} type optional type of listener to purge. If
1066          * left out, all listeners will be removed
1067          * @static
1068          */
1069         purgeElement: function(el, recurse, type) {
1070             // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el,
1071             var oEl = (Y.Lang.isString(el)) ?  Y.Selector.query(el, null, true) : el,
1072                 lis = Event.getListeners(oEl, type), i, len, props, children, child;
1073
1074             if (recurse && oEl) {
1075                 lis = lis || [];
1076                 children = Y.Selector.query('*', oEl);
1077                 i = 0;
1078                 len = children.length;
1079                 for (; i < len; ++i) {
1080                     child = Event.getListeners(children[i], type);
1081                     if (child) {
1082                         lis = lis.concat(child);
1083                     }
1084                 }
1085             }
1086
1087             if (lis) {
1088                 i = 0;
1089                 len = lis.length;
1090                 for (; i < len; ++i) {
1091                     props = lis[i];
1092                     props.detachAll();
1093                     remove(props.el, props.type, props.fn, props.capture);
1094                     delete _wrappers[props.key];
1095                     delete _el_events[props.domkey][props.key];
1096                 }
1097             }
1098
1099         },
1100
1101
1102         /**
1103          * Returns all listeners attached to the given element via addListener.
1104          * Optionally, you can specify a specific type of event to return.
1105          * @method getListeners
1106          * @param el {HTMLElement|string} the element or element id to inspect
1107          * @param type {string} optional type of listener to return. If
1108          * left out, all listeners will be returned
1109          * @return {Y.Custom.Event} the custom event wrapper for the DOM event(s)
1110          * @static
1111          */
1112         getListeners: function(el, type) {
1113             var ek = Y.stamp(el, true), evts = _el_events[ek],
1114                 results=[] , key = (type) ? 'event:' + ek + type : null,
1115                 adapters = _eventenv.plugins;
1116
1117             if (!evts) {
1118                 return null;
1119             }
1120
1121             if (key) {
1122                 // look for synthetic events
1123                 if (adapters[type] && adapters[type].eventDef) {
1124                     key += '_synth';
1125                 }
1126
1127                 if (evts[key]) {
1128                     results.push(evts[key]);
1129                 }
1130
1131                 // get native events as well
1132                 key += 'native';
1133                 if (evts[key]) {
1134                     results.push(evts[key]);
1135                 }
1136
1137             } else {
1138                 Y.each(evts, function(v, k) {
1139                     results.push(v);
1140                 });
1141             }
1142
1143             return (results.length) ? results : null;
1144         },
1145
1146         /**
1147          * Removes all listeners registered by pe.event.  Called
1148          * automatically during the unload event.
1149          * @method _unload
1150          * @static
1151          * @private
1152          */
1153         _unload: function(e) {
1154             Y.each(_wrappers, function(v, k) {
1155                 v.detachAll();
1156                 remove(v.el, v.type, v.fn, v.capture);
1157                 delete _wrappers[k];
1158                 delete _el_events[v.domkey][k];
1159             });
1160             remove(win, "unload", onUnload);
1161         },
1162
1163         /**
1164          * Adds a DOM event directly without the caching, cleanup, context adj, etc
1165          *
1166          * @method nativeAdd
1167          * @param {HTMLElement} el      the element to bind the handler to
1168          * @param {string}      type   the type of event handler
1169          * @param {function}    fn      the callback to invoke
1170          * @param {boolen}      capture capture or bubble phase
1171          * @static
1172          * @private
1173          */
1174         nativeAdd: add,
1175
1176         /**
1177          * Basic remove listener
1178          *
1179          * @method nativeRemove
1180          * @param {HTMLElement} el      the element to bind the handler to
1181          * @param {string}      type   the type of event handler
1182          * @param {function}    fn      the callback to invoke
1183          * @param {boolen}      capture capture or bubble phase
1184          * @static
1185          * @private
1186          */
1187         nativeRemove: remove
1188     };
1189
1190 }();
1191
1192 Y.Event = Event;
1193
1194 if (config.injected || YUI.Env.windowLoaded) {
1195     onLoad();
1196 } else {
1197     add(win, "load", onLoad);
1198 }
1199
1200 // Process onAvailable/onContentReady items when when the DOM is ready in IE
1201 if (Y.UA.ie) {
1202     Y.on(EVENT_READY, Event._poll);
1203 }
1204
1205 add(win, "unload", onUnload);
1206
1207 Event.Custom = Y.CustomEvent;
1208 Event.Subscriber = Y.Subscriber;
1209 Event.Target = Y.EventTarget;
1210 Event.Handle = Y.EventHandle;
1211 Event.Facade = Y.EventFacade;
1212
1213 Event._poll();
1214
1215 })();
1216
1217 /**
1218  * DOM event listener abstraction layer
1219  * @module event
1220  * @submodule event-base
1221  */
1222
1223 /**
1224  * Executes the callback as soon as the specified element
1225  * is detected in the DOM.  This function expects a selector
1226  * string for the element(s) to detect.  If you already have
1227  * an element reference, you don't need this event.
1228  * @event available
1229  * @param type {string} 'available'
1230  * @param fn {function} the callback function to execute.
1231  * @param el {string} an selector for the element(s) to attach
1232  * @param context optional argument that specifies what 'this' refers to.
1233  * @param args* 0..n additional arguments to pass on to the callback function.
1234  * These arguments will be added after the event object.
1235  * @return {EventHandle} the detach handle
1236  * @for YUI
1237  */
1238 Y.Env.evt.plugins.available = {
1239     on: function(type, fn, id, o) {
1240         var a = arguments.length > 4 ?  Y.Array(arguments, 4, true) : null;
1241         return Y.Event.onAvailable.call(Y.Event, id, fn, o, a);
1242     }
1243 };
1244
1245 /**
1246  * Executes the callback as soon as the specified element
1247  * is detected in the DOM with a nextSibling property
1248  * (indicating that the element's children are available).
1249  * This function expects a selector
1250  * string for the element(s) to detect.  If you already have
1251  * an element reference, you don't need this event.
1252  * @event contentready
1253  * @param type {string} 'contentready'
1254  * @param fn {function} the callback function to execute.
1255  * @param el {string} an selector for the element(s) to attach.
1256  * @param context optional argument that specifies what 'this' refers to.
1257  * @param args* 0..n additional arguments to pass on to the callback function.
1258  * These arguments will be added after the event object.
1259  * @return {EventHandle} the detach handle
1260  * @for YUI
1261  */
1262 Y.Env.evt.plugins.contentready = {
1263     on: function(type, fn, id, o) {
1264         var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null;
1265         return Y.Event.onContentReady.call(Y.Event, id, fn, o, a);
1266     }
1267 };
1268
1269
1270 }, '3.3.0' ,{requires:['event-custom-base']});