Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / src / ext-core / src / core / EventManager.js
1 /*!
2  * Ext JS Library 3.2.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.EventManager
9  * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
10  * several useful events directly.
11  * See {@link Ext.EventObject} for more details on normalized event objects.
12  * @singleton
13  */
14
15 Ext.EventManager = function(){
16     var docReadyEvent,
17         docReadyProcId,
18         docReadyState = false,
19         DETECT_NATIVE = Ext.isGecko || Ext.isWebKit || Ext.isSafari,
20         E = Ext.lib.Event,
21         D = Ext.lib.Dom,
22         DOC = document,
23         WINDOW = window,
24         DOMCONTENTLOADED = "DOMContentLoaded",
25         COMPLETE = 'complete',
26         propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/,
27         /*
28          * This cache is used to hold special js objects, the document and window, that don't have an id. We need to keep
29          * a reference to them so we can look them up at a later point.
30          */
31         specialElCache = [];
32
33      function getId(el){
34         var id = false,
35             i = 0,
36             len = specialElCache.length,
37             id = false,
38             skip = false,
39             o;
40         if(el){
41             if(el.getElementById || el.navigator){
42                 // look up the id
43                 for(; i < len; ++i){
44                     o = specialElCache[i];
45                     if(o.el === el){
46                         id = o.id;
47                         break;
48                     }
49                 }
50                 if(!id){
51                     // for browsers that support it, ensure that give the el the same id
52                     id = Ext.id(el);
53                     specialElCache.push({
54                         id: id,
55                         el: el
56                     });
57                     skip = true;
58                 }
59             }else{
60                 id = Ext.id(el);
61             }
62             if(!Ext.elCache[id]){
63                 Ext.Element.addToCache(new Ext.Element(el), id);
64                 if(skip){
65                     Ext.elCache[id].skipGC = true;
66                 }
67             }
68         }
69         return id;
70      };
71
72     /// There is some jquery work around stuff here that isn't needed in Ext Core.
73     function addListener(el, ename, fn, task, wrap, scope){
74         el = Ext.getDom(el);
75         var id = getId(el),
76             es = Ext.elCache[id].events,
77             wfn;
78
79         wfn = E.on(el, ename, wrap);
80         es[ename] = es[ename] || [];
81
82         /* 0 = Original Function,
83            1 = Event Manager Wrapped Function,
84            2 = Scope,
85            3 = Adapter Wrapped Function,
86            4 = Buffered Task
87         */
88         es[ename].push([fn, wrap, scope, wfn, task]);
89
90         // this is a workaround for jQuery and should somehow be removed from Ext Core in the future
91         // without breaking ExtJS.
92
93         // workaround for jQuery
94         if(el.addEventListener && ename == "mousewheel"){
95             var args = ["DOMMouseScroll", wrap, false];
96             el.addEventListener.apply(el, args);
97             Ext.EventManager.addListener(WINDOW, 'unload', function(){
98                 el.removeEventListener.apply(el, args);
99             });
100         }
101
102         // fix stopped mousedowns on the document
103         if(el == DOC && ename == "mousedown"){
104             Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
105         }
106     };
107
108     function doScrollChk(){
109         /* Notes:
110              'doScroll' will NOT work in a IFRAME/FRAMESET.
111              The method succeeds but, a DOM query done immediately after -- FAILS.
112           */
113         if(window != top){
114             return false;
115         }
116
117         try{
118             DOC.documentElement.doScroll('left');
119         }catch(e){
120              return false;
121         }
122
123         fireDocReady();
124         return true;
125     }
126     /**
127      * @return {Boolean} True if the document is in a 'complete' state (or was determined to
128      * be true by other means). If false, the state is evaluated again until canceled.
129      */
130     function checkReadyState(e){
131
132         if(Ext.isIE && doScrollChk()){
133             return true;
134         }
135         if(DOC.readyState == COMPLETE){
136             fireDocReady();
137             return true;
138         }
139         docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
140         return false;
141     }
142
143     var styles;
144     function checkStyleSheets(e){
145         styles || (styles = Ext.query('style, link[rel=stylesheet]'));
146         if(styles.length == DOC.styleSheets.length){
147             fireDocReady();
148             return true;
149         }
150         docReadyState || (docReadyProcId = setTimeout(arguments.callee, 2));
151         return false;
152     }
153
154     function OperaDOMContentLoaded(e){
155         DOC.removeEventListener(DOMCONTENTLOADED, arguments.callee, false);
156         checkStyleSheets();
157     }
158
159     function fireDocReady(e){
160         if(!docReadyState){
161             docReadyState = true; //only attempt listener removal once
162
163             if(docReadyProcId){
164                 clearTimeout(docReadyProcId);
165             }
166             if(DETECT_NATIVE) {
167                 DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
168             }
169             if(Ext.isIE && checkReadyState.bindIE){  //was this was actually set ??
170                 DOC.detachEvent('onreadystatechange', checkReadyState);
171             }
172             E.un(WINDOW, "load", arguments.callee);
173         }
174         if(docReadyEvent && !Ext.isReady){
175             Ext.isReady = true;
176             docReadyEvent.fire();
177             docReadyEvent.listeners = [];
178         }
179
180     };
181
182     function initDocReady(){
183         docReadyEvent || (docReadyEvent = new Ext.util.Event());
184         if (DETECT_NATIVE) {
185             DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
186         }
187         /*
188          * Handle additional (exceptional) detection strategies here
189          */
190         if (Ext.isIE){
191             //Use readystatechange as a backup AND primary detection mechanism for a FRAME/IFRAME
192             //See if page is already loaded
193             if(!checkReadyState()){
194                 checkReadyState.bindIE = true;
195                 DOC.attachEvent('onreadystatechange', checkReadyState);
196             }
197
198         }else if(Ext.isOpera ){
199             /* Notes:
200                Opera needs special treatment needed here because CSS rules are NOT QUITE
201                available after DOMContentLoaded is raised.
202             */
203
204             //See if page is already loaded and all styleSheets are in place
205             (DOC.readyState == COMPLETE && checkStyleSheets()) ||
206                 DOC.addEventListener(DOMCONTENTLOADED, OperaDOMContentLoaded, false);
207
208         }else if (Ext.isWebKit){
209             //Fallback for older Webkits without DOMCONTENTLOADED support
210             checkReadyState();
211         }
212         // no matter what, make sure it fires on load
213         E.on(WINDOW, "load", fireDocReady);
214     };
215
216     function createTargeted(h, o){
217         return function(){
218             var args = Ext.toArray(arguments);
219             if(o.target == Ext.EventObject.setEvent(args[0]).target){
220                 h.apply(this, args);
221             }
222         };
223     };
224
225     function createBuffered(h, o, task){
226         return function(e){
227             // create new event object impl so new events don't wipe out properties
228             task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
229         };
230     };
231
232     function createSingle(h, el, ename, fn, scope){
233         return function(e){
234             Ext.EventManager.removeListener(el, ename, fn, scope);
235             h(e);
236         };
237     };
238
239     function createDelayed(h, o, fn){
240         return function(e){
241             var task = new Ext.util.DelayedTask(h);
242             if(!fn.tasks) {
243                 fn.tasks = [];
244             }
245             fn.tasks.push(task);
246             task.delay(o.delay || 10, h, null, [new Ext.EventObjectImpl(e)]);
247         };
248     };
249
250     function listen(element, ename, opt, fn, scope){
251         var o = !Ext.isObject(opt) ? {} : opt,
252             el = Ext.getDom(element), task;
253
254         fn = fn || o.fn;
255         scope = scope || o.scope;
256
257         if(!el){
258             throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
259         }
260         function h(e){
261             // prevent errors while unload occurring
262             if(!Ext){// !window[xname]){  ==> can't we do this?
263                 return;
264             }
265             e = Ext.EventObject.setEvent(e);
266             var t;
267             if (o.delegate) {
268                 if(!(t = e.getTarget(o.delegate, el))){
269                     return;
270                 }
271             } else {
272                 t = e.target;
273             }
274             if (o.stopEvent) {
275                 e.stopEvent();
276             }
277             if (o.preventDefault) {
278                e.preventDefault();
279             }
280             if (o.stopPropagation) {
281                 e.stopPropagation();
282             }
283             if (o.normalized) {
284                 e = e.browserEvent;
285             }
286
287             fn.call(scope || el, e, t, o);
288         };
289         if(o.target){
290             h = createTargeted(h, o);
291         }
292         if(o.delay){
293             h = createDelayed(h, o, fn);
294         }
295         if(o.single){
296             h = createSingle(h, el, ename, fn, scope);
297         }
298         if(o.buffer){
299             task = new Ext.util.DelayedTask(h);
300             h = createBuffered(h, o, task);
301         }
302
303         addListener(el, ename, fn, task, h, scope);
304         return h;
305     };
306
307     var pub = {
308         /**
309          * Appends an event handler to an element.  The shorthand version {@link #on} is equivalent.  Typically you will
310          * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
311          * @param {String/HTMLElement} el The html element or id to assign the event handler to.
312          * @param {String} eventName The name of the event to listen for.
313          * @param {Function} handler The handler function the event invokes. This function is passed
314          * the following parameters:<ul>
315          * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
316          * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
317          * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
318          * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
319          * </ul>
320          * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
321          * @param {Object} options (optional) An object containing handler configuration properties.
322          * This may contain any of the following properties:<ul>
323          * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
324          * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
325          * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
326          * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
327          * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
328          * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
329          * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
330          * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
331          * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
332          * by the specified number of milliseconds. If the event fires again within that time, the original
333          * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
334          * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
335          * </ul><br>
336          * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
337          */
338         addListener : function(element, eventName, fn, scope, options){
339             if(Ext.isObject(eventName)){
340                 var o = eventName, e, val;
341                 for(e in o){
342                     val = o[e];
343                     if(!propRe.test(e)){
344                         if(Ext.isFunction(val)){
345                             // shared options
346                             listen(element, e, o, val, o.scope);
347                         }else{
348                             // individual options
349                             listen(element, e, val);
350                         }
351                     }
352                 }
353             } else {
354                 listen(element, eventName, options, fn, scope);
355             }
356         },
357
358         /**
359          * Removes an event handler from an element.  The shorthand version {@link #un} is equivalent.  Typically
360          * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
361          * @param {String/HTMLElement} el The id or html element from which to remove the listener.
362          * @param {String} eventName The name of the event.
363          * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
364          * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
365          * then this must refer to the same object.
366          */
367         removeListener : function(el, eventName, fn, scope){
368             el = Ext.getDom(el);
369             var id = getId(el),
370                 f = el && (Ext.elCache[id].events)[eventName] || [],
371                 wrap, i, l, k, len, fnc;
372
373             for (i = 0, len = f.length; i < len; i++) {
374
375                 /* 0 = Original Function,
376                    1 = Event Manager Wrapped Function,
377                    2 = Scope,
378                    3 = Adapter Wrapped Function,
379                    4 = Buffered Task
380                 */
381                 if (Ext.isArray(fnc = f[i]) && fnc[0] == fn && (!scope || fnc[2] == scope)) {
382                     if(fnc[4]) {
383                         fnc[4].cancel();
384                     }
385                     k = fn.tasks && fn.tasks.length;
386                     if(k) {
387                         while(k--) {
388                             fn.tasks[k].cancel();
389                         }
390                         delete fn.tasks;
391                     }
392                     wrap = fnc[1];
393                     E.un(el, eventName, E.extAdapter ? fnc[3] : wrap);
394
395                     // jQuery workaround that should be removed from Ext Core
396                     if(wrap && el.addEventListener && eventName == "mousewheel"){
397                         el.removeEventListener("DOMMouseScroll", wrap, false);
398                     }
399
400                     // fix stopped mousedowns on the document
401                     if(wrap && el == DOC && eventName == "mousedown"){
402                         Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
403                     }
404
405                     f.splice(i, 1);
406                     if (f.length === 0) {
407                         delete Ext.elCache[id].events[eventName];
408                     }
409                     for (k in Ext.elCache[id].events) {
410                         return false;
411                     }
412                     Ext.elCache[id].events = {};
413                     return false;
414                 }
415             }
416         },
417
418         /**
419          * Removes all event handers from an element.  Typically you will use {@link Ext.Element#removeAllListeners}
420          * directly on an Element in favor of calling this version.
421          * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
422          */
423         removeAll : function(el){
424             el = Ext.getDom(el);
425             var id = getId(el),
426                 ec = Ext.elCache[id] || {},
427                 es = ec.events || {},
428                 f, i, len, ename, fn, k, wrap;
429
430             for(ename in es){
431                 if(es.hasOwnProperty(ename)){
432                     f = es[ename];
433                     /* 0 = Original Function,
434                        1 = Event Manager Wrapped Function,
435                        2 = Scope,
436                        3 = Adapter Wrapped Function,
437                        4 = Buffered Task
438                     */
439                     for (i = 0, len = f.length; i < len; i++) {
440                         fn = f[i];
441                         if(fn[4]) {
442                             fn[4].cancel();
443                         }
444                         if(fn[0].tasks && (k = fn[0].tasks.length)) {
445                             while(k--) {
446                                 fn[0].tasks[k].cancel();
447                             }
448                             delete fn.tasks;
449                         }
450                         wrap =  fn[1];
451                         E.un(el, ename, E.extAdapter ? fn[3] : wrap);
452
453                         // jQuery workaround that should be removed from Ext Core
454                         if(el.addEventListener && wrap && ename == "mousewheel"){
455                             el.removeEventListener("DOMMouseScroll", wrap, false);
456                         }
457
458                         // fix stopped mousedowns on the document
459                         if(wrap && el == DOC &&  ename == "mousedown"){
460                             Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
461                         }
462                     }
463                 }
464             }
465             if (Ext.elCache[id]) {
466                 Ext.elCache[id].events = {};
467             }
468         },
469
470         getListeners : function(el, eventName) {
471             el = Ext.getDom(el);
472             var id = getId(el),
473                 ec = Ext.elCache[id] || {},
474                 es = ec.events || {},
475                 results = [];
476             if (es && es[eventName]) {
477                 return es[eventName];
478             } else {
479                 return null;
480             }
481         },
482
483         purgeElement : function(el, recurse, eventName) {
484             el = Ext.getDom(el);
485             var id = getId(el),
486                 ec = Ext.elCache[id] || {},
487                 es = ec.events || {},
488                 i, f, len;
489             if (eventName) {
490                 if (es && es.hasOwnProperty(eventName)) {
491                     f = es[eventName];
492                     for (i = 0, len = f.length; i < len; i++) {
493                         Ext.EventManager.removeListener(el, eventName, f[i][0]);
494                     }
495                 }
496             } else {
497                 Ext.EventManager.removeAll(el);
498             }
499             if (recurse && el && el.childNodes) {
500                 for (i = 0, len = el.childNodes.length; i < len; i++) {
501                     Ext.EventManager.purgeElement(el.childNodes[i], recurse, eventName);
502                 }
503             }
504         },
505
506         _unload : function() {
507             var el;
508             for (el in Ext.elCache) {
509                 Ext.EventManager.removeAll(el);
510             }
511             delete Ext.elCache;
512             delete Ext.Element._flyweights;
513
514             // Abort any outstanding Ajax requests
515             var c,
516                 conn,
517                 tid,
518                 ajax = Ext.lib.Ajax;
519             (Ext.isObject(ajax.conn)) ? conn = ajax.conn : conn = {};
520             for (tid in conn) {
521                 c = conn[tid];
522                 if (c) {
523                     ajax.abort({conn: c, tId: tid});
524                 }
525             }
526         },
527         /**
528          * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
529          * accessed shorthanded as Ext.onReady().
530          * @param {Function} fn The method the event invokes.
531          * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
532          * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
533          * <code>{single: true}</code> be used so that the handler is removed on first invocation.
534          */
535         onDocumentReady : function(fn, scope, options){
536             if(Ext.isReady){ // if it already fired or document.body is present
537                 docReadyEvent || (docReadyEvent = new Ext.util.Event());
538                 docReadyEvent.addListener(fn, scope, options);
539                 docReadyEvent.fire();
540                 docReadyEvent.listeners = [];
541             }else{
542                 if(!docReadyEvent){
543                     initDocReady();
544                 }
545                 options = options || {};
546                 options.delay = options.delay || 1;
547                 docReadyEvent.addListener(fn, scope, options);
548             }
549         },
550
551         /**
552          * Forces a document ready state transition for the framework.  Used when Ext is loaded
553          * into a DOM structure AFTER initial page load (Google API or other dynamic load scenario.
554          * Any pending 'onDocumentReady' handlers will be fired (if not already handled).
555          */
556         fireDocReady  : fireDocReady
557     };
558      /**
559      * Appends an event handler to an element.  Shorthand for {@link #addListener}.
560      * @param {String/HTMLElement} el The html element or id to assign the event handler to
561      * @param {String} eventName The name of the event to listen for.
562      * @param {Function} handler The handler function the event invokes.
563      * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
564      * @param {Object} options (optional) An object containing standard {@link #addListener} options
565      * @member Ext.EventManager
566      * @method on
567      */
568     pub.on = pub.addListener;
569     /**
570      * Removes an event handler from an element.  Shorthand for {@link #removeListener}.
571      * @param {String/HTMLElement} el The id or html element from which to remove the listener.
572      * @param {String} eventName The name of the event.
573      * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
574      * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
575      * then this must refer to the same object.
576      * @member Ext.EventManager
577      * @method un
578      */
579     pub.un = pub.removeListener;
580
581     pub.stoppedMouseDownEvent = new Ext.util.Event();
582     return pub;
583 }();
584 /**
585   * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
586   * @param {Function} fn The method the event invokes.
587   * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
588   * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
589   * <code>{single: true}</code> be used so that the handler is removed on first invocation.
590   * @member Ext
591   * @method onReady
592  */
593 Ext.onReady = Ext.EventManager.onDocumentReady;
594
595
596 //Initialize doc classes
597 (function(){
598
599     var initExtCss = function(){
600         // find the body element
601         var bd = document.body || document.getElementsByTagName('body')[0];
602         if(!bd){ return false; }
603         var cls = [' ',
604                 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
605                 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
606                 : Ext.isOpera ? "ext-opera"
607                 : Ext.isWebKit ? "ext-webkit" : ""];
608
609         if(Ext.isSafari){
610             cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
611         }else if(Ext.isChrome){
612             cls.push("ext-chrome");
613         }
614
615         if(Ext.isMac){
616             cls.push("ext-mac");
617         }
618         if(Ext.isLinux){
619             cls.push("ext-linux");
620         }
621
622         if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
623             var p = bd.parentNode;
624             if(p){
625                 p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
626             }
627         }
628         bd.className += cls.join(' ');
629         return true;
630     }
631
632     if(!initExtCss()){
633         Ext.onReady(initExtCss);
634     }
635 })();
636
637
638 /**
639  * @class Ext.EventObject
640  * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject
641  * wraps the browser's native event-object normalizing cross-browser differences,
642  * such as which mouse button is clicked, keys pressed, mechanisms to stop
643  * event-propagation along with a method to prevent default actions from taking place.
644  * <p>For example:</p>
645  * <pre><code>
646 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
647     e.preventDefault();
648     var target = e.getTarget(); // same as t (the target HTMLElement)
649     ...
650 }
651 var myDiv = {@link Ext#get Ext.get}("myDiv");  // get reference to an {@link Ext.Element}
652 myDiv.on(         // 'on' is shorthand for addListener
653     "click",      // perform an action on click of myDiv
654     handleClick   // reference to the action handler
655 );
656 // other methods to do the same:
657 Ext.EventManager.on("myDiv", 'click', handleClick);
658 Ext.EventManager.addListener("myDiv", 'click', handleClick);
659  </code></pre>
660  * @singleton
661  */
662 Ext.EventObject = function(){
663     var E = Ext.lib.Event,
664         // safari keypress events for special keys return bad keycodes
665         safariKeys = {
666             3 : 13, // enter
667             63234 : 37, // left
668             63235 : 39, // right
669             63232 : 38, // up
670             63233 : 40, // down
671             63276 : 33, // page up
672             63277 : 34, // page down
673             63272 : 46, // delete
674             63273 : 36, // home
675             63275 : 35  // end
676         },
677         // normalize button clicks
678         btnMap = Ext.isIE ? {1:0,4:1,2:2} :
679                 (Ext.isWebKit ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
680
681     Ext.EventObjectImpl = function(e){
682         if(e){
683             this.setEvent(e.browserEvent || e);
684         }
685     };
686
687     Ext.EventObjectImpl.prototype = {
688            /** @private */
689         setEvent : function(e){
690             var me = this;
691             if(e == me || (e && e.browserEvent)){ // already wrapped
692                 return e;
693             }
694             me.browserEvent = e;
695             if(e){
696                 // normalize buttons
697                 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
698                 if(e.type == 'click' && me.button == -1){
699                     me.button = 0;
700                 }
701                 me.type = e.type;
702                 me.shiftKey = e.shiftKey;
703                 // mac metaKey behaves like ctrlKey
704                 me.ctrlKey = e.ctrlKey || e.metaKey || false;
705                 me.altKey = e.altKey;
706                 // in getKey these will be normalized for the mac
707                 me.keyCode = e.keyCode;
708                 me.charCode = e.charCode;
709                 // cache the target for the delayed and or buffered events
710                 me.target = E.getTarget(e);
711                 // same for XY
712                 me.xy = E.getXY(e);
713             }else{
714                 me.button = -1;
715                 me.shiftKey = false;
716                 me.ctrlKey = false;
717                 me.altKey = false;
718                 me.keyCode = 0;
719                 me.charCode = 0;
720                 me.target = null;
721                 me.xy = [0, 0];
722             }
723             return me;
724         },
725
726         /**
727          * Stop the event (preventDefault and stopPropagation)
728          */
729         stopEvent : function(){
730             var me = this;
731             if(me.browserEvent){
732                 if(me.browserEvent.type == 'mousedown'){
733                     Ext.EventManager.stoppedMouseDownEvent.fire(me);
734                 }
735                 E.stopEvent(me.browserEvent);
736             }
737         },
738
739         /**
740          * Prevents the browsers default handling of the event.
741          */
742         preventDefault : function(){
743             if(this.browserEvent){
744                 E.preventDefault(this.browserEvent);
745             }
746         },
747
748         /**
749          * Cancels bubbling of the event.
750          */
751         stopPropagation : function(){
752             var me = this;
753             if(me.browserEvent){
754                 if(me.browserEvent.type == 'mousedown'){
755                     Ext.EventManager.stoppedMouseDownEvent.fire(me);
756                 }
757                 E.stopPropagation(me.browserEvent);
758             }
759         },
760
761         /**
762          * Gets the character code for the event.
763          * @return {Number}
764          */
765         getCharCode : function(){
766             return this.charCode || this.keyCode;
767         },
768
769         /**
770          * Returns a normalized keyCode for the event.
771          * @return {Number} The key code
772          */
773         getKey : function(){
774             return this.normalizeKey(this.keyCode || this.charCode)
775         },
776
777         // private
778         normalizeKey: function(k){
779             return Ext.isSafari ? (safariKeys[k] || k) : k;
780         },
781
782         /**
783          * Gets the x coordinate of the event.
784          * @return {Number}
785          */
786         getPageX : function(){
787             return this.xy[0];
788         },
789
790         /**
791          * Gets the y coordinate of the event.
792          * @return {Number}
793          */
794         getPageY : function(){
795             return this.xy[1];
796         },
797
798         /**
799          * Gets the page coordinates of the event.
800          * @return {Array} The xy values like [x, y]
801          */
802         getXY : function(){
803             return this.xy;
804         },
805
806         /**
807          * Gets the target for the event.
808          * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
809          * @param {Number/Mixed} maxDepth (optional) The max depth to
810                 search as a number or element (defaults to 10 || document.body)
811          * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
812          * @return {HTMLelement}
813          */
814         getTarget : function(selector, maxDepth, returnEl){
815             return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
816         },
817
818         /**
819          * Gets the related target.
820          * @return {HTMLElement}
821          */
822         getRelatedTarget : function(){
823             return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
824         },
825
826         /**
827          * Normalizes mouse wheel delta across browsers
828          * @return {Number} The delta
829          */
830         getWheelDelta : function(){
831             var e = this.browserEvent;
832             var delta = 0;
833             if(e.wheelDelta){ /* IE/Opera. */
834                 delta = e.wheelDelta/120;
835             }else if(e.detail){ /* Mozilla case. */
836                 delta = -e.detail/3;
837             }
838             return delta;
839         },
840
841         /**
842         * Returns true if the target of this event is a child of el.  Unless the allowEl parameter is set, it will return false if if the target is el.
843         * Example usage:<pre><code>
844         // Handle click on any child of an element
845         Ext.getBody().on('click', function(e){
846             if(e.within('some-el')){
847                 alert('Clicked on a child of some-el!');
848             }
849         });
850
851         // Handle click directly on an element, ignoring clicks on child nodes
852         Ext.getBody().on('click', function(e,t){
853             if((t.id == 'some-el') && !e.within(t, true)){
854                 alert('Clicked directly on some-el!');
855             }
856         });
857         </code></pre>
858          * @param {Mixed} el The id, DOM element or Ext.Element to check
859          * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
860          * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
861          * @return {Boolean}
862          */
863         within : function(el, related, allowEl){
864             if(el){
865                 var t = this[related ? "getRelatedTarget" : "getTarget"]();
866                 return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
867             }
868             return false;
869         }
870      };
871
872     return new Ext.EventObjectImpl();
873 }();