Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / widgets / Container.js
1 /*!
2  * Ext JS Library 3.1.0
3  * Copyright(c) 2006-2009 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     bufferResize: 50,
280
281     /**
282      * @cfg {String/Number} activeItem
283      * A string component id or the numeric index of the component that should be initially activated within the
284      * container's layout on render.  For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first
285      * item in the container's collection).  activeItem only applies to layout styles that can display
286      * items one at a time (like {@link Ext.layout.AccordionLayout}, {@link Ext.layout.CardLayout} and
287      * {@link Ext.layout.FitLayout}).  Related to {@link Ext.layout.ContainerLayout#activeItem}.
288      */
289     /**
290      * @cfg {Object/Array} items
291      * <pre><b>** IMPORTANT</b>: be sure to <b>{@link #layout specify a <code>layout</code>} if needed ! **</b></pre>
292      * <p>A single item, or an array of child Components to be added to this container,
293      * for example:</p>
294      * <pre><code>
295 // specifying a single item
296 items: {...},
297 layout: 'fit',    // specify a layout!
298
299 // specifying multiple items
300 items: [{...}, {...}],
301 layout: 'anchor', // specify a layout!
302      * </code></pre>
303      * <p>Each item may be:</p>
304      * <div><ul class="mdetail-params">
305      * <li>any type of object based on {@link Ext.Component}</li>
306      * <li>a fully instanciated object or</li>
307      * <li>an object literal that:</li>
308      * <div><ul class="mdetail-params">
309      * <li>has a specified <code>{@link Ext.Component#xtype xtype}</code></li>
310      * <li>the {@link Ext.Component#xtype} specified is associated with the Component
311      * desired and should be chosen from one of the available xtypes as listed
312      * in {@link Ext.Component}.</li>
313      * <li>If an <code>{@link Ext.Component#xtype xtype}</code> is not explicitly
314      * specified, the {@link #defaultType} for that Container is used.</li>
315      * <li>will be "lazily instanciated", avoiding the overhead of constructing a fully
316      * instanciated Component object</li>
317      * </ul></div></ul></div>
318      * <p><b>Notes</b>:</p>
319      * <div><ul class="mdetail-params">
320      * <li>Ext uses lazy rendering. Child Components will only be rendered
321      * should it become necessary. Items are automatically laid out when they are first
322      * shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</li>
323      * <li>Do not specify <code>{@link Ext.Panel#contentEl contentEl}</code>/
324      * <code>{@link Ext.Panel#html html}</code> with <code>items</code>.</li>
325      * </ul></div>
326      */
327     /**
328      * @cfg {Object|Function} defaults
329      * <p>This option is a means of applying default settings to all added items whether added through the {@link #items}
330      * config or via the {@link #add} or {@link #insert} methods.</p>
331      * <p>If an added item is a config object, and <b>not</b> an instantiated Component, then the default properties are
332      * unconditionally applied. If the added item <b>is</b> an instantiated Component, then the default properties are
333      * applied conditionally so as not to override existing properties in the item.</p>
334      * <p>If the defaults option is specified as a function, then the function will be called using this Container as the
335      * scope (<code>this</code> reference) and passing the added item as the first parameter. Any resulting object
336      * from that call is then applied to the item as default properties.</p>
337      * <p>For example, to automatically apply padding to the body of each of a set of
338      * contained {@link Ext.Panel} items, you could pass: <code>defaults: {bodyStyle:'padding:15px'}</code>.</p>
339      * <p>Usage:</p><pre><code>
340 defaults: {               // defaults are applied to items, not the container
341     autoScroll:true
342 },
343 items: [
344     {
345         xtype: 'panel',   // defaults <b>do not</b> have precedence over
346         id: 'panel1',     // options in config objects, so the defaults
347         autoScroll: false // will not be applied here, panel1 will be autoScroll:false
348     },
349     new Ext.Panel({       // defaults <b>do</b> have precedence over options
350         id: 'panel2',     // options in components, so the defaults
351         autoScroll: false // will be applied here, panel2 will be autoScroll:true.
352     })
353 ]
354      * </code></pre>
355      */
356
357
358     /** @cfg {Boolean} autoDestroy
359      * If true the container will automatically destroy any contained component that is removed from it, else
360      * destruction must be handled manually (defaults to true).
361      */
362     autoDestroy : true,
363
364     /** @cfg {Boolean} forceLayout
365      * If true the container will force a layout initially even if hidden or collapsed. This option
366      * is useful for forcing forms to render in collapsed or hidden containers. (defaults to false).
367      */
368     forceLayout: false,
369
370     /** @cfg {Boolean} hideBorders
371      * True to hide the borders of each contained component, false to defer to the component's existing
372      * border settings (defaults to false).
373      */
374     /** @cfg {String} defaultType
375      * <p>The default {@link Ext.Component xtype} of child Components to create in this Container when
376      * a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>
377      * <p>Defaults to <code>'panel'</code>, except {@link Ext.menu.Menu} which defaults to <code>'menuitem'</code>,
378      * and {@link Ext.Toolbar} and {@link Ext.ButtonGroup} which default to <code>'button'</code>.</p>
379      */
380     defaultType : 'panel',
381
382     /** @cfg {String} resizeEvent
383      * The event to listen to for resizing in layouts. Defaults to <code>'resize'</code>.
384      */
385     resizeEvent: 'resize',
386
387     /**
388      * @cfg {Array} bubbleEvents
389      * <p>An array of events that, when fired, should be bubbled to any parent container.
390      * See {@link Ext.util.Observable#enableBubble}.
391      * Defaults to <code>['add', 'remove']</code>.
392      */
393     bubbleEvents: ['add', 'remove'],
394
395     // private
396     initComponent : function(){
397         Ext.Container.superclass.initComponent.call(this);
398
399         this.addEvents(
400             /**
401              * @event afterlayout
402              * Fires when the components in this container are arranged by the associated layout manager.
403              * @param {Ext.Container} this
404              * @param {ContainerLayout} layout The ContainerLayout implementation for this container
405              */
406             'afterlayout',
407             /**
408              * @event beforeadd
409              * Fires before any {@link Ext.Component} is added or inserted into the container.
410              * A handler can return false to cancel the add.
411              * @param {Ext.Container} this
412              * @param {Ext.Component} component The component being added
413              * @param {Number} index The index at which the component will be added to the container's items collection
414              */
415             'beforeadd',
416             /**
417              * @event beforeremove
418              * Fires before any {@link Ext.Component} is removed from the container.  A handler can return
419              * false to cancel the remove.
420              * @param {Ext.Container} this
421              * @param {Ext.Component} component The component being removed
422              */
423             'beforeremove',
424             /**
425              * @event add
426              * @bubbles
427              * Fires after any {@link Ext.Component} is added or inserted into the container.
428              * @param {Ext.Container} this
429              * @param {Ext.Component} component The component that was added
430              * @param {Number} index The index at which the component was added to the container's items collection
431              */
432             'add',
433             /**
434              * @event remove
435              * @bubbles
436              * Fires after any {@link Ext.Component} is removed from the container.
437              * @param {Ext.Container} this
438              * @param {Ext.Component} component The component that was removed
439              */
440             'remove'
441         );
442
443         this.enableBubble(this.bubbleEvents);
444
445         /**
446          * The collection of components in this container as a {@link Ext.util.MixedCollection}
447          * @type MixedCollection
448          * @property items
449          */
450         var items = this.items;
451         if(items){
452             delete this.items;
453             this.add(items);
454         }
455     },
456
457     // private
458     initItems : function(){
459         if(!this.items){
460             this.items = new Ext.util.MixedCollection(false, this.getComponentId);
461             this.getLayout(); // initialize the layout
462         }
463     },
464
465     // private
466     setLayout : function(layout){
467         if(this.layout && this.layout != layout){
468             this.layout.setContainer(null);
469         }
470         this.initItems();
471         this.layout = layout;
472         layout.setContainer(this);
473     },
474
475     afterRender: function(){
476         this.layoutDone = false;
477         if(!this.layout){
478             this.layout = 'auto';
479         }
480         if(Ext.isObject(this.layout) && !this.layout.layout){
481             this.layoutConfig = this.layout;
482             this.layout = this.layoutConfig.type;
483         }
484         if(Ext.isString(this.layout)){
485             this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);
486         }
487         this.setLayout(this.layout);
488
489         // BoxComponent's afterRender will set the size.
490         // This will will trigger a layout if the layout is configured to monitor resize
491         Ext.Container.superclass.afterRender.call(this);
492
493         if(Ext.isDefined(this.activeItem)){
494             var item = this.activeItem;
495             delete this.activeItem;
496             this.layout.setActiveItem(item);
497         }
498
499         // If we have no ownerCt and the BoxComponent's sizing did not trigger a layout, force a layout
500         if(!this.ownerCt && !this.layoutDone){
501             this.doLayout(false, true);
502         }
503
504         if(this.monitorResize === true){
505             Ext.EventManager.onWindowResize(this.doLayout, this, [false]);
506         }
507     },
508
509     /**
510      * <p>Returns the Element to be used to contain the child Components of this Container.</p>
511      * <p>An implementation is provided which returns the Container's {@link #getEl Element}, but
512      * if there is a more complex structure to a Container, this may be overridden to return
513      * the element into which the {@link #layout layout} renders child Components.</p>
514      * @return {Ext.Element} The Element to render child Components into.
515      */
516     getLayoutTarget : function(){
517         return this.el;
518     },
519
520     // private - used as the key lookup function for the items collection
521     getComponentId : function(comp){
522         return comp.getItemId();
523     },
524
525     /**
526      * <p>Adds {@link Ext.Component Component}(s) to this Container.</p>
527      * <br><p><b>Description</b></u> :
528      * <div><ul class="mdetail-params">
529      * <li>Fires the {@link #beforeadd} event before adding</li>
530      * <li>The Container's {@link #defaults default config values} will be applied
531      * accordingly (see <code>{@link #defaults}</code> for details).</li>
532      * <li>Fires the {@link #add} event after the component has been added.</li>
533      * </ul></div>
534      * <br><p><b>Notes</b></u> :
535      * <div><ul class="mdetail-params">
536      * <li>If the Container is <i>already rendered</i> when <code>add</code>
537      * is called, you may need to call {@link #doLayout} to refresh the view which causes
538      * any unrendered child Components to be rendered. This is required so that you can
539      * <code>add</code> multiple child components if needed while only refreshing the layout
540      * once. For example:<pre><code>
541 var tb = new {@link Ext.Toolbar}();
542 tb.render(document.body);  // toolbar is rendered
543 tb.add({text:'Button 1'}); // add multiple items ({@link #defaultType} for {@link Ext.Toolbar Toolbar} is 'button')
544 tb.add({text:'Button 2'});
545 tb.{@link #doLayout}();             // refresh the layout
546      * </code></pre></li>
547      * <li><i>Warning:</i> Containers directly managed by the BorderLayout layout manager
548      * may not be removed or added.  See the Notes for {@link Ext.layout.BorderLayout BorderLayout}
549      * for more details.</li>
550      * </ul></div>
551      * @param {Object/Array} component
552      * <p>Either a single component or an Array of components to add.  See
553      * <code>{@link #items}</code> for additional information.</p>
554      * @param {Object} (Optional) component_2
555      * @param {Object} (Optional) component_n
556      * @return {Ext.Component} component The Component (or config object) that was added.
557      */
558     add : function(comp){
559         this.initItems();
560         var args = arguments.length > 1;
561         if(args || Ext.isArray(comp)){
562             var result = [];
563             Ext.each(args ? arguments : comp, function(c){
564                 result.push(this.add(c));
565             }, this);
566             return result;
567         }
568         var c = this.lookupComponent(this.applyDefaults(comp));
569         var index = this.items.length;
570         if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){
571             this.items.add(c);
572             // *onAdded
573             c.onAdded(this, index);
574             this.onAdd(c);
575             this.fireEvent('add', this, c, index);
576         }
577         return c;
578     },
579
580     onAdd : function(c){
581         // Empty template method
582     },
583     
584     // private
585     onAdded : function(container, pos) {
586         //overridden here so we can cascade down, not worth creating a template method.
587         this.ownerCt = container;
588         this.initRef();
589         //initialize references for child items
590         this.cascade(function(c){
591             c.initRef();
592         });
593         this.fireEvent('added', this, container, pos);
594     },
595
596     /**
597      * Inserts a Component into this Container at a specified index. Fires the
598      * {@link #beforeadd} event before inserting, then fires the {@link #add} event after the
599      * Component has been inserted.
600      * @param {Number} index The index at which the Component will be inserted
601      * into the Container's items collection
602      * @param {Ext.Component} component The child Component to insert.<br><br>
603      * Ext uses lazy rendering, and will only render the inserted Component should
604      * it become necessary.<br><br>
605      * A Component config object may be passed in order to avoid the overhead of
606      * constructing a real Component object if lazy rendering might mean that the
607      * inserted Component will not be rendered immediately. To take advantage of
608      * this 'lazy instantiation', set the {@link Ext.Component#xtype} config
609      * property to the registered type of the Component wanted.<br><br>
610      * For a list of all available xtypes, see {@link Ext.Component}.
611      * @return {Ext.Component} component The Component (or config object) that was
612      * inserted with the Container's default config values applied.
613      */
614     insert : function(index, comp){
615         this.initItems();
616         var a = arguments, len = a.length;
617         if(len > 2){
618             var result = [];
619             for(var i = len-1; i >= 1; --i) {
620                 result.push(this.insert(index, a[i]));
621             }
622             return result;
623         }
624         var c = this.lookupComponent(this.applyDefaults(comp));
625         index = Math.min(index, this.items.length);
626         if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){
627             if(c.ownerCt == this){
628                 this.items.remove(c);
629             }
630             this.items.insert(index, c);
631             c.onAdded(this, index);
632             this.onAdd(c);
633             this.fireEvent('add', this, c, index);
634         }
635         return c;
636     },
637
638     // private
639     applyDefaults : function(c){
640         var d = this.defaults;
641         if(d){
642             if(Ext.isFunction(d)){
643                 d = d.call(this, c);
644             }
645             if(Ext.isString(c)){
646                 c = Ext.ComponentMgr.get(c);
647                 Ext.apply(c, d);
648             }else if(!c.events){
649                 Ext.applyIf(c, d);
650             }else{
651                 Ext.apply(c, d);
652             }
653         }
654         return c;
655     },
656
657     // private
658     onBeforeAdd : function(item){
659         if(item.ownerCt){
660             item.ownerCt.remove(item, false);
661         }
662         if(this.hideBorders === true){
663             item.border = (item.border === true);
664         }
665     },
666
667     /**
668      * Removes a component from this container.  Fires the {@link #beforeremove} event before removing, then fires
669      * the {@link #remove} event after the component has been removed.
670      * @param {Component/String} component The component reference or id to remove.
671      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
672      * Defaults to the value of this Container's {@link #autoDestroy} config.
673      * @return {Ext.Component} component The Component that was removed.
674      */
675     remove : function(comp, autoDestroy){
676         this.initItems();
677         var c = this.getComponent(comp);
678         if(c && this.fireEvent('beforeremove', this, c) !== false){
679             this.doRemove(c, autoDestroy);
680             this.fireEvent('remove', this, c);
681         }
682         return c;
683     },
684
685     onRemove: function(c){
686         // Empty template method
687     },
688
689     // private
690     doRemove: function(c, autoDestroy){
691         if(this.layout && this.rendered){
692             this.layout.onRemove(c);
693         }
694         this.items.remove(c);
695         c.onRemoved();
696         this.onRemove(c);
697         if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){
698             c.destroy();
699         }
700     },
701
702     /**
703      * Removes all components from this container.
704      * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
705      * Defaults to the value of this Container's {@link #autoDestroy} config.
706      * @return {Array} Array of the destroyed components
707      */
708     removeAll: function(autoDestroy){
709         this.initItems();
710         var item, rem = [], items = [];
711         this.items.each(function(i){
712             rem.push(i);
713         });
714         for (var i = 0, len = rem.length; i < len; ++i){
715             item = rem[i];
716             this.remove(item, autoDestroy);
717             if(item.ownerCt !== this){
718                 items.push(item);
719             }
720         }
721         return items;
722     },
723
724     /**
725      * Examines this container's <code>{@link #items}</code> <b>property</b>
726      * and gets a direct child component of this container.
727      * @param {String/Number} comp This parameter may be any of the following:
728      * <div><ul class="mdetail-params">
729      * <li>a <b><code>String</code></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>
730      * or <code>{@link Ext.Component#id id}</code> of the child component </li>
731      * <li>a <b><code>Number</code></b> : representing the position of the child component
732      * within the <code>{@link #items}</code> <b>property</b></li>
733      * </ul></div>
734      * <p>For additional information see {@link Ext.util.MixedCollection#get}.
735      * @return Ext.Component The component (if found).
736      */
737     getComponent : function(comp){
738         if(Ext.isObject(comp)){
739             comp = comp.getItemId();
740         }
741         return this.items.get(comp);
742     },
743
744     // private
745     lookupComponent : function(comp){
746         if(Ext.isString(comp)){
747             return Ext.ComponentMgr.get(comp);
748         }else if(!comp.events){
749             return this.createComponent(comp);
750         }
751         return comp;
752     },
753
754     // private
755     createComponent : function(config, defaultType){
756         // add in ownerCt at creation time but then immediately
757         // remove so that onBeforeAdd can handle it
758         var c = config.render ? config : Ext.create(Ext.apply({
759             ownerCt: this
760         }, config), defaultType || this.defaultType);
761         delete c.ownerCt;
762         return c;
763     },
764
765     /**
766     * We can only lay out if there is a view area in which to layout.
767     * display:none on the layout target, *or any of its parent elements* will mean it has no view area.
768     */
769     canLayout: function() {
770         var el = this.getLayoutTarget(), vs;
771         return !!(el && (vs = el.dom.offsetWidth || el.dom.offsetHeight));
772     },
773
774     /**
775      * Force this container's layout to be recalculated. A call to this function is required after adding a new component
776      * to an already rendered container, or possibly after changing sizing/position properties of child components.
777      * @param {Boolean} shallow (optional) True to only calc the layout of this component, and let child components auto
778      * calc layouts as required (defaults to false, which calls doLayout recursively for each subcontainer)
779      * @param {Boolean} force (optional) True to force a layout to occur, even if the item is hidden.
780      * @return {Ext.Container} this
781      */
782     doLayout: function(shallow, force){
783         var rendered = this.rendered,
784             forceLayout = force || this.forceLayout,
785             cs, i, len, c;
786
787         this.layoutDone = true;
788         if(!this.canLayout() || this.collapsed){
789             this.deferLayout = this.deferLayout || !shallow;
790             if(!forceLayout){
791                 return;
792             }
793             shallow = shallow && !this.deferLayout;
794         } else {
795             delete this.deferLayout;
796         }
797
798         cs = (shallow !== true && this.items) ? this.items.items : [];
799
800 //      Inhibit child Containers from relaying on resize since we are about to to explicitly call doLayout on them all!
801         for(i = 0, len = cs.length; i < len; i++){
802             if ((c = cs[i]).layout) {
803                 c.suspendLayoutResize = true;
804             }
805         }
806
807 //      Tell the layout manager to ensure all child items are rendered, and sized according to their rules.
808 //      Will not cause the child items to relayout.
809         if(rendered && this.layout){
810             this.layout.layout();
811         }
812
813 //      Explicitly lay out all child items
814         for(i = 0; i < len; i++){
815             if((c = cs[i]).doLayout){
816                 c.doLayout(false, forceLayout);
817             }
818         }
819         if(rendered){
820             this.onLayout(shallow, forceLayout);
821         }
822         // Initial layout completed
823         this.hasLayout = true;
824         delete this.forceLayout;
825
826 //      Re-enable child layouts relaying on resize.
827         for(i = 0; i < len; i++){
828             if ((c = cs[i]).layout) {
829                 delete c.suspendLayoutResize;
830             }
831         }
832     },
833
834     //private
835     onLayout : Ext.emptyFn,
836
837     onResize: function(adjWidth, adjHeight, rawWidth, rawHeight){
838         Ext.Container.superclass.onResize.apply(this, arguments);
839         if ((this.rendered && this.layout && this.layout.monitorResize) && !this.suspendLayoutResize) {
840             this.layout.onResize();
841         }
842     },
843
844     // private
845     hasLayoutPending: function(){
846         // Traverse hierarchy to see if any parent container has a pending layout.
847         var pending = this.layoutPending;
848         this.ownerCt.bubble(function(c){
849             return !(pending = c.layoutPending);
850         });
851         return pending;
852
853     },
854
855     onShow : function(){
856         Ext.Container.superclass.onShow.call(this);
857         if(Ext.isDefined(this.deferLayout)){
858             this.doLayout(true);
859         }
860     },
861
862     /**
863      * Returns the layout currently in use by the container.  If the container does not currently have a layout
864      * set, a default {@link Ext.layout.ContainerLayout} will be created and set as the container's layout.
865      * @return {ContainerLayout} layout The container's layout
866      */
867     getLayout : function(){
868         if(!this.layout){
869             var layout = new Ext.layout.ContainerLayout(this.layoutConfig);
870             this.setLayout(layout);
871         }
872         return this.layout;
873     },
874
875     // private
876     beforeDestroy : function(){
877         var c;
878         if(this.items){
879             while(c = this.items.first()){
880                 this.doRemove(c, true);
881             }
882         }
883         if(this.monitorResize){
884             Ext.EventManager.removeResizeListener(this.doLayout, this);
885         }
886         Ext.destroy(this.layout);
887         Ext.Container.superclass.beforeDestroy.call(this);
888     },
889
890     /**
891      * Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of
892      * function call will be the scope provided or the current component. The arguments to the function
893      * will be the args provided or the current component. If the function returns false at any point,
894      * the bubble is stopped.
895      * @param {Function} fn The function to call
896      * @param {Object} scope (optional) The scope of the function (defaults to current node)
897      * @param {Array} args (optional) The args to call the function with (default to passing the current component)
898      * @return {Ext.Container} this
899      */
900     bubble : function(fn, scope, args){
901         var p = this;
902         while(p){
903             if(fn.apply(scope || p, args || [p]) === false){
904                 break;
905             }
906             p = p.ownerCt;
907         }
908         return this;
909     },
910
911     /**
912      * Cascades down the component/container heirarchy from this component (called first), calling the specified function with
913      * each component. The scope (<i>this</i>) of
914      * function call will be the scope provided or the current component. The arguments to the function
915      * will be the args provided or the current component. If the function returns false at any point,
916      * the cascade is stopped on that branch.
917      * @param {Function} fn The function to call
918      * @param {Object} scope (optional) The scope of the function (defaults to current component)
919      * @param {Array} args (optional) The args to call the function with (defaults to passing the current component)
920      * @return {Ext.Container} this
921      */
922     cascade : function(fn, scope, args){
923         if(fn.apply(scope || this, args || [this]) !== false){
924             if(this.items){
925                 var cs = this.items.items;
926                 for(var i = 0, len = cs.length; i < len; i++){
927                     if(cs[i].cascade){
928                         cs[i].cascade(fn, scope, args);
929                     }else{
930                         fn.apply(scope || cs[i], args || [cs[i]]);
931                     }
932                 }
933             }
934         }
935         return this;
936     },
937
938     /**
939      * Find a component under this container at any level by id
940      * @param {String} id
941      * @return Ext.Component
942      */
943     findById : function(id){
944         var m, ct = this;
945         this.cascade(function(c){
946             if(ct != c && c.id === id){
947                 m = c;
948                 return false;
949             }
950         });
951         return m || null;
952     },
953
954     /**
955      * Find a component under this container at any level by xtype or class
956      * @param {String/Class} xtype The xtype string for a component, or the class of the component directly
957      * @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is
958      * the default), or true to check whether this Component is directly of the specified xtype.
959      * @return {Array} Array of Ext.Components
960      */
961     findByType : function(xtype, shallow){
962         return this.findBy(function(c){
963             return c.isXType(xtype, shallow);
964         });
965     },
966
967     /**
968      * Find a component under this container at any level by property
969      * @param {String} prop
970      * @param {String} value
971      * @return {Array} Array of Ext.Components
972      */
973     find : function(prop, value){
974         return this.findBy(function(c){
975             return c[prop] === value;
976         });
977     },
978
979     /**
980      * Find a component under this container at any level by a custom function. If the passed function returns
981      * true, the component will be included in the results. The passed function is called with the arguments (component, this container).
982      * @param {Function} fn The function to call
983      * @param {Object} scope (optional)
984      * @return {Array} Array of Ext.Components
985      */
986     findBy : function(fn, scope){
987         var m = [], ct = this;
988         this.cascade(function(c){
989             if(ct != c && fn.call(scope || c, c, ct) === true){
990                 m.push(c);
991             }
992         });
993         return m;
994     },
995
996     /**
997      * Get a component contained by this container (alias for items.get(key))
998      * @param {String/Number} key The index or id of the component
999      * @return {Ext.Component} Ext.Component
1000      */
1001     get : function(key){
1002         return this.items.get(key);
1003     }
1004 });
1005
1006 Ext.Container.LAYOUTS = {};
1007 Ext.reg('container', Ext.Container);