Upgrade to ExtJS 3.1.1 - Released 02/08/2010
[extjs.git] / src / widgets / Container.js
1 /*!
2  * Ext JS Library 3.1.1
3  * Copyright(c) 2006-2010 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.Container
9  * @extends Ext.BoxComponent
10  * <p>Base class for any {@link Ext.BoxComponent} that may contain other Components. Containers handle the
11  * basic behavior of containing items, namely adding, inserting and removing items.</p>
12  *
13  * <p>The most commonly used Container classes are {@link Ext.Panel}, {@link Ext.Window} and {@link Ext.TabPanel}.
14  * If you do not need the capabilities offered by the aforementioned classes you can create a lightweight
15  * Container to be encapsulated by an HTML element to your specifications by using the
16  * <code><b>{@link Ext.Component#autoEl autoEl}</b></code> config option. This is a useful technique when creating
17  * embedded {@link Ext.layout.ColumnLayout column} layouts inside {@link Ext.form.FormPanel FormPanels}
18  * for example.</p>
19  *
20  * <p>The code below illustrates both how to explicitly create a Container, and how to implicitly
21  * create one using the <b><code>'container'</code></b> xtype:<pre><code>
22 // explicitly create a Container
23 var embeddedColumns = new Ext.Container({
24     autoEl: 'div',  // This is the default
25     layout: 'column',
26     defaults: {
27         // implicitly create Container by specifying xtype
28         xtype: 'container',
29         autoEl: 'div', // This is the default.
30         layout: 'form',
31         columnWidth: 0.5,
32         style: {
33             padding: '10px'
34         }
35     },
36 //  The two items below will be Ext.Containers, each encapsulated by a &lt;DIV> element.
37     items: [{
38         items: {
39             xtype: 'datefield',
40             name: 'startDate',
41             fieldLabel: 'Start date'
42         }
43     }, {
44         items: {
45             xtype: 'datefield',
46             name: 'endDate',
47             fieldLabel: 'End date'
48         }
49     }]
50 });</code></pre></p>
51  *
52  * <p><u><b>Layout</b></u></p>
53  * <p>Container classes delegate the rendering of child Components to a layout
54  * manager class which must be configured into the Container using the
55  * <code><b>{@link #layout}</b></code> configuration property.</p>
56  * <p>When either specifying child <code>{@link #items}</code> of a Container,
57  * or dynamically {@link #add adding} Components to a Container, remember to
58  * consider how you wish the Container to arrange those child elements, and
59  * whether those child elements need to be sized using one of Ext's built-in
60  * <b><code>{@link #layout}</code></b> schemes. By default, Containers use the
61  * {@link Ext.layout.ContainerLayout ContainerLayout} scheme which only
62  * renders child components, appending them one after the other inside the
63  * Container, and <b>does not apply any sizing</b> at all.</p>
64  * <p>A common mistake is when a developer neglects to specify a
65  * <b><code>{@link #layout}</code></b> (e.g. widgets like GridPanels or
66  * TreePanels are added to Containers for which no <code><b>{@link #layout}</b></code>
67  * has been specified). If a Container is left to use the default
68  * {@link Ext.layout.ContainerLayout ContainerLayout} scheme, none of its
69  * child components will be resized, or changed in any way when the Container
70  * is resized.</p>
71  * <p>Certain layout managers allow dynamic addition of child components.
72  * Those that do include {@link Ext.layout.CardLayout},
73  * {@link Ext.layout.AnchorLayout}, {@link Ext.layout.FormLayout}, and
74  * {@link Ext.layout.TableLayout}. For example:<pre><code>
75 //  Create the GridPanel.
76 var myNewGrid = new Ext.grid.GridPanel({
77     store: myStore,
78     columns: myColumnModel,
79     title: 'Results', // the title becomes the title of the tab
80 });
81
82 myTabPanel.add(myNewGrid); // {@link Ext.TabPanel} implicitly uses {@link Ext.layout.CardLayout CardLayout}
83 myTabPanel.{@link Ext.TabPanel#setActiveTab setActiveTab}(myNewGrid);
84  * </code></pre></p>
85  * <p>The example above adds a newly created GridPanel to a TabPanel. Note that
86  * a TabPanel uses {@link Ext.layout.CardLayout} as its layout manager which
87  * means all its child items are sized to {@link Ext.layout.FitLayout fit}
88  * exactly into its client area.
89  * <p><b><u>Overnesting is a common problem</u></b>.
90  * An example of overnesting occurs when a GridPanel is added to a TabPanel
91  * by wrapping the GridPanel <i>inside</i> a wrapping Panel (that has no
92  * <code><b>{@link #layout}</b></code> specified) and then add that wrapping Panel
93  * to the TabPanel. The point to realize is that a GridPanel <b>is</b> a
94  * Component which can be added directly to a Container. If the wrapping Panel
95  * has no <code><b>{@link #layout}</b></code> configuration, then the overnested
96  * GridPanel will not be sized as expected.<p>
97  *
98  * <p><u><b>Adding via remote configuration</b></u></p>
99  *
100  * <p>A server side script can be used to add Components which are generated dynamically on the server.
101  * An example of adding a GridPanel to a TabPanel where the GridPanel is generated by the server
102  * based on certain parameters:
103  * </p><pre><code>
104 // execute an Ajax request to invoke server side script:
105 Ext.Ajax.request({
106     url: 'gen-invoice-grid.php',
107     // send additional parameters to instruct server script
108     params: {
109         startDate: Ext.getCmp('start-date').getValue(),
110         endDate: Ext.getCmp('end-date').getValue()
111     },
112     // process the response object to add it to the TabPanel:
113     success: function(xhr) {
114         var newComponent = eval(xhr.responseText); // see discussion below
115         myTabPanel.add(newComponent); // add the component to the TabPanel
116         myTabPanel.setActiveTab(newComponent);
117     },
118     failure: function() {
119         Ext.Msg.alert("Grid create failed", "Server communication failure");
120     }
121 });
122 </code></pre>
123  * <p>The server script needs to return an executable Javascript statement which, when processed
124  * using <code>eval()</code>, will return either a config object with an {@link Ext.Component#xtype xtype},
125  * or an instantiated Component. The server might return this for example:</p><pre><code>
126 (function() {
127     function formatDate(value){
128         return value ? value.dateFormat('M d, Y') : '';
129     };
130
131     var store = new Ext.data.Store({
132         url: 'get-invoice-data.php',
133         baseParams: {
134             startDate: '01/01/2008',
135             endDate: '01/31/2008'
136         },
137         reader: new Ext.data.JsonReader({
138             record: 'transaction',
139             idProperty: 'id',
140             totalRecords: 'total'
141         }, [
142            'customer',
143            'invNo',
144            {name: 'date', type: 'date', dateFormat: 'm/d/Y'},
145            {name: 'value', type: 'float'}
146         ])
147     });
148
149     var grid = new Ext.grid.GridPanel({
150         title: 'Invoice Report',
151         bbar: new Ext.PagingToolbar(store),
152         store: store,
153         columns: [
154             {header: "Customer", width: 250, dataIndex: 'customer', sortable: true},
155             {header: "Invoice Number", width: 120, dataIndex: 'invNo', sortable: true},
156             {header: "Invoice Date", width: 100, dataIndex: 'date', renderer: formatDate, sortable: true},
157             {header: "Value", width: 120, dataIndex: 'value', renderer: 'usMoney', sortable: true}
158         ],
159     });
160     store.load();
161     return grid;  // return instantiated component
162 })();
163 </code></pre>
164  * <p>When the above code fragment is passed through the <code>eval</code> function in the success handler
165  * of the Ajax request, the code is executed by the Javascript processor, and the anonymous function
166  * runs, and returns the instantiated grid component.</p>
167  * <p>Note: since the code above is <i>generated</i> by a server script, the <code>baseParams</code> for
168  * the Store, the metadata to allow generation of the Record layout, and the ColumnModel
169  * can all be generated into the code since these are all known on the server.</p>
170  *
171  * @xtype container
172  */
173 Ext.Container = Ext.extend(Ext.BoxComponent, {
174     /**
175      * @cfg {Boolean} monitorResize
176      * True to automatically monitor window resize events to handle anything that is sensitive to the current size
177      * of the viewport.  This value is typically managed by the chosen <code>{@link #layout}</code> and should not need
178      * to be set manually.
179      */
180     /**
181      * @cfg {String/Object} layout
182      * <p><b>*Important</b>: In order for child items to be correctly sized and
183      * positioned, typically a layout manager <b>must</b> be specified through
184      * the <code>layout</code> configuration option.</p>
185      * <br><p>The sizing and positioning of child {@link items} is the responsibility of
186      * the Container's layout manager which creates and manages the type of layout
187      * you have in mind.  For example:</p><pre><code>
188 new Ext.Window({
189     width:300, height: 300,
190     layout: 'fit', // explicitly set layout manager: override the default (layout:'auto')
191     items: [{
192         title: 'Panel inside a Window'
193     }]
194 }).show();
195      * </code></pre>
196      * <p>If the {@link #layout} configuration is not explicitly specified for
197      * a general purpose container (e.g. Container or Panel) the
198      * {@link Ext.layout.ContainerLayout default layout manager} will be used
199      * which does nothing but render child components sequentially into the
200      * Container (no sizing or positioning will be performed in this situation).
201      * Some container classes implicitly specify a default layout
202      * (e.g. FormPanel specifies <code>layout:'form'</code>). Other specific
203      * purpose classes internally specify/manage their internal layout (e.g.
204      * GridPanel, TabPanel, TreePanel, Toolbar, Menu, etc.).</p>
205      * <br><p><b><code>layout</code></b> may be specified as either as an Object or
206      * as a String:</p><div><ul class="mdetail-params">
207      *
208      * <li><u>Specify as an Object</u></li>
209      * <div><ul class="mdetail-params">
210      * <li>Example usage:</li>
211 <pre><code>
212 layout: {
213     type: 'vbox',
214     padding: '5',
215     align: 'left'
216 }
217 </code></pre>
218      *
219      * <li><code><b>type</b></code></li>
220      * <br/><p>The layout type to be used for this container.  If not specified,
221      * a default {@link Ext.layout.ContainerLayout} will be created and used.</p>
222      * <br/><p>Valid layout <code>type</code> values are:</p>
223      * <div class="sub-desc"><ul class="mdetail-params">
224      * <li><code><b>{@link Ext.layout.AbsoluteLayout absolute}</b></code></li>
225      * <li><code><b>{@link Ext.layout.AccordionLayout accordion}</b></code></li>
226      * <li><code><b>{@link Ext.layout.AnchorLayout anchor}</b></code></li>
227      * <li><code><b>{@link Ext.layout.ContainerLayout auto}</b></code> &nbsp;&nbsp;&nbsp; <b>Default</b></li>
228      * <li><code><b>{@link Ext.layout.BorderLayout border}</b></code></li>
229      * <li><code><b>{@link Ext.layout.CardLayout card}</b></code></li>
230      * <li><code><b>{@link Ext.layout.ColumnLayout column}</b></code></li>
231      * <li><code><b>{@link Ext.layout.FitLayout fit}</b></code></li>
232      * <li><code><b>{@link Ext.layout.FormLayout form}</b></code></li>
233      * <li><code><b>{@link Ext.layout.HBoxLayout hbox}</b></code></li>
234      * <li><code><b>{@link Ext.layout.MenuLayout menu}</b></code></li>
235      * <li><code><b>{@link Ext.layout.TableLayout table}</b></code></li>
236      * <li><code><b>{@link Ext.layout.ToolbarLayout toolbar}</b></code></li>
237      * <li><code><b>{@link Ext.layout.VBoxLayout vbox}</b></code></li>
238      * </ul></div>
239      *
240      * <li>Layout specific configuration properties</li>
241      * <br/><p>Additional layout specific configuration properties may also be
242      * specified. For complete details regarding the valid config options for
243      * each layout type, see the layout class corresponding to the <code>type</code>
244      * specified.</p>
245      *
246      * </ul></div>
247      *
248      * <li><u>Specify as a String</u></li>
249      * <div><ul class="mdetail-params">
250      * <li>Example usage:</li>
251 <pre><code>
252 layout: 'vbox',
253 layoutConfig: {
254     padding: '5',
255     align: 'left'
256 }
257 </code></pre>
258      * <li><code><b>layout</b></code></li>
259      * <br/><p>The layout <code>type</code> to be used for this container (see list
260      * of valid layout type values above).</p><br/>
261      * <li><code><b>{@link #layoutConfig}</b></code></li>
262      * <br/><p>Additional layout specific configuration properties. For complete
263      * details regarding the valid config options for each layout type, see the
264      * layout class corresponding to the <code>layout</code> specified.</p>
265      * </ul></div></ul></div>
266      */
267     /**
268      * @cfg {Object} layoutConfig
269      * This is a config object containing properties specific to the chosen
270      * <b><code>{@link #layout}</code></b> if <b><code>{@link #layout}</code></b>
271      * has been specified as a <i>string</i>.</p>
272      */
273     /**
274      * @cfg {Boolean/Number} bufferResize
275      * When set to true (50 milliseconds) or a number of milliseconds, the layout assigned for this container will buffer
276      * the frequency it calculates and does a re-layout of components. This is useful for heavy containers or containers
277      * with a large quantity of sub-components for which frequent layout calls would be expensive. Defaults to <code>50</code>.
278      */
279     // Deprecated - will be removed in 3.2.x
280     bufferResize: 50,
281
282     /**
283      * @cfg {String/Number} activeItem
284      * A string component id or the numeric index of the component that should be initially activated within the
285      * container's layout on render.  For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first
286      * item in the container's collection).  activeItem only applies to layout styles that can display
287      * items one at a time (like {@link Ext.layout.AccordionLayout}, {@link Ext.layout.CardLayout} and
288      * {@link Ext.layout.FitLayout}).  Related to {@link Ext.layout.ContainerLayout#activeItem}.
289      */
290     /**
291      * @cfg {Object/Array} items
292      * <pre><b>** IMPORTANT</b>: be sure to <b>{@link #layout specify a <code>layout</code>} if needed ! **</b></pre>
293      * <p>A single item, or an array of child Components to be added to this container,
294      * for example:</p>
295      * <pre><code>
296 // specifying a single item
297 items: {...},
298 layout: 'fit',    // specify a layout!
299
300 // specifying multiple items
301 items: [{...}, {...}],
302 layout: 'anchor', // specify a layout!
303      * </code></pre>
304      * <p>Each item may be:</p>
305      * <div><ul class="mdetail-params">
306      * <li>any type of object based on {@link Ext.Component}</li>
307      * <li>a fully instanciated object or</li>
308      * <li>an object literal that:</li>
309      * <div><ul class="mdetail-params">
310      * <li>has a specified <code>{@link Ext.Component#xtype xtype}</code></li>
311      * <li>the {@link Ext.Component#xtype} specified is associated with the Component
312      * desired and should be chosen from one of the available xtypes as listed
313      * in {@link Ext.Component}.</li>
314      * <li>If an <code>{@link Ext.Component#xtype xtype}</code> is not explicitly
315      * specified, the {@link #defaultType} for that Container is used.</li>
316      * <li>will be "lazily instanciated", avoiding the overhead of constructing a fully
317      * instanciated Component object</li>
318      * </ul></div></ul></div>
319      * <p><b>Notes</b>:</p>
320      * <div><ul class="mdetail-params">
321      * <li>Ext uses lazy rendering. Child Components will only be rendered
322      * should it become necessary. Items are automatically laid out when they are first
323      * shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</li>
324      * <li>Do not specify <code>{@link Ext.Panel#contentEl contentEl}</code>/
325      * <code>{@link Ext.Panel#html html}</code> with <code>items</code>.</li>
326      * </ul></div>
327      */
328     /**
329      * @cfg {Object|Function} defaults
330      * <p>This option is a means of applying default settings to all added items whether added through the {@link #items}
331      * config or via the {@link #add} or {@link #insert} methods.</p>
332      * <p>If an added item is a config object, and <b>not</b> an instantiated Component, then the default properties are
333      * unconditionally applied. If the added item <b>is</b> an instantiated Component, then the default properties are
334      * applied conditionally so as not to override existing properties in the item.</p>
335      * <p>If the defaults option is specified as a function, then the function will be called using this Container as the
336      * scope (<code>this</code> reference) and passing the added item as the first parameter. Any resulting object
337      * from that call is then applied to the item as default properties.</p>
338      * <p>For example, to automatically apply padding to the body of each of a set of
339      * contained {@link Ext.Panel} items, you could pass: <code>defaults: {bodyStyle:'padding:15px'}</code>.</p>
340      * <p>Usage:</p><pre><code>
341 defaults: {               // defaults are applied to items, not the container
342     autoScroll:true
343 },
344 items: [
345     {
346         xtype: 'panel',   // defaults <b>do not</b> have precedence over
347         id: 'panel1',     // options in config objects, so the defaults
348         autoScroll: false // will not be applied here, panel1 will be autoScroll:false
349     },
350     new Ext.Panel({       // defaults <b>do</b> have precedence over options
351         id: 'panel2',     // options in components, so the defaults
352         autoScroll: false // will be applied here, panel2 will be autoScroll:true.
353     })
354 ]
355      * </code></pre>
356      */
357
358
359     /** @cfg {Boolean} autoDestroy
360      * If true the container will automatically destroy any contained component that is removed from it, else
361      * destruction must be handled manually (defaults to true).
362      */
363     autoDestroy : true,
364
365     /** @cfg {Boolean} forceLayout
366      * If true the container will force a layout initially even if hidden or collapsed. This option
367      * is useful for forcing forms to render in collapsed or hidden containers. (defaults to false).
368      */
369     forceLayout: false,
370
371     /** @cfg {Boolean} hideBorders
372      * True to hide the borders of each contained component, false to defer to the component's existing
373      * border settings (defaults to false).
374      */
375     /** @cfg {String} defaultType
376      * <p>The default {@link Ext.Component xtype} of child Components to create in this Container when
377      * a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>
378      * <p>Defaults to <code>'panel'</code>, except {@link Ext.menu.Menu} which defaults to <code>'menuitem'</code>,
379      * and {@link Ext.Toolbar} and {@link Ext.ButtonGroup} which default to <code>'button'</code>.</p>
380      */
381     defaultType : 'panel',
382
383     /** @cfg {String} resizeEvent
384      * The event to listen to for resizing in layouts. Defaults to <code>'resize'</code>.
385      */
386     resizeEvent: 'resize',
387
388     /**
389      * @cfg {Array} bubbleEvents
390      * <p>An array of events that, when fired, should be bubbled to any parent container.
391      * See {@link Ext.util.Observable#enableBubble}.
392      * Defaults to <code>['add', 'remove']</code>.
393      */
394     bubbleEvents: ['add', 'remove'],
395
396     // private
397     initComponent : function(){
398         Ext.Container.superclass.initComponent.call(this);
399
400         this.addEvents(
401             /**
402              * @event afterlayout
403              * Fires when the components in this container are arranged by the associated layout manager.
404              * @param {Ext.Container} this
405              * @param {ContainerLayout} layout The ContainerLayout implementation for this container
406              */
407             'afterlayout',
408             /**
409              * @event beforeadd
410              * Fires before any {@link Ext.Component} is added or inserted into the container.
411              * A handler can return false to cancel the add.
412              * @param {Ext.Container} this
413              * @param {Ext.Component} component The component being added
414              * @param {Number} index The index at which the component will be added to the container's items collection
415              */
416             'beforeadd',
417             /**
418              * @event beforeremove
419              * Fires before any {@link Ext.Component} is removed from the container.  A handler can return
420              * false to cancel the remove.
421              * @param {Ext.Container} this
422              * @param {Ext.Component} component The component being removed
423              */
424             'beforeremove',
425             /**
426              * @event add
427              * @bubbles
428              * Fires after any {@link Ext.Component} is added or inserted into the container.
429              * @param {Ext.Container} this
430              * @param {Ext.Component} component The component that was added
431              * @param {Number} index The index at which the component was added to the container's items collection
432              */
433             'add',
434             /**
435              * @event remove
436              * @bubbles
437              * Fires after any {@link Ext.Component} is removed from the container.
438              * @param {Ext.Container} this
439              * @param {Ext.Component} component The component that was removed
440              */
441             'remove'
442         );
443
444         this.enableBubble(this.bubbleEvents);
445
446         /**
447          * The collection of components in this container as a {@link Ext.util.MixedCollection}
448          * @type MixedCollection
449          * @property items
450          */
451         var items = this.items;
452         if(items){
453             delete this.items;
454             this.add(items);
455         }
456     },
457
458     // private
459     initItems : function(){
460         if(!this.items){
461             this.items = new Ext.util.MixedCollection(false, this.getComponentId);
462             this.getLayout(); // initialize the layout
463         }
464     },
465
466     // private
467     setLayout : function(layout){
468         if(this.layout && this.layout != layout){
469             this.layout.setContainer(null);
470         }
471         this.initItems();
472         this.layout = layout;
473         layout.setContainer(this);
474     },
475
476     afterRender: function(){
477         // Render this Container, this should be done before setLayout is called which
478         // will hook onResize
479         Ext.Container.superclass.afterRender.call(this);
480         if(!this.layout){
481             this.layout = 'auto';
482         }
483         if(Ext.isObject(this.layout) && !this.layout.layout){
484             this.layoutConfig = this.layout;
485             this.layout = this.layoutConfig.type;
486         }
487         if(Ext.isString(this.layout)){
488             this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);
489         }
490         this.setLayout(this.layout);
491
492         // If a CardLayout, the active item set
493         if(this.activeItem !== undefined){
494             var item = this.activeItem;
495             delete this.activeItem;
496             this.layout.setActiveItem(item);
497         }
498
499         // If we have no ownerCt, render and size all children
500         if(!this.ownerCt){
501             this.doLayout(false, true);
502         }
503
504         // This is a manually configured flag set by users in conjunction with renderTo.
505         // Not to be confused with the flag by the same name used in Layouts.
506         if(this.monitorResize === true){
507             Ext.EventManager.onWindowResize(this.doLayout, this, [false]);
508         }
509     },
510
511     /**
512      * <p>Returns the Element to be used to contain the child Components of this Container.</p>
513      * <p>An implementation is provided which returns the Container's {@link #getEl Element}, but
514      * if there is a more complex structure to a Container, this may be overridden to return
515      * the element into which the {@link #layout layout} renders child Components.</p>
516      * @return {Ext.Element} The Element to render child Components into.
517      */
518     getLayoutTarget : function(){
519         return this.el;
520     },
521
522     // private - used as the key lookup function for the items collection
523     getComponentId : function(comp){
524         return comp.getItemId();
525     },
526
527     /**
528      * <p>Adds {@link Ext.Component Component}(s) to this Container.</p>
529      * <br><p><b>Description</b></u> :
530      * <div><ul class="mdetail-params">
531      * <li>Fires the {@link #beforeadd} event before adding</li>
532      * <li>The Container's {@link #defaults default config values} will be applied
533      * accordingly (see <code>{@link #defaults}</code> for details).</li>
534      * <li>Fires the {@link #add} event after the component has been added.</li>
535      * </ul></div>
536      * <br><p><b>Notes</b></u> :
537      * <div><ul class="mdetail-params">
538      * <li>If the Container is <i>already rendered</i> when <code>add</code>
539      * is called, you may need to call {@link #doLayout} to refresh the view which causes
540      * any unrendered child Components to be rendered. This is required so that you can
541      * <code>add</code> multiple child components if needed while only refreshing the layout
542      * once. For example:<pre><code>
543 var tb = new {@link Ext.Toolbar}();
544 tb.render(document.body);  // toolbar is rendered
545 tb.add({text:'Button 1'}); // add multiple items ({@link #defaultType} for {@link Ext.Toolbar Toolbar} is 'button')
546 tb.add({text:'Button 2'});
547 tb.{@link #doLayout}();             // refresh the layout
548      * </code></pre></li>
549      * <li><i>Warning:</i> Containers directly managed by the BorderLayout layout manager
550      * may not be removed or added.  See the Notes for {@link Ext.layout.BorderLayout BorderLayout}
551      * for more details.</li>
552      * </ul></div>
553      * @param {Object/Array} component
554      * <p>Either a single component or an Array of components to add.  See
555      * <code>{@link #items}</code> for additional information.</p>
556      * @param {Object} (Optional) component_2
557      * @param {Object} (Optional) component_n
558      * @return {Ext.Component} component The Component (or config object) that was added.
559      */
560     add : function(comp){
561         this.initItems();
562         var args = arguments.length > 1;
563         if(args || Ext.isArray(comp)){
564             var result = [];
565             Ext.each(args ? arguments : comp, function(c){
566                 result.push(this.add(c));
567             }, this);
568             return result;
569         }
570         var c = this.lookupComponent(this.applyDefaults(comp));
571         var index = this.items.length;
572         if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){
573             this.items.add(c);
574             // *onAdded
575             c.onAdded(this, index);
576             this.onAdd(c);
577             this.fireEvent('add', this, c, index);
578         }
579         return c;
580     },
581
582     onAdd : function(c){
583         // Empty template method
584     },
585
586     // private
587     onAdded : function(container, pos) {
588         //overridden here so we can cascade down, not worth creating a template method.
589         this.ownerCt = container;
590         this.initRef();
591         //initialize references for child items
592         this.cascade(function(c){
593             c.initRef();
594         });
595         this.fireEvent('added', this, container, pos);
596     },
597
598     /**
599      * Inserts a Component into this Container at a specified index. Fires the
600      * {@link #beforeadd} event before inserting, then fires the {@link #add} event after the
601      * Component has been inserted.
602      * @param {Number} index The index at which the Component will be inserted
603      * into the Container's items collection
604      * @param {Ext.Component} component The child Component to insert.<br><br>
605      * Ext uses lazy rendering, and will only render the inserted Component should
606      * it become necessary.<br><br>
607      * A Component config object may be passed in order to avoid the overhead of
608      * constructing a real Component object if lazy rendering might mean that the
609      * inserted Component will not be rendered immediately. To take advantage of
610      * this 'lazy instantiation', set the {@link Ext.Component#xtype} config
611      * property to the registered type of the Component wanted.<br><br>
612      * For a list of all available xtypes, see {@link Ext.Component}.
613      * @return {Ext.Component} component The Component (or config object) that was
614      * inserted with the Container's default config values applied.
615      */
616     insert : function(index, comp){
617         this.initItems();
618         var a = arguments, len = a.length;
619         if(len > 2){
620             var result = [];
621             for(var i = len-1; i >= 1; --i) {
622                 result.push(this.insert(index, a[i]));
623             }
624             return result;
625         }
626         var c = this.lookupComponent(this.applyDefaults(comp));
627         index = Math.min(index, this.items.length);
628         if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){
629             if(c.ownerCt == this){
630                 this.items.remove(c);
631             }
632             this.items.insert(index, c);
633             c.onAdded(this, index);
634             this.onAdd(c);
635             this.fireEvent('add', this, c, index);
636         }
637         return c;
638     },
639
640     // private
641     applyDefaults : function(c){
642         var d = this.defaults;
643         if(d){
644             if(Ext.isFunction(d)){
645                 d = d.call(this, c);
646             }
647             if(Ext.isString(c)){
648                 c = Ext.ComponentMgr.get(c);
649                 Ext.apply(c, d);
650             }else if(!c.events){
651                 Ext.applyIf(c, d);
652             }else{
653                 Ext.apply(c, d);
654             }
655         }
656         return c;
657     },
658
659     // private
660     onBeforeAdd : function(item){
661         if(item.ownerCt){
662             item.ownerCt.remove(item, false);
663         }
664         if(this.hideBorders === true){
665             item.border = (item.border === true);
666         }
667     },
668
669     /**
670      * Removes a component from this container.  Fires the {@link #beforeremove} event before removing, then fires
671      * the {@link #remove} event after the component has been removed.
672      * @param {Component/String} component The component reference or id to remove.
673      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
674      * Defaults to the value of this Container's {@link #autoDestroy} config.
675      * @return {Ext.Component} component The Component that was removed.
676      */
677     remove : function(comp, autoDestroy){
678         this.initItems();
679         var c = this.getComponent(comp);
680         if(c && this.fireEvent('beforeremove', this, c) !== false){
681             this.doRemove(c, autoDestroy);
682             this.fireEvent('remove', this, c);
683         }
684         return c;
685     },
686
687     onRemove: function(c){
688         // Empty template method
689     },
690
691     // private
692     doRemove: function(c, autoDestroy){
693         var l = this.layout,
694             hasLayout = l && this.rendered;
695
696         if(hasLayout){
697             l.onRemove(c);
698         }
699         this.items.remove(c);
700         c.onRemoved();
701         this.onRemove(c);
702         if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){
703             c.destroy();
704         }
705         if(hasLayout){
706             l.afterRemove(c);
707         }
708     },
709
710     /**
711      * Removes all components from this container.
712      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
713      * Defaults to the value of this Container's {@link #autoDestroy} config.
714      * @return {Array} Array of the destroyed components
715      */
716     removeAll: function(autoDestroy){
717         this.initItems();
718         var item, rem = [], items = [];
719         this.items.each(function(i){
720             rem.push(i);
721         });
722         for (var i = 0, len = rem.length; i < len; ++i){
723             item = rem[i];
724             this.remove(item, autoDestroy);
725             if(item.ownerCt !== this){
726                 items.push(item);
727             }
728         }
729         return items;
730     },
731
732     /**
733      * Examines this container's <code>{@link #items}</code> <b>property</b>
734      * and gets a direct child component of this container.
735      * @param {String/Number} comp This parameter may be any of the following:
736      * <div><ul class="mdetail-params">
737      * <li>a <b><code>String</code></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>
738      * or <code>{@link Ext.Component#id id}</code> of the child component </li>
739      * <li>a <b><code>Number</code></b> : representing the position of the child component
740      * within the <code>{@link #items}</code> <b>property</b></li>
741      * </ul></div>
742      * <p>For additional information see {@link Ext.util.MixedCollection#get}.
743      * @return Ext.Component The component (if found).
744      */
745     getComponent : function(comp){
746         if(Ext.isObject(comp)){
747             comp = comp.getItemId();
748         }
749         return this.items.get(comp);
750     },
751
752     // private
753     lookupComponent : function(comp){
754         if(Ext.isString(comp)){
755             return Ext.ComponentMgr.get(comp);
756         }else if(!comp.events){
757             return this.createComponent(comp);
758         }
759         return comp;
760     },
761
762     // private
763     createComponent : function(config, defaultType){
764         // add in ownerCt at creation time but then immediately
765         // remove so that onBeforeAdd can handle it
766         var c = config.render ? config : Ext.create(Ext.apply({
767             ownerCt: this
768         }, config), defaultType || this.defaultType);
769         delete c.ownerCt;
770         return c;
771     },
772
773     /**
774     * We can only lay out if there is a view area in which to layout.
775     * display:none on the layout target, *or any of its parent elements* will mean it has no view area.
776     */
777
778     // private
779     canLayout : function() {
780         var el = this.getVisibilityEl();
781         return el && el.dom && !el.isStyle("display", "none");
782     },
783
784     /**
785      * Force this container's layout to be recalculated. A call to this function is required after adding a new component
786      * to an already rendered container, or possibly after changing sizing/position properties of child components.
787      * @param {Boolean} shallow (optional) True to only calc the layout of this component, and let child components auto
788      * calc layouts as required (defaults to false, which calls doLayout recursively for each subcontainer)
789      * @param {Boolean} force (optional) True to force a layout to occur, even if the item is hidden.
790      * @return {Ext.Container} this
791      */
792
793     doLayout : function(shallow, force){
794         var rendered = this.rendered,
795             forceLayout = force || this.forceLayout;
796
797         if(this.collapsed || !this.canLayout()){
798             this.deferLayout = this.deferLayout || !shallow;
799             if(!forceLayout){
800                 return;
801             }
802             shallow = shallow && !this.deferLayout;
803         } else {
804             delete this.deferLayout;
805         }
806         if(rendered && this.layout){
807             this.layout.layout();
808         }
809         if(shallow !== true && this.items){
810             var cs = this.items.items;
811             for(var i = 0, len = cs.length; i < len; i++){
812                 var c = cs[i];
813                 if(c.doLayout){
814                     c.doLayout(false, forceLayout);
815                 }
816             }
817         }
818         if(rendered){
819             this.onLayout(shallow, forceLayout);
820         }
821         // Initial layout completed
822         this.hasLayout = true;
823         delete this.forceLayout;
824     },
825
826     onLayout : Ext.emptyFn,
827
828     // private
829     shouldBufferLayout: function(){
830         /*
831          * Returns true if the container should buffer a layout.
832          * This is true only if the container has previously been laid out
833          * and has a parent container that is pending a layout.
834          */
835         var hl = this.hasLayout;
836         if(this.ownerCt){
837             // Only ever buffer if we've laid out the first time and we have one pending.
838             return hl ? !this.hasLayoutPending() : false;
839         }
840         // Never buffer initial layout
841         return hl;
842     },
843
844     // private
845     hasLayoutPending: function(){
846         // Traverse hierarchy to see if any parent container has a pending layout.
847         var pending = false;
848         this.ownerCt.bubble(function(c){
849             if(c.layoutPending){
850                 pending = true;
851                 return false;
852             }
853         });
854         return pending;
855     },
856
857     onShow : function(){
858         // removes css classes that were added to hide
859         Ext.Container.superclass.onShow.call(this);
860         // If we were sized during the time we were hidden, layout.
861         if(Ext.isDefined(this.deferLayout)){
862             delete this.deferLayout;
863             this.doLayout(true);
864         }
865     },
866
867     /**
868      * Returns the layout currently in use by the container.  If the container does not currently have a layout
869      * set, a default {@link Ext.layout.ContainerLayout} will be created and set as the container's layout.
870      * @return {ContainerLayout} layout The container's layout
871      */
872     getLayout : function(){
873         if(!this.layout){
874             var layout = new Ext.layout.ContainerLayout(this.layoutConfig);
875             this.setLayout(layout);
876         }
877         return this.layout;
878     },
879
880     // private
881     beforeDestroy : function(){
882         var c;
883         if(this.items){
884             while(c = this.items.first()){
885                 this.doRemove(c, true);
886             }
887         }
888         if(this.monitorResize){
889             Ext.EventManager.removeResizeListener(this.doLayout, this);
890         }
891         Ext.destroy(this.layout);
892         Ext.Container.superclass.beforeDestroy.call(this);
893     },
894
895     /**
896      * Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of
897      * function call will be the scope provided or the current component. The arguments to the function
898      * will be the args provided or the current component. If the function returns false at any point,
899      * the bubble is stopped.
900      * @param {Function} fn The function to call
901      * @param {Object} scope (optional) The scope of the function (defaults to current node)
902      * @param {Array} args (optional) The args to call the function with (default to passing the current component)
903      * @return {Ext.Container} this
904      */
905     bubble : function(fn, scope, args){
906         var p = this;
907         while(p){
908             if(fn.apply(scope || p, args || [p]) === false){
909                 break;
910             }
911             p = p.ownerCt;
912         }
913         return this;
914     },
915
916     /**
917      * Cascades down the component/container heirarchy from this component (called first), calling the specified function with
918      * each component. The scope (<i>this</i>) of
919      * function call will be the scope provided or the current component. The arguments to the function
920      * will be the args provided or the current component. If the function returns false at any point,
921      * the cascade is stopped on that branch.
922      * @param {Function} fn The function to call
923      * @param {Object} scope (optional) The scope of the function (defaults to current component)
924      * @param {Array} args (optional) The args to call the function with (defaults to passing the current component)
925      * @return {Ext.Container} this
926      */
927     cascade : function(fn, scope, args){
928         if(fn.apply(scope || this, args || [this]) !== false){
929             if(this.items){
930                 var cs = this.items.items;
931                 for(var i = 0, len = cs.length; i < len; i++){
932                     if(cs[i].cascade){
933                         cs[i].cascade(fn, scope, args);
934                     }else{
935                         fn.apply(scope || cs[i], args || [cs[i]]);
936                     }
937                 }
938             }
939         }
940         return this;
941     },
942
943     /**
944      * Find a component under this container at any level by id
945      * @param {String} id
946      * @return Ext.Component
947      */
948     findById : function(id){
949         var m, ct = this;
950         this.cascade(function(c){
951             if(ct != c && c.id === id){
952                 m = c;
953                 return false;
954             }
955         });
956         return m || null;
957     },
958
959     /**
960      * Find a component under this container at any level by xtype or class
961      * @param {String/Class} xtype The xtype string for a component, or the class of the component directly
962      * @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is
963      * the default), or true to check whether this Component is directly of the specified xtype.
964      * @return {Array} Array of Ext.Components
965      */
966     findByType : function(xtype, shallow){
967         return this.findBy(function(c){
968             return c.isXType(xtype, shallow);
969         });
970     },
971
972     /**
973      * Find a component under this container at any level by property
974      * @param {String} prop
975      * @param {String} value
976      * @return {Array} Array of Ext.Components
977      */
978     find : function(prop, value){
979         return this.findBy(function(c){
980             return c[prop] === value;
981         });
982     },
983
984     /**
985      * Find a component under this container at any level by a custom function. If the passed function returns
986      * true, the component will be included in the results. The passed function is called with the arguments (component, this container).
987      * @param {Function} fn The function to call
988      * @param {Object} scope (optional)
989      * @return {Array} Array of Ext.Components
990      */
991     findBy : function(fn, scope){
992         var m = [], ct = this;
993         this.cascade(function(c){
994             if(ct != c && fn.call(scope || c, c, ct) === true){
995                 m.push(c);
996             }
997         });
998         return m;
999     },
1000
1001     /**
1002      * Get a component contained by this container (alias for items.get(key))
1003      * @param {String/Number} key The index or id of the component
1004      * @return {Ext.Component} Ext.Component
1005      */
1006     get : function(key){
1007         return this.items.get(key);
1008     }
1009 });
1010
1011 Ext.Container.LAYOUTS = {};
1012 Ext.reg('container', Ext.Container);