PageRenderTime 33ms CodeModel.GetById 9ms app.highlight 16ms RepoModel.GetById 1ms app.codeStats 1ms

/hippo/src/main/webapp/ext/src/widgets/Container.js

http://hdbc.googlecode.com/
JavaScript | 894 lines | 290 code | 40 blank | 564 comment | 83 complexity | 0a7898c1e5a0c16bf39ca87cd189a63e MD5 | raw file
  1/*!
  2 * Ext JS Library 3.0.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 * <tt><b>{@link Ext.Component#autoEl autoEl}</b></tt> 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><tt>'container'</tt></b> xtype:<pre><code>
 22// explicitly create a Container
 23var 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 <tt><b>{@link #layout}</b></tt>
 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.
 76var myNewGrid = new Ext.grid.GridPanel({
 77    store: myStore,
 78    columns: myColumnModel,
 79    title: 'Results', // the title becomes the title of the tab
 80});
 81
 82myTabPanel.add(myNewGrid); // {@link Ext.TabPanel} implicitly uses {@link Ext.layout.CardLayout CardLayout}
 83myTabPanel.{@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 * <tt><b>{@link #layout}</b></tt> 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 <tt><b>{@link #layout}</b></tt> configuration, then the overnested
 96 * GridPanel will not be sized as expected.<p>
 97</code></pre>
 98 *
 99 * <p><u><b>Adding via remote configuration</b></u></p>
100 *
101 * <p>A server side script can be used to add Components which are generated dynamically on the server.
102 * An example of adding a GridPanel to a TabPanel where the GridPanel is generated by the server
103 * based on certain parameters:
104 * </p><pre><code>
105// execute an Ajax request to invoke server side script:
106Ext.Ajax.request({
107    url: 'gen-invoice-grid.php',
108    // send additional parameters to instruct server script
109    params: {
110        startDate: Ext.getCmp('start-date').getValue(),
111        endDate: Ext.getCmp('end-date').getValue()
112    },
113    // process the response object to add it to the TabPanel:
114    success: function(xhr) {
115        var newComponent = eval(xhr.responseText); // see discussion below
116        myTabPanel.add(newComponent); // add the component to the TabPanel
117        myTabPanel.setActiveTab(newComponent);
118    },
119    failure: function() {
120        Ext.Msg.alert("Grid create failed", "Server communication failure");
121    }
122});
123</code></pre>
124 * <p>The server script needs to return an executable Javascript statement which, when processed
125 * using <tt>eval()</tt>, will return either a config object with an {@link Ext.Component#xtype xtype},
126 * or an instantiated Component. The server might return this for example:</p><pre><code>
127(function() {
128    function formatDate(value){
129        return value ? value.dateFormat('M d, Y') : '';
130    };
131
132    var store = new Ext.data.Store({
133        url: 'get-invoice-data.php',
134        baseParams: {
135            startDate: '01/01/2008',
136            endDate: '01/31/2008'
137        },
138        reader: new Ext.data.JsonReader({
139            record: 'transaction',
140            idProperty: 'id',
141            totalRecords: 'total'
142        }, [
143           'customer',
144           'invNo',
145           {name: 'date', type: 'date', dateFormat: 'm/d/Y'},
146           {name: 'value', type: 'float'}
147        ])
148    });
149
150    var grid = new Ext.grid.GridPanel({
151        title: 'Invoice Report',
152        bbar: new Ext.PagingToolbar(store),
153        store: store,
154        columns: [
155            {header: "Customer", width: 250, dataIndex: 'customer', sortable: true},
156            {header: "Invoice Number", width: 120, dataIndex: 'invNo', sortable: true},
157            {header: "Invoice Date", width: 100, dataIndex: 'date', renderer: formatDate, sortable: true},
158            {header: "Value", width: 120, dataIndex: 'value', renderer: 'usMoney', sortable: true}
159        ],
160    });
161    store.load();
162    return grid;  // return instantiated component
163})();
164</code></pre>
165 * <p>When the above code fragment is passed through the <tt>eval</tt> function in the success handler
166 * of the Ajax request, the code is executed by the Javascript processor, and the anonymous function
167 * runs, and returns the instantiated grid component.</p>
168 * <p>Note: since the code above is <i>generated</i> by a server script, the <tt>baseParams</tt> for
169 * the Store, the metadata to allow generation of the Record layout, and the ColumnModel
170 * can all be generated into the code since these are all known on the server.</p>
171 *
172 * @xtype container
173 */
174Ext.Container = Ext.extend(Ext.BoxComponent, {
175    /**
176     * @cfg {Boolean} monitorResize
177     * True to automatically monitor window resize events to handle anything that is sensitive to the current size
178     * of the viewport.  This value is typically managed by the chosen <code>{@link #layout}</code> and should not need
179     * to be set manually.
180     */
181    /**
182     * @cfg {String/Object} layout
183     * When creating complex UIs, it is important to remember that sizing and
184     * positioning of child items is the responsibility of the Container's
185     * layout manager. If you expect child items to be sized in response to
186     * user interactions, <b>you must specify a layout manager</b> which
187     * creates and manages the type of layout you have in mind.  For example:<pre><code>
188new 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>Omitting the {@link #layout} config means that the
197     * {@link Ext.layout.ContainerLayout default layout manager} will be used which does
198     * nothing but render child components sequentially into the Container (no sizing or
199     * positioning will be performed in this situation).</p>
200     * <p>The layout manager class for this container may be specified as either as an
201     * Object or as a String:</p>
202     * <div><ul class="mdetail-params">
203     *
204     * <li><u>Specify as an Object</u></li>
205     * <div><ul class="mdetail-params">
206     * <li>Example usage:</li>
207<pre><code>
208layout: {
209    type: 'vbox',
210    padding: '5',
211    align: 'left'
212}
213</code></pre>
214     *
215     * <li><tt><b>type</b></tt></li>
216     * <br/><p>The layout type to be used for this container.  If not specified,
217     * a default {@link Ext.layout.ContainerLayout} will be created and used.</p>
218     * <br/><p>Valid layout <tt>type</tt> values are:</p>
219     * <div class="sub-desc"><ul class="mdetail-params">
220     * <li><tt><b>{@link Ext.layout.AbsoluteLayout absolute}</b></tt></li>
221     * <li><tt><b>{@link Ext.layout.AccordionLayout accordion}</b></tt></li>
222     * <li><tt><b>{@link Ext.layout.AnchorLayout anchor}</b></tt></li>
223     * <li><tt><b>{@link Ext.layout.ContainerLayout auto}</b></tt> &nbsp;&nbsp;&nbsp; <b>Default</b></li>
224     * <li><tt><b>{@link Ext.layout.BorderLayout border}</b></tt></li>
225     * <li><tt><b>{@link Ext.layout.CardLayout card}</b></tt></li>
226     * <li><tt><b>{@link Ext.layout.ColumnLayout column}</b></tt></li>
227     * <li><tt><b>{@link Ext.layout.FitLayout fit}</b></tt></li>
228     * <li><tt><b>{@link Ext.layout.FormLayout form}</b></tt></li>
229     * <li><tt><b>{@link Ext.layout.HBoxLayout hbox}</b></tt></li>
230     * <li><tt><b>{@link Ext.layout.MenuLayout menu}</b></tt></li>
231     * <li><tt><b>{@link Ext.layout.TableLayout table}</b></tt></li>
232     * <li><tt><b>{@link Ext.layout.ToolbarLayout toolbar}</b></tt></li>
233     * <li><tt><b>{@link Ext.layout.VBoxLayout vbox}</b></tt></li>
234     * </ul></div>
235     *
236     * <li>Layout specific configuration properties</li>
237     * <br/><p>Additional layout specific configuration properties may also be
238     * specified. For complete details regarding the valid config options for
239     * each layout type, see the layout class corresponding to the <tt>type</tt>
240     * specified.</p>
241     *
242     * </ul></div>
243     *
244     * <li><u>Specify as a String</u></li>
245     * <div><ul class="mdetail-params">
246     * <li>Example usage:</li>
247<pre><code>
248layout: 'vbox',
249layoutConfig: {
250    padding: '5',
251    align: 'left'
252}
253</code></pre>
254     * <li><tt><b>layout</b></tt></li>
255     * <br/><p>The layout <tt>type</tt> to be used for this container (see list
256     * of valid layout type values above).</p><br/>
257     * <li><tt><b>{@link #layoutConfig}</b></tt></li>
258     * <br/><p>Additional layout specific configuration properties. For complete
259     * details regarding the valid config options for each layout type, see the
260     * layout class corresponding to the <tt>layout</tt> specified.</p>
261     * </ul></div></ul></div>
262     */
263    /**
264     * @cfg {Object} layoutConfig
265     * This is a config object containing properties specific to the chosen
266     * <b><code>{@link #layout}</code></b> if <b><code>{@link #layout}</code></b>
267     * has been specified as a <i>string</i>.</p>
268     */
269    /**
270     * @cfg {Boolean/Number} bufferResize
271     * When set to true (100 milliseconds) or a number of milliseconds, the layout assigned for this container will buffer
272     * the frequency it calculates and does a re-layout of components. This is useful for heavy containers or containers
273     * with a large quantity of sub-components for which frequent layout calls would be expensive.
274     */
275    bufferResize: 100,
276    
277    /**
278     * @cfg {String/Number} activeItem
279     * A string component id or the numeric index of the component that should be initially activated within the
280     * container's layout on render.  For example, activeItem: 'item-1' or activeItem: 0 (index 0 = the first
281     * item in the container's collection).  activeItem only applies to layout styles that can display
282     * items one at a time (like {@link Ext.layout.AccordionLayout}, {@link Ext.layout.CardLayout} and
283     * {@link Ext.layout.FitLayout}).  Related to {@link Ext.layout.ContainerLayout#activeItem}.
284     */
285    /**
286     * @cfg {Object/Array} items
287     * <pre><b>** IMPORTANT</b>: be sure to specify a <b><code>{@link #layout}</code> ! **</b></pre>
288     * <p>A single item, or an array of child Components to be added to this container,
289     * for example:</p>
290     * <pre><code>
291// specifying a single item
292items: {...},
293layout: 'fit',    // specify a layout!
294
295// specifying multiple items
296items: [{...}, {...}],
297layout: 'anchor', // specify a layout!
298     * </code></pre>
299     * <p>Each item may be:</p>
300     * <div><ul class="mdetail-params">
301     * <li>any type of object based on {@link Ext.Component}</li>
302     * <li>a fully instanciated object or</li>
303     * <li>an object literal that:</li>
304     * <div><ul class="mdetail-params">
305     * <li>has a specified <code>{@link Ext.Component#xtype xtype}</code></li>
306     * <li>the {@link Ext.Component#xtype} specified is associated with the Component
307     * desired and should be chosen from one of the available xtypes as listed
308     * in {@link Ext.Component}.</li>
309     * <li>If an <code>{@link Ext.Component#xtype xtype}</code> is not explicitly
310     * specified, the {@link #defaultType} for that Container is used.</li>
311     * <li>will be "lazily instanciated", avoiding the overhead of constructing a fully
312     * instanciated Component object</li>
313     * </ul></div></ul></div>
314     * <p><b>Notes</b>:</p>
315     * <div><ul class="mdetail-params">
316     * <li>Ext uses lazy rendering. Child Components will only be rendered
317     * should it become necessary. Items are automatically laid out when they are first
318     * shown (no sizing is done while hidden), or in response to a {@link #doLayout} call.</li>
319     * <li>Do not specify <code>{@link Ext.Panel#contentEl contentEl}</code>/
320     * <code>{@link Ext.Panel#html html}</code> with <code>items</code>.</li>
321     * </ul></div>
322     */
323    /**
324     * @cfg {Object} defaults
325     * <p>A config object that will be applied to all components added to this container either via the {@link #items}
326     * config or via the {@link #add} or {@link #insert} methods.  The <tt>defaults</tt> config can contain any
327     * number of name/value property pairs to be added to each item, and should be valid for the types of items
328     * being added to the container.  For example, to automatically apply padding to the body of each of a set of
329     * contained {@link Ext.Panel} items, you could pass: <tt>defaults: {bodyStyle:'padding:15px'}</tt>.</p><br/>
330     * <p><b>Note</b>: <tt>defaults</tt> will not be applied to config objects if the option is already specified.
331     * For example:</p><pre><code>
332defaults: {               // defaults are applied to items, not the container
333    autoScroll:true
334},
335items: [
336    {
337        xtype: 'panel',   // defaults <b>do not</b> have precedence over
338        id: 'panel1',     // options in config objects, so the defaults
339        autoScroll: false // will not be applied here, panel1 will be autoScroll:false
340    },
341    new Ext.Panel({       // defaults <b>do</b> have precedence over options
342        id: 'panel2',     // options in components, so the defaults
343        autoScroll: false // will be applied here, panel2 will be autoScroll:true.
344    })
345]
346     * </code></pre>
347     */
348
349
350    /** @cfg {Boolean} autoDestroy
351     * If true the container will automatically destroy any contained component that is removed from it, else
352     * destruction must be handled manually (defaults to true).
353     */
354    autoDestroy : true,
355
356    /** @cfg {Boolean} forceLayout
357     * If true the container will force a layout initially even if hidden or collapsed. This option
358     * is useful for forcing forms to render in collapsed or hidden containers. (defaults to false).
359     */
360    forceLayout: false,
361
362    /** @cfg {Boolean} hideBorders
363     * True to hide the borders of each contained component, false to defer to the component's existing
364     * border settings (defaults to false).
365     */
366    /** @cfg {String} defaultType
367     * <p>The default {@link Ext.Component xtype} of child Components to create in this Container when
368     * a child item is specified as a raw configuration object, rather than as an instantiated Component.</p>
369     * <p>Defaults to <tt>'panel'</tt>, except {@link Ext.menu.Menu} which defaults to <tt>'menuitem'</tt>,
370     * and {@link Ext.Toolbar} and {@link Ext.ButtonGroup} which default to <tt>'button'</tt>.</p>
371     */
372    defaultType : 'panel',
373
374    // private
375    initComponent : function(){
376        Ext.Container.superclass.initComponent.call(this);
377
378        this.addEvents(
379            /**
380             * @event afterlayout
381             * Fires when the components in this container are arranged by the associated layout manager.
382             * @param {Ext.Container} this
383             * @param {ContainerLayout} layout The ContainerLayout implementation for this container
384             */
385            'afterlayout',
386            /**
387             * @event beforeadd
388             * Fires before any {@link Ext.Component} is added or inserted into the container.
389             * A handler can return false to cancel the add.
390             * @param {Ext.Container} this
391             * @param {Ext.Component} component The component being added
392             * @param {Number} index The index at which the component will be added to the container's items collection
393             */
394            'beforeadd',
395            /**
396             * @event beforeremove
397             * Fires before any {@link Ext.Component} is removed from the container.  A handler can return
398             * false to cancel the remove.
399             * @param {Ext.Container} this
400             * @param {Ext.Component} component The component being removed
401             */
402            'beforeremove',
403            /**
404             * @event add
405             * @bubbles
406             * Fires after any {@link Ext.Component} is added or inserted into the container.
407             * @param {Ext.Container} this
408             * @param {Ext.Component} component The component that was added
409             * @param {Number} index The index at which the component was added to the container's items collection
410             */
411            'add',
412            /**
413             * @event remove
414             * @bubbles
415             * Fires after any {@link Ext.Component} is removed from the container.
416             * @param {Ext.Container} this
417             * @param {Ext.Component} component The component that was removed
418             */
419            'remove'
420        );
421
422		this.enableBubble('add', 'remove');
423
424        /**
425         * The collection of components in this container as a {@link Ext.util.MixedCollection}
426         * @type MixedCollection
427         * @property items
428         */
429        var items = this.items;
430        if(items){
431            delete this.items;
432            if(Ext.isArray(items) && items.length > 0){
433                this.add.apply(this, items);
434            }else{
435                this.add(items);
436            }
437        }
438    },
439
440    // private
441    initItems : function(){
442        if(!this.items){
443            this.items = new Ext.util.MixedCollection(false, this.getComponentId);
444            this.getLayout(); // initialize the layout
445        }
446    },
447
448    // private
449    setLayout : function(layout){
450        if(this.layout && this.layout != layout){
451            this.layout.setContainer(null);
452        }
453        this.initItems();
454        this.layout = layout;
455        layout.setContainer(this);
456    },
457
458    // private
459    render : function(){
460        Ext.Container.superclass.render.apply(this, arguments);
461        if(this.layout){
462            if(Ext.isObject(this.layout) && !this.layout.layout){
463                this.layoutConfig = this.layout;
464                this.layout = this.layoutConfig.type;
465            }
466            if(typeof this.layout == 'string'){
467                this.layout = new Ext.Container.LAYOUTS[this.layout.toLowerCase()](this.layoutConfig);
468            }
469            this.setLayout(this.layout);
470
471            if(this.activeItem !== undefined){
472                var item = this.activeItem;
473                delete this.activeItem;
474                this.layout.setActiveItem(item);
475            }
476        }
477        if(!this.ownerCt){
478            // force a layout if no ownerCt is set
479            this.doLayout(false, true);
480        }
481        if(this.monitorResize === true){
482            Ext.EventManager.onWindowResize(this.doLayout, this, [false]);
483        }
484    },
485
486    /**
487     * <p>Returns the Element to be used to contain the child Components of this Container.</p>
488     * <p>An implementation is provided which returns the Container's {@link #getEl Element}, but
489     * if there is a more complex structure to a Container, this may be overridden to return
490     * the element into which the {@link #layout layout} renders child Components.</p>
491     * @return {Ext.Element} The Element to render child Components into.
492     */
493    getLayoutTarget : function(){
494        return this.el;
495    },
496
497    // private - used as the key lookup function for the items collection
498    getComponentId : function(comp){
499        return comp.getItemId();
500    },
501
502    /**
503     * <p>Adds {@link Ext.Component Component}(s) to this Container.</p>
504     * <br><p><b>Description</b></u> :
505     * <div><ul class="mdetail-params">
506     * <li>Fires the {@link #beforeadd} event before adding</li>
507     * <li>The Container's {@link #defaults default config values} will be applied
508     * accordingly (see <code>{@link #defaults}</code> for details).</li>
509     * <li>Fires the {@link #add} event after the component has been added.</li>
510     * </ul></div>
511     * <br><p><b>Notes</b></u> :
512     * <div><ul class="mdetail-params">
513     * <li>If the Container is <i>already rendered</i> when <tt>add</tt>
514     * is called, you may need to call {@link #doLayout} to refresh the view which causes
515     * any unrendered child Components to be rendered. This is required so that you can
516     * <tt>add</tt> multiple child components if needed while only refreshing the layout
517     * once. For example:<pre><code>
518var tb = new {@link Ext.Toolbar}();
519tb.render(document.body);  // toolbar is rendered
520tb.add({text:'Button 1'}); // add multiple items ({@link #defaultType} for {@link Ext.Toolbar Toolbar} is 'button')
521tb.add({text:'Button 2'});
522tb.{@link #doLayout}();             // refresh the layout
523     * </code></pre></li>
524     * <li><i>Warning:</i> Containers directly managed by the BorderLayout layout manager
525     * may not be removed or added.  See the Notes for {@link Ext.layout.BorderLayout BorderLayout}
526     * for more details.</li>
527     * </ul></div>
528     * @param {Object/Array} component
529     * <p>Either a single component or an Array of components to add.  See
530     * <code>{@link #items}</code> for additional information.</p>
531     * @param {Object} (Optional) component_2
532     * @param {Object} (Optional) component_n
533     * @return {Ext.Component} component The Component (or config object) that was added.
534     */
535    add : function(comp){
536        this.initItems();
537        var args = arguments.length > 1;
538        if(args || Ext.isArray(comp)){
539            Ext.each(args ? arguments : comp, function(c){
540                this.add(c);
541            }, this);
542            return;
543        }
544        var c = this.lookupComponent(this.applyDefaults(comp));
545        var pos = this.items.length;
546        if(this.fireEvent('beforeadd', this, c, pos) !== false && this.onBeforeAdd(c) !== false){
547            this.items.add(c);
548            c.ownerCt = this;
549            this.fireEvent('add', this, c, pos);
550        }
551        return c;
552    },
553
554    /**
555     * Inserts a Component into this Container at a specified index. Fires the
556     * {@link #beforeadd} event before inserting, then fires the {@link #add} event after the
557     * Component has been inserted.
558     * @param {Number} index The index at which the Component will be inserted
559     * into the Container's items collection
560     * @param {Ext.Component} component The child Component to insert.<br><br>
561     * Ext uses lazy rendering, and will only render the inserted Component should
562     * it become necessary.<br><br>
563     * A Component config object may be passed in order to avoid the overhead of
564     * constructing a real Component object if lazy rendering might mean that the
565     * inserted Component will not be rendered immediately. To take advantage of
566     * this 'lazy instantiation', set the {@link Ext.Component#xtype} config
567     * property to the registered type of the Component wanted.<br><br>
568     * For a list of all available xtypes, see {@link Ext.Component}.
569     * @return {Ext.Component} component The Component (or config object) that was
570     * inserted with the Container's default config values applied.
571     */
572    insert : function(index, comp){
573        this.initItems();
574        var a = arguments, len = a.length;
575        if(len > 2){
576            for(var i = len-1; i >= 1; --i) {
577                this.insert(index, a[i]);
578            }
579            return;
580        }
581        var c = this.lookupComponent(this.applyDefaults(comp));
582
583        if(c.ownerCt == this && this.items.indexOf(c) < index){
584            --index;
585        }
586
587        if(this.fireEvent('beforeadd', this, c, index) !== false && this.onBeforeAdd(c) !== false){
588            this.items.insert(index, c);
589            c.ownerCt = this;
590            this.fireEvent('add', this, c, index);
591        }
592        return c;
593    },
594
595    // private
596    applyDefaults : function(c){
597        if(this.defaults){
598            if(typeof c == 'string'){
599                c = Ext.ComponentMgr.get(c);
600                Ext.apply(c, this.defaults);
601            }else if(!c.events){
602                Ext.applyIf(c, this.defaults);
603            }else{
604                Ext.apply(c, this.defaults);
605            }
606        }
607        return c;
608    },
609
610    // private
611    onBeforeAdd : function(item){
612        if(item.ownerCt){
613            item.ownerCt.remove(item, false);
614        }
615        if(this.hideBorders === true){
616            item.border = (item.border === true);
617        }
618    },
619
620    /**
621     * Removes a component from this container.  Fires the {@link #beforeremove} event before removing, then fires
622     * the {@link #remove} event after the component has been removed.
623     * @param {Component/String} component The component reference or id to remove.
624     * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
625     * Defaults to the value of this Container's {@link #autoDestroy} config.
626     * @return {Ext.Component} component The Component that was removed.
627     */
628    remove : function(comp, autoDestroy){
629        this.initItems();
630        var c = this.getComponent(comp);
631        if(c && this.fireEvent('beforeremove', this, c) !== false){
632            this.items.remove(c);
633            delete c.ownerCt;
634            if(autoDestroy === true || (autoDestroy !== false && this.autoDestroy)){
635                c.destroy();
636            }
637            if(this.layout && this.layout.activeItem == c){
638                delete this.layout.activeItem;
639            }
640            this.fireEvent('remove', this, c);
641        }
642        return c;
643    },
644
645    /**
646     * Removes all components from this container.
647     * @param {Boolean} autoDestroy (optional) True to automatically invoke the removed Component's {@link Ext.Component#destroy} function.
648     * Defaults to the value of this Container's {@link #autoDestroy} config.
649     * @return {Array} Array of the destroyed components
650     */
651    removeAll: function(autoDestroy){
652        this.initItems();
653        var item, rem = [], items = [];
654        this.items.each(function(i){
655            rem.push(i);
656        });
657        for (var i = 0, len = rem.length; i < len; ++i){
658            item = rem[i];
659            this.remove(item, autoDestroy);
660            if(item.ownerCt !== this){
661                items.push(item);
662            }
663        }
664        return items;
665    },
666
667    /**
668     * Examines this container's <code>{@link #items}</code> <b>property</b>
669     * and gets a direct child component of this container.
670     * @param {String/Number} comp This parameter may be any of the following:
671     * <div><ul class="mdetail-params">
672     * <li>a <b><tt>String</tt></b> : representing the <code>{@link Ext.Component#itemId itemId}</code>
673     * or <code>{@link Ext.Component#id id}</code> of the child component </li>
674     * <li>a <b><tt>Number</tt></b> : representing the position of the child component
675     * within the <code>{@link #items}</code> <b>property</b></li>
676     * </ul></div>
677     * <p>For additional information see {@link Ext.util.MixedCollection#get}.
678     * @return Ext.Component The component (if found).
679     */
680    getComponent : function(comp){
681        if(Ext.isObject(comp)){
682            return comp;
683        }
684        return this.items.get(comp);
685    },
686
687    // private
688    lookupComponent : function(comp){
689        if(typeof comp == 'string'){
690            return Ext.ComponentMgr.get(comp);
691        }else if(!comp.events){
692            return this.createComponent(comp);
693        }
694        return comp;
695    },
696
697    // private
698    createComponent : function(config){
699        return Ext.create(config, this.defaultType);
700    },
701
702    /**
703     * Force this container's layout to be recalculated. A call to this function is required after adding a new component
704     * to an already rendered container, or possibly after changing sizing/position properties of child components.
705     * @param {Boolean} shallow (optional) True to only calc the layout of this component, and let child components auto
706     * calc layouts as required (defaults to false, which calls doLayout recursively for each subcontainer)
707     * @param {Boolean} force (optional) True to force a layout to occur, even if the item is hidden.
708     * @return {Ext.Container} this
709     */
710    doLayout: function(shallow, force){
711        var rendered = this.rendered,
712            forceLayout = this.forceLayout;
713
714        if(!this.isVisible() || this.collapsed){
715            this.deferLayout = this.deferLayout || !shallow;
716            if(!(force || forceLayout)){
717                return;
718            }
719            shallow = shallow && !this.deferLayout;
720        } else {
721            delete this.deferLayout;
722        }
723        if(rendered && this.layout){
724            this.layout.layout();
725        }
726        if(shallow !== true && this.items){
727            var cs = this.items.items;
728            for(var i = 0, len = cs.length; i < len; i++){
729                var c = cs[i];
730                if(c.doLayout){
731                    c.forceLayout = forceLayout;
732                    c.doLayout();
733                }
734            }
735        }
736        if(rendered){
737            this.onLayout(shallow, force);
738        }
739        delete this.forceLayout;
740    },
741
742    //private
743    onLayout : Ext.emptyFn,
744
745    onShow : function(){
746        Ext.Container.superclass.onShow.call(this);
747        if(this.deferLayout !== undefined){
748            this.doLayout(true);
749        }
750    },
751
752    /**
753     * Returns the layout currently in use by the container.  If the container does not currently have a layout
754     * set, a default {@link Ext.layout.ContainerLayout} will be created and set as the container's layout.
755     * @return {ContainerLayout} layout The container's layout
756     */
757    getLayout : function(){
758        if(!this.layout){
759            var layout = new Ext.layout.ContainerLayout(this.layoutConfig);
760            this.setLayout(layout);
761        }
762        return this.layout;
763    },
764
765    // private
766    beforeDestroy : function(){
767        if(this.items){
768            Ext.destroy.apply(Ext, this.items.items);
769        }
770        if(this.monitorResize){
771            Ext.EventManager.removeResizeListener(this.doLayout, this);
772        }
773        Ext.destroy(this.layout);
774        Ext.Container.superclass.beforeDestroy.call(this);
775    },
776
777    /**
778     * Bubbles up the component/container heirarchy, calling the specified function with each component. The scope (<i>this</i>) of
779     * function call will be the scope provided or the current component. The arguments to the function
780     * will be the args provided or the current component. If the function returns false at any point,
781     * the bubble is stopped.
782     * @param {Function} fn The function to call
783     * @param {Object} scope (optional) The scope of the function (defaults to current node)
784     * @param {Array} args (optional) The args to call the function with (default to passing the current component)
785     * @return {Ext.Container} this
786     */
787    bubble : function(fn, scope, args){
788        var p = this;
789        while(p){
790            if(fn.apply(scope || p, args || [p]) === false){
791                break;
792            }
793            p = p.ownerCt;
794        }
795        return this;
796    },
797
798    /**
799     * Cascades down the component/container heirarchy from this component (called first), calling the specified function with
800     * each component. The scope (<i>this</i>) of
801     * function call will be the scope provided or the current component. The arguments to the function
802     * will be the args provided or the current component. If the function returns false at any point,
803     * the cascade is stopped on that branch.
804     * @param {Function} fn The function to call
805     * @param {Object} scope (optional) The scope of the function (defaults to current component)
806     * @param {Array} args (optional) The args to call the function with (defaults to passing the current component)
807     * @return {Ext.Container} this
808     */
809    cascade : function(fn, scope, args){
810        if(fn.apply(scope || this, args || [this]) !== false){
811            if(this.items){
812                var cs = this.items.items;
813                for(var i = 0, len = cs.length; i < len; i++){
814                    if(cs[i].cascade){
815                        cs[i].cascade(fn, scope, args);
816                    }else{
817                        fn.apply(scope || cs[i], args || [cs[i]]);
818                    }
819                }
820            }
821        }
822        return this;
823    },
824
825    /**
826     * Find a component under this container at any level by id
827     * @param {String} id
828     * @return Ext.Component
829     */
830    findById : function(id){
831        var m, ct = this;
832        this.cascade(function(c){
833            if(ct != c && c.id === id){
834                m = c;
835                return false;
836            }
837        });
838        return m || null;
839    },
840
841    /**
842     * Find a component under this container at any level by xtype or class
843     * @param {String/Class} xtype The xtype string for a component, or the class of the component directly
844     * @param {Boolean} shallow (optional) False to check whether this Component is descended from the xtype (this is
845     * the default), or true to check whether this Component is directly of the specified xtype.
846     * @return {Array} Array of Ext.Components
847     */
848    findByType : function(xtype, shallow){
849        return this.findBy(function(c){
850            return c.isXType(xtype, shallow);
851        });
852    },
853
854    /**
855     * Find a component under this container at any level by property
856     * @param {String} prop
857     * @param {String} value
858     * @return {Array} Array of Ext.Components
859     */
860    find : function(prop, value){
861        return this.findBy(function(c){
862            return c[prop] === value;
863        });
864    },
865
866    /**
867     * Find a component under this container at any level by a custom function. If the passed function returns
868     * true, the component will be included in the results. The passed function is called with the arguments (component, this container).
869     * @param {Function} fn The function to call
870     * @param {Object} scope (optional)
871     * @return {Array} Array of Ext.Components
872     */
873    findBy : function(fn, scope){
874        var m = [], ct = this;
875        this.cascade(function(c){
876            if(ct != c && fn.call(scope || c, c, ct) === true){
877                m.push(c);
878            }
879        });
880        return m;
881    },
882
883    /**
884     * Get a component contained by this container (alias for items.get(key))
885     * @param {String/Number} key The index or id of the component
886     * @return {Ext.Component} Ext.Component
887     */
888    get : function(key){
889        return this.items.get(key);
890    }
891});
892
893Ext.Container.LAYOUTS = {};
894Ext.reg('container', Ext.Container);