Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / pkgs / pkg-tabs-debug.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.TabPanel
9  * <p>A basic tab container. TabPanels can be used exactly like a standard {@link Ext.Panel}
10  * for layout purposes, but also have special support for containing child Components
11  * (<tt>{@link Ext.Container#items items}</tt>) that are managed using a
12  * {@link Ext.layout.CardLayout CardLayout layout manager}, and displayed as separate tabs.</p>
13  *
14  * <b>Note:</b> By default, a tab's close tool <i>destroys</i> the child tab Component
15  * and all its descendants. This makes the child tab Component, and all its descendants <b>unusable</b>. To enable
16  * re-use of a tab, configure the TabPanel with <b><code>{@link #autoDestroy autoDestroy: false}</code></b>.
17  *
18  * <p><b><u>TabPanel header/footer elements</u></b></p>
19  * <p>TabPanels use their {@link Ext.Panel#header header} or {@link Ext.Panel#footer footer} element
20  * (depending on the {@link #tabPosition} configuration) to accommodate the tab selector buttons.
21  * This means that a TabPanel will not display any configured title, and will not display any
22  * configured header {@link Ext.Panel#tools tools}.</p>
23  * <p>To display a header, embed the TabPanel in a {@link Ext.Panel Panel} which uses
24  * <b><tt>{@link Ext.Container#layout layout:'fit'}</tt></b>.</p>
25  *
26  * <p><b><u>Tab Events</u></b></p>
27  * <p>There is no actual tab class &mdash; each tab is simply a {@link Ext.BoxComponent Component}
28  * such as a {@link Ext.Panel Panel}. However, when rendered in a TabPanel, each child Component
29  * can fire additional events that only exist for tabs and are not available from other Components.
30  * These events are:</p>
31  * <div><ul class="mdetail-params">
32  * <li><tt><b>{@link Ext.Panel#activate activate}</b></tt> : Fires when this Component becomes
33  * the active tab.</li>
34  * <li><tt><b>{@link Ext.Panel#deactivate deactivate}</b></tt> : Fires when the Component that
35  * was the active tab becomes deactivated.</li>
36  * </ul></div>
37  * <p><b><u>Creating TabPanels from Code</u></b></p>
38  * <p>TabPanels can be created and rendered completely in code, as in this example:</p>
39  * <pre><code>
40 var tabs = new Ext.TabPanel({
41     renderTo: Ext.getBody(),
42     activeTab: 0,
43     items: [{
44         title: 'Tab 1',
45         html: 'A simple tab'
46     },{
47         title: 'Tab 2',
48         html: 'Another one'
49     }]
50 });
51 </code></pre>
52  * <p><b><u>Creating TabPanels from Existing Markup</u></b></p>
53  * <p>TabPanels can also be rendered from pre-existing markup in a couple of ways.</p>
54  * <div><ul class="mdetail-params">
55  *
56  * <li>Pre-Structured Markup</li>
57  * <div class="sub-desc">
58  * <p>A container div with one or more nested tab divs with class <tt>'x-tab'</tt> can be rendered entirely
59  * from existing markup (See the {@link #autoTabs} example).</p>
60  * </div>
61  *
62  * <li>Un-Structured Markup</li>
63  * <div class="sub-desc">
64  * <p>A TabPanel can also be rendered from markup that is not strictly structured by simply specifying by id
65  * which elements should be the container and the tabs. Using this method tab content can be pulled from different
66  * elements within the page by id regardless of page structure. For example:</p>
67  * <pre><code>
68 var tabs = new Ext.TabPanel({
69     renderTo: 'my-tabs',
70     activeTab: 0,
71     items:[
72         {contentEl:'tab1', title:'Tab 1'},
73         {contentEl:'tab2', title:'Tab 2'}
74     ]
75 });
76
77 // Note that the tabs do not have to be nested within the container (although they can be)
78 &lt;div id="my-tabs">&lt;/div>
79 &lt;div id="tab1" class="x-hide-display">A simple tab&lt;/div>
80 &lt;div id="tab2" class="x-hide-display">Another one&lt;/div>
81 </code></pre>
82  * Note that the tab divs in this example contain the class <tt>'x-hide-display'</tt> so that they can be rendered
83  * deferred without displaying outside the tabs. You could alternately set <tt>{@link #deferredRender} = false </tt>
84  * to render all content tabs on page load.
85  * </div>
86  *
87  * </ul></div>
88  *
89  * @extends Ext.Panel
90  * @constructor
91  * @param {Object} config The configuration options
92  * @xtype tabpanel
93  */
94 Ext.TabPanel = Ext.extend(Ext.Panel,  {
95     /**
96      * @cfg {Boolean} layoutOnTabChange
97      * Set to true to force a layout of the active tab when the tab is changed. Defaults to false.
98      * See {@link Ext.layout.CardLayout}.<code>{@link Ext.layout.CardLayout#layoutOnCardChange layoutOnCardChange}</code>.
99      */
100     /**
101      * @cfg {String} tabCls <b>This config option is used on <u>child Components</u> of ths TabPanel.</b> A CSS
102      * class name applied to the tab strip item representing the child Component, allowing special
103      * styling to be applied.
104      */
105     /**
106      * @cfg {Boolean} monitorResize True to automatically monitor window resize events and rerender the layout on
107      * browser resize (defaults to true).
108      */
109     monitorResize : true,
110     /**
111      * @cfg {Boolean} deferredRender
112      * <p><tt>true</tt> by default to defer the rendering of child <tt>{@link Ext.Container#items items}</tt>
113      * to the browsers DOM until a tab is activated. <tt>false</tt> will render all contained
114      * <tt>{@link Ext.Container#items items}</tt> as soon as the {@link Ext.layout.CardLayout layout}
115      * is rendered. If there is a significant amount of content or a lot of heavy controls being
116      * rendered into panels that are not displayed by default, setting this to <tt>true</tt> might
117      * improve performance.</p>
118      * <br><p>The <tt>deferredRender</tt> property is internally passed to the layout manager for
119      * TabPanels ({@link Ext.layout.CardLayout}) as its {@link Ext.layout.CardLayout#deferredRender}
120      * configuration value.</p>
121      * <br><p><b>Note</b>: leaving <tt>deferredRender</tt> as <tt>true</tt> means that the content
122      * within an unactivated tab will not be available. For example, this means that if the TabPanel
123      * is within a {@link Ext.form.FormPanel form}, then until a tab is activated, any Fields within
124      * unactivated tabs will not be rendered, and will therefore not be submitted and will not be
125      * available to either {@link Ext.form.BasicForm#getValues getValues} or
126      * {@link Ext.form.BasicForm#setValues setValues}.</p>
127      */
128     deferredRender : true,
129     /**
130      * @cfg {Number} tabWidth The initial width in pixels of each new tab (defaults to 120).
131      */
132     tabWidth : 120,
133     /**
134      * @cfg {Number} minTabWidth The minimum width in pixels for each tab when {@link #resizeTabs} = true (defaults to 30).
135      */
136     minTabWidth : 30,
137     /**
138      * @cfg {Boolean} resizeTabs True to automatically resize each tab so that the tabs will completely fill the
139      * tab strip (defaults to false).  Setting this to true may cause specific widths that might be set per tab to
140      * be overridden in order to fit them all into view (although {@link #minTabWidth} will always be honored).
141      */
142     resizeTabs : false,
143     /**
144      * @cfg {Boolean} enableTabScroll True to enable scrolling to tabs that may be invisible due to overflowing the
145      * overall TabPanel width. Only available with tabPosition:'top' (defaults to false).
146      */
147     enableTabScroll : false,
148     /**
149      * @cfg {Number} scrollIncrement The number of pixels to scroll each time a tab scroll button is pressed
150      * (defaults to <tt>100</tt>, or if <tt>{@link #resizeTabs} = true</tt>, the calculated tab width).  Only
151      * applies when <tt>{@link #enableTabScroll} = true</tt>.
152      */
153     scrollIncrement : 0,
154     /**
155      * @cfg {Number} scrollRepeatInterval Number of milliseconds between each scroll while a tab scroll button is
156      * continuously pressed (defaults to <tt>400</tt>).
157      */
158     scrollRepeatInterval : 400,
159     /**
160      * @cfg {Float} scrollDuration The number of milliseconds that each scroll animation should last (defaults
161      * to <tt>.35</tt>). Only applies when <tt>{@link #animScroll} = true</tt>.
162      */
163     scrollDuration : 0.35,
164     /**
165      * @cfg {Boolean} animScroll True to animate tab scrolling so that hidden tabs slide smoothly into view (defaults
166      * to <tt>true</tt>).  Only applies when <tt>{@link #enableTabScroll} = true</tt>.
167      */
168     animScroll : true,
169     /**
170      * @cfg {String} tabPosition The position where the tab strip should be rendered (defaults to <tt>'top'</tt>).
171      * The only other supported value is <tt>'bottom'</tt>.  <b>Note</b>: tab scrolling is only supported for
172      * <tt>tabPosition: 'top'</tt>.
173      */
174     tabPosition : 'top',
175     /**
176      * @cfg {String} baseCls The base CSS class applied to the panel (defaults to <tt>'x-tab-panel'</tt>).
177      */
178     baseCls : 'x-tab-panel',
179     /**
180      * @cfg {Boolean} autoTabs
181      * <p><tt>true</tt> to query the DOM for any divs with a class of 'x-tab' to be automatically converted
182      * to tabs and added to this panel (defaults to <tt>false</tt>).  Note that the query will be executed within
183      * the scope of the container element only (so that multiple tab panels from markup can be supported via this
184      * method).</p>
185      * <p>This method is only possible when the markup is structured correctly as a container with nested divs
186      * containing the class <tt>'x-tab'</tt>. To create TabPanels without these limitations, or to pull tab content
187      * from other elements on the page, see the example at the top of the class for generating tabs from markup.</p>
188      * <p>There are a couple of things to note when using this method:<ul>
189      * <li>When using the <tt>autoTabs</tt> config (as opposed to passing individual tab configs in the TabPanel's
190      * {@link #items} collection), you must use <tt>{@link #applyTo}</tt> to correctly use the specified <tt>id</tt>
191      * as the tab container. The <tt>autoTabs</tt> method <em>replaces</em> existing content with the TabPanel
192      * components.</li>
193      * <li>Make sure that you set <tt>{@link #deferredRender}: false</tt> so that the content elements for each
194      * tab will be rendered into the TabPanel immediately upon page load, otherwise they will not be transformed
195      * until each tab is activated and will be visible outside the TabPanel.</li>
196      * </ul>Example usage:</p>
197      * <pre><code>
198 var tabs = new Ext.TabPanel({
199     applyTo: 'my-tabs',
200     activeTab: 0,
201     deferredRender: false,
202     autoTabs: true
203 });
204
205 // This markup will be converted to a TabPanel from the code above
206 &lt;div id="my-tabs">
207     &lt;div class="x-tab" title="Tab 1">A simple tab&lt;/div>
208     &lt;div class="x-tab" title="Tab 2">Another one&lt;/div>
209 &lt;/div>
210 </code></pre>
211      */
212     autoTabs : false,
213     /**
214      * @cfg {String} autoTabSelector The CSS selector used to search for tabs in existing markup when
215      * <tt>{@link #autoTabs} = true</tt> (defaults to <tt>'div.x-tab'</tt>).  This can be any valid selector
216      * supported by {@link Ext.DomQuery#select}. Note that the query will be executed within the scope of this
217      * tab panel only (so that multiple tab panels from markup can be supported on a page).
218      */
219     autoTabSelector : 'div.x-tab',
220     /**
221      * @cfg {String/Number} activeTab A string id or the numeric index of the tab that should be initially
222      * activated on render (defaults to none).
223      */
224     activeTab : null,
225     /**
226      * @cfg {Number} tabMargin The number of pixels of space to calculate into the sizing and scrolling of
227      * tabs. If you change the margin in CSS, you will need to update this value so calculations are correct
228      * with either <tt>{@link #resizeTabs}</tt> or scrolling tabs. (defaults to <tt>2</tt>)
229      */
230     tabMargin : 2,
231     /**
232      * @cfg {Boolean} plain </tt>true</tt> to render the tab strip without a background container image
233      * (defaults to <tt>false</tt>).
234      */
235     plain : false,
236     /**
237      * @cfg {Number} wheelIncrement For scrolling tabs, the number of pixels to increment on mouse wheel
238      * scrolling (defaults to <tt>20</tt>).
239      */
240     wheelIncrement : 20,
241
242     /*
243      * This is a protected property used when concatenating tab ids to the TabPanel id for internal uniqueness.
244      * It does not generally need to be changed, but can be if external code also uses an id scheme that can
245      * potentially clash with this one.
246      */
247     idDelimiter : '__',
248
249     // private
250     itemCls : 'x-tab-item',
251
252     // private config overrides
253     elements : 'body',
254     headerAsText : false,
255     frame : false,
256     hideBorders :true,
257
258     // private
259     initComponent : function(){
260         this.frame = false;
261         Ext.TabPanel.superclass.initComponent.call(this);
262         this.addEvents(
263             /**
264              * @event beforetabchange
265              * Fires before the active tab changes. Handlers can <tt>return false</tt> to cancel the tab change.
266              * @param {TabPanel} this
267              * @param {Panel} newTab The tab being activated
268              * @param {Panel} currentTab The current active tab
269              */
270             'beforetabchange',
271             /**
272              * @event tabchange
273              * Fires after the active tab has changed.
274              * @param {TabPanel} this
275              * @param {Panel} tab The new active tab
276              */
277             'tabchange',
278             /**
279              * @event contextmenu
280              * Relays the contextmenu event from a tab selector element in the tab strip.
281              * @param {TabPanel} this
282              * @param {Panel} tab The target tab
283              * @param {EventObject} e
284              */
285             'contextmenu'
286         );
287         /**
288          * @cfg {Object} layoutConfig
289          * TabPanel implicitly uses {@link Ext.layout.CardLayout} as its layout manager.
290          * <code>layoutConfig</code> may be used to configure this layout manager.
291          * <code>{@link #deferredRender}</code> and <code>{@link #layoutOnTabChange}</code>
292          * configured on the TabPanel will be applied as configs to the layout manager.
293          */
294         this.setLayout(new Ext.layout.CardLayout(Ext.apply({
295             layoutOnCardChange: this.layoutOnTabChange,
296             deferredRender: this.deferredRender
297         }, this.layoutConfig)));
298
299         if(this.tabPosition == 'top'){
300             this.elements += ',header';
301             this.stripTarget = 'header';
302         }else {
303             this.elements += ',footer';
304             this.stripTarget = 'footer';
305         }
306         if(!this.stack){
307             this.stack = Ext.TabPanel.AccessStack();
308         }
309         this.initItems();
310     },
311
312     // private
313     onRender : function(ct, position){
314         Ext.TabPanel.superclass.onRender.call(this, ct, position);
315
316         if(this.plain){
317             var pos = this.tabPosition == 'top' ? 'header' : 'footer';
318             this[pos].addClass('x-tab-panel-'+pos+'-plain');
319         }
320
321         var st = this[this.stripTarget];
322
323         this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{
324             tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}});
325
326         var beforeEl = (this.tabPosition=='bottom' ? this.stripWrap : null);
327         this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'}, beforeEl);
328         this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
329
330         this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'});
331         this.strip.createChild({cls:'x-clear'});
332
333         this.body.addClass('x-tab-panel-body-'+this.tabPosition);
334
335         /**
336          * @cfg {Template/XTemplate} itemTpl <p>(Optional) A {@link Ext.Template Template} or
337          * {@link Ext.XTemplate XTemplate} which may be provided to process the data object returned from
338          * <tt>{@link #getTemplateArgs}</tt> to produce a clickable selector element in the tab strip.</p>
339          * <p>The main element created should be a <tt>&lt;li></tt> element. In order for a click event on
340          * a selector element to be connected to its item, it must take its <i>id</i> from the TabPanel's
341          * native <tt>{@link #getTemplateArgs}</tt>.</p>
342          * <p>The child element which contains the title text must be marked by the CSS class
343          * <tt>x-tab-strip-inner</tt>.</p>
344          * <p>To enable closability, the created element should contain an element marked by the CSS class
345          * <tt>x-tab-strip-close</tt>.</p>
346          * <p>If a custom <tt>itemTpl</tt> is supplied, it is the developer's responsibility to create CSS
347          * style rules to create the desired appearance.</p>
348          * Below is an example of how to create customized tab selector items:<pre><code>
349 new Ext.TabPanel({
350     renderTo: document.body,
351     minTabWidth: 115,
352     tabWidth: 135,
353     enableTabScroll: true,
354     width: 600,
355     height: 250,
356     defaults: {autoScroll:true},
357     itemTpl: new Ext.XTemplate(
358     '&lt;li class="{cls}" id="{id}" style="overflow:hidden">',
359          '&lt;tpl if="closable">',
360             '&lt;a class="x-tab-strip-close" onclick="return false;">&lt;/a>',
361          '&lt;/tpl>',
362          '&lt;a class="x-tab-right" href="#" onclick="return false;" style="padding-left:6px">',
363             '&lt;em class="x-tab-left">',
364                 '&lt;span class="x-tab-strip-inner">',
365                     '&lt;img src="{src}" style="float:left;margin:3px 3px 0 0">',
366                     '&lt;span style="margin-left:20px" class="x-tab-strip-text {iconCls}">{text} {extra}&lt;/span>',
367                 '&lt;/span>',
368             '&lt;/em>',
369         '&lt;/a>',
370     '&lt;/li>'
371     ),
372     getTemplateArgs: function(item) {
373 //      Call the native method to collect the base data. Like the ID!
374         var result = Ext.TabPanel.prototype.getTemplateArgs.call(this, item);
375
376 //      Add stuff used in our template
377         return Ext.apply(result, {
378             closable: item.closable,
379             src: item.iconSrc,
380             extra: item.extraText || ''
381         });
382     },
383     items: [{
384         title: 'New Tab 1',
385         iconSrc: '../shared/icons/fam/grid.png',
386         html: 'Tab Body 1',
387         closable: true
388     }, {
389         title: 'New Tab 2',
390         iconSrc: '../shared/icons/fam/grid.png',
391         html: 'Tab Body 2',
392         extraText: 'Extra stuff in the tab button'
393     }]
394 });
395 </code></pre>
396          */
397         if(!this.itemTpl){
398             var tt = new Ext.Template(
399                  '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>',
400                  '<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">',
401                  '<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>',
402                  '</em></a></li>'
403             );
404             tt.disableFormats = true;
405             tt.compile();
406             Ext.TabPanel.prototype.itemTpl = tt;
407         }
408
409         this.items.each(this.initTab, this);
410     },
411
412     // private
413     afterRender : function(){
414         Ext.TabPanel.superclass.afterRender.call(this);
415         if(this.autoTabs){
416             this.readTabs(false);
417         }
418         if(this.activeTab !== undefined){
419             var item = Ext.isObject(this.activeTab) ? this.activeTab : this.items.get(this.activeTab);
420             delete this.activeTab;
421             this.setActiveTab(item);
422         }
423     },
424
425     // private
426     initEvents : function(){
427         Ext.TabPanel.superclass.initEvents.call(this);
428         this.mon(this.strip, {
429             scope: this,
430             mousedown: this.onStripMouseDown,
431             contextmenu: this.onStripContextMenu
432         });
433         if(this.enableTabScroll){
434             this.mon(this.strip, 'mousewheel', this.onWheel, this);
435         }
436     },
437
438     // private
439     findTargets : function(e){
440         var item = null;
441         var itemEl = e.getTarget('li', this.strip);
442         if(itemEl){
443             item = this.getComponent(itemEl.id.split(this.idDelimiter)[1]);
444             if(item.disabled){
445                 return {
446                     close : null,
447                     item : null,
448                     el : null
449                 };
450             }
451         }
452         return {
453             close : e.getTarget('.x-tab-strip-close', this.strip),
454             item : item,
455             el : itemEl
456         };
457     },
458
459     // private
460     onStripMouseDown : function(e){
461         if(e.button !== 0){
462             return;
463         }
464         e.preventDefault();
465         var t = this.findTargets(e);
466         if(t.close){
467             if (t.item.fireEvent('beforeclose', t.item) !== false) {
468                 t.item.fireEvent('close', t.item);
469                 delete t.item.tabEl;
470                 this.remove(t.item);
471             }
472             return;
473         }
474         if(t.item && t.item != this.activeTab){
475             this.setActiveTab(t.item);
476         }
477     },
478
479     // private
480     onStripContextMenu : function(e){
481         e.preventDefault();
482         var t = this.findTargets(e);
483         if(t.item){
484             this.fireEvent('contextmenu', this, t.item, e);
485         }
486     },
487
488     /**
489      * True to scan the markup in this tab panel for <tt>{@link #autoTabs}</tt> using the
490      * <tt>{@link #autoTabSelector}</tt>
491      * @param {Boolean} removeExisting True to remove existing tabs
492      */
493     readTabs : function(removeExisting){
494         if(removeExisting === true){
495             this.items.each(function(item){
496                 this.remove(item);
497             }, this);
498         }
499         var tabs = this.el.query(this.autoTabSelector);
500         for(var i = 0, len = tabs.length; i < len; i++){
501             var tab = tabs[i];
502             var title = tab.getAttribute('title');
503             tab.removeAttribute('title');
504             this.add({
505                 title: title,
506                 contentEl: tab
507             });
508         }
509     },
510
511     // private
512     initTab : function(item, index){
513         var before = this.strip.dom.childNodes[index];
514         var p = this.getTemplateArgs(item);
515         var el = before ?
516                  this.itemTpl.insertBefore(before, p) :
517                  this.itemTpl.append(this.strip, p);
518
519         Ext.fly(el).addClassOnOver('x-tab-strip-over');
520
521         if(item.tabTip){
522             Ext.fly(el).child('span.x-tab-strip-text', true).qtip = item.tabTip;
523         }
524         item.tabEl = el;
525
526         item.on('disable', this.onItemDisabled, this);
527         item.on('enable', this.onItemEnabled, this);
528         item.on('titlechange', this.onItemTitleChanged, this);
529         item.on('iconchange', this.onItemIconChanged, this);
530         item.on('beforeshow', this.onBeforeShowItem, this);
531     },
532
533     /**
534      * <p>Provides template arguments for rendering a tab selector item in the tab strip.</p>
535      * <p>This method returns an object hash containing properties used by the TabPanel's <tt>{@link #itemTpl}</tt>
536      * to create a formatted, clickable tab selector element. The properties which must be returned
537      * are:</p><div class="mdetail-params"><ul>
538      * <li><b>id</b> : String<div class="sub-desc">A unique identifier which links to the item</div></li>
539      * <li><b>text</b> : String<div class="sub-desc">The text to display</div></li>
540      * <li><b>cls</b> : String<div class="sub-desc">The CSS class name</div></li>
541      * <li><b>iconCls</b> : String<div class="sub-desc">A CSS class to provide appearance for an icon.</div></li>
542      * </ul></div>
543      * @param {BoxComponent} item The {@link Ext.BoxComponent BoxComponent} for which to create a selector element in the tab strip.
544      * @return {Object} An object hash containing the properties required to render the selector element.
545      */
546     getTemplateArgs : function(item) {
547         var cls = item.closable ? 'x-tab-strip-closable' : '';
548         if(item.disabled){
549             cls += ' x-item-disabled';
550         }
551         if(item.iconCls){
552             cls += ' x-tab-with-icon';
553         }
554         if(item.tabCls){
555             cls += ' ' + item.tabCls;
556         }
557
558         return {
559             id: this.id + this.idDelimiter + item.getItemId(),
560             text: item.title,
561             cls: cls,
562             iconCls: item.iconCls || ''
563         };
564     },
565
566     // private
567     onAdd : function(c){
568         Ext.TabPanel.superclass.onAdd.call(this, c);
569         if(this.rendered){
570             var items = this.items;
571             this.initTab(c, items.indexOf(c));
572             if(items.getCount() == 1){
573                 this.syncSize();
574             }
575             this.delegateUpdates();
576         }
577     },
578
579     // private
580     onBeforeAdd : function(item){
581         var existing = item.events ? (this.items.containsKey(item.getItemId()) ? item : null) : this.items.get(item);
582         if(existing){
583             this.setActiveTab(item);
584             return false;
585         }
586         Ext.TabPanel.superclass.onBeforeAdd.apply(this, arguments);
587         var es = item.elements;
588         item.elements = es ? es.replace(',header', '') : es;
589         item.border = (item.border === true);
590     },
591
592     // private
593     onRemove : function(c){
594         Ext.TabPanel.superclass.onRemove.call(this, c);
595         Ext.destroy(Ext.get(this.getTabEl(c)));
596         this.stack.remove(c);
597         c.un('disable', this.onItemDisabled, this);
598         c.un('enable', this.onItemEnabled, this);
599         c.un('titlechange', this.onItemTitleChanged, this);
600         c.un('iconchange', this.onItemIconChanged, this);
601         c.un('beforeshow', this.onBeforeShowItem, this);
602         if(c == this.activeTab){
603             var next = this.stack.next();
604             if(next){
605                 this.setActiveTab(next);
606             }else if(this.items.getCount() > 0){
607                 this.setActiveTab(0);
608             }else{
609                 this.activeTab = null;
610             }
611         }
612         this.delegateUpdates();
613     },
614
615     // private
616     onBeforeShowItem : function(item){
617         if(item != this.activeTab){
618             this.setActiveTab(item);
619             return false;
620         }
621     },
622
623     // private
624     onItemDisabled : function(item){
625         var el = this.getTabEl(item);
626         if(el){
627             Ext.fly(el).addClass('x-item-disabled');
628         }
629         this.stack.remove(item);
630     },
631
632     // private
633     onItemEnabled : function(item){
634         var el = this.getTabEl(item);
635         if(el){
636             Ext.fly(el).removeClass('x-item-disabled');
637         }
638     },
639
640     // private
641     onItemTitleChanged : function(item){
642         var el = this.getTabEl(item);
643         if(el){
644             Ext.fly(el).child('span.x-tab-strip-text', true).innerHTML = item.title;
645         }
646     },
647
648     //private
649     onItemIconChanged : function(item, iconCls, oldCls){
650         var el = this.getTabEl(item);
651         if(el){
652             el = Ext.get(el);
653             el.child('span.x-tab-strip-text').replaceClass(oldCls, iconCls);
654             el[Ext.isEmpty(iconCls) ? 'removeClass' : 'addClass']('x-tab-with-icon');
655         }
656     },
657
658     /**
659      * Gets the DOM element for the tab strip item which activates the child panel with the specified
660      * ID. Access this to change the visual treatment of the item, for example by changing the CSS class name.
661      * @param {Panel/Number/String} tab The tab component, or the tab's index, or the tabs id or itemId.
662      * @return {HTMLElement} The DOM node
663      */
664     getTabEl : function(item){
665         return document.getElementById(this.id + this.idDelimiter + this.getComponent(item).getItemId());
666     },
667
668     // private
669     onResize : function(){
670         Ext.TabPanel.superclass.onResize.apply(this, arguments);
671         this.delegateUpdates();
672     },
673
674     /**
675      * Suspends any internal calculations or scrolling while doing a bulk operation. See {@link #endUpdate}
676      */
677     beginUpdate : function(){
678         this.suspendUpdates = true;
679     },
680
681     /**
682      * Resumes calculations and scrolling at the end of a bulk operation. See {@link #beginUpdate}
683      */
684     endUpdate : function(){
685         this.suspendUpdates = false;
686         this.delegateUpdates();
687     },
688
689     /**
690      * Hides the tab strip item for the passed tab
691      * @param {Number/String/Panel} item The tab index, id or item
692      */
693     hideTabStripItem : function(item){
694         item = this.getComponent(item);
695         var el = this.getTabEl(item);
696         if(el){
697             el.style.display = 'none';
698             this.delegateUpdates();
699         }
700         this.stack.remove(item);
701     },
702
703     /**
704      * Unhides the tab strip item for the passed tab
705      * @param {Number/String/Panel} item The tab index, id or item
706      */
707     unhideTabStripItem : function(item){
708         item = this.getComponent(item);
709         var el = this.getTabEl(item);
710         if(el){
711             el.style.display = '';
712             this.delegateUpdates();
713         }
714     },
715
716     // private
717     delegateUpdates : function(){
718         if(this.suspendUpdates){
719             return;
720         }
721         if(this.resizeTabs && this.rendered){
722             this.autoSizeTabs();
723         }
724         if(this.enableTabScroll && this.rendered){
725             this.autoScrollTabs();
726         }
727     },
728
729     // private
730     autoSizeTabs : function(){
731         var count = this.items.length;
732         var ce = this.tabPosition != 'bottom' ? 'header' : 'footer';
733         var ow = this[ce].dom.offsetWidth;
734         var aw = this[ce].dom.clientWidth;
735
736         if(!this.resizeTabs || count < 1 || !aw){ // !aw for display:none
737             return;
738         }
739
740         var each = Math.max(Math.min(Math.floor((aw-4) / count) - this.tabMargin, this.tabWidth), this.minTabWidth); // -4 for float errors in IE
741         this.lastTabWidth = each;
742         var lis = this.strip.query("li:not([className^=x-tab-edge])");
743         for(var i = 0, len = lis.length; i < len; i++) {
744             var li = lis[i];
745             var inner = Ext.fly(li).child('.x-tab-strip-inner', true);
746             var tw = li.offsetWidth;
747             var iw = inner.offsetWidth;
748             inner.style.width = (each - (tw-iw)) + 'px';
749         }
750     },
751
752     // private
753     adjustBodyWidth : function(w){
754         if(this.header){
755             this.header.setWidth(w);
756         }
757         if(this.footer){
758             this.footer.setWidth(w);
759         }
760         return w;
761     },
762
763     /**
764      * Sets the specified tab as the active tab. This method fires the {@link #beforetabchange} event which
765      * can <tt>return false</tt> to cancel the tab change.
766      * @param {String/Number} item
767      * The id or tab Panel to activate. This parameter may be any of the following:
768      * <div><ul class="mdetail-params">
769      * <li>a <b><tt>String</tt></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>
770      * or <code>{@link Ext.Component#id id}</code> of the child component </li>
771      * <li>a <b><tt>Number</tt></b> : representing the position of the child component
772      * within the <code>{@link Ext.Container#items items}</code> <b>property</b></li>
773      * </ul></div>
774      * <p>For additional information see {@link Ext.util.MixedCollection#get}.
775      */
776     setActiveTab : function(item){
777         item = this.getComponent(item);
778         if(!item || this.fireEvent('beforetabchange', this, item, this.activeTab) === false){
779             return;
780         }
781         if(!this.rendered){
782             this.activeTab = item;
783             return;
784         }
785         if(this.activeTab != item){
786             if(this.activeTab){
787                 var oldEl = this.getTabEl(this.activeTab);
788                 if(oldEl){
789                     Ext.fly(oldEl).removeClass('x-tab-strip-active');
790                 }
791                 this.activeTab.fireEvent('deactivate', this.activeTab);
792             }
793             var el = this.getTabEl(item);
794             Ext.fly(el).addClass('x-tab-strip-active');
795             this.activeTab = item;
796             this.stack.add(item);
797
798             this.layout.setActiveItem(item);
799             if(this.scrolling){
800                 this.scrollToTab(item, this.animScroll);
801             }
802
803             item.fireEvent('activate', item);
804             this.fireEvent('tabchange', this, item);
805         }
806     },
807
808     /**
809      * Gets the currently active tab.
810      * @return {Panel} The active tab
811      */
812     getActiveTab : function(){
813         return this.activeTab || null;
814     },
815
816     /**
817      * Gets the specified tab by id.
818      * @param {String} id The tab id
819      * @return {Panel} The tab
820      */
821     getItem : function(item){
822         return this.getComponent(item);
823     },
824
825     // private
826     autoScrollTabs : function(){
827         this.pos = this.tabPosition=='bottom' ? this.footer : this.header;
828         var count = this.items.length;
829         var ow = this.pos.dom.offsetWidth;
830         var tw = this.pos.dom.clientWidth;
831
832         var wrap = this.stripWrap;
833         var wd = wrap.dom;
834         var cw = wd.offsetWidth;
835         var pos = this.getScrollPos();
836         var l = this.edge.getOffsetsTo(this.stripWrap)[0] + pos;
837
838         if(!this.enableTabScroll || count < 1 || cw < 20){ // 20 to prevent display:none issues
839             return;
840         }
841         if(l <= tw){
842             wd.scrollLeft = 0;
843             wrap.setWidth(tw);
844             if(this.scrolling){
845                 this.scrolling = false;
846                 this.pos.removeClass('x-tab-scrolling');
847                 this.scrollLeft.hide();
848                 this.scrollRight.hide();
849                 // See here: http://extjs.com/forum/showthread.php?t=49308&highlight=isSafari
850                 if(Ext.isAir || Ext.isWebKit){
851                     wd.style.marginLeft = '';
852                     wd.style.marginRight = '';
853                 }
854             }
855         }else{
856             if(!this.scrolling){
857                 this.pos.addClass('x-tab-scrolling');
858                 // See here: http://extjs.com/forum/showthread.php?t=49308&highlight=isSafari
859                 if(Ext.isAir || Ext.isWebKit){
860                     wd.style.marginLeft = '18px';
861                     wd.style.marginRight = '18px';
862                 }
863             }
864             tw -= wrap.getMargins('lr');
865             wrap.setWidth(tw > 20 ? tw : 20);
866             if(!this.scrolling){
867                 if(!this.scrollLeft){
868                     this.createScrollers();
869                 }else{
870                     this.scrollLeft.show();
871                     this.scrollRight.show();
872                 }
873             }
874             this.scrolling = true;
875             if(pos > (l-tw)){ // ensure it stays within bounds
876                 wd.scrollLeft = l-tw;
877             }else{ // otherwise, make sure the active tab is still visible
878                 this.scrollToTab(this.activeTab, false);
879             }
880             this.updateScrollButtons();
881         }
882     },
883
884     // private
885     createScrollers : function(){
886         this.pos.addClass('x-tab-scrolling-' + this.tabPosition);
887         var h = this.stripWrap.dom.offsetHeight;
888
889         // left
890         var sl = this.pos.insertFirst({
891             cls:'x-tab-scroller-left'
892         });
893         sl.setHeight(h);
894         sl.addClassOnOver('x-tab-scroller-left-over');
895         this.leftRepeater = new Ext.util.ClickRepeater(sl, {
896             interval : this.scrollRepeatInterval,
897             handler: this.onScrollLeft,
898             scope: this
899         });
900         this.scrollLeft = sl;
901
902         // right
903         var sr = this.pos.insertFirst({
904             cls:'x-tab-scroller-right'
905         });
906         sr.setHeight(h);
907         sr.addClassOnOver('x-tab-scroller-right-over');
908         this.rightRepeater = new Ext.util.ClickRepeater(sr, {
909             interval : this.scrollRepeatInterval,
910             handler: this.onScrollRight,
911             scope: this
912         });
913         this.scrollRight = sr;
914     },
915
916     // private
917     getScrollWidth : function(){
918         return this.edge.getOffsetsTo(this.stripWrap)[0] + this.getScrollPos();
919     },
920
921     // private
922     getScrollPos : function(){
923         return parseInt(this.stripWrap.dom.scrollLeft, 10) || 0;
924     },
925
926     // private
927     getScrollArea : function(){
928         return parseInt(this.stripWrap.dom.clientWidth, 10) || 0;
929     },
930
931     // private
932     getScrollAnim : function(){
933         return {duration:this.scrollDuration, callback: this.updateScrollButtons, scope: this};
934     },
935
936     // private
937     getScrollIncrement : function(){
938         return this.scrollIncrement || (this.resizeTabs ? this.lastTabWidth+2 : 100);
939     },
940
941     /**
942      * Scrolls to a particular tab if tab scrolling is enabled
943      * @param {Panel} item The item to scroll to
944      * @param {Boolean} animate True to enable animations
945      */
946
947     scrollToTab : function(item, animate){
948         if(!item){ return; }
949         var el = this.getTabEl(item);
950         var pos = this.getScrollPos(), area = this.getScrollArea();
951         var left = Ext.fly(el).getOffsetsTo(this.stripWrap)[0] + pos;
952         var right = left + el.offsetWidth;
953         if(left < pos){
954             this.scrollTo(left, animate);
955         }else if(right > (pos + area)){
956             this.scrollTo(right - area, animate);
957         }
958     },
959
960     // private
961     scrollTo : function(pos, animate){
962         this.stripWrap.scrollTo('left', pos, animate ? this.getScrollAnim() : false);
963         if(!animate){
964             this.updateScrollButtons();
965         }
966     },
967
968     onWheel : function(e){
969         var d = e.getWheelDelta()*this.wheelIncrement*-1;
970         e.stopEvent();
971
972         var pos = this.getScrollPos();
973         var newpos = pos + d;
974         var sw = this.getScrollWidth()-this.getScrollArea();
975
976         var s = Math.max(0, Math.min(sw, newpos));
977         if(s != pos){
978             this.scrollTo(s, false);
979         }
980     },
981
982     // private
983     onScrollRight : function(){
984         var sw = this.getScrollWidth()-this.getScrollArea();
985         var pos = this.getScrollPos();
986         var s = Math.min(sw, pos + this.getScrollIncrement());
987         if(s != pos){
988             this.scrollTo(s, this.animScroll);
989         }
990     },
991
992     // private
993     onScrollLeft : function(){
994         var pos = this.getScrollPos();
995         var s = Math.max(0, pos - this.getScrollIncrement());
996         if(s != pos){
997             this.scrollTo(s, this.animScroll);
998         }
999     },
1000
1001     // private
1002     updateScrollButtons : function(){
1003         var pos = this.getScrollPos();
1004         this.scrollLeft[pos === 0 ? 'addClass' : 'removeClass']('x-tab-scroller-left-disabled');
1005         this.scrollRight[pos >= (this.getScrollWidth()-this.getScrollArea()) ? 'addClass' : 'removeClass']('x-tab-scroller-right-disabled');
1006     },
1007
1008     // private
1009     beforeDestroy : function() {
1010         if(this.items){
1011             this.items.each(function(item){
1012                 if(item && item.tabEl){
1013                     Ext.get(item.tabEl).removeAllListeners();
1014                     item.tabEl = null;
1015                 }
1016             }, this);
1017         }
1018         if(this.strip){
1019             this.strip.removeAllListeners();
1020         }
1021         Ext.TabPanel.superclass.beforeDestroy.apply(this);
1022     }
1023
1024     /**
1025      * @cfg {Boolean} collapsible
1026      * @hide
1027      */
1028     /**
1029      * @cfg {String} header
1030      * @hide
1031      */
1032     /**
1033      * @cfg {Boolean} headerAsText
1034      * @hide
1035      */
1036     /**
1037      * @property header
1038      * @hide
1039      */
1040     /**
1041      * @cfg title
1042      * @hide
1043      */
1044     /**
1045      * @cfg {Array} tools
1046      * @hide
1047      */
1048     /**
1049      * @cfg {Array} toolTemplate
1050      * @hide
1051      */
1052     /**
1053      * @cfg {Boolean} hideCollapseTool
1054      * @hide
1055      */
1056     /**
1057      * @cfg {Boolean} titleCollapse
1058      * @hide
1059      */
1060     /**
1061      * @cfg {Boolean} collapsed
1062      * @hide
1063      */
1064     /**
1065      * @cfg {String} layout
1066      * @hide
1067      */
1068     /**
1069      * @cfg {Boolean} preventBodyReset
1070      * @hide
1071      */
1072 });
1073 Ext.reg('tabpanel', Ext.TabPanel);
1074
1075 /**
1076  * See {@link #setActiveTab}. Sets the specified tab as the active tab. This method fires
1077  * the {@link #beforetabchange} event which can <tt>return false</tt> to cancel the tab change.
1078  * @param {String/Panel} tab The id or tab Panel to activate
1079  * @method activate
1080  */
1081 Ext.TabPanel.prototype.activate = Ext.TabPanel.prototype.setActiveTab;
1082
1083 // private utility class used by TabPanel
1084 Ext.TabPanel.AccessStack = function(){
1085     var items = [];
1086     return {
1087         add : function(item){
1088             items.push(item);
1089             if(items.length > 10){
1090                 items.shift();
1091             }
1092         },
1093
1094         remove : function(item){
1095             var s = [];
1096             for(var i = 0, len = items.length; i < len; i++) {
1097                 if(items[i] != item){
1098                     s.push(items[i]);
1099                 }
1100             }
1101             items = s;
1102         },
1103
1104         next : function(){
1105             return items.pop();
1106         }
1107     };
1108 };