Upgrade to ExtJS 3.3.0 - Released 10/06/2010
[extjs.git] / pkgs / pkg-forms-debug.js
1 /*!
2  * Ext JS Library 3.3.0
3  * Copyright(c) 2006-2010 Ext JS, Inc.
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.form.Field
9  * @extends Ext.BoxComponent
10  * Base class for form fields that provides default event handling, sizing, value handling and other functionality.
11  * @constructor
12  * Creates a new Field
13  * @param {Object} config Configuration options
14  * @xtype field
15  */
16 Ext.form.Field = Ext.extend(Ext.BoxComponent,  {
17     /**
18      * <p>The label Element associated with this Field. <b>Only available after this Field has been rendered by a
19      * {@link form Ext.layout.FormLayout} layout manager.</b></p>
20      * @type Ext.Element
21      * @property label
22      */
23     /**
24      * @cfg {String} inputType The type attribute for input fields -- e.g. radio, text, password, file (defaults
25      * to 'text'). The types 'file' and 'password' must be used to render those field types currently -- there are
26      * no separate Ext components for those. Note that if you use <tt>inputType:'file'</tt>, {@link #emptyText}
27      * is not supported and should be avoided.
28      */
29     /**
30      * @cfg {Number} tabIndex The tabIndex for this field. Note this only applies to fields that are rendered,
31      * not those which are built via applyTo (defaults to undefined).
32      */
33     /**
34      * @cfg {Mixed} value A value to initialize this field with (defaults to undefined).
35      */
36     /**
37      * @cfg {String} name The field's HTML name attribute (defaults to '').
38      * <b>Note</b>: this property must be set if this field is to be automatically included with
39      * {@link Ext.form.BasicForm#submit form submit()}.
40      */
41     /**
42      * @cfg {String} cls A custom CSS class to apply to the field's underlying element (defaults to '').
43      */
44
45     /**
46      * @cfg {String} invalidClass The CSS class to use when marking a field invalid (defaults to 'x-form-invalid')
47      */
48     invalidClass : 'x-form-invalid',
49     /**
50      * @cfg {String} invalidText The error text to use when marking a field invalid and no message is provided
51      * (defaults to 'The value in this field is invalid')
52      */
53     invalidText : 'The value in this field is invalid',
54     /**
55      * @cfg {String} focusClass The CSS class to use when the field receives focus (defaults to 'x-form-focus')
56      */
57     focusClass : 'x-form-focus',
58     /**
59      * @cfg {Boolean} preventMark
60      * <tt>true</tt> to disable {@link #markInvalid marking the field invalid}.
61      * Defaults to <tt>false</tt>.
62      */
63     /**
64      * @cfg {String/Boolean} validationEvent The event that should initiate field validation. Set to false to disable
65       automatic validation (defaults to 'keyup').
66      */
67     validationEvent : 'keyup',
68     /**
69      * @cfg {Boolean} validateOnBlur Whether the field should validate when it loses focus (defaults to true).
70      */
71     validateOnBlur : true,
72     /**
73      * @cfg {Number} validationDelay The length of time in milliseconds after user input begins until validation
74      * is initiated (defaults to 250)
75      */
76     validationDelay : 250,
77     /**
78      * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
79      * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
80      * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:</p>
81      * <pre><code>{tag: 'input', type: 'text', size: '20', autocomplete: 'off'}</code></pre>
82      */
83     defaultAutoCreate : {tag: 'input', type: 'text', size: '20', autocomplete: 'off'},
84     /**
85      * @cfg {String} fieldClass The default CSS class for the field (defaults to 'x-form-field')
86      */
87     fieldClass : 'x-form-field',
88     /**
89      * @cfg {String} msgTarget <p>The location where the message text set through {@link #markInvalid} should display.
90      * Must be one of the following values:</p>
91      * <div class="mdetail-params"><ul>
92      * <li><code>qtip</code> Display a quick tip containing the message when the user hovers over the field. This is the default.
93      * <div class="subdesc"><b>{@link Ext.QuickTips#init Ext.QuickTips.init} must have been called for this setting to work.</b></div</li>
94      * <li><code>title</code> Display the message in a default browser title attribute popup.</li>
95      * <li><code>under</code> Add a block div beneath the field containing the error message.</li>
96      * <li><code>side</code> Add an error icon to the right of the field, displaying the message in a popup on hover.</li>
97      * <li><code>[element id]</code> Add the error message directly to the innerHTML of the specified element.</li>
98      * </ul></div>
99      */
100     msgTarget : 'qtip',
101     /**
102      * @cfg {String} msgFx <b>Experimental</b> The effect used when displaying a validation message under the field
103      * (defaults to 'normal').
104      */
105     msgFx : 'normal',
106     /**
107      * @cfg {Boolean} readOnly <tt>true</tt> to mark the field as readOnly in HTML
108      * (defaults to <tt>false</tt>).
109      * <br><p><b>Note</b>: this only sets the element's readOnly DOM attribute.
110      * Setting <code>readOnly=true</code>, for example, will not disable triggering a
111      * ComboBox or DateField; it gives you the option of forcing the user to choose
112      * via the trigger without typing in the text box. To hide the trigger use
113      * <code>{@link Ext.form.TriggerField#hideTrigger hideTrigger}</code>.</p>
114      */
115     readOnly : false,
116     /**
117      * @cfg {Boolean} disabled True to disable the field (defaults to false).
118      * <p>Be aware that conformant with the <a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1">HTML specification</a>,
119      * disabled Fields will not be {@link Ext.form.BasicForm#submit submitted}.</p>
120      */
121     disabled : false,
122     /**
123      * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
124      * Defaults to <tt>true</tt>.
125      */
126     submitValue: true,
127
128     // private
129     isFormField : true,
130
131     // private
132     msgDisplay: '',
133
134     // private
135     hasFocus : false,
136
137     // private
138     initComponent : function(){
139         Ext.form.Field.superclass.initComponent.call(this);
140         this.addEvents(
141             /**
142              * @event focus
143              * Fires when this field receives input focus.
144              * @param {Ext.form.Field} this
145              */
146             'focus',
147             /**
148              * @event blur
149              * Fires when this field loses input focus.
150              * @param {Ext.form.Field} this
151              */
152             'blur',
153             /**
154              * @event specialkey
155              * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed.
156              * To handle other keys see {@link Ext.Panel#keys} or {@link Ext.KeyMap}.
157              * You can check {@link Ext.EventObject#getKey} to determine which key was pressed.
158              * For example: <pre><code>
159 var form = new Ext.form.FormPanel({
160     ...
161     items: [{
162             fieldLabel: 'Field 1',
163             name: 'field1',
164             allowBlank: false
165         },{
166             fieldLabel: 'Field 2',
167             name: 'field2',
168             listeners: {
169                 specialkey: function(field, e){
170                     // e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
171                     // e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
172                     if (e.{@link Ext.EventObject#getKey getKey()} == e.ENTER) {
173                         var form = field.ownerCt.getForm();
174                         form.submit();
175                     }
176                 }
177             }
178         }
179     ],
180     ...
181 });
182              * </code></pre>
183              * @param {Ext.form.Field} this
184              * @param {Ext.EventObject} e The event object
185              */
186             'specialkey',
187             /**
188              * @event change
189              * Fires just before the field blurs if the field value has changed.
190              * @param {Ext.form.Field} this
191              * @param {Mixed} newValue The new value
192              * @param {Mixed} oldValue The original value
193              */
194             'change',
195             /**
196              * @event invalid
197              * Fires after the field has been marked as invalid.
198              * @param {Ext.form.Field} this
199              * @param {String} msg The validation message
200              */
201             'invalid',
202             /**
203              * @event valid
204              * Fires after the field has been validated with no errors.
205              * @param {Ext.form.Field} this
206              */
207             'valid'
208         );
209     },
210
211     /**
212      * Returns the {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
213      * attribute of the field if available.
214      * @return {String} name The field {@link Ext.form.Field#name name} or {@link Ext.form.ComboBox#hiddenName hiddenName}
215      */
216     getName : function(){
217         return this.rendered && this.el.dom.name ? this.el.dom.name : this.name || this.id || '';
218     },
219
220     // private
221     onRender : function(ct, position){
222         if(!this.el){
223             var cfg = this.getAutoCreate();
224
225             if(!cfg.name){
226                 cfg.name = this.name || this.id;
227             }
228             if(this.inputType){
229                 cfg.type = this.inputType;
230             }
231             this.autoEl = cfg;
232         }
233         Ext.form.Field.superclass.onRender.call(this, ct, position);
234         if(this.submitValue === false){
235             this.el.dom.removeAttribute('name');
236         }
237         var type = this.el.dom.type;
238         if(type){
239             if(type == 'password'){
240                 type = 'text';
241             }
242             this.el.addClass('x-form-'+type);
243         }
244         if(this.readOnly){
245             this.setReadOnly(true);
246         }
247         if(this.tabIndex !== undefined){
248             this.el.dom.setAttribute('tabIndex', this.tabIndex);
249         }
250
251         this.el.addClass([this.fieldClass, this.cls]);
252     },
253
254     // private
255     getItemCt : function(){
256         return this.itemCt;
257     },
258
259     // private
260     initValue : function(){
261         if(this.value !== undefined){
262             this.setValue(this.value);
263         }else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
264             this.setValue(this.el.dom.value);
265         }
266         /**
267          * The original value of the field as configured in the {@link #value} configuration, or
268          * as loaded by the last form load operation if the form's {@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
269          * setting is <code>true</code>.
270          * @type mixed
271          * @property originalValue
272          */
273         this.originalValue = this.getValue();
274     },
275
276     /**
277      * <p>Returns true if the value of this Field has been changed from its original value.
278      * Will return false if the field is disabled or has not been rendered yet.</p>
279      * <p>Note that if the owning {@link Ext.form.BasicForm form} was configured with
280      * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
281      * then the <i>original value</i> is updated when the values are loaded by
282      * {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#setValues setValues}.</p>
283      * @return {Boolean} True if this field has been changed from its original value (and
284      * is not disabled), false otherwise.
285      */
286     isDirty : function() {
287         if(this.disabled || !this.rendered) {
288             return false;
289         }
290         return String(this.getValue()) !== String(this.originalValue);
291     },
292
293     /**
294      * Sets the read only state of this field.
295      * @param {Boolean} readOnly Whether the field should be read only.
296      */
297     setReadOnly : function(readOnly){
298         if(this.rendered){
299             this.el.dom.readOnly = readOnly;
300         }
301         this.readOnly = readOnly;
302     },
303
304     // private
305     afterRender : function(){
306         Ext.form.Field.superclass.afterRender.call(this);
307         this.initEvents();
308         this.initValue();
309     },
310
311     // private
312     fireKey : function(e){
313         if(e.isSpecialKey()){
314             this.fireEvent('specialkey', this, e);
315         }
316     },
317
318     /**
319      * Resets the current field value to the originally loaded value and clears any validation messages.
320      * See {@link Ext.form.BasicForm}.{@link Ext.form.BasicForm#trackResetOnLoad trackResetOnLoad}
321      */
322     reset : function(){
323         this.setValue(this.originalValue);
324         this.clearInvalid();
325     },
326
327     // private
328     initEvents : function(){
329         this.mon(this.el, Ext.EventManager.getKeyEvent(), this.fireKey,  this);
330         this.mon(this.el, 'focus', this.onFocus, this);
331
332         // standardise buffer across all browsers + OS-es for consistent event order.
333         // (the 10ms buffer for Editors fixes a weird FF/Win editor issue when changing OS window focus)
334         this.mon(this.el, 'blur', this.onBlur, this, this.inEditor ? {buffer:10} : null);
335     },
336
337     // private
338     preFocus: Ext.emptyFn,
339
340     // private
341     onFocus : function(){
342         this.preFocus();
343         if(this.focusClass){
344             this.el.addClass(this.focusClass);
345         }
346         if(!this.hasFocus){
347             this.hasFocus = true;
348             /**
349              * <p>The value that the Field had at the time it was last focused. This is the value that is passed
350              * to the {@link #change} event which is fired if the value has been changed when the Field is blurred.</p>
351              * <p><b>This will be undefined until the Field has been visited.</b> Compare {@link #originalValue}.</p>
352              * @type mixed
353              * @property startValue
354              */
355             this.startValue = this.getValue();
356             this.fireEvent('focus', this);
357         }
358     },
359
360     // private
361     beforeBlur : Ext.emptyFn,
362
363     // private
364     onBlur : function(){
365         this.beforeBlur();
366         if(this.focusClass){
367             this.el.removeClass(this.focusClass);
368         }
369         this.hasFocus = false;
370         if(this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == 'blur')){
371             this.validate();
372         }
373         var v = this.getValue();
374         if(String(v) !== String(this.startValue)){
375             this.fireEvent('change', this, v, this.startValue);
376         }
377         this.fireEvent('blur', this);
378         this.postBlur();
379     },
380
381     // private
382     postBlur : Ext.emptyFn,
383
384     /**
385      * Returns whether or not the field value is currently valid by
386      * {@link #validateValue validating} the {@link #processValue processed value}
387      * of the field. <b>Note</b>: {@link #disabled} fields are ignored.
388      * @param {Boolean} preventMark True to disable marking the field invalid
389      * @return {Boolean} True if the value is valid, else false
390      */
391     isValid : function(preventMark){
392         if(this.disabled){
393             return true;
394         }
395         var restore = this.preventMark;
396         this.preventMark = preventMark === true;
397         var v = this.validateValue(this.processValue(this.getRawValue()));
398         this.preventMark = restore;
399         return v;
400     },
401
402     /**
403      * Validates the field value
404      * @return {Boolean} True if the value is valid, else false
405      */
406     validate : function(){
407         if(this.disabled || this.validateValue(this.processValue(this.getRawValue()))){
408             this.clearInvalid();
409             return true;
410         }
411         return false;
412     },
413
414     /**
415      * This method should only be overridden if necessary to prepare raw values
416      * for validation (see {@link #validate} and {@link #isValid}).  This method
417      * is expected to return the processed value for the field which will
418      * be used for validation (see validateValue method).
419      * @param {Mixed} value
420      */
421     processValue : function(value){
422         return value;
423     },
424
425     /**
426      * Uses getErrors to build an array of validation errors. If any errors are found, markInvalid is called
427      * with the first and false is returned, otherwise true is returned. Previously, subclasses were invited
428      * to provide an implementation of this to process validations - from 3.2 onwards getErrors should be
429      * overridden instead.
430      * @param {Mixed} The current value of the field
431      * @return {Boolean} True if all validations passed, false if one or more failed
432      */
433      validateValue : function(value) {
434          //currently, we only show 1 error at a time for a field, so just use the first one
435          var error = this.getErrors(value)[0];
436
437          if (error == undefined) {
438              return true;
439          } else {
440              this.markInvalid(error);
441              return false;
442          }
443      },
444     
445     /**
446      * Runs this field's validators and returns an array of error messages for any validation failures.
447      * This is called internally during validation and would not usually need to be used manually.
448      * Each subclass should override or augment the return value to provide their own errors
449      * @return {Array} All error messages for this field
450      */
451     getErrors: function() {
452         return [];
453     },
454
455     /**
456      * Gets the active error message for this field.
457      * @return {String} Returns the active error message on the field, if there is no error, an empty string is returned.
458      */
459     getActiveError : function(){
460         return this.activeError || '';
461     },
462
463     /**
464      * <p>Display an error message associated with this field, using {@link #msgTarget} to determine how to
465      * display the message and applying {@link #invalidClass} to the field's UI element.</p>
466      * <p><b>Note</b>: this method does not cause the Field's {@link #validate} method to return <code>false</code>
467      * if the value does <i>pass</i> validation. So simply marking a Field as invalid will not prevent
468      * submission of forms submitted with the {@link Ext.form.Action.Submit#clientValidation} option set.</p>
469      * {@link #isValid invalid}.
470      * @param {String} msg (optional) The validation message (defaults to {@link #invalidText})
471      */
472     markInvalid : function(msg){
473         //don't set the error icon if we're not rendered or marking is prevented
474         if (this.rendered && !this.preventMark) {
475             msg = msg || this.invalidText;
476
477             var mt = this.getMessageHandler();
478             if(mt){
479                 mt.mark(this, msg);
480             }else if(this.msgTarget){
481                 this.el.addClass(this.invalidClass);
482                 var t = Ext.getDom(this.msgTarget);
483                 if(t){
484                     t.innerHTML = msg;
485                     t.style.display = this.msgDisplay;
486                 }
487             }
488         }
489         
490         this.setActiveError(msg);
491     },
492     
493     /**
494      * Clear any invalid styles/messages for this field
495      */
496     clearInvalid : function(){
497         //don't remove the error icon if we're not rendered or marking is prevented
498         if (this.rendered && !this.preventMark) {
499             this.el.removeClass(this.invalidClass);
500             var mt = this.getMessageHandler();
501             if(mt){
502                 mt.clear(this);
503             }else if(this.msgTarget){
504                 this.el.removeClass(this.invalidClass);
505                 var t = Ext.getDom(this.msgTarget);
506                 if(t){
507                     t.innerHTML = '';
508                     t.style.display = 'none';
509                 }
510             }
511         }
512         
513         this.unsetActiveError();
514     },
515
516     /**
517      * Sets the current activeError to the given string. Fires the 'invalid' event.
518      * This does not set up the error icon, only sets the message and fires the event. To show the error icon,
519      * use markInvalid instead, which calls this method internally
520      * @param {String} msg The error message
521      * @param {Boolean} suppressEvent True to suppress the 'invalid' event from being fired
522      */
523     setActiveError: function(msg, suppressEvent) {
524         this.activeError = msg;
525         if (suppressEvent !== true) this.fireEvent('invalid', this, msg);
526     },
527     
528     /**
529      * Clears the activeError and fires the 'valid' event. This is called internally by clearInvalid and would not
530      * usually need to be called manually
531      * @param {Boolean} suppressEvent True to suppress the 'invalid' event from being fired
532      */
533     unsetActiveError: function(suppressEvent) {
534         delete this.activeError;
535         if (suppressEvent !== true) this.fireEvent('valid', this);
536     },
537
538     // private
539     getMessageHandler : function(){
540         return Ext.form.MessageTargets[this.msgTarget];
541     },
542
543     // private
544     getErrorCt : function(){
545         return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
546             this.el.findParent('.x-form-field-wrap', 5, true);   // else direct field wrap
547     },
548
549     // Alignment for 'under' target
550     alignErrorEl : function(){
551         this.errorEl.setWidth(this.getErrorCt().getWidth(true) - 20);
552     },
553
554     // Alignment for 'side' target
555     alignErrorIcon : function(){
556         this.errorIcon.alignTo(this.el, 'tl-tr', [2, 0]);
557     },
558
559     /**
560      * Returns the raw data value which may or may not be a valid, defined value.  To return a normalized value see {@link #getValue}.
561      * @return {Mixed} value The field value
562      */
563     getRawValue : function(){
564         var v = this.rendered ? this.el.getValue() : Ext.value(this.value, '');
565         if(v === this.emptyText){
566             v = '';
567         }
568         return v;
569     },
570
571     /**
572      * Returns the normalized data value (undefined or emptyText will be returned as '').  To return the raw value see {@link #getRawValue}.
573      * @return {Mixed} value The field value
574      */
575     getValue : function(){
576         if(!this.rendered) {
577             return this.value;
578         }
579         var v = this.el.getValue();
580         if(v === this.emptyText || v === undefined){
581             v = '';
582         }
583         return v;
584     },
585
586     /**
587      * Sets the underlying DOM field's value directly, bypassing validation.  To set the value with validation see {@link #setValue}.
588      * @param {Mixed} value The value to set
589      * @return {Mixed} value The field value that is set
590      */
591     setRawValue : function(v){
592         return this.rendered ? (this.el.dom.value = (Ext.isEmpty(v) ? '' : v)) : '';
593     },
594
595     /**
596      * Sets a data value into the field and validates it.  To set the value directly without validation see {@link #setRawValue}.
597      * @param {Mixed} value The value to set
598      * @return {Ext.form.Field} this
599      */
600     setValue : function(v){
601         this.value = v;
602         if(this.rendered){
603             this.el.dom.value = (Ext.isEmpty(v) ? '' : v);
604             this.validate();
605         }
606         return this;
607     },
608
609     // private, does not work for all fields
610     append : function(v){
611          this.setValue([this.getValue(), v].join(''));
612     }
613
614     /**
615      * @cfg {Boolean} autoWidth @hide
616      */
617     /**
618      * @cfg {Boolean} autoHeight @hide
619      */
620
621     /**
622      * @cfg {String} autoEl @hide
623      */
624 });
625
626
627 Ext.form.MessageTargets = {
628     'qtip' : {
629         mark: function(field, msg){
630             field.el.addClass(field.invalidClass);
631             field.el.dom.qtip = msg;
632             field.el.dom.qclass = 'x-form-invalid-tip';
633             if(Ext.QuickTips){ // fix for floating editors interacting with DND
634                 Ext.QuickTips.enable();
635             }
636         },
637         clear: function(field){
638             field.el.removeClass(field.invalidClass);
639             field.el.dom.qtip = '';
640         }
641     },
642     'title' : {
643         mark: function(field, msg){
644             field.el.addClass(field.invalidClass);
645             field.el.dom.title = msg;
646         },
647         clear: function(field){
648             field.el.dom.title = '';
649         }
650     },
651     'under' : {
652         mark: function(field, msg){
653             field.el.addClass(field.invalidClass);
654             if(!field.errorEl){
655                 var elp = field.getErrorCt();
656                 if(!elp){ // field has no container el
657                     field.el.dom.title = msg;
658                     return;
659                 }
660                 field.errorEl = elp.createChild({cls:'x-form-invalid-msg'});
661                 field.on('resize', field.alignErrorEl, field);
662                 field.on('destroy', function(){
663                     Ext.destroy(this.errorEl);
664                 }, field);
665             }
666             field.alignErrorEl();
667             field.errorEl.update(msg);
668             Ext.form.Field.msgFx[field.msgFx].show(field.errorEl, field);
669         },
670         clear: function(field){
671             field.el.removeClass(field.invalidClass);
672             if(field.errorEl){
673                 Ext.form.Field.msgFx[field.msgFx].hide(field.errorEl, field);
674             }else{
675                 field.el.dom.title = '';
676             }
677         }
678     },
679     'side' : {
680         mark: function(field, msg){
681             field.el.addClass(field.invalidClass);
682             if(!field.errorIcon){
683                 var elp = field.getErrorCt();
684                 // field has no container el
685                 if(!elp){
686                     field.el.dom.title = msg;
687                     return;
688                 }
689                 field.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
690                 if (field.ownerCt) {
691                     field.ownerCt.on('afterlayout', field.alignErrorIcon, field);
692                     field.ownerCt.on('expand', field.alignErrorIcon, field);
693                 }
694                 field.on('resize', field.alignErrorIcon, field);
695                 field.on('destroy', function(){
696                     Ext.destroy(this.errorIcon);
697                 }, field);
698             }
699             field.alignErrorIcon();
700             field.errorIcon.dom.qtip = msg;
701             field.errorIcon.dom.qclass = 'x-form-invalid-tip';
702             field.errorIcon.show();
703         },
704         clear: function(field){
705             field.el.removeClass(field.invalidClass);
706             if(field.errorIcon){
707                 field.errorIcon.dom.qtip = '';
708                 field.errorIcon.hide();
709             }else{
710                 field.el.dom.title = '';
711             }
712         }
713     }
714 };
715
716 // anything other than normal should be considered experimental
717 Ext.form.Field.msgFx = {
718     normal : {
719         show: function(msgEl, f){
720             msgEl.setDisplayed('block');
721         },
722
723         hide : function(msgEl, f){
724             msgEl.setDisplayed(false).update('');
725         }
726     },
727
728     slide : {
729         show: function(msgEl, f){
730             msgEl.slideIn('t', {stopFx:true});
731         },
732
733         hide : function(msgEl, f){
734             msgEl.slideOut('t', {stopFx:true,useDisplay:true});
735         }
736     },
737
738     slideRight : {
739         show: function(msgEl, f){
740             msgEl.fixDisplay();
741             msgEl.alignTo(f.el, 'tl-tr');
742             msgEl.slideIn('l', {stopFx:true});
743         },
744
745         hide : function(msgEl, f){
746             msgEl.slideOut('l', {stopFx:true,useDisplay:true});
747         }
748     }
749 };
750 Ext.reg('field', Ext.form.Field);
751 /**
752  * @class Ext.form.TextField
753  * @extends Ext.form.Field
754  * <p>Basic text field.  Can be used as a direct replacement for traditional text inputs,
755  * or as the base class for more sophisticated input controls (like {@link Ext.form.TextArea}
756  * and {@link Ext.form.ComboBox}).</p>
757  * <p><b><u>Validation</u></b></p>
758  * <p>The validation procedure is described in the documentation for {@link #validateValue}.</p>
759  * <p><b><u>Alter Validation Behavior</u></b></p>
760  * <p>Validation behavior for each field can be configured:</p>
761  * <div class="mdetail-params"><ul>
762  * <li><code>{@link Ext.form.TextField#invalidText invalidText}</code> : the default validation message to
763  * show if any validation step above does not provide a message when invalid</li>
764  * <li><code>{@link Ext.form.TextField#maskRe maskRe}</code> : filter out keystrokes before any validation occurs</li>
765  * <li><code>{@link Ext.form.TextField#stripCharsRe stripCharsRe}</code> : filter characters after being typed in,
766  * but before being validated</li>
767  * <li><code>{@link Ext.form.Field#invalidClass invalidClass}</code> : alternate style when invalid</li>
768  * <li><code>{@link Ext.form.Field#validateOnBlur validateOnBlur}</code>,
769  * <code>{@link Ext.form.Field#validationDelay validationDelay}</code>, and
770  * <code>{@link Ext.form.Field#validationEvent validationEvent}</code> : modify how/when validation is triggered</li>
771  * </ul></div>
772  * 
773  * @constructor Creates a new TextField
774  * @param {Object} config Configuration options
775  * 
776  * @xtype textfield
777  */
778 Ext.form.TextField = Ext.extend(Ext.form.Field,  {
779     /**
780      * @cfg {String} vtypeText A custom error message to display in place of the default message provided
781      * for the <b><code>{@link #vtype}</code></b> currently set for this field (defaults to <tt>''</tt>).  <b>Note</b>:
782      * only applies if <b><code>{@link #vtype}</code></b> is set, else ignored.
783      */
784     /**
785      * @cfg {RegExp} stripCharsRe A JavaScript RegExp object used to strip unwanted content from the value
786      * before validation (defaults to <tt>null</tt>).
787      */
788     /**
789      * @cfg {Boolean} grow <tt>true</tt> if this field should automatically grow and shrink to its content
790      * (defaults to <tt>false</tt>)
791      */
792     grow : false,
793     /**
794      * @cfg {Number} growMin The minimum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
795      * to <tt>30</tt>)
796      */
797     growMin : 30,
798     /**
799      * @cfg {Number} growMax The maximum width to allow when <code><b>{@link #grow}</b> = true</code> (defaults
800      * to <tt>800</tt>)
801      */
802     growMax : 800,
803     /**
804      * @cfg {String} vtype A validation type name as defined in {@link Ext.form.VTypes} (defaults to <tt>null</tt>)
805      */
806     vtype : null,
807     /**
808      * @cfg {RegExp} maskRe An input mask regular expression that will be used to filter keystrokes that do
809      * not match (defaults to <tt>null</tt>)
810      */
811     maskRe : null,
812     /**
813      * @cfg {Boolean} disableKeyFilter Specify <tt>true</tt> to disable input keystroke filtering (defaults
814      * to <tt>false</tt>)
815      */
816     disableKeyFilter : false,
817     /**
818      * @cfg {Boolean} allowBlank Specify <tt>false</tt> to validate that the value's length is > 0 (defaults to
819      * <tt>true</tt>)
820      */
821     allowBlank : true,
822     /**
823      * @cfg {Number} minLength Minimum input field length required (defaults to <tt>0</tt>)
824      */
825     minLength : 0,
826     /**
827      * @cfg {Number} maxLength Maximum input field length allowed by validation (defaults to Number.MAX_VALUE).
828      * This behavior is intended to provide instant feedback to the user by improving usability to allow pasting
829      * and editing or overtyping and back tracking. To restrict the maximum number of characters that can be
830      * entered into the field use <tt><b>{@link Ext.form.Field#autoCreate autoCreate}</b></tt> to add
831      * any attributes you want to a field, for example:<pre><code>
832 var myField = new Ext.form.NumberField({
833     id: 'mobile',
834     anchor:'90%',
835     fieldLabel: 'Mobile',
836     maxLength: 16, // for validation
837     autoCreate: {tag: 'input', type: 'text', size: '20', autocomplete: 'off', maxlength: '10'}
838 });
839 </code></pre>
840      */
841     maxLength : Number.MAX_VALUE,
842     /**
843      * @cfg {String} minLengthText Error text to display if the <b><tt>{@link #minLength minimum length}</tt></b>
844      * validation fails (defaults to <tt>'The minimum length for this field is {minLength}'</tt>)
845      */
846     minLengthText : 'The minimum length for this field is {0}',
847     /**
848      * @cfg {String} maxLengthText Error text to display if the <b><tt>{@link #maxLength maximum length}</tt></b>
849      * validation fails (defaults to <tt>'The maximum length for this field is {maxLength}'</tt>)
850      */
851     maxLengthText : 'The maximum length for this field is {0}',
852     /**
853      * @cfg {Boolean} selectOnFocus <tt>true</tt> to automatically select any existing field text when the field
854      * receives input focus (defaults to <tt>false</tt>)
855      */
856     selectOnFocus : false,
857     /**
858      * @cfg {String} blankText The error text to display if the <b><tt>{@link #allowBlank}</tt></b> validation
859      * fails (defaults to <tt>'This field is required'</tt>)
860      */
861     blankText : 'This field is required',
862     /**
863      * @cfg {Function} validator
864      * <p>A custom validation function to be called during field validation ({@link #validateValue})
865      * (defaults to <tt>null</tt>). If specified, this function will be called first, allowing the
866      * developer to override the default validation process.</p>
867      * <br><p>This function will be passed the following Parameters:</p>
868      * <div class="mdetail-params"><ul>
869      * <li><code>value</code>: <i>Mixed</i>
870      * <div class="sub-desc">The current field value</div></li>
871      * </ul></div>
872      * <br><p>This function is to Return:</p>
873      * <div class="mdetail-params"><ul>
874      * <li><code>true</code>: <i>Boolean</i>
875      * <div class="sub-desc"><code>true</code> if the value is valid</div></li>
876      * <li><code>msg</code>: <i>String</i>
877      * <div class="sub-desc">An error message if the value is invalid</div></li>
878      * </ul></div>
879      */
880     validator : null,
881     /**
882      * @cfg {RegExp} regex A JavaScript RegExp object to be tested against the field value during validation
883      * (defaults to <tt>null</tt>). If the test fails, the field will be marked invalid using
884      * <b><tt>{@link #regexText}</tt></b>.
885      */
886     regex : null,
887     /**
888      * @cfg {String} regexText The error text to display if <b><tt>{@link #regex}</tt></b> is used and the
889      * test fails during validation (defaults to <tt>''</tt>)
890      */
891     regexText : '',
892     /**
893      * @cfg {String} emptyText The default text to place into an empty field (defaults to <tt>null</tt>).
894      * <b>Note</b>: that this value will be submitted to the server if this field is enabled and configured
895      * with a {@link #name}.
896      */
897     emptyText : null,
898     /**
899      * @cfg {String} emptyClass The CSS class to apply to an empty field to style the <b><tt>{@link #emptyText}</tt></b>
900      * (defaults to <tt>'x-form-empty-field'</tt>).  This class is automatically added and removed as needed
901      * depending on the current field value.
902      */
903     emptyClass : 'x-form-empty-field',
904
905     /**
906      * @cfg {Boolean} enableKeyEvents <tt>true</tt> to enable the proxying of key events for the HTML input
907      * field (defaults to <tt>false</tt>)
908      */
909
910     initComponent : function(){
911         Ext.form.TextField.superclass.initComponent.call(this);
912         this.addEvents(
913             /**
914              * @event autosize
915              * Fires when the <tt><b>{@link #autoSize}</b></tt> function is triggered. The field may or
916              * may not have actually changed size according to the default logic, but this event provides
917              * a hook for the developer to apply additional logic at runtime to resize the field if needed.
918              * @param {Ext.form.Field} this This text field
919              * @param {Number} width The new field width
920              */
921             'autosize',
922
923             /**
924              * @event keydown
925              * Keydown input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
926              * is set to true.
927              * @param {Ext.form.TextField} this This text field
928              * @param {Ext.EventObject} e
929              */
930             'keydown',
931             /**
932              * @event keyup
933              * Keyup input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
934              * is set to true.
935              * @param {Ext.form.TextField} this This text field
936              * @param {Ext.EventObject} e
937              */
938             'keyup',
939             /**
940              * @event keypress
941              * Keypress input field event. This event only fires if <tt><b>{@link #enableKeyEvents}</b></tt>
942              * is set to true.
943              * @param {Ext.form.TextField} this This text field
944              * @param {Ext.EventObject} e
945              */
946             'keypress'
947         );
948     },
949
950     // private
951     initEvents : function(){
952         Ext.form.TextField.superclass.initEvents.call(this);
953         if(this.validationEvent == 'keyup'){
954             this.validationTask = new Ext.util.DelayedTask(this.validate, this);
955             this.mon(this.el, 'keyup', this.filterValidation, this);
956         }
957         else if(this.validationEvent !== false && this.validationEvent != 'blur'){
958                 this.mon(this.el, this.validationEvent, this.validate, this, {buffer: this.validationDelay});
959         }
960         if(this.selectOnFocus || this.emptyText){            
961             this.mon(this.el, 'mousedown', this.onMouseDown, this);
962             
963             if(this.emptyText){
964                 this.applyEmptyText();
965             }
966         }
967         if(this.maskRe || (this.vtype && this.disableKeyFilter !== true && (this.maskRe = Ext.form.VTypes[this.vtype+'Mask']))){
968                 this.mon(this.el, 'keypress', this.filterKeys, this);
969         }
970         if(this.grow){
971                 this.mon(this.el, 'keyup', this.onKeyUpBuffered, this, {buffer: 50});
972                         this.mon(this.el, 'click', this.autoSize, this);
973         }
974         if(this.enableKeyEvents){
975             this.mon(this.el, {
976                 scope: this,
977                 keyup: this.onKeyUp,
978                 keydown: this.onKeyDown,
979                 keypress: this.onKeyPress
980             });
981         }
982     },
983     
984     onMouseDown: function(e){
985         if(!this.hasFocus){
986             this.mon(this.el, 'mouseup', Ext.emptyFn, this, { single: true, preventDefault: true });
987         }
988     },
989
990     processValue : function(value){
991         if(this.stripCharsRe){
992             var newValue = value.replace(this.stripCharsRe, '');
993             if(newValue !== value){
994                 this.setRawValue(newValue);
995                 return newValue;
996             }
997         }
998         return value;
999     },
1000
1001     filterValidation : function(e){
1002         if(!e.isNavKeyPress()){
1003             this.validationTask.delay(this.validationDelay);
1004         }
1005     },
1006     
1007     //private
1008     onDisable: function(){
1009         Ext.form.TextField.superclass.onDisable.call(this);
1010         if(Ext.isIE){
1011             this.el.dom.unselectable = 'on';
1012         }
1013     },
1014     
1015     //private
1016     onEnable: function(){
1017         Ext.form.TextField.superclass.onEnable.call(this);
1018         if(Ext.isIE){
1019             this.el.dom.unselectable = '';
1020         }
1021     },
1022
1023     // private
1024     onKeyUpBuffered : function(e){
1025         if(this.doAutoSize(e)){
1026             this.autoSize();
1027         }
1028     },
1029     
1030     // private
1031     doAutoSize : function(e){
1032         return !e.isNavKeyPress();
1033     },
1034
1035     // private
1036     onKeyUp : function(e){
1037         this.fireEvent('keyup', this, e);
1038     },
1039
1040     // private
1041     onKeyDown : function(e){
1042         this.fireEvent('keydown', this, e);
1043     },
1044
1045     // private
1046     onKeyPress : function(e){
1047         this.fireEvent('keypress', this, e);
1048     },
1049
1050     /**
1051      * Resets the current field value to the originally-loaded value and clears any validation messages.
1052      * Also adds <tt><b>{@link #emptyText}</b></tt> and <tt><b>{@link #emptyClass}</b></tt> if the
1053      * original value was blank.
1054      */
1055     reset : function(){
1056         Ext.form.TextField.superclass.reset.call(this);
1057         this.applyEmptyText();
1058     },
1059
1060     applyEmptyText : function(){
1061         if(this.rendered && this.emptyText && this.getRawValue().length < 1 && !this.hasFocus){
1062             this.setRawValue(this.emptyText);
1063             this.el.addClass(this.emptyClass);
1064         }
1065     },
1066
1067     // private
1068     preFocus : function(){
1069         var el = this.el,
1070             isEmpty;
1071         if(this.emptyText){
1072             if(el.dom.value == this.emptyText){
1073                 this.setRawValue('');
1074                 isEmpty = true;
1075             }
1076             el.removeClass(this.emptyClass);
1077         }
1078         if(this.selectOnFocus || isEmpty){
1079             el.dom.select();
1080         }
1081     },
1082
1083     // private
1084     postBlur : function(){
1085         this.applyEmptyText();
1086     },
1087
1088     // private
1089     filterKeys : function(e){
1090         if(e.ctrlKey){
1091             return;
1092         }
1093         var k = e.getKey();
1094         if(Ext.isGecko && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
1095             return;
1096         }
1097         var cc = String.fromCharCode(e.getCharCode());
1098         if(!Ext.isGecko && e.isSpecialKey() && !cc){
1099             return;
1100         }
1101         if(!this.maskRe.test(cc)){
1102             e.stopEvent();
1103         }
1104     },
1105
1106     setValue : function(v){
1107         if(this.emptyText && this.el && !Ext.isEmpty(v)){
1108             this.el.removeClass(this.emptyClass);
1109         }
1110         Ext.form.TextField.superclass.setValue.apply(this, arguments);
1111         this.applyEmptyText();
1112         this.autoSize();
1113         return this;
1114     },
1115
1116     /**
1117      * <p>Validates a value according to the field's validation rules and returns an array of errors
1118      * for any failing validations. Validation rules are processed in the following order:</p>
1119      * <div class="mdetail-params"><ul>
1120      * 
1121      * <li><b>1. Field specific validator</b>
1122      * <div class="sub-desc">
1123      * <p>A validator offers a way to customize and reuse a validation specification.
1124      * If a field is configured with a <code>{@link #validator}</code>
1125      * function, it will be passed the current field value.  The <code>{@link #validator}</code>
1126      * function is expected to return either:
1127      * <div class="mdetail-params"><ul>
1128      * <li>Boolean <tt>true</tt> if the value is valid (validation continues).</li>
1129      * <li>a String to represent the invalid message if invalid (validation halts).</li>
1130      * </ul></div>
1131      * </div></li>
1132      * 
1133      * <li><b>2. Basic Validation</b>
1134      * <div class="sub-desc">
1135      * <p>If the <code>{@link #validator}</code> has not halted validation,
1136      * basic validation proceeds as follows:</p>
1137      * 
1138      * <div class="mdetail-params"><ul>
1139      * 
1140      * <li><code>{@link #allowBlank}</code> : (Invalid message =
1141      * <code>{@link #emptyText}</code>)<div class="sub-desc">
1142      * Depending on the configuration of <code>{@link #allowBlank}</code>, a
1143      * blank field will cause validation to halt at this step and return
1144      * Boolean true or false accordingly.  
1145      * </div></li>
1146      * 
1147      * <li><code>{@link #minLength}</code> : (Invalid message =
1148      * <code>{@link #minLengthText}</code>)<div class="sub-desc">
1149      * If the passed value does not satisfy the <code>{@link #minLength}</code>
1150      * specified, validation halts.
1151      * </div></li>
1152      * 
1153      * <li><code>{@link #maxLength}</code> : (Invalid message =
1154      * <code>{@link #maxLengthText}</code>)<div class="sub-desc">
1155      * If the passed value does not satisfy the <code>{@link #maxLength}</code>
1156      * specified, validation halts.
1157      * </div></li>
1158      * 
1159      * </ul></div>
1160      * </div></li>
1161      * 
1162      * <li><b>3. Preconfigured Validation Types (VTypes)</b>
1163      * <div class="sub-desc">
1164      * <p>If none of the prior validation steps halts validation, a field
1165      * configured with a <code>{@link #vtype}</code> will utilize the
1166      * corresponding {@link Ext.form.VTypes VTypes} validation function.
1167      * If invalid, either the field's <code>{@link #vtypeText}</code> or
1168      * the VTypes vtype Text property will be used for the invalid message.
1169      * Keystrokes on the field will be filtered according to the VTypes
1170      * vtype Mask property.</p>
1171      * </div></li>
1172      * 
1173      * <li><b>4. Field specific regex test</b>
1174      * <div class="sub-desc">
1175      * <p>If none of the prior validation steps halts validation, a field's
1176      * configured <code>{@link #regex}</code> test will be processed.
1177      * The invalid message for this test is configured with
1178      * <code>{@link #regexText}</code>.</p>
1179      * </div></li>
1180      * 
1181      * @param {Mixed} value The value to validate. The processed raw value will be used if nothing is passed
1182      * @return {Array} Array of any validation errors
1183      */
1184     getErrors: function(value) {
1185         var errors = Ext.form.TextField.superclass.getErrors.apply(this, arguments);
1186         
1187         value = Ext.isDefined(value) ? value : this.processValue(this.getRawValue());        
1188         
1189         if (Ext.isFunction(this.validator)) {
1190             var msg = this.validator(value);
1191             if (msg !== true) {
1192                 errors.push(msg);
1193             }
1194         }
1195         
1196         if (value.length < 1 || value === this.emptyText) {
1197             if (this.allowBlank) {
1198                 //if value is blank and allowBlank is true, there cannot be any additional errors
1199                 return errors;
1200             } else {
1201                 errors.push(this.blankText);
1202             }
1203         }
1204         
1205         if (!this.allowBlank && (value.length < 1 || value === this.emptyText)) { // if it's blank
1206             errors.push(this.blankText);
1207         }
1208         
1209         if (value.length < this.minLength) {
1210             errors.push(String.format(this.minLengthText, this.minLength));
1211         }
1212         
1213         if (value.length > this.maxLength) {
1214             errors.push(String.format(this.maxLengthText, this.maxLength));
1215         }
1216         
1217         if (this.vtype) {
1218             var vt = Ext.form.VTypes;
1219             if(!vt[this.vtype](value, this)){
1220                 errors.push(this.vtypeText || vt[this.vtype +'Text']);
1221             }
1222         }
1223         
1224         if (this.regex && !this.regex.test(value)) {
1225             errors.push(this.regexText);
1226         }
1227         
1228         return errors;
1229     },
1230
1231     /**
1232      * Selects text in this field
1233      * @param {Number} start (optional) The index where the selection should start (defaults to 0)
1234      * @param {Number} end (optional) The index where the selection should end (defaults to the text length)
1235      */
1236     selectText : function(start, end){
1237         var v = this.getRawValue();
1238         var doFocus = false;
1239         if(v.length > 0){
1240             start = start === undefined ? 0 : start;
1241             end = end === undefined ? v.length : end;
1242             var d = this.el.dom;
1243             if(d.setSelectionRange){
1244                 d.setSelectionRange(start, end);
1245             }else if(d.createTextRange){
1246                 var range = d.createTextRange();
1247                 range.moveStart('character', start);
1248                 range.moveEnd('character', end-v.length);
1249                 range.select();
1250             }
1251             doFocus = Ext.isGecko || Ext.isOpera;
1252         }else{
1253             doFocus = true;
1254         }
1255         if(doFocus){
1256             this.focus();
1257         }
1258     },
1259
1260     /**
1261      * Automatically grows the field to accomodate the width of the text up to the maximum field width allowed.
1262      * This only takes effect if <tt><b>{@link #grow}</b> = true</tt>, and fires the {@link #autosize} event.
1263      */
1264     autoSize : function(){
1265         if(!this.grow || !this.rendered){
1266             return;
1267         }
1268         if(!this.metrics){
1269             this.metrics = Ext.util.TextMetrics.createInstance(this.el);
1270         }
1271         var el = this.el;
1272         var v = el.dom.value;
1273         var d = document.createElement('div');
1274         d.appendChild(document.createTextNode(v));
1275         v = d.innerHTML;
1276         Ext.removeNode(d);
1277         d = null;
1278         v += '&#160;';
1279         var w = Math.min(this.growMax, Math.max(this.metrics.getWidth(v) + /* add extra padding */ 10, this.growMin));
1280         this.el.setWidth(w);
1281         this.fireEvent('autosize', this, w);
1282     },
1283         
1284         onDestroy: function(){
1285                 if(this.validationTask){
1286                         this.validationTask.cancel();
1287                         this.validationTask = null;
1288                 }
1289                 Ext.form.TextField.superclass.onDestroy.call(this);
1290         }
1291 });
1292 Ext.reg('textfield', Ext.form.TextField);
1293 /**
1294  * @class Ext.form.TriggerField
1295  * @extends Ext.form.TextField
1296  * Provides a convenient wrapper for TextFields that adds a clickable trigger button (looks like a combobox by default).
1297  * The trigger has no default action, so you must assign a function to implement the trigger click handler by
1298  * overriding {@link #onTriggerClick}. You can create a TriggerField directly, as it renders exactly like a combobox
1299  * for which you can provide a custom implementation.  For example:
1300  * <pre><code>
1301 var trigger = new Ext.form.TriggerField();
1302 trigger.onTriggerClick = myTriggerFn;
1303 trigger.applyToMarkup('my-field');
1304 </code></pre>
1305  *
1306  * However, in general you will most likely want to use TriggerField as the base class for a reusable component.
1307  * {@link Ext.form.DateField} and {@link Ext.form.ComboBox} are perfect examples of this.
1308  *
1309  * @constructor
1310  * Create a new TriggerField.
1311  * @param {Object} config Configuration options (valid {@Ext.form.TextField} config options will also be applied
1312  * to the base TextField)
1313  * @xtype trigger
1314  */
1315 Ext.form.TriggerField = Ext.extend(Ext.form.TextField,  {
1316     /**
1317      * @cfg {String} triggerClass
1318      * An additional CSS class used to style the trigger button.  The trigger will always get the
1319      * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
1320      */
1321     /**
1322      * @cfg {Mixed} triggerConfig
1323      * <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the
1324      * trigger element for this Field. (Optional).</p>
1325      * <p>Specify this when you need a customized element to act as the trigger button for a TriggerField.</p>
1326      * <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing, positioning
1327      * and appearance of the trigger.  Defaults to:</p>
1328      * <pre><code>{tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.triggerClass}</code></pre>
1329      */
1330     /**
1331      * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
1332      * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
1333      * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:</p>
1334      * <pre><code>{tag: "input", type: "text", size: "16", autocomplete: "off"}</code></pre>
1335      */
1336     defaultAutoCreate : {tag: "input", type: "text", size: "16", autocomplete: "off"},
1337     /**
1338      * @cfg {Boolean} hideTrigger <tt>true</tt> to hide the trigger element and display only the base
1339      * text field (defaults to <tt>false</tt>)
1340      */
1341     hideTrigger:false,
1342     /**
1343      * @cfg {Boolean} editable <tt>false</tt> to prevent the user from typing text directly into the field,
1344      * the field will only respond to a click on the trigger to set the value. (defaults to <tt>true</tt>).
1345      */
1346     editable: true,
1347     /**
1348      * @cfg {Boolean} readOnly <tt>true</tt> to prevent the user from changing the field, and
1349      * hides the trigger.  Superceeds the editable and hideTrigger options if the value is true.
1350      * (defaults to <tt>false</tt>)
1351      */
1352     readOnly: false,
1353     /**
1354      * @cfg {String} wrapFocusClass The class added to the to the wrap of the trigger element. Defaults to
1355      * <tt>x-trigger-wrap-focus</tt>.
1356      */
1357     wrapFocusClass: 'x-trigger-wrap-focus',
1358     /**
1359      * @hide
1360      * @method autoSize
1361      */
1362     autoSize: Ext.emptyFn,
1363     // private
1364     monitorTab : true,
1365     // private
1366     deferHeight : true,
1367     // private
1368     mimicing : false,
1369
1370     actionMode: 'wrap',
1371
1372     defaultTriggerWidth: 17,
1373
1374     // private
1375     onResize : function(w, h){
1376         Ext.form.TriggerField.superclass.onResize.call(this, w, h);
1377         var tw = this.getTriggerWidth();
1378         if(Ext.isNumber(w)){
1379             this.el.setWidth(w - tw);
1380         }
1381         this.wrap.setWidth(this.el.getWidth() + tw);
1382     },
1383
1384     getTriggerWidth: function(){
1385         var tw = this.trigger.getWidth();
1386         if(!this.hideTrigger && !this.readOnly && tw === 0){
1387             tw = this.defaultTriggerWidth;
1388         }
1389         return tw;
1390     },
1391
1392     // private
1393     alignErrorIcon : function(){
1394         if(this.wrap){
1395             this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
1396         }
1397     },
1398
1399     // private
1400     onRender : function(ct, position){
1401         this.doc = Ext.isIE ? Ext.getBody() : Ext.getDoc();
1402         Ext.form.TriggerField.superclass.onRender.call(this, ct, position);
1403
1404         this.wrap = this.el.wrap({cls: 'x-form-field-wrap x-form-field-trigger-wrap'});
1405         this.trigger = this.wrap.createChild(this.triggerConfig ||
1406                 {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.triggerClass});
1407         this.initTrigger();
1408         if(!this.width){
1409             this.wrap.setWidth(this.el.getWidth()+this.trigger.getWidth());
1410         }
1411         this.resizeEl = this.positionEl = this.wrap;
1412     },
1413
1414     getWidth: function() {
1415         return(this.el.getWidth() + this.trigger.getWidth());
1416     },
1417
1418     updateEditState: function(){
1419         if(this.rendered){
1420             if (this.readOnly) {
1421                 this.el.dom.readOnly = true;
1422                 this.el.addClass('x-trigger-noedit');
1423                 this.mun(this.el, 'click', this.onTriggerClick, this);
1424                 this.trigger.setDisplayed(false);
1425             } else {
1426                 if (!this.editable) {
1427                     this.el.dom.readOnly = true;
1428                     this.el.addClass('x-trigger-noedit');
1429                     this.mon(this.el, 'click', this.onTriggerClick, this);
1430                 } else {
1431                     this.el.dom.readOnly = false;
1432                     this.el.removeClass('x-trigger-noedit');
1433                     this.mun(this.el, 'click', this.onTriggerClick, this);
1434                 }
1435                 this.trigger.setDisplayed(!this.hideTrigger);
1436             }
1437             this.onResize(this.width || this.wrap.getWidth());
1438         }
1439     },
1440
1441     /**
1442      * Changes the hidden status of the trigger.
1443      * @param {Boolean} hideTrigger True to hide the trigger, false to show it.
1444      */
1445     setHideTrigger: function(hideTrigger){
1446         if(hideTrigger != this.hideTrigger){
1447             this.hideTrigger = hideTrigger;
1448             this.updateEditState();
1449         }
1450     },
1451
1452     /**
1453      * Allow or prevent the user from directly editing the field text.  If false is passed,
1454      * the user will only be able to modify the field using the trigger.  Will also add
1455      * a click event to the text field which will call the trigger. This method
1456      * is the runtime equivalent of setting the {@link #editable} config option at config time.
1457      * @param {Boolean} value True to allow the user to directly edit the field text.
1458      */
1459     setEditable: function(editable){
1460         if(editable != this.editable){
1461             this.editable = editable;
1462             this.updateEditState();
1463         }
1464     },
1465
1466     /**
1467      * Setting this to true will supersede settings {@link #editable} and {@link #hideTrigger}.
1468      * Setting this to false will defer back to {@link #editable} and {@link #hideTrigger}. This method
1469      * is the runtime equivalent of setting the {@link #readOnly} config option at config time.
1470      * @param {Boolean} value True to prevent the user changing the field and explicitly
1471      * hide the trigger.
1472      */
1473     setReadOnly: function(readOnly){
1474         if(readOnly != this.readOnly){
1475             this.readOnly = readOnly;
1476             this.updateEditState();
1477         }
1478     },
1479
1480     afterRender : function(){
1481         Ext.form.TriggerField.superclass.afterRender.call(this);
1482         this.updateEditState();
1483     },
1484
1485     // private
1486     initTrigger : function(){
1487         this.mon(this.trigger, 'click', this.onTriggerClick, this, {preventDefault:true});
1488         this.trigger.addClassOnOver('x-form-trigger-over');
1489         this.trigger.addClassOnClick('x-form-trigger-click');
1490     },
1491
1492     // private
1493     onDestroy : function(){
1494         Ext.destroy(this.trigger, this.wrap);
1495         if (this.mimicing){
1496             this.doc.un('mousedown', this.mimicBlur, this);
1497         }
1498         delete this.doc;
1499         Ext.form.TriggerField.superclass.onDestroy.call(this);
1500     },
1501
1502     // private
1503     onFocus : function(){
1504         Ext.form.TriggerField.superclass.onFocus.call(this);
1505         if(!this.mimicing){
1506             this.wrap.addClass(this.wrapFocusClass);
1507             this.mimicing = true;
1508             this.doc.on('mousedown', this.mimicBlur, this, {delay: 10});
1509             if(this.monitorTab){
1510                 this.on('specialkey', this.checkTab, this);
1511             }
1512         }
1513     },
1514
1515     // private
1516     checkTab : function(me, e){
1517         if(e.getKey() == e.TAB){
1518             this.triggerBlur();
1519         }
1520     },
1521
1522     // private
1523     onBlur : Ext.emptyFn,
1524
1525     // private
1526     mimicBlur : function(e){
1527         if(!this.isDestroyed && !this.wrap.contains(e.target) && this.validateBlur(e)){
1528             this.triggerBlur();
1529         }
1530     },
1531
1532     // private
1533     triggerBlur : function(){
1534         this.mimicing = false;
1535         this.doc.un('mousedown', this.mimicBlur, this);
1536         if(this.monitorTab && this.el){
1537             this.un('specialkey', this.checkTab, this);
1538         }
1539         Ext.form.TriggerField.superclass.onBlur.call(this);
1540         if(this.wrap){
1541             this.wrap.removeClass(this.wrapFocusClass);
1542         }
1543     },
1544
1545     beforeBlur : Ext.emptyFn,
1546
1547     // private
1548     // This should be overriden by any subclass that needs to check whether or not the field can be blurred.
1549     validateBlur : function(e){
1550         return true;
1551     },
1552
1553     /**
1554      * The function that should handle the trigger's click event.  This method does nothing by default
1555      * until overridden by an implementing function.  See Ext.form.ComboBox and Ext.form.DateField for
1556      * sample implementations.
1557      * @method
1558      * @param {EventObject} e
1559      */
1560     onTriggerClick : Ext.emptyFn
1561
1562     /**
1563      * @cfg {Boolean} grow @hide
1564      */
1565     /**
1566      * @cfg {Number} growMin @hide
1567      */
1568     /**
1569      * @cfg {Number} growMax @hide
1570      */
1571 });
1572
1573 /**
1574  * @class Ext.form.TwinTriggerField
1575  * @extends Ext.form.TriggerField
1576  * TwinTriggerField is not a public class to be used directly.  It is meant as an abstract base class
1577  * to be extended by an implementing class.  For an example of implementing this class, see the custom
1578  * SearchField implementation here:
1579  * <a href="http://extjs.com/deploy/ext/examples/form/custom.html">http://extjs.com/deploy/ext/examples/form/custom.html</a>
1580  */
1581 Ext.form.TwinTriggerField = Ext.extend(Ext.form.TriggerField, {
1582     /**
1583      * @cfg {Mixed} triggerConfig
1584      * <p>A {@link Ext.DomHelper DomHelper} config object specifying the structure of the trigger elements
1585      * for this Field. (Optional).</p>
1586      * <p>Specify this when you need a customized element to contain the two trigger elements for this Field.
1587      * Each trigger element must be marked by the CSS class <tt>x-form-trigger</tt> (also see
1588      * <tt>{@link #trigger1Class}</tt> and <tt>{@link #trigger2Class}</tt>).</p>
1589      * <p>Note that when using this option, it is the developer's responsibility to ensure correct sizing,
1590      * positioning and appearance of the triggers.</p>
1591      */
1592     /**
1593      * @cfg {String} trigger1Class
1594      * An additional CSS class used to style the trigger button.  The trigger will always get the
1595      * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
1596      */
1597     /**
1598      * @cfg {String} trigger2Class
1599      * An additional CSS class used to style the trigger button.  The trigger will always get the
1600      * class <tt>'x-form-trigger'</tt> by default and <tt>triggerClass</tt> will be <b>appended</b> if specified.
1601      */
1602
1603     initComponent : function(){
1604         Ext.form.TwinTriggerField.superclass.initComponent.call(this);
1605
1606         this.triggerConfig = {
1607             tag:'span', cls:'x-form-twin-triggers', cn:[
1608             {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.trigger1Class},
1609             {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.trigger2Class}
1610         ]};
1611     },
1612
1613     getTrigger : function(index){
1614         return this.triggers[index];
1615     },
1616     
1617     afterRender: function(){
1618         Ext.form.TwinTriggerField.superclass.afterRender.call(this);
1619         var triggers = this.triggers,
1620             i = 0,
1621             len = triggers.length;
1622             
1623         for(; i < len; ++i){
1624             if(this['hideTrigger' + (i + 1)]){
1625                     triggers[i].hide();
1626                 }
1627
1628         }    
1629     },
1630
1631     initTrigger : function(){
1632         var ts = this.trigger.select('.x-form-trigger', true),
1633             triggerField = this;
1634             
1635         ts.each(function(t, all, index){
1636             var triggerIndex = 'Trigger'+(index+1);
1637             t.hide = function(){
1638                 var w = triggerField.wrap.getWidth();
1639                 this.dom.style.display = 'none';
1640                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
1641                 triggerField['hidden' + triggerIndex] = true;
1642             };
1643             t.show = function(){
1644                 var w = triggerField.wrap.getWidth();
1645                 this.dom.style.display = '';
1646                 triggerField.el.setWidth(w-triggerField.trigger.getWidth());
1647                 triggerField['hidden' + triggerIndex] = false;
1648             };
1649             this.mon(t, 'click', this['on'+triggerIndex+'Click'], this, {preventDefault:true});
1650             t.addClassOnOver('x-form-trigger-over');
1651             t.addClassOnClick('x-form-trigger-click');
1652         }, this);
1653         this.triggers = ts.elements;
1654     },
1655
1656     getTriggerWidth: function(){
1657         var tw = 0;
1658         Ext.each(this.triggers, function(t, index){
1659             var triggerIndex = 'Trigger' + (index + 1),
1660                 w = t.getWidth();
1661             if(w === 0 && !this['hidden' + triggerIndex]){
1662                 tw += this.defaultTriggerWidth;
1663             }else{
1664                 tw += w;
1665             }
1666         }, this);
1667         return tw;
1668     },
1669
1670     // private
1671     onDestroy : function() {
1672         Ext.destroy(this.triggers);
1673         Ext.form.TwinTriggerField.superclass.onDestroy.call(this);
1674     },
1675
1676     /**
1677      * The function that should handle the trigger's click event.  This method does nothing by default
1678      * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
1679      * for additional information.
1680      * @method
1681      * @param {EventObject} e
1682      */
1683     onTrigger1Click : Ext.emptyFn,
1684     /**
1685      * The function that should handle the trigger's click event.  This method does nothing by default
1686      * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
1687      * for additional information.
1688      * @method
1689      * @param {EventObject} e
1690      */
1691     onTrigger2Click : Ext.emptyFn
1692 });
1693 Ext.reg('trigger', Ext.form.TriggerField);
1694 /**
1695  * @class Ext.form.TextArea
1696  * @extends Ext.form.TextField
1697  * Multiline text field.  Can be used as a direct replacement for traditional textarea fields, plus adds
1698  * support for auto-sizing.
1699  * @constructor
1700  * Creates a new TextArea
1701  * @param {Object} config Configuration options
1702  * @xtype textarea
1703  */
1704 Ext.form.TextArea = Ext.extend(Ext.form.TextField,  {
1705     /**
1706      * @cfg {Number} growMin The minimum height to allow when <tt>{@link Ext.form.TextField#grow grow}=true</tt>
1707      * (defaults to <tt>60</tt>)
1708      */
1709     growMin : 60,
1710     /**
1711      * @cfg {Number} growMax The maximum height to allow when <tt>{@link Ext.form.TextField#grow grow}=true</tt>
1712      * (defaults to <tt>1000</tt>)
1713      */
1714     growMax: 1000,
1715     growAppend : '&#160;\n&#160;',
1716
1717     enterIsSpecial : false,
1718
1719     /**
1720      * @cfg {Boolean} preventScrollbars <tt>true</tt> to prevent scrollbars from appearing regardless of how much text is
1721      * in the field. This option is only relevant when {@link #grow} is <tt>true</tt>. Equivalent to setting overflow: hidden, defaults to 
1722      * <tt>false</tt>.
1723      */
1724     preventScrollbars: false,
1725     /**
1726      * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or true for a default
1727      * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
1728      * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:</p>
1729      * <pre><code>{tag: "textarea", style: "width:100px;height:60px;", autocomplete: "off"}</code></pre>
1730      */
1731
1732     // private
1733     onRender : function(ct, position){
1734         if(!this.el){
1735             this.defaultAutoCreate = {
1736                 tag: "textarea",
1737                 style:"width:100px;height:60px;",
1738                 autocomplete: "off"
1739             };
1740         }
1741         Ext.form.TextArea.superclass.onRender.call(this, ct, position);
1742         if(this.grow){
1743             this.textSizeEl = Ext.DomHelper.append(document.body, {
1744                 tag: "pre", cls: "x-form-grow-sizer"
1745             });
1746             if(this.preventScrollbars){
1747                 this.el.setStyle("overflow", "hidden");
1748             }
1749             this.el.setHeight(this.growMin);
1750         }
1751     },
1752
1753     onDestroy : function(){
1754         Ext.removeNode(this.textSizeEl);
1755         Ext.form.TextArea.superclass.onDestroy.call(this);
1756     },
1757
1758     fireKey : function(e){
1759         if(e.isSpecialKey() && (this.enterIsSpecial || (e.getKey() != e.ENTER || e.hasModifier()))){
1760             this.fireEvent("specialkey", this, e);
1761         }
1762     },
1763     
1764     // private
1765     doAutoSize : function(e){
1766         return !e.isNavKeyPress() || e.getKey() == e.ENTER;
1767     },
1768     
1769     // inherit docs
1770     filterValidation: function(e) {            
1771         if(!e.isNavKeyPress() || (!this.enterIsSpecial && e.keyCode == e.ENTER)){
1772             this.validationTask.delay(this.validationDelay);
1773         }
1774     },
1775
1776     /**
1777      * Automatically grows the field to accomodate the height of the text up to the maximum field height allowed.
1778      * This only takes effect if grow = true, and fires the {@link #autosize} event if the height changes.
1779      */
1780     autoSize: function(){
1781         if(!this.grow || !this.textSizeEl){
1782             return;
1783         }
1784         var el = this.el,
1785             v = Ext.util.Format.htmlEncode(el.dom.value),
1786             ts = this.textSizeEl,
1787             h;
1788             
1789         Ext.fly(ts).setWidth(this.el.getWidth());
1790         if(v.length < 1){
1791             v = "&#160;&#160;";
1792         }else{
1793             v += this.growAppend;
1794             if(Ext.isIE){
1795                 v = v.replace(/\n/g, '&#160;<br />');
1796             }
1797         }
1798         ts.innerHTML = v;
1799         h = Math.min(this.growMax, Math.max(ts.offsetHeight, this.growMin));
1800         if(h != this.lastHeight){
1801             this.lastHeight = h;
1802             this.el.setHeight(h);
1803             this.fireEvent("autosize", this, h);
1804         }
1805     }
1806 });
1807 Ext.reg('textarea', Ext.form.TextArea);/**
1808  * @class Ext.form.NumberField
1809  * @extends Ext.form.TextField
1810  * Numeric text field that provides automatic keystroke filtering and numeric validation.
1811  * @constructor
1812  * Creates a new NumberField
1813  * @param {Object} config Configuration options
1814  * @xtype numberfield
1815  */
1816 Ext.form.NumberField = Ext.extend(Ext.form.TextField,  {
1817     /**
1818      * @cfg {RegExp} stripCharsRe @hide
1819      */
1820     /**
1821      * @cfg {RegExp} maskRe @hide
1822      */
1823     /**
1824      * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field x-form-num-field")
1825      */
1826     fieldClass: "x-form-field x-form-num-field",
1827     
1828     /**
1829      * @cfg {Boolean} allowDecimals False to disallow decimal values (defaults to true)
1830      */
1831     allowDecimals : true,
1832     
1833     /**
1834      * @cfg {String} decimalSeparator Character(s) to allow as the decimal separator (defaults to '.')
1835      */
1836     decimalSeparator : ".",
1837     
1838     /**
1839      * @cfg {Number} decimalPrecision The maximum precision to display after the decimal separator (defaults to 2)
1840      */
1841     decimalPrecision : 2,
1842     
1843     /**
1844      * @cfg {Boolean} allowNegative False to prevent entering a negative sign (defaults to true)
1845      */
1846     allowNegative : true,
1847     
1848     /**
1849      * @cfg {Number} minValue The minimum allowed value (defaults to Number.NEGATIVE_INFINITY)
1850      */
1851     minValue : Number.NEGATIVE_INFINITY,
1852     
1853     /**
1854      * @cfg {Number} maxValue The maximum allowed value (defaults to Number.MAX_VALUE)
1855      */
1856     maxValue : Number.MAX_VALUE,
1857     
1858     /**
1859      * @cfg {String} minText Error text to display if the minimum value validation fails (defaults to "The minimum value for this field is {minValue}")
1860      */
1861     minText : "The minimum value for this field is {0}",
1862     
1863     /**
1864      * @cfg {String} maxText Error text to display if the maximum value validation fails (defaults to "The maximum value for this field is {maxValue}")
1865      */
1866     maxText : "The maximum value for this field is {0}",
1867     
1868     /**
1869      * @cfg {String} nanText Error text to display if the value is not a valid number.  For example, this can happen
1870      * if a valid character like '.' or '-' is left in the field with no number (defaults to "{value} is not a valid number")
1871      */
1872     nanText : "{0} is not a valid number",
1873     
1874     /**
1875      * @cfg {String} baseChars The base set of characters to evaluate as valid numbers (defaults to '0123456789').
1876      */
1877     baseChars : "0123456789",
1878     
1879     /**
1880      * @cfg {Boolean} autoStripChars True to automatically strip not allowed characters from the field. Defaults to <tt>false</tt>
1881      */
1882     autoStripChars: false,
1883
1884     // private
1885     initEvents : function() {
1886         var allowed = this.baseChars + '';
1887         if (this.allowDecimals) {
1888             allowed += this.decimalSeparator;
1889         }
1890         if (this.allowNegative) {
1891             allowed += '-';
1892         }
1893         allowed = Ext.escapeRe(allowed);
1894         this.maskRe = new RegExp('[' + allowed + ']');
1895         if (this.autoStripChars) {
1896             this.stripCharsRe = new RegExp('[^' + allowed + ']', 'gi');
1897         }
1898         
1899         Ext.form.NumberField.superclass.initEvents.call(this);
1900     },
1901     
1902     /**
1903      * Runs all of NumberFields validations and returns an array of any errors. Note that this first
1904      * runs TextField's validations, so the returned array is an amalgamation of all field errors.
1905      * The additional validations run test that the value is a number, and that it is within the
1906      * configured min and max values.
1907      * @param {Mixed} value The value to get errors for (defaults to the current field value)
1908      * @return {Array} All validation errors for this field
1909      */
1910     getErrors: function(value) {
1911         var errors = Ext.form.NumberField.superclass.getErrors.apply(this, arguments);
1912         
1913         value = Ext.isDefined(value) ? value : this.processValue(this.getRawValue());
1914         
1915         if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
1916              return errors;
1917         }
1918         
1919         value = String(value).replace(this.decimalSeparator, ".");
1920         
1921         if(isNaN(value)){
1922             errors.push(String.format(this.nanText, value));
1923         }
1924         
1925         var num = this.parseValue(value);
1926         
1927         if (num < this.minValue) {
1928             errors.push(String.format(this.minText, this.minValue));
1929         }
1930         
1931         if (num > this.maxValue) {
1932             errors.push(String.format(this.maxText, this.maxValue));
1933         }
1934         
1935         return errors;
1936     },
1937
1938     getValue : function() {
1939         return this.fixPrecision(this.parseValue(Ext.form.NumberField.superclass.getValue.call(this)));
1940     },
1941
1942     setValue : function(v) {
1943         v = this.fixPrecision(v);
1944         v = Ext.isNumber(v) ? v : parseFloat(String(v).replace(this.decimalSeparator, "."));
1945         v = isNaN(v) ? '' : String(v).replace(".", this.decimalSeparator);
1946         return Ext.form.NumberField.superclass.setValue.call(this, v);
1947     },
1948     
1949     /**
1950      * Replaces any existing {@link #minValue} with the new value.
1951      * @param {Number} value The minimum value
1952      */
1953     setMinValue : function(value) {
1954         this.minValue = Ext.num(value, Number.NEGATIVE_INFINITY);
1955     },
1956     
1957     /**
1958      * Replaces any existing {@link #maxValue} with the new value.
1959      * @param {Number} value The maximum value
1960      */
1961     setMaxValue : function(value) {
1962         this.maxValue = Ext.num(value, Number.MAX_VALUE);    
1963     },
1964
1965     // private
1966     parseValue : function(value) {
1967         value = parseFloat(String(value).replace(this.decimalSeparator, "."));
1968         return isNaN(value) ? '' : value;
1969     },
1970
1971     /**
1972      * @private
1973      * 
1974      */
1975     fixPrecision : function(value) {
1976         var nan = isNaN(value);
1977         
1978         if (!this.allowDecimals || this.decimalPrecision == -1 || nan || !value) {
1979             return nan ? '' : value;
1980         }
1981         
1982         return parseFloat(parseFloat(value).toFixed(this.decimalPrecision));
1983     },
1984
1985     beforeBlur : function() {
1986         var v = this.parseValue(this.getRawValue());
1987         
1988         if (!Ext.isEmpty(v)) {
1989             this.setValue(v);
1990         }
1991     }
1992 });
1993
1994 Ext.reg('numberfield', Ext.form.NumberField);
1995 /**
1996  * @class Ext.form.DateField
1997  * @extends Ext.form.TriggerField
1998  * Provides a date input field with a {@link Ext.DatePicker} dropdown and automatic date validation.
1999  * @constructor
2000  * Create a new DateField
2001  * @param {Object} config
2002  * @xtype datefield
2003  */
2004 Ext.form.DateField = Ext.extend(Ext.form.TriggerField,  {
2005     /**
2006      * @cfg {String} format
2007      * The default date format string which can be overriden for localization support.  The format must be
2008      * valid according to {@link Date#parseDate} (defaults to <tt>'m/d/Y'</tt>).
2009      */
2010     format : "m/d/Y",
2011     /**
2012      * @cfg {String} altFormats
2013      * Multiple date formats separated by "<tt>|</tt>" to try when parsing a user input value and it
2014      * does not match the defined format (defaults to
2015      * <tt>'m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j'</tt>).
2016      */
2017     altFormats : "m/d/Y|n/j/Y|n/j/y|m/j/y|n/d/y|m/j/Y|n/d/Y|m-d-y|m-d-Y|m/d|m-d|md|mdy|mdY|d|Y-m-d|n-j|n/j",
2018     /**
2019      * @cfg {String} disabledDaysText
2020      * The tooltip to display when the date falls on a disabled day (defaults to <tt>'Disabled'</tt>)
2021      */
2022     disabledDaysText : "Disabled",
2023     /**
2024      * @cfg {String} disabledDatesText
2025      * The tooltip text to display when the date falls on a disabled date (defaults to <tt>'Disabled'</tt>)
2026      */
2027     disabledDatesText : "Disabled",
2028     /**
2029      * @cfg {String} minText
2030      * The error text to display when the date in the cell is before <tt>{@link #minValue}</tt> (defaults to
2031      * <tt>'The date in this field must be after {minValue}'</tt>).
2032      */
2033     minText : "The date in this field must be equal to or after {0}",
2034     /**
2035      * @cfg {String} maxText
2036      * The error text to display when the date in the cell is after <tt>{@link #maxValue}</tt> (defaults to
2037      * <tt>'The date in this field must be before {maxValue}'</tt>).
2038      */
2039     maxText : "The date in this field must be equal to or before {0}",
2040     /**
2041      * @cfg {String} invalidText
2042      * The error text to display when the date in the field is invalid (defaults to
2043      * <tt>'{value} is not a valid date - it must be in the format {format}'</tt>).
2044      */
2045     invalidText : "{0} is not a valid date - it must be in the format {1}",
2046     /**
2047      * @cfg {String} triggerClass
2048      * An additional CSS class used to style the trigger button.  The trigger will always get the
2049      * class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
2050      * (defaults to <tt>'x-form-date-trigger'</tt> which displays a calendar icon).
2051      */
2052     triggerClass : 'x-form-date-trigger',
2053     /**
2054      * @cfg {Boolean} showToday
2055      * <tt>false</tt> to hide the footer area of the DatePicker containing the Today button and disable
2056      * the keyboard handler for spacebar that selects the current date (defaults to <tt>true</tt>).
2057      */
2058     showToday : true,
2059     
2060     /**
2061      * @cfg {Number} startDay
2062      * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
2063      */
2064     startDay : 0,
2065     
2066     /**
2067      * @cfg {Date/String} minValue
2068      * The minimum allowed date. Can be either a Javascript date object or a string date in a
2069      * valid format (defaults to null).
2070      */
2071     /**
2072      * @cfg {Date/String} maxValue
2073      * The maximum allowed date. Can be either a Javascript date object or a string date in a
2074      * valid format (defaults to null).
2075      */
2076     /**
2077      * @cfg {Array} disabledDays
2078      * An array of days to disable, 0 based (defaults to null). Some examples:<pre><code>
2079 // disable Sunday and Saturday:
2080 disabledDays:  [0, 6]
2081 // disable weekdays:
2082 disabledDays: [1,2,3,4,5]
2083      * </code></pre>
2084      */
2085     /**
2086      * @cfg {Array} disabledDates
2087      * An array of "dates" to disable, as strings. These strings will be used to build a dynamic regular
2088      * expression so they are very powerful. Some examples:<pre><code>
2089 // disable these exact dates:
2090 disabledDates: ["03/08/2003", "09/16/2003"]
2091 // disable these days for every year:
2092 disabledDates: ["03/08", "09/16"]
2093 // only match the beginning (useful if you are using short years):
2094 disabledDates: ["^03/08"]
2095 // disable every day in March 2006:
2096 disabledDates: ["03/../2006"]
2097 // disable every day in every March:
2098 disabledDates: ["^03"]
2099      * </code></pre>
2100      * Note that the format of the dates included in the array should exactly match the {@link #format} config.
2101      * In order to support regular expressions, if you are using a {@link #format date format} that has "." in
2102      * it, you will have to escape the dot when restricting dates. For example: <tt>["03\\.08\\.03"]</tt>.
2103      */
2104     /**
2105      * @cfg {String/Object} autoCreate
2106      * A {@link Ext.DomHelper DomHelper element specification object}, or <tt>true</tt> for the default element
2107      * specification object:<pre><code>
2108      * autoCreate: {tag: "input", type: "text", size: "10", autocomplete: "off"}
2109      * </code></pre>
2110      */
2111
2112     // private
2113     defaultAutoCreate : {tag: "input", type: "text", size: "10", autocomplete: "off"},
2114
2115     // in the absence of a time value, a default value of 12 noon will be used
2116     // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
2117     initTime: '12', // 24 hour format
2118
2119     initTimeFormat: 'H',
2120
2121     // PUBLIC -- to be documented
2122     safeParse : function(value, format) {
2123         if (/[gGhH]/.test(format.replace(/(\\.)/g, ''))) {
2124             // if parse format contains hour information, no DST adjustment is necessary
2125             return Date.parseDate(value, format);
2126         } else {
2127             // set time to 12 noon, then clear the time
2128             var parsedDate = Date.parseDate(value + ' ' + this.initTime, format + ' ' + this.initTimeFormat);
2129
2130             if (parsedDate) {
2131                 return parsedDate.clearTime();
2132             }
2133         }
2134     },
2135
2136     initComponent : function(){
2137         Ext.form.DateField.superclass.initComponent.call(this);
2138
2139         this.addEvents(
2140             /**
2141              * @event select
2142              * Fires when a date is selected via the date picker.
2143              * @param {Ext.form.DateField} this
2144              * @param {Date} date The date that was selected
2145              */
2146             'select'
2147         );
2148
2149         if(Ext.isString(this.minValue)){
2150             this.minValue = this.parseDate(this.minValue);
2151         }
2152         if(Ext.isString(this.maxValue)){
2153             this.maxValue = this.parseDate(this.maxValue);
2154         }
2155         this.disabledDatesRE = null;
2156         this.initDisabledDays();
2157     },
2158
2159     initEvents: function() {
2160         Ext.form.DateField.superclass.initEvents.call(this);
2161         this.keyNav = new Ext.KeyNav(this.el, {
2162             "down": function(e) {
2163                 this.onTriggerClick();
2164             },
2165             scope: this,
2166             forceKeyDown: true
2167         });
2168     },
2169
2170
2171     // private
2172     initDisabledDays : function(){
2173         if(this.disabledDates){
2174             var dd = this.disabledDates,
2175                 len = dd.length - 1,
2176                 re = "(?:";
2177
2178             Ext.each(dd, function(d, i){
2179                 re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
2180                 if(i != len){
2181                     re += '|';
2182                 }
2183             }, this);
2184             this.disabledDatesRE = new RegExp(re + ')');
2185         }
2186     },
2187
2188     /**
2189      * Replaces any existing disabled dates with new values and refreshes the DatePicker.
2190      * @param {Array} disabledDates An array of date strings (see the <tt>{@link #disabledDates}</tt> config
2191      * for details on supported values) used to disable a pattern of dates.
2192      */
2193     setDisabledDates : function(dd){
2194         this.disabledDates = dd;
2195         this.initDisabledDays();
2196         if(this.menu){
2197             this.menu.picker.setDisabledDates(this.disabledDatesRE);
2198         }
2199     },
2200
2201     /**
2202      * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
2203      * @param {Array} disabledDays An array of disabled day indexes. See the <tt>{@link #disabledDays}</tt>
2204      * config for details on supported values.
2205      */
2206     setDisabledDays : function(dd){
2207         this.disabledDays = dd;
2208         if(this.menu){
2209             this.menu.picker.setDisabledDays(dd);
2210         }
2211     },
2212
2213     /**
2214      * Replaces any existing <tt>{@link #minValue}</tt> with the new value and refreshes the DatePicker.
2215      * @param {Date} value The minimum date that can be selected
2216      */
2217     setMinValue : function(dt){
2218         this.minValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
2219         if(this.menu){
2220             this.menu.picker.setMinDate(this.minValue);
2221         }
2222     },
2223
2224     /**
2225      * Replaces any existing <tt>{@link #maxValue}</tt> with the new value and refreshes the DatePicker.
2226      * @param {Date} value The maximum date that can be selected
2227      */
2228     setMaxValue : function(dt){
2229         this.maxValue = (Ext.isString(dt) ? this.parseDate(dt) : dt);
2230         if(this.menu){
2231             this.menu.picker.setMaxDate(this.maxValue);
2232         }
2233     },
2234
2235     /**
2236      * Runs all of NumberFields validations and returns an array of any errors. Note that this first
2237      * runs TextField's validations, so the returned array is an amalgamation of all field errors.
2238      * The additional validation checks are testing that the date format is valid, that the chosen
2239      * date is within the min and max date constraints set, that the date chosen is not in the disabledDates
2240      * regex and that the day chosed is not one of the disabledDays.
2241      * @param {Mixed} value The value to get errors for (defaults to the current field value)
2242      * @return {Array} All validation errors for this field
2243      */
2244     getErrors: function(value) {
2245         var errors = Ext.form.DateField.superclass.getErrors.apply(this, arguments);
2246
2247         value = this.formatDate(value || this.processValue(this.getRawValue()));
2248
2249         if (value.length < 1) { // if it's blank and textfield didn't flag it then it's valid
2250              return errors;
2251         }
2252
2253         var svalue = value;
2254         value = this.parseDate(value);
2255         if (!value) {
2256             errors.push(String.format(this.invalidText, svalue, this.format));
2257             return errors;
2258         }
2259
2260         var time = value.getTime();
2261         if (this.minValue && time < this.minValue.clearTime().getTime()) {
2262             errors.push(String.format(this.minText, this.formatDate(this.minValue)));
2263         }
2264
2265         if (this.maxValue && time > this.maxValue.clearTime().getTime()) {
2266             errors.push(String.format(this.maxText, this.formatDate(this.maxValue)));
2267         }
2268
2269         if (this.disabledDays) {
2270             var day = value.getDay();
2271
2272             for(var i = 0; i < this.disabledDays.length; i++) {
2273                 if (day === this.disabledDays[i]) {
2274                     errors.push(this.disabledDaysText);
2275                     break;
2276                 }
2277             }
2278         }
2279
2280         var fvalue = this.formatDate(value);
2281         if (this.disabledDatesRE && this.disabledDatesRE.test(fvalue)) {
2282             errors.push(String.format(this.disabledDatesText, fvalue));
2283         }
2284
2285         return errors;
2286     },
2287
2288     // private
2289     // Provides logic to override the default TriggerField.validateBlur which just returns true
2290     validateBlur : function(){
2291         return !this.menu || !this.menu.isVisible();
2292     },
2293
2294     /**
2295      * Returns the current date value of the date field.
2296      * @return {Date} The date value
2297      */
2298     getValue : function(){
2299         return this.parseDate(Ext.form.DateField.superclass.getValue.call(this)) || "";
2300     },
2301
2302     /**
2303      * Sets the value of the date field.  You can pass a date object or any string that can be
2304      * parsed into a valid date, using <tt>{@link #format}</tt> as the date format, according
2305      * to the same rules as {@link Date#parseDate} (the default format used is <tt>"m/d/Y"</tt>).
2306      * <br />Usage:
2307      * <pre><code>
2308 //All of these calls set the same date value (May 4, 2006)
2309
2310 //Pass a date object:
2311 var dt = new Date('5/4/2006');
2312 dateField.setValue(dt);
2313
2314 //Pass a date string (default format):
2315 dateField.setValue('05/04/2006');
2316
2317 //Pass a date string (custom format):
2318 dateField.format = 'Y-m-d';
2319 dateField.setValue('2006-05-04');
2320 </code></pre>
2321      * @param {String/Date} date The date or valid date string
2322      * @return {Ext.form.Field} this
2323      */
2324     setValue : function(date){
2325         return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
2326     },
2327
2328     // private
2329     parseDate : function(value) {
2330         if(!value || Ext.isDate(value)){
2331             return value;
2332         }
2333
2334         var v = this.safeParse(value, this.format),
2335             af = this.altFormats,
2336             afa = this.altFormatsArray;
2337
2338         if (!v && af) {
2339             afa = afa || af.split("|");
2340
2341             for (var i = 0, len = afa.length; i < len && !v; i++) {
2342                 v = this.safeParse(value, afa[i]);
2343             }
2344         }
2345         return v;
2346     },
2347
2348     // private
2349     onDestroy : function(){
2350         Ext.destroy(this.menu, this.keyNav);
2351         Ext.form.DateField.superclass.onDestroy.call(this);
2352     },
2353
2354     // private
2355     formatDate : function(date){
2356         return Ext.isDate(date) ? date.dateFormat(this.format) : date;
2357     },
2358
2359     /**
2360      * @method onTriggerClick
2361      * @hide
2362      */
2363     // private
2364     // Implements the default empty TriggerField.onTriggerClick function to display the DatePicker
2365     onTriggerClick : function(){
2366         if(this.disabled){
2367             return;
2368         }
2369         if(this.menu == null){
2370             this.menu = new Ext.menu.DateMenu({
2371                 hideOnClick: false,
2372                 focusOnSelect: false
2373             });
2374         }
2375         this.onFocus();
2376         Ext.apply(this.menu.picker,  {
2377             minDate : this.minValue,
2378             maxDate : this.maxValue,
2379             disabledDatesRE : this.disabledDatesRE,
2380             disabledDatesText : this.disabledDatesText,
2381             disabledDays : this.disabledDays,
2382             disabledDaysText : this.disabledDaysText,
2383             format : this.format,
2384             showToday : this.showToday,
2385             startDay: this.startDay,
2386             minText : String.format(this.minText, this.formatDate(this.minValue)),
2387             maxText : String.format(this.maxText, this.formatDate(this.maxValue))
2388         });
2389         this.menu.picker.setValue(this.getValue() || new Date());
2390         this.menu.show(this.el, "tl-bl?");
2391         this.menuEvents('on');
2392     },
2393
2394     //private
2395     menuEvents: function(method){
2396         this.menu[method]('select', this.onSelect, this);
2397         this.menu[method]('hide', this.onMenuHide, this);
2398         this.menu[method]('show', this.onFocus, this);
2399     },
2400
2401     onSelect: function(m, d){
2402         this.setValue(d);
2403         this.fireEvent('select', this, d);
2404         this.menu.hide();
2405     },
2406
2407     onMenuHide: function(){
2408         this.focus(false, 60);
2409         this.menuEvents('un');
2410     },
2411
2412     // private
2413     beforeBlur : function(){
2414         var v = this.parseDate(this.getRawValue());
2415         if(v){
2416             this.setValue(v);
2417         }
2418     }
2419
2420     /**
2421      * @cfg {Boolean} grow @hide
2422      */
2423     /**
2424      * @cfg {Number} growMin @hide
2425      */
2426     /**
2427      * @cfg {Number} growMax @hide
2428      */
2429     /**
2430      * @hide
2431      * @method autoSize
2432      */
2433 });
2434 Ext.reg('datefield', Ext.form.DateField);
2435 /**
2436  * @class Ext.form.DisplayField
2437  * @extends Ext.form.Field
2438  * A display-only text field which is not validated and not submitted.
2439  * @constructor
2440  * Creates a new DisplayField.
2441  * @param {Object} config Configuration options
2442  * @xtype displayfield
2443  */
2444 Ext.form.DisplayField = Ext.extend(Ext.form.Field,  {
2445     validationEvent : false,
2446     validateOnBlur : false,
2447     defaultAutoCreate : {tag: "div"},
2448     /**
2449      * @cfg {String} fieldClass The default CSS class for the field (defaults to <tt>"x-form-display-field"</tt>)
2450      */
2451     fieldClass : "x-form-display-field",
2452     /**
2453      * @cfg {Boolean} htmlEncode <tt>false</tt> to skip HTML-encoding the text when rendering it (defaults to
2454      * <tt>false</tt>). This might be useful if you want to include tags in the field's innerHTML rather than
2455      * rendering them as string literals per the default logic.
2456      */
2457     htmlEncode: false,
2458
2459     // private
2460     initEvents : Ext.emptyFn,
2461
2462     isValid : function(){
2463         return true;
2464     },
2465
2466     validate : function(){
2467         return true;
2468     },
2469
2470     getRawValue : function(){
2471         var v = this.rendered ? this.el.dom.innerHTML : Ext.value(this.value, '');
2472         if(v === this.emptyText){
2473             v = '';
2474         }
2475         if(this.htmlEncode){
2476             v = Ext.util.Format.htmlDecode(v);
2477         }
2478         return v;
2479     },
2480
2481     getValue : function(){
2482         return this.getRawValue();
2483     },
2484     
2485     getName: function() {
2486         return this.name;
2487     },
2488
2489     setRawValue : function(v){
2490         if(this.htmlEncode){
2491             v = Ext.util.Format.htmlEncode(v);
2492         }
2493         return this.rendered ? (this.el.dom.innerHTML = (Ext.isEmpty(v) ? '' : v)) : (this.value = v);
2494     },
2495
2496     setValue : function(v){
2497         this.setRawValue(v);
2498         return this;
2499     }
2500     /** 
2501      * @cfg {String} inputType 
2502      * @hide
2503      */
2504     /** 
2505      * @cfg {Boolean} disabled 
2506      * @hide
2507      */
2508     /** 
2509      * @cfg {Boolean} readOnly 
2510      * @hide
2511      */
2512     /** 
2513      * @cfg {Boolean} validateOnBlur 
2514      * @hide
2515      */
2516     /** 
2517      * @cfg {Number} validationDelay 
2518      * @hide
2519      */
2520     /** 
2521      * @cfg {String/Boolean} validationEvent 
2522      * @hide
2523      */
2524 });
2525
2526 Ext.reg('displayfield', Ext.form.DisplayField);
2527 /**
2528  * @class Ext.form.ComboBox
2529  * @extends Ext.form.TriggerField
2530  * <p>A combobox control with support for autocomplete, remote-loading, paging and many other features.</p>
2531  * <p>A ComboBox works in a similar manner to a traditional HTML &lt;select> field. The difference is
2532  * that to submit the {@link #valueField}, you must specify a {@link #hiddenName} to create a hidden input
2533  * field to hold the value of the valueField. The <i>{@link #displayField}</i> is shown in the text field
2534  * which is named according to the {@link #name}.</p>
2535  * <p><b><u>Events</u></b></p>
2536  * <p>To do something when something in ComboBox is selected, configure the select event:<pre><code>
2537 var cb = new Ext.form.ComboBox({
2538     // all of your config options
2539     listeners:{
2540          scope: yourScope,
2541          'select': yourFunction
2542     }
2543 });
2544
2545 // Alternatively, you can assign events after the object is created:
2546 var cb = new Ext.form.ComboBox(yourOptions);
2547 cb.on('select', yourFunction, yourScope);
2548  * </code></pre></p>
2549  *
2550  * <p><b><u>ComboBox in Grid</u></b></p>
2551  * <p>If using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a {@link Ext.grid.Column#renderer renderer}
2552  * will be needed to show the displayField when the editor is not active.  Set up the renderer manually, or implement
2553  * a reusable render, for example:<pre><code>
2554 // create reusable renderer
2555 Ext.util.Format.comboRenderer = function(combo){
2556     return function(value){
2557         var record = combo.findRecord(combo.{@link #valueField}, value);
2558         return record ? record.get(combo.{@link #displayField}) : combo.{@link #valueNotFoundText};
2559     }
2560 }
2561
2562 // create the combo instance
2563 var combo = new Ext.form.ComboBox({
2564     {@link #typeAhead}: true,
2565     {@link #triggerAction}: 'all',
2566     {@link #lazyRender}:true,
2567     {@link #mode}: 'local',
2568     {@link #store}: new Ext.data.ArrayStore({
2569         id: 0,
2570         fields: [
2571             'myId',
2572             'displayText'
2573         ],
2574         data: [[1, 'item1'], [2, 'item2']]
2575     }),
2576     {@link #valueField}: 'myId',
2577     {@link #displayField}: 'displayText'
2578 });
2579
2580 // snippet of column model used within grid
2581 var cm = new Ext.grid.ColumnModel([{
2582        ...
2583     },{
2584        header: "Some Header",
2585        dataIndex: 'whatever',
2586        width: 130,
2587        editor: combo, // specify reference to combo instance
2588        renderer: Ext.util.Format.comboRenderer(combo) // pass combo instance to reusable renderer
2589     },
2590     ...
2591 ]);
2592  * </code></pre></p>
2593  *
2594  * <p><b><u>Filtering</u></b></p>
2595  * <p>A ComboBox {@link #doQuery uses filtering itself}, for information about filtering the ComboBox
2596  * store manually see <tt>{@link #lastQuery}</tt>.</p>
2597  * @constructor
2598  * Create a new ComboBox.
2599  * @param {Object} config Configuration options
2600  * @xtype combo
2601  */
2602 Ext.form.ComboBox = Ext.extend(Ext.form.TriggerField, {
2603     /**
2604      * @cfg {Mixed} transform The id, DOM node or element of an existing HTML SELECT to convert to a ComboBox.
2605      * Note that if you specify this and the combo is going to be in an {@link Ext.form.BasicForm} or
2606      * {@link Ext.form.FormPanel}, you must also set <tt>{@link #lazyRender} = true</tt>.
2607      */
2608     /**
2609      * @cfg {Boolean} lazyRender <tt>true</tt> to prevent the ComboBox from rendering until requested
2610      * (should always be used when rendering into an {@link Ext.Editor} (e.g. {@link Ext.grid.EditorGridPanel Grids}),
2611      * defaults to <tt>false</tt>).
2612      */
2613     /**
2614      * @cfg {String/Object} autoCreate <p>A {@link Ext.DomHelper DomHelper} element spec, or <tt>true</tt> for a default
2615      * element spec. Used to create the {@link Ext.Component#getEl Element} which will encapsulate this Component.
2616      * See <tt>{@link Ext.Component#autoEl autoEl}</tt> for details.  Defaults to:</p>
2617      * <pre><code>{tag: "input", type: "text", size: "24", autocomplete: "off"}</code></pre>
2618      */
2619     /**
2620      * @cfg {Ext.data.Store/Array} store The data source to which this combo is bound (defaults to <tt>undefined</tt>).
2621      * Acceptable values for this property are:
2622      * <div class="mdetail-params"><ul>
2623      * <li><b>any {@link Ext.data.Store Store} subclass</b></li>
2624      * <li><b>an Array</b> : Arrays will be converted to a {@link Ext.data.ArrayStore} internally,
2625      * automatically generating {@link Ext.data.Field#name field names} to work with all data components.
2626      * <div class="mdetail-params"><ul>
2627      * <li><b>1-dimensional array</b> : (e.g., <tt>['Foo','Bar']</tt>)<div class="sub-desc">
2628      * A 1-dimensional array will automatically be expanded (each array item will be used for both the combo
2629      * {@link #valueField} and {@link #displayField})</div></li>
2630      * <li><b>2-dimensional array</b> : (e.g., <tt>[['f','Foo'],['b','Bar']]</tt>)<div class="sub-desc">
2631      * For a multi-dimensional array, the value in index 0 of each item will be assumed to be the combo
2632      * {@link #valueField}, while the value at index 1 is assumed to be the combo {@link #displayField}.
2633      * </div></li></ul></div></li></ul></div>
2634      * <p>See also <tt>{@link #mode}</tt>.</p>
2635      */
2636     /**
2637      * @cfg {String} title If supplied, a header element is created containing this text and added into the top of
2638      * the dropdown list (defaults to undefined, with no header element)
2639      */
2640
2641     // private
2642     defaultAutoCreate : {tag: "input", type: "text", size: "24", autocomplete: "off"},
2643     /**
2644      * @cfg {Number} listWidth The width (used as a parameter to {@link Ext.Element#setWidth}) of the dropdown
2645      * list (defaults to the width of the ComboBox field).  See also <tt>{@link #minListWidth}
2646      */
2647     /**
2648      * @cfg {String} displayField The underlying {@link Ext.data.Field#name data field name} to bind to this
2649      * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field1'</tt> if
2650      * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
2651      * the store configuration}).
2652      * <p>See also <tt>{@link #valueField}</tt>.</p>
2653      * <p><b>Note</b>: if using a ComboBox in an {@link Ext.grid.EditorGridPanel Editor Grid} a
2654      * {@link Ext.grid.Column#renderer renderer} will be needed to show the displayField when the editor is not
2655      * active.</p>
2656      */
2657     /**
2658      * @cfg {String} valueField The underlying {@link Ext.data.Field#name data value name} to bind to this
2659      * ComboBox (defaults to undefined if <tt>{@link #mode} = 'remote'</tt> or <tt>'field2'</tt> if
2660      * {@link #transform transforming a select} or if the {@link #store field name is autogenerated based on
2661      * the store configuration}).
2662      * <p><b>Note</b>: use of a <tt>valueField</tt> requires the user to make a selection in order for a value to be
2663      * mapped.  See also <tt>{@link #hiddenName}</tt>, <tt>{@link #hiddenValue}</tt>, and <tt>{@link #displayField}</tt>.</p>
2664      */
2665     /**
2666      * @cfg {String} hiddenName If specified, a hidden form field with this name is dynamically generated to store the
2667      * field's data value (defaults to the underlying DOM element's name). Required for the combo's value to automatically
2668      * post during a form submission.  See also {@link #valueField}.
2669      */
2670     /**
2671      * @cfg {String} hiddenId If <tt>{@link #hiddenName}</tt> is specified, <tt>hiddenId</tt> can also be provided
2672      * to give the hidden field a unique id.  The <tt>hiddenId</tt> and combo {@link Ext.Component#id id} should be 
2673      * different, since no two DOM nodes should share the same id.
2674      */
2675     /**
2676      * @cfg {String} hiddenValue Sets the initial value of the hidden field if {@link #hiddenName} is
2677      * specified to contain the selected {@link #valueField}, from the Store. Defaults to the configured
2678      * <tt>{@link Ext.form.Field#value value}</tt>.
2679      */
2680     /**
2681      * @cfg {String} listClass The CSS class to add to the predefined <tt>'x-combo-list'</tt> class
2682      * applied the dropdown list element (defaults to '').
2683      */
2684     listClass : '',
2685     /**
2686      * @cfg {String} selectedClass CSS class to apply to the selected item in the dropdown list
2687      * (defaults to <tt>'x-combo-selected'</tt>)
2688      */
2689     selectedClass : 'x-combo-selected',
2690     /**
2691      * @cfg {String} listEmptyText The empty text to display in the data view if no items are found.
2692      * (defaults to '')
2693      */
2694     listEmptyText: '',
2695     /**
2696      * @cfg {String} triggerClass An additional CSS class used to style the trigger button.  The trigger will always
2697      * get the class <tt>'x-form-trigger'</tt> and <tt>triggerClass</tt> will be <b>appended</b> if specified
2698      * (defaults to <tt>'x-form-arrow-trigger'</tt> which displays a downward arrow icon).
2699      */
2700     triggerClass : 'x-form-arrow-trigger',
2701     /**
2702      * @cfg {Boolean/String} shadow <tt>true</tt> or <tt>"sides"</tt> for the default effect, <tt>"frame"</tt> for
2703      * 4-way shadow, and <tt>"drop"</tt> for bottom-right
2704      */
2705     shadow : 'sides',
2706     /**
2707      * @cfg {String/Array} listAlign A valid anchor position value. See <tt>{@link Ext.Element#alignTo}</tt> for details
2708      * on supported anchor positions and offsets. To specify x/y offsets as well, this value
2709      * may be specified as an Array of <tt>{@link Ext.Element#alignTo}</tt> method arguments.</p>
2710      * <pre><code>[ 'tl-bl?', [6,0] ]</code></pre>(defaults to <tt>'tl-bl?'</tt>)
2711      */
2712     listAlign : 'tl-bl?',
2713     /**
2714      * @cfg {Number} maxHeight The maximum height in pixels of the dropdown list before scrollbars are shown
2715      * (defaults to <tt>300</tt>)
2716      */
2717     maxHeight : 300,
2718     /**
2719      * @cfg {Number} minHeight The minimum height in pixels of the dropdown list when the list is constrained by its
2720      * distance to the viewport edges (defaults to <tt>90</tt>)
2721      */
2722     minHeight : 90,
2723     /**
2724      * @cfg {String} triggerAction The action to execute when the trigger is clicked.
2725      * <div class="mdetail-params"><ul>
2726      * <li><b><tt>'query'</tt></b> : <b>Default</b>
2727      * <p class="sub-desc">{@link #doQuery run the query} using the {@link Ext.form.Field#getRawValue raw value}.</p></li>
2728      * <li><b><tt>'all'</tt></b> :
2729      * <p class="sub-desc">{@link #doQuery run the query} specified by the <tt>{@link #allQuery}</tt> config option</p></li>
2730      * </ul></div>
2731      * <p>See also <code>{@link #queryParam}</code>.</p>
2732      */
2733     triggerAction : 'query',
2734     /**
2735      * @cfg {Number} minChars The minimum number of characters the user must type before autocomplete and
2736      * {@link #typeAhead} activate (defaults to <tt>4</tt> if <tt>{@link #mode} = 'remote'</tt> or <tt>0</tt> if
2737      * <tt>{@link #mode} = 'local'</tt>, does not apply if
2738      * <tt>{@link Ext.form.TriggerField#editable editable} = false</tt>).
2739      */
2740     minChars : 4,
2741     /**
2742      * @cfg {Boolean} autoSelect <tt>true</tt> to select the first result gathered by the data store (defaults
2743      * to <tt>true</tt>).  A false value would require a manual selection from the dropdown list to set the components value
2744      * unless the value of ({@link #typeAheadDelay}) were true.
2745      */
2746     autoSelect : true,
2747     /**
2748      * @cfg {Boolean} typeAhead <tt>true</tt> to populate and autoselect the remainder of the text being
2749      * typed after a configurable delay ({@link #typeAheadDelay}) if it matches a known value (defaults
2750      * to <tt>false</tt>)
2751      */
2752     typeAhead : false,
2753     /**
2754      * @cfg {Number} queryDelay The length of time in milliseconds to delay between the start of typing and
2755      * sending the query to filter the dropdown list (defaults to <tt>500</tt> if <tt>{@link #mode} = 'remote'</tt>
2756      * or <tt>10</tt> if <tt>{@link #mode} = 'local'</tt>)
2757      */
2758     queryDelay : 500,
2759     /**
2760      * @cfg {Number} pageSize If greater than <tt>0</tt>, a {@link Ext.PagingToolbar} is displayed in the
2761      * footer of the dropdown list and the {@link #doQuery filter queries} will execute with page start and
2762      * {@link Ext.PagingToolbar#pageSize limit} parameters. Only applies when <tt>{@link #mode} = 'remote'</tt>
2763      * (defaults to <tt>0</tt>).
2764      */
2765     pageSize : 0,
2766     /**
2767      * @cfg {Boolean} selectOnFocus <tt>true</tt> to select any existing text in the field immediately on focus.
2768      * Only applies when <tt>{@link Ext.form.TriggerField#editable editable} = true</tt> (defaults to
2769      * <tt>false</tt>).
2770      */
2771     selectOnFocus : false,
2772     /**
2773      * @cfg {String} queryParam Name of the query ({@link Ext.data.Store#baseParam baseParam} name for the store)
2774      * as it will be passed on the querystring (defaults to <tt>'query'</tt>)
2775      */
2776     queryParam : 'query',
2777     /**
2778      * @cfg {String} loadingText The text to display in the dropdown list while data is loading.  Only applies
2779      * when <tt>{@link #mode} = 'remote'</tt> (defaults to <tt>'Loading...'</tt>)
2780      */
2781     loadingText : 'Loading...',
2782     /**
2783      * @cfg {Boolean} resizable <tt>true</tt> to add a resize handle to the bottom of the dropdown list
2784      * (creates an {@link Ext.Resizable} with 'se' {@link Ext.Resizable#pinned pinned} handles).
2785      * Defaults to <tt>false</tt>.
2786      */
2787     resizable : false,
2788     /**
2789      * @cfg {Number} handleHeight The height in pixels of the dropdown list resize handle if
2790      * <tt>{@link #resizable} = true</tt> (defaults to <tt>8</tt>)
2791      */
2792     handleHeight : 8,
2793     /**
2794      * @cfg {String} allQuery The text query to send to the server to return all records for the list
2795      * with no filtering (defaults to '')
2796      */
2797     allQuery: '',
2798     /**
2799      * @cfg {String} mode Acceptable values are:
2800      * <div class="mdetail-params"><ul>
2801      * <li><b><tt>'remote'</tt></b> : <b>Default</b>
2802      * <p class="sub-desc">Automatically loads the <tt>{@link #store}</tt> the <b>first</b> time the trigger
2803      * is clicked. If you do not want the store to be automatically loaded the first time the trigger is
2804      * clicked, set to <tt>'local'</tt> and manually load the store.  To force a requery of the store
2805      * <b>every</b> time the trigger is clicked see <tt>{@link #lastQuery}</tt>.</p></li>
2806      * <li><b><tt>'local'</tt></b> :
2807      * <p class="sub-desc">ComboBox loads local data</p>
2808      * <pre><code>
2809 var combo = new Ext.form.ComboBox({
2810     renderTo: document.body,
2811     mode: 'local',
2812     store: new Ext.data.ArrayStore({
2813         id: 0,
2814         fields: [
2815             'myId',  // numeric value is the key
2816             'displayText'
2817         ],
2818         data: [[1, 'item1'], [2, 'item2']]  // data is local
2819     }),
2820     valueField: 'myId',
2821     displayField: 'displayText',
2822     triggerAction: 'all'
2823 });
2824      * </code></pre></li>
2825      * </ul></div>
2826      */
2827     mode: 'remote',
2828     /**
2829      * @cfg {Number} minListWidth The minimum width of the dropdown list in pixels (defaults to <tt>70</tt>, will
2830      * be ignored if <tt>{@link #listWidth}</tt> has a higher value)
2831      */
2832     minListWidth : 70,
2833     /**
2834      * @cfg {Boolean} forceSelection <tt>true</tt> to restrict the selected value to one of the values in the list,
2835      * <tt>false</tt> to allow the user to set arbitrary text into the field (defaults to <tt>false</tt>)
2836      */
2837     forceSelection : false,
2838     /**
2839      * @cfg {Number} typeAheadDelay The length of time in milliseconds to wait until the typeahead text is displayed
2840      * if <tt>{@link #typeAhead} = true</tt> (defaults to <tt>250</tt>)
2841      */
2842     typeAheadDelay : 250,
2843     /**
2844      * @cfg {String} valueNotFoundText When using a name/value combo, if the value passed to setValue is not found in
2845      * the store, valueNotFoundText will be displayed as the field text if defined (defaults to undefined). If this
2846      * default text is used, it means there is no value set and no validation will occur on this field.
2847      */
2848
2849     /**
2850      * @cfg {Boolean} lazyInit <tt>true</tt> to not initialize the list for this combo until the field is focused
2851      * (defaults to <tt>true</tt>)
2852      */
2853     lazyInit : true,
2854
2855     /**
2856      * @cfg {Boolean} clearFilterOnReset <tt>true</tt> to clear any filters on the store (when in local mode) when reset is called
2857      * (defaults to <tt>true</tt>)
2858      */
2859     clearFilterOnReset : true,
2860
2861     /**
2862      * @cfg {Boolean} submitValue False to clear the name attribute on the field so that it is not submitted during a form post.
2863      * If a hiddenName is specified, setting this to true will cause both the hidden field and the element to be submitted.
2864      * Defaults to <tt>undefined</tt>.
2865      */
2866     submitValue: undefined,
2867
2868     /**
2869      * The value of the match string used to filter the store. Delete this property to force a requery.
2870      * Example use:
2871      * <pre><code>
2872 var combo = new Ext.form.ComboBox({
2873     ...
2874     mode: 'remote',
2875     ...
2876     listeners: {
2877         // delete the previous query in the beforequery event or set
2878         // combo.lastQuery = null (this will reload the store the next time it expands)
2879         beforequery: function(qe){
2880             delete qe.combo.lastQuery;
2881         }
2882     }
2883 });
2884      * </code></pre>
2885      * To make sure the filter in the store is not cleared the first time the ComboBox trigger is used
2886      * configure the combo with <tt>lastQuery=''</tt>. Example use:
2887      * <pre><code>
2888 var combo = new Ext.form.ComboBox({
2889     ...
2890     mode: 'local',
2891     triggerAction: 'all',
2892     lastQuery: ''
2893 });
2894      * </code></pre>
2895      * @property lastQuery
2896      * @type String
2897      */
2898
2899     // private
2900     initComponent : function(){
2901         Ext.form.ComboBox.superclass.initComponent.call(this);
2902         this.addEvents(
2903             /**
2904              * @event expand
2905              * Fires when the dropdown list is expanded
2906              * @param {Ext.form.ComboBox} combo This combo box
2907              */
2908             'expand',
2909             /**
2910              * @event collapse
2911              * Fires when the dropdown list is collapsed
2912              * @param {Ext.form.ComboBox} combo This combo box
2913              */
2914             'collapse',
2915
2916             /**
2917              * @event beforeselect
2918              * Fires before a list item is selected. Return false to cancel the selection.
2919              * @param {Ext.form.ComboBox} combo This combo box
2920              * @param {Ext.data.Record} record The data record returned from the underlying store
2921              * @param {Number} index The index of the selected item in the dropdown list
2922              */
2923             'beforeselect',
2924             /**
2925              * @event select
2926              * Fires when a list item is selected
2927              * @param {Ext.form.ComboBox} combo This combo box
2928              * @param {Ext.data.Record} record The data record returned from the underlying store
2929              * @param {Number} index The index of the selected item in the dropdown list
2930              */
2931             'select',
2932             /**
2933              * @event beforequery
2934              * Fires before all queries are processed. Return false to cancel the query or set the queryEvent's
2935              * cancel property to true.
2936              * @param {Object} queryEvent An object that has these properties:<ul>
2937              * <li><code>combo</code> : Ext.form.ComboBox <div class="sub-desc">This combo box</div></li>
2938              * <li><code>query</code> : String <div class="sub-desc">The query</div></li>
2939              * <li><code>forceAll</code> : Boolean <div class="sub-desc">True to force "all" query</div></li>
2940              * <li><code>cancel</code> : Boolean <div class="sub-desc">Set to true to cancel the query</div></li>
2941              * </ul>
2942              */
2943             'beforequery'
2944         );
2945         if(this.transform){
2946             var s = Ext.getDom(this.transform);
2947             if(!this.hiddenName){
2948                 this.hiddenName = s.name;
2949             }
2950             if(!this.store){
2951                 this.mode = 'local';
2952                 var d = [], opts = s.options;
2953                 for(var i = 0, len = opts.length;i < len; i++){
2954                     var o = opts[i],
2955                         value = (o.hasAttribute ? o.hasAttribute('value') : o.getAttributeNode('value').specified) ? o.value : o.text;
2956                     if(o.selected && Ext.isEmpty(this.value, true)) {
2957                         this.value = value;
2958                     }
2959                     d.push([value, o.text]);
2960                 }
2961                 this.store = new Ext.data.ArrayStore({
2962                     idIndex: 0,
2963                     fields: ['value', 'text'],
2964                     data : d,
2965                     autoDestroy: true
2966                 });
2967                 this.valueField = 'value';
2968                 this.displayField = 'text';
2969             }
2970             s.name = Ext.id(); // wipe out the name in case somewhere else they have a reference
2971             if(!this.lazyRender){
2972                 this.target = true;
2973                 this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
2974                 this.render(this.el.parentNode, s);
2975             }
2976             Ext.removeNode(s);
2977         }
2978         //auto-configure store from local array data
2979         else if(this.store){
2980             this.store = Ext.StoreMgr.lookup(this.store);
2981             if(this.store.autoCreated){
2982                 this.displayField = this.valueField = 'field1';
2983                 if(!this.store.expandData){
2984                     this.displayField = 'field2';
2985                 }
2986                 this.mode = 'local';
2987             }
2988         }
2989
2990         this.selectedIndex = -1;
2991         if(this.mode == 'local'){
2992             if(!Ext.isDefined(this.initialConfig.queryDelay)){
2993                 this.queryDelay = 10;
2994             }
2995             if(!Ext.isDefined(this.initialConfig.minChars)){
2996                 this.minChars = 0;
2997             }
2998         }
2999     },
3000
3001     // private
3002     onRender : function(ct, position){
3003         if(this.hiddenName && !Ext.isDefined(this.submitValue)){
3004             this.submitValue = false;
3005         }
3006         Ext.form.ComboBox.superclass.onRender.call(this, ct, position);
3007         if(this.hiddenName){
3008             this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
3009                     id: (this.hiddenId || Ext.id())}, 'before', true);
3010
3011         }
3012         if(Ext.isGecko){
3013             this.el.dom.setAttribute('autocomplete', 'off');
3014         }
3015
3016         if(!this.lazyInit){
3017             this.initList();
3018         }else{
3019             this.on('focus', this.initList, this, {single: true});
3020         }
3021     },
3022
3023     // private
3024     initValue : function(){
3025         Ext.form.ComboBox.superclass.initValue.call(this);
3026         if(this.hiddenField){
3027             this.hiddenField.value =
3028                 Ext.value(Ext.isDefined(this.hiddenValue) ? this.hiddenValue : this.value, '');
3029         }
3030     },
3031
3032     getParentZIndex : function(){
3033         var zindex;
3034         if (this.ownerCt){
3035             this.findParentBy(function(ct){
3036                 zindex = parseInt(ct.getPositionEl().getStyle('z-index'), 10);
3037                 return !!zindex;
3038             });
3039         }
3040         return zindex;
3041     },
3042     
3043     getZIndex : function(listParent){
3044         listParent = listParent || Ext.getDom(this.getListParent() || Ext.getBody());
3045         var zindex = parseInt(Ext.fly(listParent).getStyle('z-index'), 10);
3046         if(!zindex){
3047             zindex = this.getParentZIndex();
3048         }
3049         return (zindex || 12000) + 5;
3050     },
3051
3052     // private
3053     initList : function(){
3054         if(!this.list){
3055             var cls = 'x-combo-list',
3056                 listParent = Ext.getDom(this.getListParent() || Ext.getBody());
3057
3058             this.list = new Ext.Layer({
3059                 parentEl: listParent,
3060                 shadow: this.shadow,
3061                 cls: [cls, this.listClass].join(' '),
3062                 constrain:false,
3063                 zindex: this.getZIndex(listParent)
3064             });
3065
3066             var lw = this.listWidth || Math.max(this.wrap.getWidth(), this.minListWidth);
3067             this.list.setSize(lw, 0);
3068             this.list.swallowEvent('mousewheel');
3069             this.assetHeight = 0;
3070             if(this.syncFont !== false){
3071                 this.list.setStyle('font-size', this.el.getStyle('font-size'));
3072             }
3073             if(this.title){
3074                 this.header = this.list.createChild({cls:cls+'-hd', html: this.title});
3075                 this.assetHeight += this.header.getHeight();
3076             }
3077
3078             this.innerList = this.list.createChild({cls:cls+'-inner'});
3079             this.mon(this.innerList, 'mouseover', this.onViewOver, this);
3080             this.mon(this.innerList, 'mousemove', this.onViewMove, this);
3081             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
3082
3083             if(this.pageSize){
3084                 this.footer = this.list.createChild({cls:cls+'-ft'});
3085                 this.pageTb = new Ext.PagingToolbar({
3086                     store: this.store,
3087                     pageSize: this.pageSize,
3088                     renderTo:this.footer
3089                 });
3090                 this.assetHeight += this.footer.getHeight();
3091             }
3092
3093             if(!this.tpl){
3094                 /**
3095                 * @cfg {String/Ext.XTemplate} tpl <p>The template string, or {@link Ext.XTemplate} instance to
3096                 * use to display each item in the dropdown list. The dropdown list is displayed in a
3097                 * DataView. See {@link #view}.</p>
3098                 * <p>The default template string is:</p><pre><code>
3099                   '&lt;tpl for=".">&lt;div class="x-combo-list-item">{' + this.displayField + '}&lt;/div>&lt;/tpl>'
3100                 * </code></pre>
3101                 * <p>Override the default value to create custom UI layouts for items in the list.
3102                 * For example:</p><pre><code>
3103                   '&lt;tpl for=".">&lt;div ext:qtip="{state}. {nick}" class="x-combo-list-item">{state}&lt;/div>&lt;/tpl>'
3104                 * </code></pre>
3105                 * <p>The template <b>must</b> contain one or more substitution parameters using field
3106                 * names from the Combo's</b> {@link #store Store}. In the example above an
3107                 * <pre>ext:qtip</pre> attribute is added to display other fields from the Store.</p>
3108                 * <p>To preserve the default visual look of list items, add the CSS class name
3109                 * <pre>x-combo-list-item</pre> to the template's container element.</p>
3110                 * <p>Also see {@link #itemSelector} for additional details.</p>
3111                 */
3112                 this.tpl = '<tpl for="."><div class="'+cls+'-item">{' + this.displayField + '}</div></tpl>';
3113                 /**
3114                  * @cfg {String} itemSelector
3115                  * <p>A simple CSS selector (e.g. div.some-class or span:first-child) that will be
3116                  * used to determine what nodes the {@link #view Ext.DataView} which handles the dropdown
3117                  * display will be working with.</p>
3118                  * <p><b>Note</b>: this setting is <b>required</b> if a custom XTemplate has been
3119                  * specified in {@link #tpl} which assigns a class other than <pre>'x-combo-list-item'</pre>
3120                  * to dropdown list items</b>
3121                  */
3122             }
3123
3124             /**
3125             * The {@link Ext.DataView DataView} used to display the ComboBox's options.
3126             * @type Ext.DataView
3127             */
3128             this.view = new Ext.DataView({
3129                 applyTo: this.innerList,
3130                 tpl: this.tpl,
3131                 singleSelect: true,
3132                 selectedClass: this.selectedClass,
3133                 itemSelector: this.itemSelector || '.' + cls + '-item',
3134                 emptyText: this.listEmptyText,
3135                 deferEmptyText: false
3136             });
3137
3138             this.mon(this.view, {
3139                 containerclick : this.onViewClick,
3140                 click : this.onViewClick,
3141                 scope :this
3142             });
3143
3144             this.bindStore(this.store, true);
3145
3146             if(this.resizable){
3147                 this.resizer = new Ext.Resizable(this.list,  {
3148                    pinned:true, handles:'se'
3149                 });
3150                 this.mon(this.resizer, 'resize', function(r, w, h){
3151                     this.maxHeight = h-this.handleHeight-this.list.getFrameWidth('tb')-this.assetHeight;
3152                     this.listWidth = w;
3153                     this.innerList.setWidth(w - this.list.getFrameWidth('lr'));
3154                     this.restrictHeight();
3155                 }, this);
3156
3157                 this[this.pageSize?'footer':'innerList'].setStyle('margin-bottom', this.handleHeight+'px');
3158             }
3159         }
3160     },
3161
3162     /**
3163      * <p>Returns the element used to house this ComboBox's pop-up list. Defaults to the document body.</p>
3164      * A custom implementation may be provided as a configuration option if the floating list needs to be rendered
3165      * to a different Element. An example might be rendering the list inside a Menu so that clicking
3166      * the list does not hide the Menu:<pre><code>
3167 var store = new Ext.data.ArrayStore({
3168     autoDestroy: true,
3169     fields: ['initials', 'fullname'],
3170     data : [
3171         ['FF', 'Fred Flintstone'],
3172         ['BR', 'Barney Rubble']
3173     ]
3174 });
3175
3176 var combo = new Ext.form.ComboBox({
3177     store: store,
3178     displayField: 'fullname',
3179     emptyText: 'Select a name...',
3180     forceSelection: true,
3181     getListParent: function() {
3182         return this.el.up('.x-menu');
3183     },
3184     iconCls: 'no-icon', //use iconCls if placing within menu to shift to right side of menu
3185     mode: 'local',
3186     selectOnFocus: true,
3187     triggerAction: 'all',
3188     typeAhead: true,
3189     width: 135
3190 });
3191
3192 var menu = new Ext.menu.Menu({
3193     id: 'mainMenu',
3194     items: [
3195         combo // A Field in a Menu
3196     ]
3197 });
3198 </code></pre>
3199      */
3200     getListParent : function() {
3201         return document.body;
3202     },
3203
3204     /**
3205      * Returns the store associated with this combo.
3206      * @return {Ext.data.Store} The store
3207      */
3208     getStore : function(){
3209         return this.store;
3210     },
3211
3212     // private
3213     bindStore : function(store, initial){
3214         if(this.store && !initial){
3215             if(this.store !== store && this.store.autoDestroy){
3216                 this.store.destroy();
3217             }else{
3218                 this.store.un('beforeload', this.onBeforeLoad, this);
3219                 this.store.un('load', this.onLoad, this);
3220                 this.store.un('exception', this.collapse, this);
3221             }
3222             if(!store){
3223                 this.store = null;
3224                 if(this.view){
3225                     this.view.bindStore(null);
3226                 }
3227                 if(this.pageTb){
3228                     this.pageTb.bindStore(null);
3229                 }
3230             }
3231         }
3232         if(store){
3233             if(!initial) {
3234                 this.lastQuery = null;
3235                 if(this.pageTb) {
3236                     this.pageTb.bindStore(store);
3237                 }
3238             }
3239
3240             this.store = Ext.StoreMgr.lookup(store);
3241             this.store.on({
3242                 scope: this,
3243                 beforeload: this.onBeforeLoad,
3244                 load: this.onLoad,
3245                 exception: this.collapse
3246             });
3247
3248             if(this.view){
3249                 this.view.bindStore(store);
3250             }
3251         }
3252     },
3253
3254     reset : function(){
3255         if(this.clearFilterOnReset && this.mode == 'local'){
3256             this.store.clearFilter();
3257         }
3258         Ext.form.ComboBox.superclass.reset.call(this);
3259     },
3260
3261     // private
3262     initEvents : function(){
3263         Ext.form.ComboBox.superclass.initEvents.call(this);
3264
3265         /**
3266          * @property keyNav
3267          * @type Ext.KeyNav
3268          * <p>A {@link Ext.KeyNav KeyNav} object which handles navigation keys for this ComboBox. This performs actions
3269          * based on keystrokes typed when the input field is focused.</p>
3270          * <p><b>After the ComboBox has been rendered</b>, you may override existing navigation key functionality,
3271          * or add your own based upon key names as specified in the {@link Ext.KeyNav KeyNav} class.</p>
3272          * <p>The function is executed in the scope (<code>this</code> reference of the ComboBox. Example:</p><pre><code>
3273 myCombo.keyNav.esc = function(e) {  // Override ESC handling function
3274     this.collapse();                // Standard behaviour of Ext's ComboBox.
3275     this.setValue(this.startValue); // We reset to starting value on ESC
3276 };
3277 myCombo.keyNav.tab = function() {   // Override TAB handling function
3278     this.onViewClick(false);        // Select the currently highlighted row
3279 };
3280 </code></pre>
3281          */
3282         this.keyNav = new Ext.KeyNav(this.el, {
3283             "up" : function(e){
3284                 this.inKeyMode = true;
3285                 this.selectPrev();
3286             },
3287
3288             "down" : function(e){
3289                 if(!this.isExpanded()){
3290                     this.onTriggerClick();
3291                 }else{
3292                     this.inKeyMode = true;
3293                     this.selectNext();
3294                 }
3295             },
3296
3297             "enter" : function(e){
3298                 this.onViewClick();
3299             },
3300
3301             "esc" : function(e){
3302                 this.collapse();
3303             },
3304
3305             "tab" : function(e){
3306                 if (this.forceSelection === true) {
3307                     this.collapse();
3308                 } else {
3309                     this.onViewClick(false);
3310                 }
3311                 return true;
3312             },
3313
3314             scope : this,
3315
3316             doRelay : function(e, h, hname){
3317                 if(hname == 'down' || this.scope.isExpanded()){
3318                     // this MUST be called before ComboBox#fireKey()
3319                     var relay = Ext.KeyNav.prototype.doRelay.apply(this, arguments);
3320                     if(!Ext.isIE && Ext.EventManager.useKeydown){
3321                         // call Combo#fireKey() for browsers which use keydown event (except IE)
3322                         this.scope.fireKey(e);
3323                     }
3324                     return relay;
3325                 }
3326                 return true;
3327             },
3328
3329             forceKeyDown : true,
3330             defaultEventAction: 'stopEvent'
3331         });
3332         this.queryDelay = Math.max(this.queryDelay || 10,
3333                 this.mode == 'local' ? 10 : 250);
3334         this.dqTask = new Ext.util.DelayedTask(this.initQuery, this);
3335         if(this.typeAhead){
3336             this.taTask = new Ext.util.DelayedTask(this.onTypeAhead, this);
3337         }
3338         if(!this.enableKeyEvents){
3339             this.mon(this.el, 'keyup', this.onKeyUp, this);
3340         }
3341     },
3342
3343
3344     // private
3345     onDestroy : function(){
3346         if (this.dqTask){
3347             this.dqTask.cancel();
3348             this.dqTask = null;
3349         }
3350         this.bindStore(null);
3351         Ext.destroy(
3352             this.resizer,
3353             this.view,
3354             this.pageTb,
3355             this.list
3356         );
3357         Ext.destroyMembers(this, 'hiddenField');
3358         Ext.form.ComboBox.superclass.onDestroy.call(this);
3359     },
3360
3361     // private
3362     fireKey : function(e){
3363         if (!this.isExpanded()) {
3364             Ext.form.ComboBox.superclass.fireKey.call(this, e);
3365         }
3366     },
3367
3368     // private
3369     onResize : function(w, h){
3370         Ext.form.ComboBox.superclass.onResize.apply(this, arguments);
3371         if(!isNaN(w) && this.isVisible() && this.list){
3372             this.doResize(w);
3373         }else{
3374             this.bufferSize = w;
3375         }
3376     },
3377
3378     doResize: function(w){
3379         if(!Ext.isDefined(this.listWidth)){
3380             var lw = Math.max(w, this.minListWidth);
3381             this.list.setWidth(lw);
3382             this.innerList.setWidth(lw - this.list.getFrameWidth('lr'));
3383         }
3384     },
3385
3386     // private
3387     onEnable : function(){
3388         Ext.form.ComboBox.superclass.onEnable.apply(this, arguments);
3389         if(this.hiddenField){
3390             this.hiddenField.disabled = false;
3391         }
3392     },
3393
3394     // private
3395     onDisable : function(){
3396         Ext.form.ComboBox.superclass.onDisable.apply(this, arguments);
3397         if(this.hiddenField){
3398             this.hiddenField.disabled = true;
3399         }
3400     },
3401
3402     // private
3403     onBeforeLoad : function(){
3404         if(!this.hasFocus){
3405             return;
3406         }
3407         this.innerList.update(this.loadingText ?
3408                '<div class="loading-indicator">'+this.loadingText+'</div>' : '');
3409         this.restrictHeight();
3410         this.selectedIndex = -1;
3411     },
3412
3413     // private
3414     onLoad : function(){
3415         if(!this.hasFocus){
3416             return;
3417         }
3418         if(this.store.getCount() > 0 || this.listEmptyText){
3419             this.expand();
3420             this.restrictHeight();
3421             if(this.lastQuery == this.allQuery){
3422                 if(this.editable){
3423                     this.el.dom.select();
3424                 }
3425
3426                 if(this.autoSelect !== false && !this.selectByValue(this.value, true)){
3427                     this.select(0, true);
3428                 }
3429             }else{
3430                 if(this.autoSelect !== false){
3431                     this.selectNext();
3432                 }
3433                 if(this.typeAhead && this.lastKey != Ext.EventObject.BACKSPACE && this.lastKey != Ext.EventObject.DELETE){
3434                     this.taTask.delay(this.typeAheadDelay);
3435                 }
3436             }
3437         }else{
3438             this.collapse();
3439         }
3440
3441     },
3442
3443     // private
3444     onTypeAhead : function(){
3445         if(this.store.getCount() > 0){
3446             var r = this.store.getAt(0);
3447             var newValue = r.data[this.displayField];
3448             var len = newValue.length;
3449             var selStart = this.getRawValue().length;
3450             if(selStart != len){
3451                 this.setRawValue(newValue);
3452                 this.selectText(selStart, newValue.length);
3453             }
3454         }
3455     },
3456
3457     // private
3458     assertValue  : function(){
3459         var val = this.getRawValue(),
3460             rec = this.findRecord(this.displayField, val);
3461
3462         if(!rec && this.forceSelection){
3463             if(val.length > 0 && val != this.emptyText){
3464                 this.el.dom.value = Ext.value(this.lastSelectionText, '');
3465                 this.applyEmptyText();
3466             }else{
3467                 this.clearValue();
3468             }
3469         }else{
3470             if(rec){
3471                 // onSelect may have already set the value and by doing so
3472                 // set the display field properly.  Let's not wipe out the
3473                 // valueField here by just sending the displayField.
3474                 if (val == rec.get(this.displayField) && this.value == rec.get(this.valueField)){
3475                     return;
3476                 }
3477                 val = rec.get(this.valueField || this.displayField);
3478             }
3479             this.setValue(val);
3480         }
3481     },
3482
3483     // private
3484     onSelect : function(record, index){
3485         if(this.fireEvent('beforeselect', this, record, index) !== false){
3486             this.setValue(record.data[this.valueField || this.displayField]);
3487             this.collapse();
3488             this.fireEvent('select', this, record, index);
3489         }
3490     },
3491
3492     // inherit docs
3493     getName: function(){
3494         var hf = this.hiddenField;
3495         return hf && hf.name ? hf.name : this.hiddenName || Ext.form.ComboBox.superclass.getName.call(this);
3496     },
3497
3498     /**
3499      * Returns the currently selected field value or empty string if no value is set.
3500      * @return {String} value The selected value
3501      */
3502     getValue : function(){
3503         if(this.valueField){
3504             return Ext.isDefined(this.value) ? this.value : '';
3505         }else{
3506             return Ext.form.ComboBox.superclass.getValue.call(this);
3507         }
3508     },
3509
3510     /**
3511      * Clears any text/value currently set in the field
3512      */
3513     clearValue : function(){
3514         if(this.hiddenField){
3515             this.hiddenField.value = '';
3516         }
3517         this.setRawValue('');
3518         this.lastSelectionText = '';
3519         this.applyEmptyText();
3520         this.value = '';
3521     },
3522
3523     /**
3524      * Sets the specified value into the field.  If the value finds a match, the corresponding record text
3525      * will be displayed in the field.  If the value does not match the data value of an existing item,
3526      * and the valueNotFoundText config option is defined, it will be displayed as the default field text.
3527      * Otherwise the field will be blank (although the value will still be set).
3528      * @param {String} value The value to match
3529      * @return {Ext.form.Field} this
3530      */
3531     setValue : function(v){
3532         var text = v;
3533         if(this.valueField){
3534             var r = this.findRecord(this.valueField, v);
3535             if(r){
3536                 text = r.data[this.displayField];
3537             }else if(Ext.isDefined(this.valueNotFoundText)){
3538                 text = this.valueNotFoundText;
3539             }
3540         }
3541         this.lastSelectionText = text;
3542         if(this.hiddenField){
3543             this.hiddenField.value = Ext.value(v, '');
3544         }
3545         Ext.form.ComboBox.superclass.setValue.call(this, text);
3546         this.value = v;
3547         return this;
3548     },
3549
3550     // private
3551     findRecord : function(prop, value){
3552         var record;
3553         if(this.store.getCount() > 0){
3554             this.store.each(function(r){
3555                 if(r.data[prop] == value){
3556                     record = r;
3557                     return false;
3558                 }
3559             });
3560         }
3561         return record;
3562     },
3563
3564     // private
3565     onViewMove : function(e, t){
3566         this.inKeyMode = false;
3567     },
3568
3569     // private
3570     onViewOver : function(e, t){
3571         if(this.inKeyMode){ // prevent key nav and mouse over conflicts
3572             return;
3573         }
3574         var item = this.view.findItemFromChild(t);
3575         if(item){
3576             var index = this.view.indexOf(item);
3577             this.select(index, false);
3578         }
3579     },
3580
3581     // private
3582     onViewClick : function(doFocus){
3583         var index = this.view.getSelectedIndexes()[0],
3584             s = this.store,
3585             r = s.getAt(index);
3586         if(r){
3587             this.onSelect(r, index);
3588         }else {
3589             this.collapse();
3590         }
3591         if(doFocus !== false){
3592             this.el.focus();
3593         }
3594     },
3595
3596
3597     // private
3598     restrictHeight : function(){
3599         this.innerList.dom.style.height = '';
3600         var inner = this.innerList.dom,
3601             pad = this.list.getFrameWidth('tb') + (this.resizable ? this.handleHeight : 0) + this.assetHeight,
3602             h = Math.max(inner.clientHeight, inner.offsetHeight, inner.scrollHeight),
3603             ha = this.getPosition()[1]-Ext.getBody().getScroll().top,
3604             hb = Ext.lib.Dom.getViewHeight()-ha-this.getSize().height,
3605             space = Math.max(ha, hb, this.minHeight || 0)-this.list.shadowOffset-pad-5;
3606
3607         h = Math.min(h, space, this.maxHeight);
3608
3609         this.innerList.setHeight(h);
3610         this.list.beginUpdate();
3611         this.list.setHeight(h+pad);
3612         this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
3613         this.list.endUpdate();
3614     },
3615
3616     /**
3617      * Returns true if the dropdown list is expanded, else false.
3618      */
3619     isExpanded : function(){
3620         return this.list && this.list.isVisible();
3621     },
3622
3623     /**
3624      * Select an item in the dropdown list by its data value. This function does NOT cause the select event to fire.
3625      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
3626      * @param {String} value The data value of the item to select
3627      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
3628      * selected item if it is not currently in view (defaults to true)
3629      * @return {Boolean} True if the value matched an item in the list, else false
3630      */
3631     selectByValue : function(v, scrollIntoView){
3632         if(!Ext.isEmpty(v, true)){
3633             var r = this.findRecord(this.valueField || this.displayField, v);
3634             if(r){
3635                 this.select(this.store.indexOf(r), scrollIntoView);
3636                 return true;
3637             }
3638         }
3639         return false;
3640     },
3641
3642     /**
3643      * Select an item in the dropdown list by its numeric index in the list. This function does NOT cause the select event to fire.
3644      * The store must be loaded and the list expanded for this function to work, otherwise use setValue.
3645      * @param {Number} index The zero-based index of the list item to select
3646      * @param {Boolean} scrollIntoView False to prevent the dropdown list from autoscrolling to display the
3647      * selected item if it is not currently in view (defaults to true)
3648      */
3649     select : function(index, scrollIntoView){
3650         this.selectedIndex = index;
3651         this.view.select(index);
3652         if(scrollIntoView !== false){
3653             var el = this.view.getNode(index);
3654             if(el){
3655                 this.innerList.scrollChildIntoView(el, false);
3656             }
3657         }
3658
3659     },
3660
3661     // private
3662     selectNext : function(){
3663         var ct = this.store.getCount();
3664         if(ct > 0){
3665             if(this.selectedIndex == -1){
3666                 this.select(0);
3667             }else if(this.selectedIndex < ct-1){
3668                 this.select(this.selectedIndex+1);
3669             }
3670         }
3671     },
3672
3673     // private
3674     selectPrev : function(){
3675         var ct = this.store.getCount();
3676         if(ct > 0){
3677             if(this.selectedIndex == -1){
3678                 this.select(0);
3679             }else if(this.selectedIndex !== 0){
3680                 this.select(this.selectedIndex-1);
3681             }
3682         }
3683     },
3684
3685     // private
3686     onKeyUp : function(e){
3687         var k = e.getKey();
3688         if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){
3689
3690             this.lastKey = k;
3691             this.dqTask.delay(this.queryDelay);
3692         }
3693         Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
3694     },
3695
3696     // private
3697     validateBlur : function(){
3698         return !this.list || !this.list.isVisible();
3699     },
3700
3701     // private
3702     initQuery : function(){
3703         this.doQuery(this.getRawValue());
3704     },
3705
3706     // private
3707     beforeBlur : function(){
3708         this.assertValue();
3709     },
3710
3711     // private
3712     postBlur  : function(){
3713         Ext.form.ComboBox.superclass.postBlur.call(this);
3714         this.collapse();
3715         this.inKeyMode = false;
3716     },
3717
3718     /**
3719      * Execute a query to filter the dropdown list.  Fires the {@link #beforequery} event prior to performing the
3720      * query allowing the query action to be canceled if needed.
3721      * @param {String} query The SQL query to execute
3722      * @param {Boolean} forceAll <tt>true</tt> to force the query to execute even if there are currently fewer
3723      * characters in the field than the minimum specified by the <tt>{@link #minChars}</tt> config option.  It
3724      * also clears any filter previously saved in the current store (defaults to <tt>false</tt>)
3725      */
3726     doQuery : function(q, forceAll){
3727         q = Ext.isEmpty(q) ? '' : q;
3728         var qe = {
3729             query: q,
3730             forceAll: forceAll,
3731             combo: this,
3732             cancel:false
3733         };
3734         if(this.fireEvent('beforequery', qe)===false || qe.cancel){
3735             return false;
3736         }
3737         q = qe.query;
3738         forceAll = qe.forceAll;
3739         if(forceAll === true || (q.length >= this.minChars)){
3740             if(this.lastQuery !== q){
3741                 this.lastQuery = q;
3742                 if(this.mode == 'local'){
3743                     this.selectedIndex = -1;
3744                     if(forceAll){
3745                         this.store.clearFilter();
3746                     }else{
3747                         this.store.filter(this.displayField, q);
3748                     }
3749                     this.onLoad();
3750                 }else{
3751                     this.store.baseParams[this.queryParam] = q;
3752                     this.store.load({
3753                         params: this.getParams(q)
3754                     });
3755                     this.expand();
3756                 }
3757             }else{
3758                 this.selectedIndex = -1;
3759                 this.onLoad();
3760             }
3761         }
3762     },
3763
3764     // private
3765     getParams : function(q){
3766         var params = {},
3767             paramNames = this.store.paramNames;
3768         if(this.pageSize){
3769             params[paramNames.start] = 0;
3770             params[paramNames.limit] = this.pageSize;
3771         }
3772         return params;
3773     },
3774
3775     /**
3776      * Hides the dropdown list if it is currently expanded. Fires the {@link #collapse} event on completion.
3777      */
3778     collapse : function(){
3779         if(!this.isExpanded()){
3780             return;
3781         }
3782         this.list.hide();
3783         Ext.getDoc().un('mousewheel', this.collapseIf, this);
3784         Ext.getDoc().un('mousedown', this.collapseIf, this);
3785         this.fireEvent('collapse', this);
3786     },
3787
3788     // private
3789     collapseIf : function(e){
3790         if(!this.isDestroyed && !e.within(this.wrap) && !e.within(this.list)){
3791             this.collapse();
3792         }
3793     },
3794
3795     /**
3796      * Expands the dropdown list if it is currently hidden. Fires the {@link #expand} event on completion.
3797      */
3798     expand : function(){
3799         if(this.isExpanded() || !this.hasFocus){
3800             return;
3801         }
3802
3803         if(this.title || this.pageSize){
3804             this.assetHeight = 0;
3805             if(this.title){
3806                 this.assetHeight += this.header.getHeight();
3807             }
3808             if(this.pageSize){
3809                 this.assetHeight += this.footer.getHeight();
3810             }
3811         }
3812
3813         if(this.bufferSize){
3814             this.doResize(this.bufferSize);
3815             delete this.bufferSize;
3816         }
3817         this.list.alignTo.apply(this.list, [this.el].concat(this.listAlign));
3818
3819         // zindex can change, re-check it and set it if necessary
3820         this.list.setZIndex(this.getZIndex());
3821         this.list.show();
3822         if(Ext.isGecko2){
3823             this.innerList.setOverflow('auto'); // necessary for FF 2.0/Mac
3824         }
3825         this.mon(Ext.getDoc(), {
3826             scope: this,
3827             mousewheel: this.collapseIf,
3828             mousedown: this.collapseIf
3829         });
3830         this.fireEvent('expand', this);
3831     },
3832
3833     /**
3834      * @method onTriggerClick
3835      * @hide
3836      */
3837     // private
3838     // Implements the default empty TriggerField.onTriggerClick function
3839     onTriggerClick : function(){
3840         if(this.readOnly || this.disabled){
3841             return;
3842         }
3843         if(this.isExpanded()){
3844             this.collapse();
3845             this.el.focus();
3846         }else {
3847             this.onFocus({});
3848             if(this.triggerAction == 'all') {
3849                 this.doQuery(this.allQuery, true);
3850             } else {
3851                 this.doQuery(this.getRawValue());
3852             }
3853             this.el.focus();
3854         }
3855     }
3856
3857     /**
3858      * @hide
3859      * @method autoSize
3860      */
3861     /**
3862      * @cfg {Boolean} grow @hide
3863      */
3864     /**
3865      * @cfg {Number} growMin @hide
3866      */
3867     /**
3868      * @cfg {Number} growMax @hide
3869      */
3870
3871 });
3872 Ext.reg('combo', Ext.form.ComboBox);
3873 /**
3874  * @class Ext.form.Checkbox
3875  * @extends Ext.form.Field
3876  * Single checkbox field.  Can be used as a direct replacement for traditional checkbox fields.
3877  * @constructor
3878  * Creates a new Checkbox
3879  * @param {Object} config Configuration options
3880  * @xtype checkbox
3881  */
3882 Ext.form.Checkbox = Ext.extend(Ext.form.Field,  {
3883     /**
3884      * @cfg {String} focusClass The CSS class to use when the checkbox receives focus (defaults to undefined)
3885      */
3886     focusClass : undefined,
3887     /**
3888      * @cfg {String} fieldClass The default CSS class for the checkbox (defaults to 'x-form-field')
3889      */
3890     fieldClass : 'x-form-field',
3891     /**
3892      * @cfg {Boolean} checked <tt>true</tt> if the checkbox should render initially checked (defaults to <tt>false</tt>)
3893      */
3894     checked : false,
3895     /**
3896      * @cfg {String} boxLabel The text that appears beside the checkbox
3897      */
3898     boxLabel: '&#160;',
3899     /**
3900      * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
3901      * {tag: 'input', type: 'checkbox', autocomplete: 'off'})
3902      */
3903     defaultAutoCreate : { tag: 'input', type: 'checkbox', autocomplete: 'off'},
3904     /**
3905      * @cfg {String} boxLabel The text that appears beside the checkbox
3906      */
3907     /**
3908      * @cfg {String} inputValue The value that should go into the generated input element's value attribute
3909      */
3910     /**
3911      * @cfg {Function} handler A function called when the {@link #checked} value changes (can be used instead of
3912      * handling the check event). The handler is passed the following parameters:
3913      * <div class="mdetail-params"><ul>
3914      * <li><b>checkbox</b> : Ext.form.Checkbox<div class="sub-desc">The Checkbox being toggled.</div></li>
3915      * <li><b>checked</b> : Boolean<div class="sub-desc">The new checked state of the checkbox.</div></li>
3916      * </ul></div>
3917      */
3918     /**
3919      * @cfg {Object} scope An object to use as the scope ('this' reference) of the {@link #handler} function
3920      * (defaults to this Checkbox).
3921      */
3922
3923     // private
3924     actionMode : 'wrap',
3925
3926         // private
3927     initComponent : function(){
3928         Ext.form.Checkbox.superclass.initComponent.call(this);
3929         this.addEvents(
3930             /**
3931              * @event check
3932              * Fires when the checkbox is checked or unchecked.
3933              * @param {Ext.form.Checkbox} this This checkbox
3934              * @param {Boolean} checked The new checked value
3935              */
3936             'check'
3937         );
3938     },
3939
3940     // private
3941     onResize : function(){
3942         Ext.form.Checkbox.superclass.onResize.apply(this, arguments);
3943         if(!this.boxLabel && !this.fieldLabel){
3944             this.el.alignTo(this.wrap, 'c-c');
3945         }
3946     },
3947
3948     // private
3949     initEvents : function(){
3950         Ext.form.Checkbox.superclass.initEvents.call(this);
3951         this.mon(this.el, {
3952             scope: this,
3953             click: this.onClick,
3954             change: this.onClick
3955         });
3956     },
3957
3958     /**
3959      * @hide
3960      * Overridden and disabled. The editor element does not support standard valid/invalid marking.
3961      * @method
3962      */
3963     markInvalid : Ext.emptyFn,
3964     /**
3965      * @hide
3966      * Overridden and disabled. The editor element does not support standard valid/invalid marking.
3967      * @method
3968      */
3969     clearInvalid : Ext.emptyFn,
3970
3971     // private
3972     onRender : function(ct, position){
3973         Ext.form.Checkbox.superclass.onRender.call(this, ct, position);
3974         if(this.inputValue !== undefined){
3975             this.el.dom.value = this.inputValue;
3976         }
3977         this.wrap = this.el.wrap({cls: 'x-form-check-wrap'});
3978         if(this.boxLabel){
3979             this.wrap.createChild({tag: 'label', htmlFor: this.el.id, cls: 'x-form-cb-label', html: this.boxLabel});
3980         }
3981         if(this.checked){
3982             this.setValue(true);
3983         }else{
3984             this.checked = this.el.dom.checked;
3985         }
3986         // Need to repaint for IE, otherwise positioning is broken
3987         if (Ext.isIE && !Ext.isStrict) {
3988             this.wrap.repaint();
3989         }
3990         this.resizeEl = this.positionEl = this.wrap;
3991     },
3992
3993     // private
3994     onDestroy : function(){
3995         Ext.destroy(this.wrap);
3996         Ext.form.Checkbox.superclass.onDestroy.call(this);
3997     },
3998
3999     // private
4000     initValue : function() {
4001         this.originalValue = this.getValue();
4002     },
4003
4004     /**
4005      * Returns the checked state of the checkbox.
4006      * @return {Boolean} True if checked, else false
4007      */
4008     getValue : function(){
4009         if(this.rendered){
4010             return this.el.dom.checked;
4011         }
4012         return this.checked;
4013     },
4014
4015         // private
4016     onClick : function(){
4017         if(this.el.dom.checked != this.checked){
4018             this.setValue(this.el.dom.checked);
4019         }
4020     },
4021
4022     /**
4023      * Sets the checked state of the checkbox, fires the 'check' event, and calls a
4024      * <code>{@link #handler}</code> (if configured).
4025      * @param {Boolean/String} checked The following values will check the checkbox:
4026      * <code>true, 'true', '1', or 'on'</code>. Any other value will uncheck the checkbox.
4027      * @return {Ext.form.Field} this
4028      */
4029     setValue : function(v){
4030         var checked = this.checked,
4031             inputVal = this.inputValue;
4032             
4033         this.checked = (v === true || v === 'true' || v == '1' || (inputVal ? v == inputVal : String(v).toLowerCase() == 'on'));
4034         if(this.rendered){
4035             this.el.dom.checked = this.checked;
4036             this.el.dom.defaultChecked = this.checked;
4037         }
4038         if(checked != this.checked){
4039             this.fireEvent('check', this, this.checked);
4040             if(this.handler){
4041                 this.handler.call(this.scope || this, this, this.checked);
4042             }
4043         }
4044         return this;
4045     }
4046 });
4047 Ext.reg('checkbox', Ext.form.Checkbox);
4048 /**
4049  * @class Ext.form.CheckboxGroup
4050  * @extends Ext.form.Field
4051  * <p>A grouping container for {@link Ext.form.Checkbox} controls.</p>
4052  * <p>Sample usage:</p>
4053  * <pre><code>
4054 var myCheckboxGroup = new Ext.form.CheckboxGroup({
4055     id:'myGroup',
4056     xtype: 'checkboxgroup',
4057     fieldLabel: 'Single Column',
4058     itemCls: 'x-check-group-alt',
4059     // Put all controls in a single column with width 100%
4060     columns: 1,
4061     items: [
4062         {boxLabel: 'Item 1', name: 'cb-col-1'},
4063         {boxLabel: 'Item 2', name: 'cb-col-2', checked: true},
4064         {boxLabel: 'Item 3', name: 'cb-col-3'}
4065     ]
4066 });
4067  * </code></pre>
4068  * @constructor
4069  * Creates a new CheckboxGroup
4070  * @param {Object} config Configuration options
4071  * @xtype checkboxgroup
4072  */
4073 Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
4074     /**
4075      * @cfg {Array} items An Array of {@link Ext.form.Checkbox Checkbox}es or Checkbox config objects
4076      * to arrange in the group.
4077      */
4078     /**
4079      * @cfg {String/Number/Array} columns Specifies the number of columns to use when displaying grouped
4080      * checkbox/radio controls using automatic layout.  This config can take several types of values:
4081      * <ul><li><b>'auto'</b> : <p class="sub-desc">The controls will be rendered one per column on one row and the width
4082      * of each column will be evenly distributed based on the width of the overall field container. This is the default.</p></li>
4083      * <li><b>Number</b> : <p class="sub-desc">If you specific a number (e.g., 3) that number of columns will be
4084      * created and the contained controls will be automatically distributed based on the value of {@link #vertical}.</p></li>
4085      * <li><b>Array</b> : Object<p class="sub-desc">You can also specify an array of column widths, mixing integer
4086      * (fixed width) and float (percentage width) values as needed (e.g., [100, .25, .75]). Any integer values will
4087      * be rendered first, then any float values will be calculated as a percentage of the remaining space. Float
4088      * values do not have to add up to 1 (100%) although if you want the controls to take up the entire field
4089      * container you should do so.</p></li></ul>
4090      */
4091     columns : 'auto',
4092     /**
4093      * @cfg {Boolean} vertical True to distribute contained controls across columns, completely filling each column
4094      * top to bottom before starting on the next column.  The number of controls in each column will be automatically
4095      * calculated to keep columns as even as possible.  The default value is false, so that controls will be added
4096      * to columns one at a time, completely filling each row left to right before starting on the next row.
4097      */
4098     vertical : false,
4099     /**
4100      * @cfg {Boolean} allowBlank False to validate that at least one item in the group is checked (defaults to true).
4101      * If no items are selected at validation time, {@link @blankText} will be used as the error text.
4102      */
4103     allowBlank : true,
4104     /**
4105      * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails (defaults to "You must
4106      * select at least one item in this group")
4107      */
4108     blankText : "You must select at least one item in this group",
4109
4110     // private
4111     defaultType : 'checkbox',
4112
4113     // private
4114     groupCls : 'x-form-check-group',
4115
4116     // private
4117     initComponent: function(){
4118         this.addEvents(
4119             /**
4120              * @event change
4121              * Fires when the state of a child checkbox changes.
4122              * @param {Ext.form.CheckboxGroup} this
4123              * @param {Array} checked An array containing the checked boxes.
4124              */
4125             'change'
4126         );
4127         this.on('change', this.validate, this);
4128         Ext.form.CheckboxGroup.superclass.initComponent.call(this);
4129     },
4130
4131     // private
4132     onRender : function(ct, position){
4133         if(!this.el){
4134             var panelCfg = {
4135                 autoEl: {
4136                     id: this.id
4137                 },
4138                 cls: this.groupCls,
4139                 layout: 'column',
4140                 renderTo: ct,
4141                 bufferResize: false // Default this to false, since it doesn't really have a proper ownerCt.
4142             };
4143             var colCfg = {
4144                 xtype: 'container',
4145                 defaultType: this.defaultType,
4146                 layout: 'form',
4147                 defaults: {
4148                     hideLabel: true,
4149                     anchor: '100%'
4150                 }
4151             };
4152
4153             if(this.items[0].items){
4154
4155                 // The container has standard ColumnLayout configs, so pass them in directly
4156
4157                 Ext.apply(panelCfg, {
4158                     layoutConfig: {columns: this.items.length},
4159                     defaults: this.defaults,
4160                     items: this.items
4161                 });
4162                 for(var i=0, len=this.items.length; i<len; i++){
4163                     Ext.applyIf(this.items[i], colCfg);
4164                 }
4165
4166             }else{
4167
4168                 // The container has field item configs, so we have to generate the column
4169                 // panels first then move the items into the columns as needed.
4170
4171                 var numCols, cols = [];
4172
4173                 if(typeof this.columns == 'string'){ // 'auto' so create a col per item
4174                     this.columns = this.items.length;
4175                 }
4176                 if(!Ext.isArray(this.columns)){
4177                     var cs = [];
4178                     for(var i=0; i<this.columns; i++){
4179                         cs.push((100/this.columns)*.01); // distribute by even %
4180                     }
4181                     this.columns = cs;
4182                 }
4183
4184                 numCols = this.columns.length;
4185
4186                 // Generate the column configs with the correct width setting
4187                 for(var i=0; i<numCols; i++){
4188                     var cc = Ext.apply({items:[]}, colCfg);
4189                     cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
4190                     if(this.defaults){
4191                         cc.defaults = Ext.apply(cc.defaults || {}, this.defaults);
4192                     }
4193                     cols.push(cc);
4194                 };
4195
4196                 // Distribute the original items into the columns
4197                 if(this.vertical){
4198                     var rows = Math.ceil(this.items.length / numCols), ri = 0;
4199                     for(var i=0, len=this.items.length; i<len; i++){
4200                         if(i>0 && i%rows==0){
4201                             ri++;
4202                         }
4203                         if(this.items[i].fieldLabel){
4204                             this.items[i].hideLabel = false;
4205                         }
4206                         cols[ri].items.push(this.items[i]);
4207                     };
4208                 }else{
4209                     for(var i=0, len=this.items.length; i<len; i++){
4210                         var ci = i % numCols;
4211                         if(this.items[i].fieldLabel){
4212                             this.items[i].hideLabel = false;
4213                         }
4214                         cols[ci].items.push(this.items[i]);
4215                     };
4216                 }
4217
4218                 Ext.apply(panelCfg, {
4219                     layoutConfig: {columns: numCols},
4220                     items: cols
4221                 });
4222             }
4223
4224             this.panel = new Ext.Container(panelCfg);
4225             this.panel.ownerCt = this;
4226             this.el = this.panel.getEl();
4227
4228             if(this.forId && this.itemCls){
4229                 var l = this.el.up(this.itemCls).child('label', true);
4230                 if(l){
4231                     l.setAttribute('htmlFor', this.forId);
4232                 }
4233             }
4234
4235             var fields = this.panel.findBy(function(c){
4236                 return c.isFormField;
4237             }, this);
4238
4239             this.items = new Ext.util.MixedCollection();
4240             this.items.addAll(fields);
4241         }
4242         Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
4243     },
4244
4245     initValue : function(){
4246         if(this.value){
4247             this.setValue.apply(this, this.buffered ? this.value : [this.value]);
4248             delete this.buffered;
4249             delete this.value;
4250         }
4251     },
4252
4253     afterRender : function(){
4254         Ext.form.CheckboxGroup.superclass.afterRender.call(this);
4255         this.eachItem(function(item){
4256             item.on('check', this.fireChecked, this);
4257             item.inGroup = true;
4258         });
4259     },
4260
4261     // private
4262     doLayout: function(){
4263         //ugly method required to layout hidden items
4264         if(this.rendered){
4265             this.panel.forceLayout = this.ownerCt.forceLayout;
4266             this.panel.doLayout();
4267         }
4268     },
4269
4270     // private
4271     fireChecked: function(){
4272         var arr = [];
4273         this.eachItem(function(item){
4274             if(item.checked){
4275                 arr.push(item);
4276             }
4277         });
4278         this.fireEvent('change', this, arr);
4279     },
4280     
4281     /**
4282      * Runs CheckboxGroup's validations and returns an array of any errors. The only error by default
4283      * is if allowBlank is set to true and no items are checked.
4284      * @return {Array} Array of all validation errors
4285      */
4286     getErrors: function() {
4287         var errors = Ext.form.CheckboxGroup.superclass.getErrors.apply(this, arguments);
4288         
4289         if (!this.allowBlank) {
4290             var blank = true;
4291             
4292             this.eachItem(function(f){
4293                 if (f.checked) {
4294                     return (blank = false);
4295                 }
4296             });
4297             
4298             if (blank) errors.push(this.blankText);
4299         }
4300         
4301         return errors;
4302     },
4303
4304     // private
4305     isDirty: function(){
4306         //override the behaviour to check sub items.
4307         if (this.disabled || !this.rendered) {
4308             return false;
4309         }
4310
4311         var dirty = false;
4312         
4313         this.eachItem(function(item){
4314             if(item.isDirty()){
4315                 dirty = true;
4316                 return false;
4317             }
4318         });
4319         
4320         return dirty;
4321     },
4322
4323     // private
4324     setReadOnly : function(readOnly){
4325         if(this.rendered){
4326             this.eachItem(function(item){
4327                 item.setReadOnly(readOnly);
4328             });
4329         }
4330         this.readOnly = readOnly;
4331     },
4332
4333     // private
4334     onDisable : function(){
4335         this.eachItem(function(item){
4336             item.disable();
4337         });
4338     },
4339
4340     // private
4341     onEnable : function(){
4342         this.eachItem(function(item){
4343             item.enable();
4344         });
4345     },
4346
4347     // private
4348     onResize : function(w, h){
4349         this.panel.setSize(w, h);
4350         this.panel.doLayout();
4351     },
4352
4353     // inherit docs from Field
4354     reset : function(){
4355         if (this.originalValue) {
4356             // Clear all items
4357             this.eachItem(function(c){
4358                 if(c.setValue){
4359                     c.setValue(false);
4360                     c.originalValue = c.getValue();
4361                 }
4362             });
4363             // Set items stored in originalValue, ugly - set a flag to reset the originalValue
4364             // during the horrible onSetValue.  This will allow trackResetOnLoad to function.
4365             this.resetOriginal = true;
4366             this.setValue(this.originalValue);
4367             delete this.resetOriginal;
4368         } else {
4369             this.eachItem(function(c){
4370                 if(c.reset){
4371                     c.reset();
4372                 }
4373             });
4374         }
4375         // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
4376         // Important because reset is being called on both the group and the individual items.
4377         (function() {
4378             this.clearInvalid();
4379         }).defer(50, this);
4380     },
4381
4382     /**
4383      * {@link Ext.form.Checkbox#setValue Set the value(s)} of an item or items
4384      * in the group. Examples illustrating how this method may be called:
4385      * <pre><code>
4386 // call with name and value
4387 myCheckboxGroup.setValue('cb-col-1', true);
4388 // call with an array of boolean values
4389 myCheckboxGroup.setValue([true, false, false]);
4390 // call with an object literal specifying item:value pairs
4391 myCheckboxGroup.setValue({
4392     'cb-col-2': false,
4393     'cb-col-3': true
4394 });
4395 // use comma separated string to set items with name to true (checked)
4396 myCheckboxGroup.setValue('cb-col-1,cb-col-3');
4397      * </code></pre>
4398      * See {@link Ext.form.Checkbox#setValue} for additional information.
4399      * @param {Mixed} id The checkbox to check, or as described by example shown.
4400      * @param {Boolean} value (optional) The value to set the item.
4401      * @return {Ext.form.CheckboxGroup} this
4402      */
4403     setValue: function(){
4404         if(this.rendered){
4405             this.onSetValue.apply(this, arguments);
4406         }else{
4407             this.buffered = true;
4408             this.value = arguments;
4409         }
4410         return this;
4411     },
4412
4413     /**
4414      * @private
4415      * Sets the values of one or more of the items within the CheckboxGroup
4416      * @param {String|Array|Object} id Can take multiple forms. Can be optionally:
4417      * <ul>
4418      *   <li>An ID string to be used with a second argument</li>
4419      *   <li>An array of the form ['some', 'list', 'of', 'ids', 'to', 'mark', 'checked']</li>
4420      *   <li>An array in the form [true, true, false, true, false] etc, where each item relates to the check status of
4421      *       the checkbox at the same index</li>
4422      *   <li>An object containing ids of the checkboxes as keys and check values as properties</li>
4423      * </ul>
4424      * @param {String} value The value to set the field to if the first argument was a string
4425      */
4426     onSetValue: function(id, value){
4427         if(arguments.length == 1){
4428             if(Ext.isArray(id)){
4429                 Ext.each(id, function(val, idx){
4430                     if (Ext.isObject(val) && val.setValue){ // array of checkbox components to be checked
4431                         val.setValue(true);
4432                         if (this.resetOriginal === true) {
4433                             val.originalValue = val.getValue();
4434                         }
4435                     } else { // an array of boolean values
4436                         var item = this.items.itemAt(idx);
4437                         if(item){
4438                             item.setValue(val);
4439                         }
4440                     }
4441                 }, this);
4442             }else if(Ext.isObject(id)){
4443                 // set of name/value pairs
4444                 for(var i in id){
4445                     var f = this.getBox(i);
4446                     if(f){
4447                         f.setValue(id[i]);
4448                     }
4449                 }
4450             }else{
4451                 this.setValueForItem(id);
4452             }
4453         }else{
4454             var f = this.getBox(id);
4455             if(f){
4456                 f.setValue(value);
4457             }
4458         }
4459     },
4460
4461     // private
4462     beforeDestroy: function(){
4463         Ext.destroy(this.panel);
4464         if (!this.rendered) {
4465             Ext.destroy(this.items);
4466         }
4467         Ext.form.CheckboxGroup.superclass.beforeDestroy.call(this);
4468
4469     },
4470
4471     setValueForItem : function(val){
4472         val = String(val).split(',');
4473         this.eachItem(function(item){
4474             if(val.indexOf(item.inputValue)> -1){
4475                 item.setValue(true);
4476             }
4477         });
4478     },
4479
4480     // private
4481     getBox : function(id){
4482         var box = null;
4483         this.eachItem(function(f){
4484             if(id == f || f.dataIndex == id || f.id == id || f.getName() == id){
4485                 box = f;
4486                 return false;
4487             }
4488         });
4489         return box;
4490     },
4491
4492     /**
4493      * Gets an array of the selected {@link Ext.form.Checkbox} in the group.
4494      * @return {Array} An array of the selected checkboxes.
4495      */
4496     getValue : function(){
4497         var out = [];
4498         this.eachItem(function(item){
4499             if(item.checked){
4500                 out.push(item);
4501             }
4502         });
4503         return out;
4504     },
4505
4506     /**
4507      * @private
4508      * Convenience function which passes the given function to every item in the composite
4509      * @param {Function} fn The function to call
4510      * @param {Object} scope Optional scope object
4511      */
4512     eachItem: function(fn, scope) {
4513         if(this.items && this.items.each){
4514             this.items.each(fn, scope || this);
4515         }
4516     },
4517
4518     /**
4519      * @cfg {String} name
4520      * @hide
4521      */
4522
4523     /**
4524      * @method getRawValue
4525      * @hide
4526      */
4527     getRawValue : Ext.emptyFn,
4528
4529     /**
4530      * @method setRawValue
4531      * @hide
4532      */
4533     setRawValue : Ext.emptyFn
4534
4535 });
4536
4537 Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);
4538 /**
4539  * @class Ext.form.CompositeField
4540  * @extends Ext.form.Field
4541  * Composite field allowing a number of form Fields to be rendered on the same row. The fields are rendered
4542  * using an hbox layout internally, so all of the normal HBox layout config items are available. Example usage:
4543  * <pre>
4544 {
4545     xtype: 'compositefield',
4546     labelWidth: 120
4547     items: [
4548         {
4549             xtype     : 'textfield',
4550             fieldLabel: 'Title',
4551             width     : 20
4552         },
4553         {
4554             xtype     : 'textfield',
4555             fieldLabel: 'First',
4556             flex      : 1
4557         },
4558         {
4559             xtype     : 'textfield',
4560             fieldLabel: 'Last',
4561             flex      : 1
4562         }
4563     ]
4564 }
4565  * </pre>
4566  * In the example above the composite's fieldLabel will be set to 'Title, First, Last' as it groups the fieldLabels
4567  * of each of its children. This can be overridden by setting a fieldLabel on the compositefield itself:
4568  * <pre>
4569 {
4570     xtype: 'compositefield',
4571     fieldLabel: 'Custom label',
4572     items: [...]
4573 }
4574  * </pre>
4575  * Any Ext.form.* component can be placed inside a composite field.
4576  */
4577 Ext.form.CompositeField = Ext.extend(Ext.form.Field, {
4578
4579     /**
4580      * @property defaultMargins
4581      * @type String
4582      * The margins to apply by default to each field in the composite
4583      */
4584     defaultMargins: '0 5 0 0',
4585
4586     /**
4587      * @property skipLastItemMargin
4588      * @type Boolean
4589      * If true, the defaultMargins are not applied to the last item in the composite field set (defaults to true)
4590      */
4591     skipLastItemMargin: true,
4592
4593     /**
4594      * @property isComposite
4595      * @type Boolean
4596      * Signifies that this is a Composite field
4597      */
4598     isComposite: true,
4599
4600     /**
4601      * @property combineErrors
4602      * @type Boolean
4603      * True to combine errors from the individual fields into a single error message at the CompositeField level (defaults to true)
4604      */
4605     combineErrors: true,
4606     
4607     /**
4608      * @cfg {String} labelConnector The string to use when joining segments of the built label together (defaults to ', ')
4609      */
4610     labelConnector: ', ',
4611     
4612     /**
4613      * @cfg {Object} defaults Any default properties to assign to the child fields.
4614      */
4615
4616     //inherit docs
4617     //Builds the composite field label
4618     initComponent: function() {
4619         var labels = [],
4620             items  = this.items,
4621             item;
4622
4623         for (var i=0, j = items.length; i < j; i++) {
4624             item = items[i];
4625
4626             labels.push(item.fieldLabel);
4627
4628             //apply any defaults
4629             Ext.applyIf(item, this.defaults);
4630
4631             //apply default margins to each item except the last
4632             if (!(i == j - 1 && this.skipLastItemMargin)) {
4633                 Ext.applyIf(item, {margins: this.defaultMargins});
4634             }
4635         }
4636
4637         this.fieldLabel = this.fieldLabel || this.buildLabel(labels);
4638
4639         /**
4640          * @property fieldErrors
4641          * @type Ext.util.MixedCollection
4642          * MixedCollection of current errors on the Composite's subfields. This is used internally to track when
4643          * to show and hide error messages at the Composite level. Listeners are attached to the MixedCollection's
4644          * add, remove and replace events to update the error icon in the UI as errors are added or removed.
4645          */
4646         this.fieldErrors = new Ext.util.MixedCollection(true, function(item) {
4647             return item.field;
4648         });
4649
4650         this.fieldErrors.on({
4651             scope  : this,
4652             add    : this.updateInvalidMark,
4653             remove : this.updateInvalidMark,
4654             replace: this.updateInvalidMark
4655         });
4656
4657         Ext.form.CompositeField.superclass.initComponent.apply(this, arguments);
4658         
4659         this.innerCt = new Ext.Container({
4660             layout  : 'hbox',
4661             items   : this.items,
4662             cls     : 'x-form-composite',
4663             defaultMargins: '0 3 0 0'
4664         });
4665         
4666         var fields = this.innerCt.findBy(function(c) {
4667             return c.isFormField;
4668         }, this);
4669
4670         /**
4671          * @property items
4672          * @type Ext.util.MixedCollection
4673          * Internal collection of all of the subfields in this Composite
4674          */
4675         this.items = new Ext.util.MixedCollection();
4676         this.items.addAll(fields);
4677         
4678     },
4679
4680     /**
4681      * @private
4682      * Creates an internal container using hbox and renders the fields to it
4683      */
4684     onRender: function(ct, position) {
4685         if (!this.el) {
4686             /**
4687              * @property innerCt
4688              * @type Ext.Container
4689              * A container configured with hbox layout which is responsible for laying out the subfields
4690              */
4691             var innerCt = this.innerCt;
4692             innerCt.render(ct);
4693
4694             this.el = innerCt.getEl();
4695
4696             //if we're combining subfield errors into a single message, override the markInvalid and clearInvalid
4697             //methods of each subfield and show them at the Composite level instead
4698             if (this.combineErrors) {
4699                 this.eachItem(function(field) {
4700                     Ext.apply(field, {
4701                         markInvalid : this.onFieldMarkInvalid.createDelegate(this, [field], 0),
4702                         clearInvalid: this.onFieldClearInvalid.createDelegate(this, [field], 0)
4703                     });
4704                 });
4705             }
4706
4707             //set the label 'for' to the first item
4708             var l = this.el.parent().parent().child('label', true);
4709             if (l) {
4710                 l.setAttribute('for', this.items.items[0].id);
4711             }
4712         }
4713
4714         Ext.form.CompositeField.superclass.onRender.apply(this, arguments);
4715     },
4716
4717     /**
4718      * Called if combineErrors is true and a subfield's markInvalid method is called.
4719      * By default this just adds the subfield's error to the internal fieldErrors MixedCollection
4720      * @param {Ext.form.Field} field The field that was marked invalid
4721      * @param {String} message The error message
4722      */
4723     onFieldMarkInvalid: function(field, message) {
4724         var name  = field.getName(),
4725             error = {
4726                 field: name, 
4727                 errorName: field.fieldLabel || name,
4728                 error: message
4729             };
4730
4731         this.fieldErrors.replace(name, error);
4732
4733         field.el.addClass(field.invalidClass);
4734     },
4735
4736     /**
4737      * Called if combineErrors is true and a subfield's clearInvalid method is called.
4738      * By default this just updates the internal fieldErrors MixedCollection.
4739      * @param {Ext.form.Field} field The field that was marked invalid
4740      */
4741     onFieldClearInvalid: function(field) {
4742         this.fieldErrors.removeKey(field.getName());
4743
4744         field.el.removeClass(field.invalidClass);
4745     },
4746
4747     /**
4748      * @private
4749      * Called after a subfield is marked valid or invalid, this checks to see if any of the subfields are
4750      * currently invalid. If any subfields are invalid it builds a combined error message marks the composite
4751      * invalid, otherwise clearInvalid is called
4752      */
4753     updateInvalidMark: function() {
4754         var ieStrict = Ext.isIE6 && Ext.isStrict;
4755
4756         if (this.fieldErrors.length == 0) {
4757             this.clearInvalid();
4758
4759             //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
4760             if (ieStrict) {
4761                 this.clearInvalid.defer(50, this);
4762             }
4763         } else {
4764             var message = this.buildCombinedErrorMessage(this.fieldErrors.items);
4765
4766             this.sortErrors();
4767             this.markInvalid(message);
4768
4769             //IE6 in strict mode has a layout bug when using 'under' as the error message target. This fixes it
4770             if (ieStrict) {
4771                 this.markInvalid(message);
4772             }
4773         }
4774     },
4775
4776     /**
4777      * Performs validation checks on each subfield and returns false if any of them fail validation.
4778      * @return {Boolean} False if any subfield failed validation
4779      */
4780     validateValue: function() {
4781         var valid = true;
4782
4783         this.eachItem(function(field) {
4784             if (!field.isValid()) valid = false;
4785         });
4786
4787         return valid;
4788     },
4789
4790     /**
4791      * Takes an object containing error messages for contained fields, returning a combined error
4792      * string (defaults to just placing each item on a new line). This can be overridden to provide
4793      * custom combined error message handling.
4794      * @param {Array} errors Array of errors in format: [{field: 'title', error: 'some error'}]
4795      * @return {String} The combined error message
4796      */
4797     buildCombinedErrorMessage: function(errors) {
4798         var combined = [],
4799             error;
4800
4801         for (var i = 0, j = errors.length; i < j; i++) {
4802             error = errors[i];
4803
4804             combined.push(String.format("{0}: {1}", error.errorName, error.error));
4805         }
4806
4807         return combined.join("<br />");
4808     },
4809
4810     /**
4811      * Sorts the internal fieldErrors MixedCollection by the order in which the fields are defined.
4812      * This is called before displaying errors to ensure that the errors are presented in the expected order.
4813      * This function can be overridden to provide a custom sorting order if needed.
4814      */
4815     sortErrors: function() {
4816         var fields = this.items;
4817
4818         this.fieldErrors.sort("ASC", function(a, b) {
4819             var findByName = function(key) {
4820                 return function(field) {
4821                     return field.getName() == key;
4822                 };
4823             };
4824
4825             var aIndex = fields.findIndexBy(findByName(a.field)),
4826                 bIndex = fields.findIndexBy(findByName(b.field));
4827
4828             return aIndex < bIndex ? -1 : 1;
4829         });
4830     },
4831
4832     /**
4833      * Resets each field in the composite to their previous value
4834      */
4835     reset: function() {
4836         this.eachItem(function(item) {
4837             item.reset();
4838         });
4839
4840         // Defer the clearInvalid so if BaseForm's collection is being iterated it will be called AFTER it is complete.
4841         // Important because reset is being called on both the group and the individual items.
4842         (function() {
4843             this.clearInvalid();
4844         }).defer(50, this);
4845     },
4846     
4847     /**
4848      * Calls clearInvalid on all child fields. This is a convenience function and should not often need to be called
4849      * as fields usually take care of clearing themselves
4850      */
4851     clearInvalidChildren: function() {
4852         this.eachItem(function(item) {
4853             item.clearInvalid();
4854         });
4855     },
4856
4857     /**
4858      * Builds a label string from an array of subfield labels.
4859      * By default this just joins the labels together with a comma
4860      * @param {Array} segments Array of each of the labels in the composite field's subfields
4861      * @return {String} The built label
4862      */
4863     buildLabel: function(segments) {
4864         return Ext.clean(segments).join(this.labelConnector);
4865     },
4866
4867     /**
4868      * Checks each field in the composite and returns true if any is dirty
4869      * @return {Boolean} True if any field is dirty
4870      */
4871     isDirty: function(){
4872         //override the behaviour to check sub items.
4873         if (this.disabled || !this.rendered) {
4874             return false;
4875         }
4876
4877         var dirty = false;
4878         this.eachItem(function(item){
4879             if(item.isDirty()){
4880                 dirty = true;
4881                 return false;
4882             }
4883         });
4884         return dirty;
4885     },
4886
4887     /**
4888      * @private
4889      * Convenience function which passes the given function to every item in the composite
4890      * @param {Function} fn The function to call
4891      * @param {Object} scope Optional scope object
4892      */
4893     eachItem: function(fn, scope) {
4894         if(this.items && this.items.each){
4895             this.items.each(fn, scope || this);
4896         }
4897     },
4898
4899     /**
4900      * @private
4901      * Passes the resize call through to the inner panel
4902      */
4903     onResize: function(adjWidth, adjHeight, rawWidth, rawHeight) {
4904         var innerCt = this.innerCt;
4905
4906         if (this.rendered && innerCt.rendered) {
4907             innerCt.setSize(adjWidth, adjHeight);
4908         }
4909
4910         Ext.form.CompositeField.superclass.onResize.apply(this, arguments);
4911     },
4912
4913     /**
4914      * @private
4915      * Forces the internal container to be laid out again
4916      */
4917     doLayout: function(shallow, force) {
4918         if (this.rendered) {
4919             var innerCt = this.innerCt;
4920
4921             innerCt.forceLayout = this.ownerCt.forceLayout;
4922             innerCt.doLayout(shallow, force);
4923         }
4924     },
4925
4926     /**
4927      * @private
4928      */
4929     beforeDestroy: function(){
4930         Ext.destroy(this.innerCt);
4931
4932         Ext.form.CompositeField.superclass.beforeDestroy.call(this);
4933     },
4934
4935     //override the behaviour to check sub items.
4936     setReadOnly : function(readOnly) {
4937         if (readOnly == undefined) {
4938             readOnly = true;
4939         }
4940         readOnly = !!readOnly;
4941
4942         if(this.rendered){
4943             this.eachItem(function(item){
4944                 item.setReadOnly(readOnly);
4945             });
4946         }
4947         this.readOnly = readOnly;
4948     },
4949
4950     onShow : function() {
4951         Ext.form.CompositeField.superclass.onShow.call(this);
4952         this.doLayout();
4953     },
4954
4955     //override the behaviour to check sub items.
4956     onDisable : function(){
4957         this.eachItem(function(item){
4958             item.disable();
4959         });
4960     },
4961
4962     //override the behaviour to check sub items.
4963     onEnable : function(){
4964         this.eachItem(function(item){
4965             item.enable();
4966         });
4967     }
4968 });
4969
4970 Ext.reg('compositefield', Ext.form.CompositeField);/**
4971  * @class Ext.form.Radio
4972  * @extends Ext.form.Checkbox
4973  * Single radio field.  Same as Checkbox, but provided as a convenience for automatically setting the input type.
4974  * Radio grouping is handled automatically by the browser if you give each radio in a group the same name.
4975  * @constructor
4976  * Creates a new Radio
4977  * @param {Object} config Configuration options
4978  * @xtype radio
4979  */
4980 Ext.form.Radio = Ext.extend(Ext.form.Checkbox, {
4981     inputType: 'radio',
4982
4983     /**
4984      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
4985      * @method
4986      */
4987     markInvalid : Ext.emptyFn,
4988     /**
4989      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
4990      * @method
4991      */
4992     clearInvalid : Ext.emptyFn,
4993
4994     /**
4995      * If this radio is part of a group, it will return the selected value
4996      * @return {String}
4997      */
4998     getGroupValue : function(){
4999         var p = this.el.up('form') || Ext.getBody();
5000         var c = p.child('input[name='+this.el.dom.name+']:checked', true);
5001         return c ? c.value : null;
5002     },
5003
5004     /**
5005      * Sets either the checked/unchecked status of this Radio, or, if a string value
5006      * is passed, checks a sibling Radio of the same name whose value is the value specified.
5007      * @param value {String/Boolean} Checked value, or the value of the sibling radio button to check.
5008      * @return {Ext.form.Field} this
5009      */
5010     setValue : function(v){
5011         var checkEl,
5012             els,
5013             radio;
5014         if (typeof v == 'boolean') {
5015             Ext.form.Radio.superclass.setValue.call(this, v);
5016         } else if (this.rendered) {
5017             checkEl = this.getCheckEl();
5018             radio = checkEl.child('input[name=' + this.el.dom.name + '][value=' + v + ']', true);
5019             if(radio){
5020                 Ext.getCmp(radio.id).setValue(true);
5021             }
5022         }
5023         if(this.rendered && this.checked){
5024             checkEl = checkEl || this.getCheckEl();
5025             els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
5026                         els.each(function(el){
5027                                 if(el.dom.id != this.id){
5028                                         Ext.getCmp(el.dom.id).setValue(false);
5029                                 }
5030                         }, this);
5031         }
5032         return this;
5033     },
5034
5035     // private
5036     getCheckEl: function(){
5037         if(this.inGroup){
5038             return this.el.up('.x-form-radio-group');
5039         }
5040         return this.el.up('form') || Ext.getBody();
5041     }
5042 });
5043 Ext.reg('radio', Ext.form.Radio);
5044 /**
5045  * @class Ext.form.RadioGroup
5046  * @extends Ext.form.CheckboxGroup
5047  * A grouping container for {@link Ext.form.Radio} controls.
5048  * @constructor
5049  * Creates a new RadioGroup
5050  * @param {Object} config Configuration options
5051  * @xtype radiogroup
5052  */
5053 Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, {
5054     /**
5055      * @cfg {Array} items An Array of {@link Ext.form.Radio Radio}s or Radio config objects
5056      * to arrange in the group.
5057      */
5058     /**
5059      * @cfg {Boolean} allowBlank True to allow every item in the group to be blank (defaults to true).
5060      * If allowBlank = false and no items are selected at validation time, {@link @blankText} will
5061      * be used as the error text.
5062      */
5063     allowBlank : true,
5064     /**
5065      * @cfg {String} blankText Error text to display if the {@link #allowBlank} validation fails
5066      * (defaults to 'You must select one item in this group')
5067      */
5068     blankText : 'You must select one item in this group',
5069     
5070     // private
5071     defaultType : 'radio',
5072     
5073     // private
5074     groupCls : 'x-form-radio-group',
5075     
5076     /**
5077      * @event change
5078      * Fires when the state of a child radio changes.
5079      * @param {Ext.form.RadioGroup} this
5080      * @param {Ext.form.Radio} checked The checked radio
5081      */
5082     
5083     /**
5084      * Gets the selected {@link Ext.form.Radio} in the group, if it exists.
5085      * @return {Ext.form.Radio} The selected radio.
5086      */
5087     getValue : function(){
5088         var out = null;
5089         this.eachItem(function(item){
5090             if(item.checked){
5091                 out = item;
5092                 return false;
5093             }
5094         });
5095         return out;
5096     },
5097     
5098     /**
5099      * Sets the checked radio in the group.
5100      * @param {String/Ext.form.Radio} id The radio to check.
5101      * @param {Boolean} value The value to set the radio.
5102      * @return {Ext.form.RadioGroup} this
5103      */
5104     onSetValue : function(id, value){
5105         if(arguments.length > 1){
5106             var f = this.getBox(id);
5107             if(f){
5108                 f.setValue(value);
5109                 if(f.checked){
5110                     this.eachItem(function(item){
5111                         if (item !== f){
5112                             item.setValue(false);
5113                         }
5114                     });
5115                 }
5116             }
5117         }else{
5118             this.setValueForItem(id);
5119         }
5120     },
5121     
5122     setValueForItem : function(val){
5123         val = String(val).split(',')[0];
5124         this.eachItem(function(item){
5125             item.setValue(val == item.inputValue);
5126         });
5127     },
5128     
5129     // private
5130     fireChecked : function(){
5131         if(!this.checkTask){
5132             this.checkTask = new Ext.util.DelayedTask(this.bufferChecked, this);
5133         }
5134         this.checkTask.delay(10);
5135     },
5136     
5137     // private
5138     bufferChecked : function(){
5139         var out = null;
5140         this.eachItem(function(item){
5141             if(item.checked){
5142                 out = item;
5143                 return false;
5144             }
5145         });
5146         this.fireEvent('change', this, out);
5147     },
5148     
5149     onDestroy : function(){
5150         if(this.checkTask){
5151             this.checkTask.cancel();
5152             this.checkTask = null;
5153         }
5154         Ext.form.RadioGroup.superclass.onDestroy.call(this);
5155     }
5156
5157 });
5158
5159 Ext.reg('radiogroup', Ext.form.RadioGroup);
5160 /**
5161  * @class Ext.form.Hidden
5162  * @extends Ext.form.Field
5163  * A basic hidden field for storing hidden values in forms that need to be passed in the form submit.
5164  * @constructor
5165  * Create a new Hidden field.
5166  * @param {Object} config Configuration options
5167  * @xtype hidden
5168  */
5169 Ext.form.Hidden = Ext.extend(Ext.form.Field, {
5170     // private
5171     inputType : 'hidden',
5172     
5173     shouldLayout: false,
5174
5175     // private
5176     onRender : function(){
5177         Ext.form.Hidden.superclass.onRender.apply(this, arguments);
5178     },
5179
5180     // private
5181     initEvents : function(){
5182         this.originalValue = this.getValue();
5183     },
5184
5185     // These are all private overrides
5186     setSize : Ext.emptyFn,
5187     setWidth : Ext.emptyFn,
5188     setHeight : Ext.emptyFn,
5189     setPosition : Ext.emptyFn,
5190     setPagePosition : Ext.emptyFn,
5191     markInvalid : Ext.emptyFn,
5192     clearInvalid : Ext.emptyFn
5193 });
5194 Ext.reg('hidden', Ext.form.Hidden);/**
5195  * @class Ext.form.BasicForm
5196  * @extends Ext.util.Observable
5197  * <p>Encapsulates the DOM &lt;form> element at the heart of the {@link Ext.form.FormPanel FormPanel} class, and provides
5198  * input field management, validation, submission, and form loading services.</p>
5199  * <p>By default, Ext Forms are submitted through Ajax, using an instance of {@link Ext.form.Action.Submit}.
5200  * To enable normal browser submission of an Ext Form, use the {@link #standardSubmit} config option.</p>
5201  * <p><b><u>File Uploads</u></b></p>
5202  * <p>{@link #fileUpload File uploads} are not performed using Ajax submission, that
5203  * is they are <b>not</b> performed using XMLHttpRequests. Instead the form is submitted in the standard
5204  * manner with the DOM <tt>&lt;form></tt> element temporarily modified to have its
5205  * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
5206  * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
5207  * but removed after the return data has been gathered.</p>
5208  * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
5209  * server is using JSON to send the return object, then the
5210  * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
5211  * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
5212  * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
5213  * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
5214  * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
5215  * is created containing a <tt>responseText</tt> property in order to conform to the
5216  * requirements of event handlers and callbacks.</p>
5217  * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
5218  * and some server technologies (notably JEE) may require some custom processing in order to
5219  * retrieve parameter names and parameter values from the packet content.</p>
5220  * @constructor
5221  * @param {Mixed} el The form element or its id
5222  * @param {Object} config Configuration options
5223  */
5224 Ext.form.BasicForm = Ext.extend(Ext.util.Observable, {
5225
5226     constructor: function(el, config){
5227         Ext.apply(this, config);
5228         if(Ext.isString(this.paramOrder)){
5229             this.paramOrder = this.paramOrder.split(/[\s,|]/);
5230         }
5231         /**
5232          * A {@link Ext.util.MixedCollection MixedCollection} containing all the Ext.form.Fields in this form.
5233          * @type MixedCollection
5234          * @property items
5235          */
5236         this.items = new Ext.util.MixedCollection(false, function(o){
5237             return o.getItemId();
5238         });
5239         this.addEvents(
5240             /**
5241              * @event beforeaction
5242              * Fires before any action is performed. Return false to cancel the action.
5243              * @param {Form} this
5244              * @param {Action} action The {@link Ext.form.Action} to be performed
5245              */
5246             'beforeaction',
5247             /**
5248              * @event actionfailed
5249              * Fires when an action fails.
5250              * @param {Form} this
5251              * @param {Action} action The {@link Ext.form.Action} that failed
5252              */
5253             'actionfailed',
5254             /**
5255              * @event actioncomplete
5256              * Fires when an action is completed.
5257              * @param {Form} this
5258              * @param {Action} action The {@link Ext.form.Action} that completed
5259              */
5260             'actioncomplete'
5261         );
5262
5263         if(el){
5264             this.initEl(el);
5265         }
5266         Ext.form.BasicForm.superclass.constructor.call(this);
5267     },
5268
5269     /**
5270      * @cfg {String} method
5271      * The request method to use (GET or POST) for form actions if one isn't supplied in the action options.
5272      */
5273     /**
5274      * @cfg {DataReader} reader
5275      * An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to read
5276      * data when executing 'load' actions. This is optional as there is built-in
5277      * support for processing JSON.  For additional information on using an XMLReader
5278      * see the example provided in examples/form/xml-form.html.
5279      */
5280     /**
5281      * @cfg {DataReader} errorReader
5282      * <p>An Ext.data.DataReader (e.g. {@link Ext.data.XmlReader}) to be used to
5283      * read field error messages returned from 'submit' actions. This is optional
5284      * as there is built-in support for processing JSON.</p>
5285      * <p>The Records which provide messages for the invalid Fields must use the
5286      * Field name (or id) as the Record ID, and must contain a field called 'msg'
5287      * which contains the error message.</p>
5288      * <p>The errorReader does not have to be a full-blown implementation of a
5289      * DataReader. It simply needs to implement a <tt>read(xhr)</tt> function
5290      * which returns an Array of Records in an object with the following
5291      * structure:</p><pre><code>
5292 {
5293     records: recordArray
5294 }
5295 </code></pre>
5296      */
5297     /**
5298      * @cfg {String} url
5299      * The URL to use for form actions if one isn't supplied in the
5300      * <code>{@link #doAction doAction} options</code>.
5301      */
5302     /**
5303      * @cfg {Boolean} fileUpload
5304      * Set to true if this form is a file upload.
5305      * <p>File uploads are not performed using normal 'Ajax' techniques, that is they are <b>not</b>
5306      * performed using XMLHttpRequests. Instead the form is submitted in the standard manner with the
5307      * DOM <tt>&lt;form></tt> element temporarily modified to have its
5308      * <a href="http://www.w3.org/TR/REC-html40/present/frames.html#adef-target">target</a> set to refer
5309      * to a dynamically generated, hidden <tt>&lt;iframe></tt> which is inserted into the document
5310      * but removed after the return data has been gathered.</p>
5311      * <p>The server response is parsed by the browser to create the document for the IFRAME. If the
5312      * server is using JSON to send the return object, then the
5313      * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17">Content-Type</a> header
5314      * must be set to "text/html" in order to tell the browser to insert the text unchanged into the document body.</p>
5315      * <p>Characters which are significant to an HTML parser must be sent as HTML entities, so encode
5316      * "&lt;" as "&amp;lt;", "&amp;" as "&amp;amp;" etc.</p>
5317      * <p>The response text is retrieved from the document, and a fake XMLHttpRequest object
5318      * is created containing a <tt>responseText</tt> property in order to conform to the
5319      * requirements of event handlers and callbacks.</p>
5320      * <p>Be aware that file upload packets are sent with the content type <a href="http://www.faqs.org/rfcs/rfc2388.html">multipart/form</a>
5321      * and some server technologies (notably JEE) may require some custom processing in order to
5322      * retrieve parameter names and parameter values from the packet content.</p>
5323      */
5324     /**
5325      * @cfg {Object} baseParams
5326      * <p>Parameters to pass with all requests. e.g. baseParams: {id: '123', foo: 'bar'}.</p>
5327      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
5328      */
5329     /**
5330      * @cfg {Number} timeout Timeout for form actions in seconds (default is 30 seconds).
5331      */
5332     timeout: 30,
5333
5334     /**
5335      * @cfg {Object} api (Optional) If specified load and submit actions will be handled
5336      * with {@link Ext.form.Action.DirectLoad} and {@link Ext.form.Action.DirectSubmit}.
5337      * Methods which have been imported by Ext.Direct can be specified here to load and submit
5338      * forms.
5339      * Such as the following:<pre><code>
5340 api: {
5341     load: App.ss.MyProfile.load,
5342     submit: App.ss.MyProfile.submit
5343 }
5344 </code></pre>
5345      * <p>Load actions can use <code>{@link #paramOrder}</code> or <code>{@link #paramsAsHash}</code>
5346      * to customize how the load method is invoked.
5347      * Submit actions will always use a standard form submit. The formHandler configuration must
5348      * be set on the associated server-side method which has been imported by Ext.Direct</p>
5349      */
5350
5351     /**
5352      * @cfg {Array/String} paramOrder <p>A list of params to be executed server side.
5353      * Defaults to <tt>undefined</tt>. Only used for the <code>{@link #api}</code>
5354      * <code>load</code> configuration.</p>
5355      * <br><p>Specify the params in the order in which they must be executed on the
5356      * server-side as either (1) an Array of String values, or (2) a String of params
5357      * delimited by either whitespace, comma, or pipe. For example,
5358      * any of the following would be acceptable:</p><pre><code>
5359 paramOrder: ['param1','param2','param3']
5360 paramOrder: 'param1 param2 param3'
5361 paramOrder: 'param1,param2,param3'
5362 paramOrder: 'param1|param2|param'
5363      </code></pre>
5364      */
5365     paramOrder: undefined,
5366
5367     /**
5368      * @cfg {Boolean} paramsAsHash Only used for the <code>{@link #api}</code>
5369      * <code>load</code> configuration. Send parameters as a collection of named
5370      * arguments (defaults to <tt>false</tt>). Providing a
5371      * <tt>{@link #paramOrder}</tt> nullifies this configuration.
5372      */
5373     paramsAsHash: false,
5374
5375     /**
5376      * @cfg {String} waitTitle
5377      * The default title to show for the waiting message box (defaults to <tt>'Please Wait...'</tt>)
5378      */
5379     waitTitle: 'Please Wait...',
5380
5381     // private
5382     activeAction : null,
5383
5384     /**
5385      * @cfg {Boolean} trackResetOnLoad If set to <tt>true</tt>, {@link #reset}() resets to the last loaded
5386      * or {@link #setValues}() data instead of when the form was first created.  Defaults to <tt>false</tt>.
5387      */
5388     trackResetOnLoad : false,
5389
5390     /**
5391      * @cfg {Boolean} standardSubmit
5392      * <p>If set to <tt>true</tt>, standard HTML form submits are used instead
5393      * of XHR (Ajax) style form submissions. Defaults to <tt>false</tt>.</p>
5394      * <br><p><b>Note:</b> When using <code>standardSubmit</code>, the
5395      * <code>options</code> to <code>{@link #submit}</code> are ignored because
5396      * Ext's Ajax infrastracture is bypassed. To pass extra parameters (e.g.
5397      * <code>baseParams</code> and <code>params</code>), utilize hidden fields
5398      * to submit extra data, for example:</p>
5399      * <pre><code>
5400 new Ext.FormPanel({
5401     standardSubmit: true,
5402     baseParams: {
5403         foo: 'bar'
5404     },
5405     {@link url}: 'myProcess.php',
5406     items: [{
5407         xtype: 'textfield',
5408         name: 'userName'
5409     }],
5410     buttons: [{
5411         text: 'Save',
5412         handler: function(){
5413             var fp = this.ownerCt.ownerCt,
5414                 form = fp.getForm();
5415             if (form.isValid()) {
5416                 // check if there are baseParams and if
5417                 // hiddent items have been added already
5418                 if (fp.baseParams && !fp.paramsAdded) {
5419                     // add hidden items for all baseParams
5420                     for (i in fp.baseParams) {
5421                         fp.add({
5422                             xtype: 'hidden',
5423                             name: i,
5424                             value: fp.baseParams[i]
5425                         });
5426                     }
5427                     fp.doLayout();
5428                     // set a custom flag to prevent re-adding
5429                     fp.paramsAdded = true;
5430                 }
5431                 form.{@link #submit}();
5432             }
5433         }
5434     }]
5435 });
5436      * </code></pre>
5437      */
5438     /**
5439      * By default wait messages are displayed with Ext.MessageBox.wait. You can target a specific
5440      * element by passing it or its id or mask the form itself by passing in true.
5441      * @type Mixed
5442      * @property waitMsgTarget
5443      */
5444
5445     // private
5446     initEl : function(el){
5447         this.el = Ext.get(el);
5448         this.id = this.el.id || Ext.id();
5449         if(!this.standardSubmit){
5450             this.el.on('submit', this.onSubmit, this);
5451         }
5452         this.el.addClass('x-form');
5453     },
5454
5455     /**
5456      * Get the HTML form Element
5457      * @return Ext.Element
5458      */
5459     getEl: function(){
5460         return this.el;
5461     },
5462
5463     // private
5464     onSubmit : function(e){
5465         e.stopEvent();
5466     },
5467
5468     /**
5469      * Destroys this object.
5470      * @private
5471      * @param {Boolean} bound true if the object is bound to a form panel. If this is the case
5472      * the FormPanel will take care of destroying certain things, so we're just doubling up.
5473      */
5474     destroy: function(bound){
5475         if(bound !== true){
5476             this.items.each(function(f){
5477                 Ext.destroy(f);
5478             });
5479             Ext.destroy(this.el);
5480         }
5481         this.items.clear();
5482         this.purgeListeners();
5483     },
5484
5485     /**
5486      * Returns true if client-side validation on the form is successful.
5487      * @return Boolean
5488      */
5489     isValid : function(){
5490         var valid = true;
5491         this.items.each(function(f){
5492            if(!f.validate()){
5493                valid = false;
5494            }
5495         });
5496         return valid;
5497     },
5498
5499     /**
5500      * <p>Returns true if any fields in this form have changed from their original values.</p>
5501      * <p>Note that if this BasicForm was configured with {@link #trackResetOnLoad} then the
5502      * Fields' <i>original values</i> are updated when the values are loaded by {@link #setValues}
5503      * or {@link #loadRecord}.</p>
5504      * @return Boolean
5505      */
5506     isDirty : function(){
5507         var dirty = false;
5508         this.items.each(function(f){
5509            if(f.isDirty()){
5510                dirty = true;
5511                return false;
5512            }
5513         });
5514         return dirty;
5515     },
5516
5517     /**
5518      * Performs a predefined action ({@link Ext.form.Action.Submit} or
5519      * {@link Ext.form.Action.Load}) or a custom extension of {@link Ext.form.Action}
5520      * to perform application-specific processing.
5521      * @param {String/Object} actionName The name of the predefined action type,
5522      * or instance of {@link Ext.form.Action} to perform.
5523      * @param {Object} options (optional) The options to pass to the {@link Ext.form.Action}.
5524      * All of the config options listed below are supported by both the
5525      * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
5526      * actions unless otherwise noted (custom actions could also accept
5527      * other config options):<ul>
5528      *
5529      * <li><b>url</b> : String<div class="sub-desc">The url for the action (defaults
5530      * to the form's {@link #url}.)</div></li>
5531      *
5532      * <li><b>method</b> : String<div class="sub-desc">The form method to use (defaults
5533      * to the form's method, or POST if not defined)</div></li>
5534      *
5535      * <li><b>params</b> : String/Object<div class="sub-desc"><p>The params to pass
5536      * (defaults to the form's baseParams, or none if not defined)</p>
5537      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
5538      *
5539      * <li><b>headers</b> : Object<div class="sub-desc">Request headers to set for the action
5540      * (defaults to the form's default headers)</div></li>
5541      *
5542      * <li><b>success</b> : Function<div class="sub-desc">The callback that will
5543      * be invoked after a successful response (see top of
5544      * {@link Ext.form.Action.Submit submit} and {@link Ext.form.Action.Load load}
5545      * for a description of what constitutes a successful response).
5546      * The function is passed the following parameters:<ul>
5547      * <li><tt>form</tt> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
5548      * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
5549      * <div class="sub-desc">The action object contains these properties of interest:<ul>
5550      * <li><tt>{@link Ext.form.Action#response response}</tt></li>
5551      * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
5552      * <li><tt>{@link Ext.form.Action#type type}</tt></li>
5553      * </ul></div></li></ul></div></li>
5554      *
5555      * <li><b>failure</b> : Function<div class="sub-desc">The callback that will be invoked after a
5556      * failed transaction attempt. The function is passed the following parameters:<ul>
5557      * <li><tt>form</tt> : The {@link Ext.form.BasicForm} that requested the action.</li>
5558      * <li><tt>action</tt> : The {@link Ext.form.Action Action} object which performed the operation.
5559      * <div class="sub-desc">The action object contains these properties of interest:<ul>
5560      * <li><tt>{@link Ext.form.Action#failureType failureType}</tt></li>
5561      * <li><tt>{@link Ext.form.Action#response response}</tt></li>
5562      * <li><tt>{@link Ext.form.Action#result result}</tt> : interrogate for custom postprocessing</li>
5563      * <li><tt>{@link Ext.form.Action#type type}</tt></li>
5564      * </ul></div></li></ul></div></li>
5565      *
5566      * <li><b>scope</b> : Object<div class="sub-desc">The scope in which to call the
5567      * callback functions (The <tt>this</tt> reference for the callback functions).</div></li>
5568      *
5569      * <li><b>clientValidation</b> : Boolean<div class="sub-desc">Submit Action only.
5570      * Determines whether a Form's fields are validated in a final call to
5571      * {@link Ext.form.BasicForm#isValid isValid} prior to submission. Set to <tt>false</tt>
5572      * to prevent this. If undefined, pre-submission field validation is performed.</div></li></ul>
5573      *
5574      * @return {BasicForm} this
5575      */
5576     doAction : function(action, options){
5577         if(Ext.isString(action)){
5578             action = new Ext.form.Action.ACTION_TYPES[action](this, options);
5579         }
5580         if(this.fireEvent('beforeaction', this, action) !== false){
5581             this.beforeAction(action);
5582             action.run.defer(100, action);
5583         }
5584         return this;
5585     },
5586
5587     /**
5588      * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Submit submit action}.
5589      * @param {Object} options The options to pass to the action (see {@link #doAction} for details).<br>
5590      * <p><b>Note:</b> this is ignored when using the {@link #standardSubmit} option.</p>
5591      * <p>The following code:</p><pre><code>
5592 myFormPanel.getForm().submit({
5593     clientValidation: true,
5594     url: 'updateConsignment.php',
5595     params: {
5596         newStatus: 'delivered'
5597     },
5598     success: function(form, action) {
5599        Ext.Msg.alert('Success', action.result.msg);
5600     },
5601     failure: function(form, action) {
5602         switch (action.failureType) {
5603             case Ext.form.Action.CLIENT_INVALID:
5604                 Ext.Msg.alert('Failure', 'Form fields may not be submitted with invalid values');
5605                 break;
5606             case Ext.form.Action.CONNECT_FAILURE:
5607                 Ext.Msg.alert('Failure', 'Ajax communication failed');
5608                 break;
5609             case Ext.form.Action.SERVER_INVALID:
5610                Ext.Msg.alert('Failure', action.result.msg);
5611        }
5612     }
5613 });
5614 </code></pre>
5615      * would process the following server response for a successful submission:<pre><code>
5616 {
5617     "success":true, // note this is Boolean, not string
5618     "msg":"Consignment updated"
5619 }
5620 </code></pre>
5621      * and the following server response for a failed submission:<pre><code>
5622 {
5623     "success":false, // note this is Boolean, not string
5624     "msg":"You do not have permission to perform this operation"
5625 }
5626 </code></pre>
5627      * @return {BasicForm} this
5628      */
5629     submit : function(options){
5630         options = options || {};
5631         if(this.standardSubmit){
5632             var v = options.clientValidation === false || this.isValid();
5633             if(v){
5634                 var el = this.el.dom;
5635                 if(this.url && Ext.isEmpty(el.action)){
5636                     el.action = this.url;
5637                 }
5638                 el.submit();
5639             }
5640             return v;
5641         }
5642         var submitAction = String.format('{0}submit', this.api ? 'direct' : '');
5643         this.doAction(submitAction, options);
5644         return this;
5645     },
5646
5647     /**
5648      * Shortcut to {@link #doAction do} a {@link Ext.form.Action.Load load action}.
5649      * @param {Object} options The options to pass to the action (see {@link #doAction} for details)
5650      * @return {BasicForm} this
5651      */
5652     load : function(options){
5653         var loadAction = String.format('{0}load', this.api ? 'direct' : '');
5654         this.doAction(loadAction, options);
5655         return this;
5656     },
5657
5658     /**
5659      * Persists the values in this form into the passed {@link Ext.data.Record} object in a beginEdit/endEdit block.
5660      * @param {Record} record The record to edit
5661      * @return {BasicForm} this
5662      */
5663     updateRecord : function(record){
5664         record.beginEdit();
5665         var fs = record.fields;
5666         fs.each(function(f){
5667             var field = this.findField(f.name);
5668             if(field){
5669                 var value = field.getValue();
5670                 if ( value.getGroupValue ) {
5671                     value = value.getGroupValue();
5672                 } else if ( field.eachItem ) {
5673                     value = [];
5674                     field.eachItem(function(item){
5675                         value.push(item.getValue());
5676                     });
5677                 }
5678                 record.set(f.name, value);
5679             }
5680         }, this);
5681         record.endEdit();
5682         return this;
5683     },
5684
5685     /**
5686      * Loads an {@link Ext.data.Record} into this form by calling {@link #setValues} with the
5687      * {@link Ext.data.Record#data record data}.
5688      * See also {@link #trackResetOnLoad}.
5689      * @param {Record} record The record to load
5690      * @return {BasicForm} this
5691      */
5692     loadRecord : function(record){
5693         this.setValues(record.data);
5694         return this;
5695     },
5696
5697     // private
5698     beforeAction : function(action){
5699         // Call HtmlEditor's syncValue before actions
5700         this.items.each(function(f){
5701             if(f.isFormField && f.syncValue){
5702                 f.syncValue();
5703             }
5704         });
5705         var o = action.options;
5706         if(o.waitMsg){
5707             if(this.waitMsgTarget === true){
5708                 this.el.mask(o.waitMsg, 'x-mask-loading');
5709             }else if(this.waitMsgTarget){
5710                 this.waitMsgTarget = Ext.get(this.waitMsgTarget);
5711                 this.waitMsgTarget.mask(o.waitMsg, 'x-mask-loading');
5712             }else{
5713                 Ext.MessageBox.wait(o.waitMsg, o.waitTitle || this.waitTitle);
5714             }
5715         }
5716     },
5717
5718     // private
5719     afterAction : function(action, success){
5720         this.activeAction = null;
5721         var o = action.options;
5722         if(o.waitMsg){
5723             if(this.waitMsgTarget === true){
5724                 this.el.unmask();
5725             }else if(this.waitMsgTarget){
5726                 this.waitMsgTarget.unmask();
5727             }else{
5728                 Ext.MessageBox.updateProgress(1);
5729                 Ext.MessageBox.hide();
5730             }
5731         }
5732         if(success){
5733             if(o.reset){
5734                 this.reset();
5735             }
5736             Ext.callback(o.success, o.scope, [this, action]);
5737             this.fireEvent('actioncomplete', this, action);
5738         }else{
5739             Ext.callback(o.failure, o.scope, [this, action]);
5740             this.fireEvent('actionfailed', this, action);
5741         }
5742     },
5743
5744     /**
5745      * Find a {@link Ext.form.Field} in this form.
5746      * @param {String} id The value to search for (specify either a {@link Ext.Component#id id},
5747      * {@link Ext.grid.Column#dataIndex dataIndex}, {@link Ext.form.Field#getName name or hiddenName}).
5748      * @return Field
5749      */
5750     findField : function(id) {
5751         var field = this.items.get(id);
5752
5753         if (!Ext.isObject(field)) {
5754             //searches for the field corresponding to the given id. Used recursively for composite fields
5755             var findMatchingField = function(f) {
5756                 if (f.isFormField) {
5757                     if (f.dataIndex == id || f.id == id || f.getName() == id) {
5758                         field = f;
5759                         return false;
5760                     } else if (f.isComposite) {
5761                         return f.items.each(findMatchingField);
5762                     } else if (f instanceof Ext.form.CheckboxGroup && f.rendered) {
5763                         return f.eachItem(findMatchingField);
5764                     }
5765                 }
5766             };
5767
5768             this.items.each(findMatchingField);
5769         }
5770         return field || null;
5771     },
5772
5773
5774     /**
5775      * Mark fields in this form invalid in bulk.
5776      * @param {Array/Object} errors Either an array in the form [{id:'fieldId', msg:'The message'},...] or an object hash of {id: msg, id2: msg2}
5777      * @return {BasicForm} this
5778      */
5779     markInvalid : function(errors){
5780         if (Ext.isArray(errors)) {
5781             for(var i = 0, len = errors.length; i < len; i++){
5782                 var fieldError = errors[i];
5783                 var f = this.findField(fieldError.id);
5784                 if(f){
5785                     f.markInvalid(fieldError.msg);
5786                 }
5787             }
5788         } else {
5789             var field, id;
5790             for(id in errors){
5791                 if(!Ext.isFunction(errors[id]) && (field = this.findField(id))){
5792                     field.markInvalid(errors[id]);
5793                 }
5794             }
5795         }
5796
5797         return this;
5798     },
5799
5800     /**
5801      * Set values for fields in this form in bulk.
5802      * @param {Array/Object} values Either an array in the form:<pre><code>
5803 [{id:'clientName', value:'Fred. Olsen Lines'},
5804  {id:'portOfLoading', value:'FXT'},
5805  {id:'portOfDischarge', value:'OSL'} ]</code></pre>
5806      * or an object hash of the form:<pre><code>
5807 {
5808     clientName: 'Fred. Olsen Lines',
5809     portOfLoading: 'FXT',
5810     portOfDischarge: 'OSL'
5811 }</code></pre>
5812      * @return {BasicForm} this
5813      */
5814     setValues : function(values){
5815         if(Ext.isArray(values)){ // array of objects
5816             for(var i = 0, len = values.length; i < len; i++){
5817                 var v = values[i];
5818                 var f = this.findField(v.id);
5819                 if(f){
5820                     f.setValue(v.value);
5821                     if(this.trackResetOnLoad){
5822                         f.originalValue = f.getValue();
5823                     }
5824                 }
5825             }
5826         }else{ // object hash
5827             var field, id;
5828             for(id in values){
5829                 if(!Ext.isFunction(values[id]) && (field = this.findField(id))){
5830                     field.setValue(values[id]);
5831                     if(this.trackResetOnLoad){
5832                         field.originalValue = field.getValue();
5833                     }
5834                 }
5835             }
5836         }
5837         return this;
5838     },
5839
5840     /**
5841      * <p>Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit.
5842      * If multiple fields exist with the same name they are returned as an array.</p>
5843      * <p><b>Note:</b> The values are collected from all enabled HTML input elements within the form, <u>not</u> from
5844      * the Ext Field objects. This means that all returned values are Strings (or Arrays of Strings) and that the
5845      * value can potentially be the emptyText of a field.</p>
5846      * @param {Boolean} asString (optional) Pass true to return the values as a string. (defaults to false, returning an Object)
5847      * @return {String/Object}
5848      */
5849     getValues : function(asString){
5850         var fs = Ext.lib.Ajax.serializeForm(this.el.dom);
5851         if(asString === true){
5852             return fs;
5853         }
5854         return Ext.urlDecode(fs);
5855     },
5856
5857     /**
5858      * Retrieves the fields in the form as a set of key/value pairs, using the {@link Ext.form.Field#getValue getValue()} method.
5859      * If multiple fields exist with the same name they are returned as an array.
5860      * @param {Boolean} dirtyOnly (optional) True to return only fields that are dirty.
5861      * @return {Object} The values in the form
5862      */
5863     getFieldValues : function(dirtyOnly){
5864         var o = {},
5865             n,
5866             key,
5867             val;
5868         this.items.each(function(f) {
5869             if (!f.disabled && (dirtyOnly !== true || f.isDirty())) {
5870                 n = f.getName();
5871                 key = o[n];
5872                 val = f.getValue();
5873
5874                 if(Ext.isDefined(key)){
5875                     if(Ext.isArray(key)){
5876                         o[n].push(val);
5877                     }else{
5878                         o[n] = [key, val];
5879                     }
5880                 }else{
5881                     o[n] = val;
5882                 }
5883             }
5884         });
5885         return o;
5886     },
5887
5888     /**
5889      * Clears all invalid messages in this form.
5890      * @return {BasicForm} this
5891      */
5892     clearInvalid : function(){
5893         this.items.each(function(f){
5894            f.clearInvalid();
5895         });
5896         return this;
5897     },
5898
5899     /**
5900      * Resets this form.
5901      * @return {BasicForm} this
5902      */
5903     reset : function(){
5904         this.items.each(function(f){
5905             f.reset();
5906         });
5907         return this;
5908     },
5909
5910     /**
5911      * Add Ext.form Components to this form's Collection. This does not result in rendering of
5912      * the passed Component, it just enables the form to validate Fields, and distribute values to
5913      * Fields.
5914      * <p><b>You will not usually call this function. In order to be rendered, a Field must be added
5915      * to a {@link Ext.Container Container}, usually an {@link Ext.form.FormPanel FormPanel}.
5916      * The FormPanel to which the field is added takes care of adding the Field to the BasicForm's
5917      * collection.</b></p>
5918      * @param {Field} field1
5919      * @param {Field} field2 (optional)
5920      * @param {Field} etc (optional)
5921      * @return {BasicForm} this
5922      */
5923     add : function(){
5924         this.items.addAll(Array.prototype.slice.call(arguments, 0));
5925         return this;
5926     },
5927
5928     /**
5929      * Removes a field from the items collection (does NOT remove its markup).
5930      * @param {Field} field
5931      * @return {BasicForm} this
5932      */
5933     remove : function(field){
5934         this.items.remove(field);
5935         return this;
5936     },
5937
5938     /**
5939      * Removes all fields from the collection that have been destroyed.
5940      */
5941     cleanDestroyed : function() {
5942         this.items.filterBy(function(o) { return !!o.isDestroyed; }).each(this.remove, this);
5943     },
5944
5945     /**
5946      * Iterates through the {@link Ext.form.Field Field}s which have been {@link #add add}ed to this BasicForm,
5947      * checks them for an id attribute, and calls {@link Ext.form.Field#applyToMarkup} on the existing dom element with that id.
5948      * @return {BasicForm} this
5949      */
5950     render : function(){
5951         this.items.each(function(f){
5952             if(f.isFormField && !f.rendered && document.getElementById(f.id)){ // if the element exists
5953                 f.applyToMarkup(f.id);
5954             }
5955         });
5956         return this;
5957     },
5958
5959     /**
5960      * Calls {@link Ext#apply} for all fields in this form with the passed object.
5961      * @param {Object} values
5962      * @return {BasicForm} this
5963      */
5964     applyToFields : function(o){
5965         this.items.each(function(f){
5966            Ext.apply(f, o);
5967         });
5968         return this;
5969     },
5970
5971     /**
5972      * Calls {@link Ext#applyIf} for all field in this form with the passed object.
5973      * @param {Object} values
5974      * @return {BasicForm} this
5975      */
5976     applyIfToFields : function(o){
5977         this.items.each(function(f){
5978            Ext.applyIf(f, o);
5979         });
5980         return this;
5981     },
5982
5983     callFieldMethod : function(fnName, args){
5984         args = args || [];
5985         this.items.each(function(f){
5986             if(Ext.isFunction(f[fnName])){
5987                 f[fnName].apply(f, args);
5988             }
5989         });
5990         return this;
5991     }
5992 });
5993
5994 // back compat
5995 Ext.BasicForm = Ext.form.BasicForm;
5996 /**
5997  * @class Ext.form.FormPanel
5998  * @extends Ext.Panel
5999  * <p>Standard form container.</p>
6000  *
6001  * <p><b><u>Layout</u></b></p>
6002  * <p>By default, FormPanel is configured with <tt>layout:'form'</tt> to use an {@link Ext.layout.FormLayout}
6003  * layout manager, which styles and renders fields and labels correctly. When nesting additional Containers
6004  * within a FormPanel, you should ensure that any descendant Containers which host input Fields use the
6005  * {@link Ext.layout.FormLayout} layout manager.</p>
6006  *
6007  * <p><b><u>BasicForm</u></b></p>
6008  * <p>Although <b>not listed</b> as configuration options of FormPanel, the FormPanel class accepts all
6009  * of the config options required to configure its internal {@link Ext.form.BasicForm} for:
6010  * <div class="mdetail-params"><ul>
6011  * <li>{@link Ext.form.BasicForm#fileUpload file uploads}</li>
6012  * <li>functionality for {@link Ext.form.BasicForm#doAction loading, validating and submitting} the form</li>
6013  * </ul></div>
6014  *
6015  * <p><b>Note</b>: If subclassing FormPanel, any configuration options for the BasicForm must be applied to
6016  * the <tt><b>initialConfig</b></tt> property of the FormPanel. Applying {@link Ext.form.BasicForm BasicForm}
6017  * configuration settings to <b><tt>this</tt></b> will <b>not</b> affect the BasicForm's configuration.</p>
6018  *
6019  * <p><b><u>Form Validation</u></b></p>
6020  * <p>For information on form validation see the following:</p>
6021  * <div class="mdetail-params"><ul>
6022  * <li>{@link Ext.form.TextField}</li>
6023  * <li>{@link Ext.form.VTypes}</li>
6024  * <li>{@link Ext.form.BasicForm#doAction BasicForm.doAction <b>clientValidation</b> notes}</li>
6025  * <li><tt>{@link Ext.form.FormPanel#monitorValid monitorValid}</tt></li>
6026  * </ul></div>
6027  *
6028  * <p><b><u>Form Submission</u></b></p>
6029  * <p>By default, Ext Forms are submitted through Ajax, using {@link Ext.form.Action}. To enable normal browser
6030  * submission of the {@link Ext.form.BasicForm BasicForm} contained in this FormPanel, see the
6031  * <tt><b>{@link Ext.form.BasicForm#standardSubmit standardSubmit}</b></tt> option.</p>
6032  *
6033  * @constructor
6034  * @param {Object} config Configuration options
6035  * @xtype form
6036  */
6037 Ext.FormPanel = Ext.extend(Ext.Panel, {
6038     /**
6039      * @cfg {String} formId (optional) The id of the FORM tag (defaults to an auto-generated id).
6040      */
6041     /**
6042      * @cfg {Boolean} hideLabels
6043      * <p><tt>true</tt> to hide field labels by default (sets <tt>display:none</tt>). Defaults to
6044      * <tt>false</tt>.</p>
6045      * <p>Also see {@link Ext.Component}.<tt>{@link Ext.Component#hideLabel hideLabel}</tt>.
6046      */
6047     /**
6048      * @cfg {Number} labelPad
6049      * The default padding in pixels for field labels (defaults to <tt>5</tt>). <tt>labelPad</tt> only
6050      * applies if <tt>{@link #labelWidth}</tt> is also specified, otherwise it will be ignored.
6051      */
6052     /**
6053      * @cfg {String} labelSeparator
6054      * See {@link Ext.Component}.<tt>{@link Ext.Component#labelSeparator labelSeparator}</tt>
6055      */
6056     /**
6057      * @cfg {Number} labelWidth The width of labels in pixels. This property cascades to child containers
6058      * and can be overridden on any child container (e.g., a fieldset can specify a different <tt>labelWidth</tt>
6059      * for its fields) (defaults to <tt>100</tt>).
6060      */
6061     /**
6062      * @cfg {String} itemCls A css class to apply to the x-form-item of fields. This property cascades to child containers.
6063      */
6064     /**
6065      * @cfg {Array} buttons
6066      * An array of {@link Ext.Button}s or {@link Ext.Button} configs used to add buttons to the footer of this FormPanel.<br>
6067      * <p>Buttons in the footer of a FormPanel may be configured with the option <tt>formBind: true</tt>. This causes
6068      * the form's {@link #monitorValid valid state monitor task} to enable/disable those Buttons depending on
6069      * the form's valid/invalid state.</p>
6070      */
6071
6072
6073     /**
6074      * @cfg {Number} minButtonWidth Minimum width of all buttons in pixels (defaults to <tt>75</tt>).
6075      */
6076     minButtonWidth : 75,
6077
6078     /**
6079      * @cfg {String} labelAlign The label alignment value used for the <tt>text-align</tt> specification
6080      * for the <b>container</b>. Valid values are <tt>"left</tt>", <tt>"top"</tt> or <tt>"right"</tt>
6081      * (defaults to <tt>"left"</tt>). This property cascades to child <b>containers</b> and can be
6082      * overridden on any child <b>container</b> (e.g., a fieldset can specify a different <tt>labelAlign</tt>
6083      * for its fields).
6084      */
6085     labelAlign : 'left',
6086
6087     /**
6088      * @cfg {Boolean} monitorValid If <tt>true</tt>, the form monitors its valid state <b>client-side</b> and
6089      * regularly fires the {@link #clientvalidation} event passing that state.<br>
6090      * <p>When monitoring valid state, the FormPanel enables/disables any of its configured
6091      * {@link #buttons} which have been configured with <code>formBind: true</code> depending
6092      * on whether the {@link Ext.form.BasicForm#isValid form is valid} or not. Defaults to <tt>false</tt></p>
6093      */
6094     monitorValid : false,
6095
6096     /**
6097      * @cfg {Number} monitorPoll The milliseconds to poll valid state, ignored if monitorValid is not true (defaults to 200)
6098      */
6099     monitorPoll : 200,
6100
6101     /**
6102      * @cfg {String} layout Defaults to <tt>'form'</tt>.  Normally this configuration property should not be altered.
6103      * For additional details see {@link Ext.layout.FormLayout} and {@link Ext.Container#layout Ext.Container.layout}.
6104      */
6105     layout : 'form',
6106
6107     // private
6108     initComponent : function(){
6109         this.form = this.createForm();
6110         Ext.FormPanel.superclass.initComponent.call(this);
6111
6112         this.bodyCfg = {
6113             tag: 'form',
6114             cls: this.baseCls + '-body',
6115             method : this.method || 'POST',
6116             id : this.formId || Ext.id()
6117         };
6118         if(this.fileUpload) {
6119             this.bodyCfg.enctype = 'multipart/form-data';
6120         }
6121         this.initItems();
6122
6123         this.addEvents(
6124             /**
6125              * @event clientvalidation
6126              * If the monitorValid config option is true, this event fires repetitively to notify of valid state
6127              * @param {Ext.form.FormPanel} this
6128              * @param {Boolean} valid true if the form has passed client-side validation
6129              */
6130             'clientvalidation'
6131         );
6132
6133         this.relayEvents(this.form, ['beforeaction', 'actionfailed', 'actioncomplete']);
6134     },
6135
6136     // private
6137     createForm : function(){
6138         var config = Ext.applyIf({listeners: {}}, this.initialConfig);
6139         return new Ext.form.BasicForm(null, config);
6140     },
6141
6142     // private
6143     initFields : function(){
6144         var f = this.form;
6145         var formPanel = this;
6146         var fn = function(c){
6147             if(formPanel.isField(c)){
6148                 f.add(c);
6149             }else if(c.findBy && c != formPanel){
6150                 formPanel.applySettings(c);
6151                 //each check required for check/radio groups.
6152                 if(c.items && c.items.each){
6153                     c.items.each(fn, this);
6154                 }
6155             }
6156         };
6157         this.items.each(fn, this);
6158     },
6159
6160     // private
6161     applySettings: function(c){
6162         var ct = c.ownerCt;
6163         Ext.applyIf(c, {
6164             labelAlign: ct.labelAlign,
6165             labelWidth: ct.labelWidth,
6166             itemCls: ct.itemCls
6167         });
6168     },
6169
6170     // private
6171     getLayoutTarget : function(){
6172         return this.form.el;
6173     },
6174
6175     /**
6176      * Provides access to the {@link Ext.form.BasicForm Form} which this Panel contains.
6177      * @return {Ext.form.BasicForm} The {@link Ext.form.BasicForm Form} which this Panel contains.
6178      */
6179     getForm : function(){
6180         return this.form;
6181     },
6182
6183     // private
6184     onRender : function(ct, position){
6185         this.initFields();
6186         Ext.FormPanel.superclass.onRender.call(this, ct, position);
6187         this.form.initEl(this.body);
6188     },
6189
6190     // private
6191     beforeDestroy : function(){
6192         this.stopMonitoring();
6193         this.form.destroy(true);
6194         Ext.FormPanel.superclass.beforeDestroy.call(this);
6195     },
6196
6197     // Determine if a Component is usable as a form Field.
6198     isField : function(c) {
6199         return !!c.setValue && !!c.getValue && !!c.markInvalid && !!c.clearInvalid;
6200     },
6201
6202     // private
6203     initEvents : function(){
6204         Ext.FormPanel.superclass.initEvents.call(this);
6205         // Listeners are required here to catch bubbling events from children.
6206         this.on({
6207             scope: this,
6208             add: this.onAddEvent,
6209             remove: this.onRemoveEvent
6210         });
6211         if(this.monitorValid){ // initialize after render
6212             this.startMonitoring();
6213         }
6214     },
6215
6216     // private
6217     onAdd: function(c){
6218         Ext.FormPanel.superclass.onAdd.call(this, c);
6219         this.processAdd(c);
6220     },
6221
6222     // private
6223     onAddEvent: function(ct, c){
6224         if(ct !== this){
6225             this.processAdd(c);
6226         }
6227     },
6228
6229     // private
6230     processAdd : function(c){
6231         // If a single form Field, add it
6232         if(this.isField(c)){
6233             this.form.add(c);
6234         // If a Container, add any Fields it might contain
6235         }else if(c.findBy){
6236             this.applySettings(c);
6237             this.form.add.apply(this.form, c.findBy(this.isField));
6238         }
6239     },
6240
6241     // private
6242     onRemove: function(c){
6243         Ext.FormPanel.superclass.onRemove.call(this, c);
6244         this.processRemove(c);
6245     },
6246
6247     onRemoveEvent: function(ct, c){
6248         if(ct !== this){
6249             this.processRemove(c);
6250         }
6251     },
6252
6253     // private
6254     processRemove: function(c){
6255         if(!this.destroying){
6256             // If a single form Field, remove it
6257             if(this.isField(c)){
6258                 this.form.remove(c);
6259             // If a Container, its already destroyed by the time it gets here.  Remove any references to destroyed fields.
6260             }else if (c.findBy){
6261                 Ext.each(c.findBy(this.isField), this.form.remove, this.form);
6262                 /*
6263                  * This isn't the most efficient way of getting rid of the items, however it's the most
6264                  * correct, which in this case is most important.
6265                  */
6266                 this.form.cleanDestroyed();
6267             }
6268         }
6269     },
6270
6271     /**
6272      * Starts monitoring of the valid state of this form. Usually this is done by passing the config
6273      * option "monitorValid"
6274      */
6275     startMonitoring : function(){
6276         if(!this.validTask){
6277             this.validTask = new Ext.util.TaskRunner();
6278             this.validTask.start({
6279                 run : this.bindHandler,
6280                 interval : this.monitorPoll || 200,
6281                 scope: this
6282             });
6283         }
6284     },
6285
6286     /**
6287      * Stops monitoring of the valid state of this form
6288      */
6289     stopMonitoring : function(){
6290         if(this.validTask){
6291             this.validTask.stopAll();
6292             this.validTask = null;
6293         }
6294     },
6295
6296     /**
6297      * This is a proxy for the underlying BasicForm's {@link Ext.form.BasicForm#load} call.
6298      * @param {Object} options The options to pass to the action (see {@link Ext.form.BasicForm#doAction} for details)
6299      */
6300     load : function(){
6301         this.form.load.apply(this.form, arguments);
6302     },
6303
6304     // private
6305     onDisable : function(){
6306         Ext.FormPanel.superclass.onDisable.call(this);
6307         if(this.form){
6308             this.form.items.each(function(){
6309                  this.disable();
6310             });
6311         }
6312     },
6313
6314     // private
6315     onEnable : function(){
6316         Ext.FormPanel.superclass.onEnable.call(this);
6317         if(this.form){
6318             this.form.items.each(function(){
6319                  this.enable();
6320             });
6321         }
6322     },
6323
6324     // private
6325     bindHandler : function(){
6326         var valid = true;
6327         this.form.items.each(function(f){
6328             if(!f.isValid(true)){
6329                 valid = false;
6330                 return false;
6331             }
6332         });
6333         if(this.fbar){
6334             var fitems = this.fbar.items.items;
6335             for(var i = 0, len = fitems.length; i < len; i++){
6336                 var btn = fitems[i];
6337                 if(btn.formBind === true && btn.disabled === valid){
6338                     btn.setDisabled(!valid);
6339                 }
6340             }
6341         }
6342         this.fireEvent('clientvalidation', this, valid);
6343     }
6344 });
6345 Ext.reg('form', Ext.FormPanel);
6346
6347 Ext.form.FormPanel = Ext.FormPanel;
6348 /**
6349  * @class Ext.form.FieldSet
6350  * @extends Ext.Panel
6351  * Standard container used for grouping items within a {@link Ext.form.FormPanel form}.
6352  * <pre><code>
6353 var form = new Ext.FormPanel({
6354     title: 'Simple Form with FieldSets',
6355     labelWidth: 75, // label settings here cascade unless overridden
6356     url: 'save-form.php',
6357     frame:true,
6358     bodyStyle:'padding:5px 5px 0',
6359     width: 700,
6360     renderTo: document.body,
6361     layout:'column', // arrange items in columns
6362     defaults: {      // defaults applied to items
6363         layout: 'form',
6364         border: false,
6365         bodyStyle: 'padding:4px'
6366     },
6367     items: [{
6368         // Fieldset in Column 1
6369         xtype:'fieldset',
6370         columnWidth: 0.5,
6371         title: 'Fieldset 1',
6372         collapsible: true,
6373         autoHeight:true,
6374         defaults: {
6375             anchor: '-20' // leave room for error icon
6376         },
6377         defaultType: 'textfield',
6378         items :[{
6379                 fieldLabel: 'Field 1'
6380             }, {
6381                 fieldLabel: 'Field 2'
6382             }, {
6383                 fieldLabel: 'Field 3'
6384             }
6385         ]
6386     },{
6387         // Fieldset in Column 2 - Panel inside
6388         xtype:'fieldset',
6389         title: 'Show Panel', // title, header, or checkboxToggle creates fieldset header
6390         autoHeight:true,
6391         columnWidth: 0.5,
6392         checkboxToggle: true,
6393         collapsed: true, // fieldset initially collapsed
6394         layout:'anchor',
6395         items :[{
6396             xtype: 'panel',
6397             anchor: '100%',
6398             title: 'Panel inside a fieldset',
6399             frame: true,
6400             height: 100
6401         }]
6402     }]
6403 });
6404  * </code></pre>
6405  * @constructor
6406  * @param {Object} config Configuration options
6407  * @xtype fieldset
6408  */
6409 Ext.form.FieldSet = Ext.extend(Ext.Panel, {
6410     /**
6411      * @cfg {Mixed} checkboxToggle <tt>true</tt> to render a checkbox into the fieldset frame just
6412      * in front of the legend to expand/collapse the fieldset when the checkbox is toggled. (defaults
6413      * to <tt>false</tt>).
6414      * <p>A {@link Ext.DomHelper DomHelper} element spec may also be specified to create the checkbox.
6415      * If <tt>true</tt> is specified, the default DomHelper config object used to create the element
6416      * is:</p><pre><code>
6417      * {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'}
6418      * </code></pre>
6419      */
6420     /**
6421      * @cfg {String} checkboxName The name to assign to the fieldset's checkbox if <tt>{@link #checkboxToggle} = true</tt>
6422      * (defaults to <tt>'[checkbox id]-checkbox'</tt>).
6423      */
6424     /**
6425      * @cfg {Boolean} collapsible
6426      * <tt>true</tt> to make the fieldset collapsible and have the expand/collapse toggle button automatically
6427      * rendered into the legend element, <tt>false</tt> to keep the fieldset statically sized with no collapse
6428      * button (defaults to <tt>false</tt>). Another option is to configure <tt>{@link #checkboxToggle}</tt>.
6429      */
6430     /**
6431      * @cfg {Number} labelWidth The width of labels. This property cascades to child containers.
6432      */
6433     /**
6434      * @cfg {String} itemCls A css class to apply to the <tt>x-form-item</tt> of fields (see
6435      * {@link Ext.layout.FormLayout}.{@link Ext.layout.FormLayout#fieldTpl fieldTpl} for details).
6436      * This property cascades to child containers.
6437      */
6438     /**
6439      * @cfg {String} baseCls The base CSS class applied to the fieldset (defaults to <tt>'x-fieldset'</tt>).
6440      */
6441     baseCls : 'x-fieldset',
6442     /**
6443      * @cfg {String} layout The {@link Ext.Container#layout} to use inside the fieldset (defaults to <tt>'form'</tt>).
6444      */
6445     layout : 'form',
6446     /**
6447      * @cfg {Boolean} animCollapse
6448      * <tt>true</tt> to animate the transition when the panel is collapsed, <tt>false</tt> to skip the
6449      * animation (defaults to <tt>false</tt>).
6450      */
6451     animCollapse : false,
6452
6453     // private
6454     onRender : function(ct, position){
6455         if(!this.el){
6456             this.el = document.createElement('fieldset');
6457             this.el.id = this.id;
6458             if (this.title || this.header || this.checkboxToggle) {
6459                 this.el.appendChild(document.createElement('legend')).className = this.baseCls + '-header';
6460             }
6461         }
6462
6463         Ext.form.FieldSet.superclass.onRender.call(this, ct, position);
6464
6465         if(this.checkboxToggle){
6466             var o = typeof this.checkboxToggle == 'object' ?
6467                     this.checkboxToggle :
6468                     {tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'};
6469             this.checkbox = this.header.insertFirst(o);
6470             this.checkbox.dom.checked = !this.collapsed;
6471             this.mon(this.checkbox, 'click', this.onCheckClick, this);
6472         }
6473     },
6474
6475     // private
6476     onCollapse : function(doAnim, animArg){
6477         if(this.checkbox){
6478             this.checkbox.dom.checked = false;
6479         }
6480         Ext.form.FieldSet.superclass.onCollapse.call(this, doAnim, animArg);
6481
6482     },
6483
6484     // private
6485     onExpand : function(doAnim, animArg){
6486         if(this.checkbox){
6487             this.checkbox.dom.checked = true;
6488         }
6489         Ext.form.FieldSet.superclass.onExpand.call(this, doAnim, animArg);
6490     },
6491
6492     /**
6493      * This function is called by the fieldset's checkbox when it is toggled (only applies when
6494      * checkboxToggle = true).  This method should never be called externally, but can be
6495      * overridden to provide custom behavior when the checkbox is toggled if needed.
6496      */
6497     onCheckClick : function(){
6498         this[this.checkbox.dom.checked ? 'expand' : 'collapse']();
6499     }
6500
6501     /**
6502      * @cfg {String/Number} activeItem
6503      * @hide
6504      */
6505     /**
6506      * @cfg {Mixed} applyTo
6507      * @hide
6508      */
6509     /**
6510      * @cfg {Boolean} bodyBorder
6511      * @hide
6512      */
6513     /**
6514      * @cfg {Boolean} border
6515      * @hide
6516      */
6517     /**
6518      * @cfg {Boolean/Number} bufferResize
6519      * @hide
6520      */
6521     /**
6522      * @cfg {Boolean} collapseFirst
6523      * @hide
6524      */
6525     /**
6526      * @cfg {String} defaultType
6527      * @hide
6528      */
6529     /**
6530      * @cfg {String} disabledClass
6531      * @hide
6532      */
6533     /**
6534      * @cfg {String} elements
6535      * @hide
6536      */
6537     /**
6538      * @cfg {Boolean} floating
6539      * @hide
6540      */
6541     /**
6542      * @cfg {Boolean} footer
6543      * @hide
6544      */
6545     /**
6546      * @cfg {Boolean} frame
6547      * @hide
6548      */
6549     /**
6550      * @cfg {Boolean} header
6551      * @hide
6552      */
6553     /**
6554      * @cfg {Boolean} headerAsText
6555      * @hide
6556      */
6557     /**
6558      * @cfg {Boolean} hideCollapseTool
6559      * @hide
6560      */
6561     /**
6562      * @cfg {String} iconCls
6563      * @hide
6564      */
6565     /**
6566      * @cfg {Boolean/String} shadow
6567      * @hide
6568      */
6569     /**
6570      * @cfg {Number} shadowOffset
6571      * @hide
6572      */
6573     /**
6574      * @cfg {Boolean} shim
6575      * @hide
6576      */
6577     /**
6578      * @cfg {Object/Array} tbar
6579      * @hide
6580      */
6581     /**
6582      * @cfg {Array} tools
6583      * @hide
6584      */
6585     /**
6586      * @cfg {Ext.Template/Ext.XTemplate} toolTemplate
6587      * @hide
6588      */
6589     /**
6590      * @cfg {String} xtype
6591      * @hide
6592      */
6593     /**
6594      * @property header
6595      * @hide
6596      */
6597     /**
6598      * @property footer
6599      * @hide
6600      */
6601     /**
6602      * @method focus
6603      * @hide
6604      */
6605     /**
6606      * @method getBottomToolbar
6607      * @hide
6608      */
6609     /**
6610      * @method getTopToolbar
6611      * @hide
6612      */
6613     /**
6614      * @method setIconClass
6615      * @hide
6616      */
6617     /**
6618      * @event activate
6619      * @hide
6620      */
6621     /**
6622      * @event beforeclose
6623      * @hide
6624      */
6625     /**
6626      * @event bodyresize
6627      * @hide
6628      */
6629     /**
6630      * @event close
6631      * @hide
6632      */
6633     /**
6634      * @event deactivate
6635      * @hide
6636      */
6637 });
6638 Ext.reg('fieldset', Ext.form.FieldSet);/**
6639  * @class Ext.form.HtmlEditor
6640  * @extends Ext.form.Field
6641  * Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be
6642  * automatically hidden when needed.  These are noted in the config options where appropriate.
6643  * <br><br>The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not
6644  * enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}.
6645  * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT
6646  * supported by this editor.</b>
6647  * <br><br>An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within
6648  * any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs.
6649  * <br><br>Example usage:
6650  * <pre><code>
6651 // Simple example rendered with default options:
6652 Ext.QuickTips.init();  // enable tooltips
6653 new Ext.form.HtmlEditor({
6654     renderTo: Ext.getBody(),
6655     width: 800,
6656     height: 300
6657 });
6658
6659 // Passed via xtype into a container and with custom options:
6660 Ext.QuickTips.init();  // enable tooltips
6661 new Ext.Panel({
6662     title: 'HTML Editor',
6663     renderTo: Ext.getBody(),
6664     width: 600,
6665     height: 300,
6666     frame: true,
6667     layout: 'fit',
6668     items: {
6669         xtype: 'htmleditor',
6670         enableColors: false,
6671         enableAlignments: false
6672     }
6673 });
6674 </code></pre>
6675  * @constructor
6676  * Create a new HtmlEditor
6677  * @param {Object} config
6678  * @xtype htmleditor
6679  */
6680
6681 Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, {
6682     /**
6683      * @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true)
6684      */
6685     enableFormat : true,
6686     /**
6687      * @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true)
6688      */
6689     enableFontSize : true,
6690     /**
6691      * @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true)
6692      */
6693     enableColors : true,
6694     /**
6695      * @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true)
6696      */
6697     enableAlignments : true,
6698     /**
6699      * @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true)
6700      */
6701     enableLists : true,
6702     /**
6703      * @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true)
6704      */
6705     enableSourceEdit : true,
6706     /**
6707      * @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true)
6708      */
6709     enableLinks : true,
6710     /**
6711      * @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true)
6712      */
6713     enableFont : true,
6714     /**
6715      * @cfg {String} createLinkText The default text for the create link prompt
6716      */
6717     createLinkText : 'Please enter the URL for the link:',
6718     /**
6719      * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /)
6720      */
6721     defaultLinkValue : 'http:/'+'/',
6722     /**
6723      * @cfg {Array} fontFamilies An array of available font families
6724      */
6725     fontFamilies : [
6726         'Arial',
6727         'Courier New',
6728         'Tahoma',
6729         'Times New Roman',
6730         'Verdana'
6731     ],
6732     defaultFont: 'tahoma',
6733     /**
6734      * @cfg {String} defaultValue A default value to be put into the editor to resolve focus issues (defaults to &#160; (Non-breaking space) in Opera and IE6, &#8203; (Zero-width space) in all other browsers).
6735      */
6736     defaultValue: (Ext.isOpera || Ext.isIE6) ? '&#160;' : '&#8203;',
6737
6738     // private properties
6739     actionMode: 'wrap',
6740     validationEvent : false,
6741     deferHeight: true,
6742     initialized : false,
6743     activated : false,
6744     sourceEditMode : false,
6745     onFocus : Ext.emptyFn,
6746     iframePad:3,
6747     hideMode:'offsets',
6748     defaultAutoCreate : {
6749         tag: "textarea",
6750         style:"width:500px;height:300px;",
6751         autocomplete: "off"
6752     },
6753
6754     // private
6755     initComponent : function(){
6756         this.addEvents(
6757             /**
6758              * @event initialize
6759              * Fires when the editor is fully initialized (including the iframe)
6760              * @param {HtmlEditor} this
6761              */
6762             'initialize',
6763             /**
6764              * @event activate
6765              * Fires when the editor is first receives the focus. Any insertion must wait
6766              * until after this event.
6767              * @param {HtmlEditor} this
6768              */
6769             'activate',
6770              /**
6771              * @event beforesync
6772              * Fires before the textarea is updated with content from the editor iframe. Return false
6773              * to cancel the sync.
6774              * @param {HtmlEditor} this
6775              * @param {String} html
6776              */
6777             'beforesync',
6778              /**
6779              * @event beforepush
6780              * Fires before the iframe editor is updated with content from the textarea. Return false
6781              * to cancel the push.
6782              * @param {HtmlEditor} this
6783              * @param {String} html
6784              */
6785             'beforepush',
6786              /**
6787              * @event sync
6788              * Fires when the textarea is updated with content from the editor iframe.
6789              * @param {HtmlEditor} this
6790              * @param {String} html
6791              */
6792             'sync',
6793              /**
6794              * @event push
6795              * Fires when the iframe editor is updated with content from the textarea.
6796              * @param {HtmlEditor} this
6797              * @param {String} html
6798              */
6799             'push',
6800              /**
6801              * @event editmodechange
6802              * Fires when the editor switches edit modes
6803              * @param {HtmlEditor} this
6804              * @param {Boolean} sourceEdit True if source edit, false if standard editing.
6805              */
6806             'editmodechange'
6807         );
6808         Ext.form.HtmlEditor.superclass.initComponent.call(this);
6809     },
6810
6811     // private
6812     createFontOptions : function(){
6813         var buf = [], fs = this.fontFamilies, ff, lc;
6814         for(var i = 0, len = fs.length; i< len; i++){
6815             ff = fs[i];
6816             lc = ff.toLowerCase();
6817             buf.push(
6818                 '<option value="',lc,'" style="font-family:',ff,';"',
6819                     (this.defaultFont == lc ? ' selected="true">' : '>'),
6820                     ff,
6821                 '</option>'
6822             );
6823         }
6824         return buf.join('');
6825     },
6826
6827     /*
6828      * Protected method that will not generally be called directly. It
6829      * is called when the editor creates its toolbar. Override this method if you need to
6830      * add custom toolbar buttons.
6831      * @param {HtmlEditor} editor
6832      */
6833     createToolbar : function(editor){
6834         var items = [];
6835         var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled();
6836
6837
6838         function btn(id, toggle, handler){
6839             return {
6840                 itemId : id,
6841                 cls : 'x-btn-icon',
6842                 iconCls: 'x-edit-'+id,
6843                 enableToggle:toggle !== false,
6844                 scope: editor,
6845                 handler:handler||editor.relayBtnCmd,
6846                 clickEvent:'mousedown',
6847                 tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined,
6848                 overflowText: editor.buttonTips[id].title || undefined,
6849                 tabIndex:-1
6850             };
6851         }
6852
6853
6854         if(this.enableFont && !Ext.isSafari2){
6855             var fontSelectItem = new Ext.Toolbar.Item({
6856                autoEl: {
6857                     tag:'select',
6858                     cls:'x-font-select',
6859                     html: this.createFontOptions()
6860                }
6861             });
6862
6863             items.push(
6864                 fontSelectItem,
6865                 '-'
6866             );
6867         }
6868
6869         if(this.enableFormat){
6870             items.push(
6871                 btn('bold'),
6872                 btn('italic'),
6873                 btn('underline')
6874             );
6875         }
6876
6877         if(this.enableFontSize){
6878             items.push(
6879                 '-',
6880                 btn('increasefontsize', false, this.adjustFont),
6881                 btn('decreasefontsize', false, this.adjustFont)
6882             );
6883         }
6884
6885         if(this.enableColors){
6886             items.push(
6887                 '-', {
6888                     itemId:'forecolor',
6889                     cls:'x-btn-icon',
6890                     iconCls: 'x-edit-forecolor',
6891                     clickEvent:'mousedown',
6892                     tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined,
6893                     tabIndex:-1,
6894                     menu : new Ext.menu.ColorMenu({
6895                         allowReselect: true,
6896                         focus: Ext.emptyFn,
6897                         value:'000000',
6898                         plain:true,
6899                         listeners: {
6900                             scope: this,
6901                             select: function(cp, color){
6902                                 this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
6903                                 this.deferFocus();
6904                             }
6905                         },
6906                         clickEvent:'mousedown'
6907                     })
6908                 }, {
6909                     itemId:'backcolor',
6910                     cls:'x-btn-icon',
6911                     iconCls: 'x-edit-backcolor',
6912                     clickEvent:'mousedown',
6913                     tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined,
6914                     tabIndex:-1,
6915                     menu : new Ext.menu.ColorMenu({
6916                         focus: Ext.emptyFn,
6917                         value:'FFFFFF',
6918                         plain:true,
6919                         allowReselect: true,
6920                         listeners: {
6921                             scope: this,
6922                             select: function(cp, color){
6923                                 if(Ext.isGecko){
6924                                     this.execCmd('useCSS', false);
6925                                     this.execCmd('hilitecolor', color);
6926                                     this.execCmd('useCSS', true);
6927                                     this.deferFocus();
6928                                 }else{
6929                                     this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color);
6930                                     this.deferFocus();
6931                                 }
6932                             }
6933                         },
6934                         clickEvent:'mousedown'
6935                     })
6936                 }
6937             );
6938         }
6939
6940         if(this.enableAlignments){
6941             items.push(
6942                 '-',
6943                 btn('justifyleft'),
6944                 btn('justifycenter'),
6945                 btn('justifyright')
6946             );
6947         }
6948
6949         if(!Ext.isSafari2){
6950             if(this.enableLinks){
6951                 items.push(
6952                     '-',
6953                     btn('createlink', false, this.createLink)
6954                 );
6955             }
6956
6957             if(this.enableLists){
6958                 items.push(
6959                     '-',
6960                     btn('insertorderedlist'),
6961                     btn('insertunorderedlist')
6962                 );
6963             }
6964             if(this.enableSourceEdit){
6965                 items.push(
6966                     '-',
6967                     btn('sourceedit', true, function(btn){
6968                         this.toggleSourceEdit(!this.sourceEditMode);
6969                     })
6970                 );
6971             }
6972         }
6973
6974         // build the toolbar
6975         var tb = new Ext.Toolbar({
6976             renderTo: this.wrap.dom.firstChild,
6977             items: items
6978         });
6979
6980         if (fontSelectItem) {
6981             this.fontSelect = fontSelectItem.el;
6982
6983             this.mon(this.fontSelect, 'change', function(){
6984                 var font = this.fontSelect.dom.value;
6985                 this.relayCmd('fontname', font);
6986                 this.deferFocus();
6987             }, this);
6988         }
6989
6990         // stop form submits
6991         this.mon(tb.el, 'click', function(e){
6992             e.preventDefault();
6993         });
6994
6995         this.tb = tb;
6996         this.tb.doLayout();
6997     },
6998
6999     onDisable: function(){
7000         this.wrap.mask();
7001         Ext.form.HtmlEditor.superclass.onDisable.call(this);
7002     },
7003
7004     onEnable: function(){
7005         this.wrap.unmask();
7006         Ext.form.HtmlEditor.superclass.onEnable.call(this);
7007     },
7008
7009     setReadOnly: function(readOnly){
7010
7011         Ext.form.HtmlEditor.superclass.setReadOnly.call(this, readOnly);
7012         if(this.initialized){
7013             if(Ext.isIE){
7014                 this.getEditorBody().contentEditable = !readOnly;
7015             }else{
7016                 this.setDesignMode(!readOnly);
7017             }
7018             var bd = this.getEditorBody();
7019             if(bd){
7020                 bd.style.cursor = this.readOnly ? 'default' : 'text';
7021             }
7022             this.disableItems(readOnly);
7023         }
7024     },
7025
7026     /**
7027      * Protected method that will not generally be called directly. It
7028      * is called when the editor initializes the iframe with HTML contents. Override this method if you
7029      * want to change the initialization markup of the iframe (e.g. to add stylesheets).
7030      *
7031      * Note: IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility
7032      */
7033     getDocMarkup : function(){
7034         var h = Ext.fly(this.iframe).getHeight() - this.iframePad * 2;
7035         return String.format('<html><head><style type="text/css">body{border: 0; margin: 0; padding: {0}px; height: {1}px; cursor: text}</style></head><body></body></html>', this.iframePad, h);
7036     },
7037
7038     // private
7039     getEditorBody : function(){
7040         var doc = this.getDoc();
7041         return doc.body || doc.documentElement;
7042     },
7043
7044     // private
7045     getDoc : function(){
7046         return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document);
7047     },
7048
7049     // private
7050     getWin : function(){
7051         return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name];
7052     },
7053
7054     // private
7055     onRender : function(ct, position){
7056         Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position);
7057         this.el.dom.style.border = '0 none';
7058         this.el.dom.setAttribute('tabIndex', -1);
7059         this.el.addClass('x-hidden');
7060         if(Ext.isIE){ // fix IE 1px bogus margin
7061             this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;');
7062         }
7063         this.wrap = this.el.wrap({
7064             cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'}
7065         });
7066
7067         this.createToolbar(this);
7068
7069         this.disableItems(true);
7070
7071         this.tb.doLayout();
7072
7073         this.createIFrame();
7074
7075         if(!this.width){
7076             var sz = this.el.getSize();
7077             this.setSize(sz.width, this.height || sz.height);
7078         }
7079         this.resizeEl = this.positionEl = this.wrap;
7080     },
7081
7082     createIFrame: function(){
7083         var iframe = document.createElement('iframe');
7084         iframe.name = Ext.id();
7085         iframe.frameBorder = '0';
7086         iframe.style.overflow = 'auto';
7087         iframe.src = Ext.SSL_SECURE_URL;
7088
7089         this.wrap.dom.appendChild(iframe);
7090         this.iframe = iframe;
7091
7092         this.monitorTask = Ext.TaskMgr.start({
7093             run: this.checkDesignMode,
7094             scope: this,
7095             interval:100
7096         });
7097     },
7098
7099     initFrame : function(){
7100         Ext.TaskMgr.stop(this.monitorTask);
7101         var doc = this.getDoc();
7102         this.win = this.getWin();
7103
7104         doc.open();
7105         doc.write(this.getDocMarkup());
7106         doc.close();
7107
7108         var task = { // must defer to wait for browser to be ready
7109             run : function(){
7110                 var doc = this.getDoc();
7111                 if(doc.body || doc.readyState == 'complete'){
7112                     Ext.TaskMgr.stop(task);
7113                     this.setDesignMode(true);
7114                     this.initEditor.defer(10, this);
7115                 }
7116             },
7117             interval : 10,
7118             duration:10000,
7119             scope: this
7120         };
7121         Ext.TaskMgr.start(task);
7122     },
7123
7124
7125     checkDesignMode : function(){
7126         if(this.wrap && this.wrap.dom.offsetWidth){
7127             var doc = this.getDoc();
7128             if(!doc){
7129                 return;
7130             }
7131             if(!doc.editorInitialized || this.getDesignMode() != 'on'){
7132                 this.initFrame();
7133             }
7134         }
7135     },
7136
7137     /* private
7138      * set current design mode. To enable, mode can be true or 'on', off otherwise
7139      */
7140     setDesignMode : function(mode){
7141         var doc = this.getDoc();
7142         if (doc) {
7143             if(this.readOnly){
7144                 mode = false;
7145             }
7146             doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off';
7147         }
7148
7149     },
7150
7151     // private
7152     getDesignMode : function(){
7153         var doc = this.getDoc();
7154         if(!doc){ return ''; }
7155         return String(doc.designMode).toLowerCase();
7156
7157     },
7158
7159     disableItems: function(disabled){
7160         if(this.fontSelect){
7161             this.fontSelect.dom.disabled = disabled;
7162         }
7163         this.tb.items.each(function(item){
7164             if(item.getItemId() != 'sourceedit'){
7165                 item.setDisabled(disabled);
7166             }
7167         });
7168     },
7169
7170     // private
7171     onResize : function(w, h){
7172         Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments);
7173         if(this.el && this.iframe){
7174             if(Ext.isNumber(w)){
7175                 var aw = w - this.wrap.getFrameWidth('lr');
7176                 this.el.setWidth(aw);
7177                 this.tb.setWidth(aw);
7178                 this.iframe.style.width = Math.max(aw, 0) + 'px';
7179             }
7180             if(Ext.isNumber(h)){
7181                 var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight();
7182                 this.el.setHeight(ah);
7183                 this.iframe.style.height = Math.max(ah, 0) + 'px';
7184                 var bd = this.getEditorBody();
7185                 if(bd){
7186                     bd.style.height = Math.max((ah - (this.iframePad*2)), 0) + 'px';
7187                 }
7188             }
7189         }
7190     },
7191
7192     /**
7193      * Toggles the editor between standard and source edit mode.
7194      * @param {Boolean} sourceEdit (optional) True for source edit, false for standard
7195      */
7196     toggleSourceEdit : function(sourceEditMode){
7197         var iframeHeight,
7198             elHeight;
7199
7200         if (sourceEditMode === undefined) {
7201             sourceEditMode = !this.sourceEditMode;
7202         }
7203         this.sourceEditMode = sourceEditMode === true;
7204         var btn = this.tb.getComponent('sourceedit');
7205
7206         if (btn.pressed !== this.sourceEditMode) {
7207             btn.toggle(this.sourceEditMode);
7208             if (!btn.xtbHidden) {
7209                 return;
7210             }
7211         }
7212         if (this.sourceEditMode) {
7213             // grab the height of the containing panel before we hide the iframe
7214             this.previousSize = this.getSize();
7215
7216             iframeHeight = Ext.get(this.iframe).getHeight();
7217
7218             this.disableItems(true);
7219             this.syncValue();
7220             this.iframe.className = 'x-hidden';
7221             this.el.removeClass('x-hidden');
7222             this.el.dom.removeAttribute('tabIndex');
7223             this.el.focus();
7224             this.el.dom.style.height = iframeHeight + 'px';
7225         }
7226         else {
7227             elHeight = parseInt(this.el.dom.style.height, 10);
7228             if (this.initialized) {
7229                 this.disableItems(this.readOnly);
7230             }
7231             this.pushValue();
7232             this.iframe.className = '';
7233             this.el.addClass('x-hidden');
7234             this.el.dom.setAttribute('tabIndex', -1);
7235             this.deferFocus();
7236
7237             this.setSize(this.previousSize);
7238             delete this.previousSize;
7239             this.iframe.style.height = elHeight + 'px';
7240         }
7241         this.fireEvent('editmodechange', this, this.sourceEditMode);
7242     },
7243
7244     // private used internally
7245     createLink : function() {
7246         var url = prompt(this.createLinkText, this.defaultLinkValue);
7247         if(url && url != 'http:/'+'/'){
7248             this.relayCmd('createlink', url);
7249         }
7250     },
7251
7252     // private
7253     initEvents : function(){
7254         this.originalValue = this.getValue();
7255     },
7256
7257     /**
7258      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
7259      * @method
7260      */
7261     markInvalid : Ext.emptyFn,
7262
7263     /**
7264      * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide
7265      * @method
7266      */
7267     clearInvalid : Ext.emptyFn,
7268
7269     // docs inherit from Field
7270     setValue : function(v){
7271         Ext.form.HtmlEditor.superclass.setValue.call(this, v);
7272         this.pushValue();
7273         return this;
7274     },
7275
7276     /**
7277      * Protected method that will not generally be called directly. If you need/want
7278      * custom HTML cleanup, this is the method you should override.
7279      * @param {String} html The HTML to be cleaned
7280      * @return {String} The cleaned HTML
7281      */
7282     cleanHtml: function(html) {
7283         html = String(html);
7284         if(Ext.isWebKit){ // strip safari nonsense
7285             html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, '');
7286         }
7287
7288         /*
7289          * Neat little hack. Strips out all the non-digit characters from the default
7290          * value and compares it to the character code of the first character in the string
7291          * because it can cause encoding issues when posted to the server.
7292          */
7293         if(html.charCodeAt(0) == this.defaultValue.replace(/\D/g, '')){
7294             html = html.substring(1);
7295         }
7296         return html;
7297     },
7298
7299     /**
7300      * Protected method that will not generally be called directly. Syncs the contents
7301      * of the editor iframe with the textarea.
7302      */
7303     syncValue : function(){
7304         if(this.initialized){
7305             var bd = this.getEditorBody();
7306             var html = bd.innerHTML;
7307             if(Ext.isWebKit){
7308                 var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element!
7309                 var m = bs.match(/text-align:(.*?);/i);
7310                 if(m && m[1]){
7311                     html = '<div style="'+m[0]+'">' + html + '</div>';
7312                 }
7313             }
7314             html = this.cleanHtml(html);
7315             if(this.fireEvent('beforesync', this, html) !== false){
7316                 this.el.dom.value = html;
7317                 this.fireEvent('sync', this, html);
7318             }
7319         }
7320     },
7321
7322     //docs inherit from Field
7323     getValue : function() {
7324         this[this.sourceEditMode ? 'pushValue' : 'syncValue']();
7325         return Ext.form.HtmlEditor.superclass.getValue.call(this);
7326     },
7327
7328     /**
7329      * Protected method that will not generally be called directly. Pushes the value of the textarea
7330      * into the iframe editor.
7331      */
7332     pushValue : function(){
7333         if(this.initialized){
7334             var v = this.el.dom.value;
7335             if(!this.activated && v.length < 1){
7336                 v = this.defaultValue;
7337             }
7338             if(this.fireEvent('beforepush', this, v) !== false){
7339                 this.getEditorBody().innerHTML = v;
7340                 if(Ext.isGecko){
7341                     // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8
7342                     this.setDesignMode(false);  //toggle off first
7343                     this.setDesignMode(true);
7344                 }
7345                 this.fireEvent('push', this, v);
7346             }
7347
7348         }
7349     },
7350
7351     // private
7352     deferFocus : function(){
7353         this.focus.defer(10, this);
7354     },
7355
7356     // docs inherit from Field
7357     focus : function(){
7358         if(this.win && !this.sourceEditMode){
7359             this.win.focus();
7360         }else{
7361             this.el.focus();
7362         }
7363     },
7364
7365     // private
7366     initEditor : function(){
7367         //Destroying the component during/before initEditor can cause issues.
7368         try{
7369             var dbody = this.getEditorBody(),
7370                 ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat', 'background-color', 'color'),
7371                 doc,
7372                 fn;
7373
7374             ss['background-attachment'] = 'fixed'; // w3c
7375             dbody.bgProperties = 'fixed'; // ie
7376
7377             Ext.DomHelper.applyStyles(dbody, ss);
7378
7379             doc = this.getDoc();
7380
7381             if(doc){
7382                 try{
7383                     Ext.EventManager.removeAll(doc);
7384                 }catch(e){}
7385             }
7386
7387             /*
7388              * We need to use createDelegate here, because when using buffer, the delayed task is added
7389              * as a property to the function. When the listener is removed, the task is deleted from the function.
7390              * Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors
7391              * is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function.
7392              */
7393             fn = this.onEditorEvent.createDelegate(this);
7394             Ext.EventManager.on(doc, {
7395                 mousedown: fn,
7396                 dblclick: fn,
7397                 click: fn,
7398                 keyup: fn,
7399                 buffer:100
7400             });
7401
7402             if(Ext.isGecko){
7403                 Ext.EventManager.on(doc, 'keypress', this.applyCommand, this);
7404             }
7405             if(Ext.isIE || Ext.isWebKit || Ext.isOpera){
7406                 Ext.EventManager.on(doc, 'keydown', this.fixKeys, this);
7407             }
7408             doc.editorInitialized = true;
7409             this.initialized = true;
7410             this.pushValue();
7411             this.setReadOnly(this.readOnly);
7412             this.fireEvent('initialize', this);
7413         }catch(e){}
7414     },
7415
7416     // private
7417     beforeDestroy : function(){
7418         if(this.monitorTask){
7419             Ext.TaskMgr.stop(this.monitorTask);
7420         }
7421         if(this.rendered){
7422             Ext.destroy(this.tb);
7423             var doc = this.getDoc();
7424             if(doc){
7425                 try{
7426                     Ext.EventManager.removeAll(doc);
7427                     for (var prop in doc){
7428                         delete doc[prop];
7429                     }
7430                 }catch(e){}
7431             }
7432             if(this.wrap){
7433                 this.wrap.dom.innerHTML = '';
7434                 this.wrap.remove();
7435             }
7436         }
7437         Ext.form.HtmlEditor.superclass.beforeDestroy.call(this);
7438     },
7439
7440     // private
7441     onFirstFocus : function(){
7442         this.activated = true;
7443         this.disableItems(this.readOnly);
7444         if(Ext.isGecko){ // prevent silly gecko errors
7445             this.win.focus();
7446             var s = this.win.getSelection();
7447             if(!s.focusNode || s.focusNode.nodeType != 3){
7448                 var r = s.getRangeAt(0);
7449                 r.selectNodeContents(this.getEditorBody());
7450                 r.collapse(true);
7451                 this.deferFocus();
7452             }
7453             try{
7454                 this.execCmd('useCSS', true);
7455                 this.execCmd('styleWithCSS', false);
7456             }catch(e){}
7457         }
7458         this.fireEvent('activate', this);
7459     },
7460
7461     // private
7462     adjustFont: function(btn){
7463         var adjust = btn.getItemId() == 'increasefontsize' ? 1 : -1,
7464             doc = this.getDoc(),
7465             v = parseInt(doc.queryCommandValue('FontSize') || 2, 10);
7466         if((Ext.isSafari && !Ext.isSafari2) || Ext.isChrome || Ext.isAir){
7467             // Safari 3 values
7468             // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px
7469             if(v <= 10){
7470                 v = 1 + adjust;
7471             }else if(v <= 13){
7472                 v = 2 + adjust;
7473             }else if(v <= 16){
7474                 v = 3 + adjust;
7475             }else if(v <= 18){
7476                 v = 4 + adjust;
7477             }else if(v <= 24){
7478                 v = 5 + adjust;
7479             }else {
7480                 v = 6 + adjust;
7481             }
7482             v = v.constrain(1, 6);
7483         }else{
7484             if(Ext.isSafari){ // safari
7485                 adjust *= 2;
7486             }
7487             v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0);
7488         }
7489         this.execCmd('FontSize', v);
7490     },
7491
7492     // private
7493     onEditorEvent : function(e){
7494         this.updateToolbar();
7495     },
7496
7497
7498     /**
7499      * Protected method that will not generally be called directly. It triggers
7500      * a toolbar update by reading the markup state of the current selection in the editor.
7501      */
7502     updateToolbar: function(){
7503
7504         if(this.readOnly){
7505             return;
7506         }
7507
7508         if(!this.activated){
7509             this.onFirstFocus();
7510             return;
7511         }
7512
7513         var btns = this.tb.items.map,
7514             doc = this.getDoc();
7515
7516         if(this.enableFont && !Ext.isSafari2){
7517             var name = (doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase();
7518             if(name != this.fontSelect.dom.value){
7519                 this.fontSelect.dom.value = name;
7520             }
7521         }
7522         if(this.enableFormat){
7523             btns.bold.toggle(doc.queryCommandState('bold'));
7524             btns.italic.toggle(doc.queryCommandState('italic'));
7525             btns.underline.toggle(doc.queryCommandState('underline'));
7526         }
7527         if(this.enableAlignments){
7528             btns.justifyleft.toggle(doc.queryCommandState('justifyleft'));
7529             btns.justifycenter.toggle(doc.queryCommandState('justifycenter'));
7530             btns.justifyright.toggle(doc.queryCommandState('justifyright'));
7531         }
7532         if(!Ext.isSafari2 && this.enableLists){
7533             btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist'));
7534             btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist'));
7535         }
7536
7537         Ext.menu.MenuMgr.hideAll();
7538
7539         this.syncValue();
7540     },
7541
7542     // private
7543     relayBtnCmd : function(btn){
7544         this.relayCmd(btn.getItemId());
7545     },
7546
7547     /**
7548      * Executes a Midas editor command on the editor document and performs necessary focus and
7549      * toolbar updates. <b>This should only be called after the editor is initialized.</b>
7550      * @param {String} cmd The Midas command
7551      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
7552      */
7553     relayCmd : function(cmd, value){
7554         (function(){
7555             this.focus();
7556             this.execCmd(cmd, value);
7557             this.updateToolbar();
7558         }).defer(10, this);
7559     },
7560
7561     /**
7562      * Executes a Midas editor command directly on the editor document.
7563      * For visual commands, you should use {@link #relayCmd} instead.
7564      * <b>This should only be called after the editor is initialized.</b>
7565      * @param {String} cmd The Midas command
7566      * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null)
7567      */
7568     execCmd : function(cmd, value){
7569         var doc = this.getDoc();
7570         doc.execCommand(cmd, false, value === undefined ? null : value);
7571         this.syncValue();
7572     },
7573
7574     // private
7575     applyCommand : function(e){
7576         if(e.ctrlKey){
7577             var c = e.getCharCode(), cmd;
7578             if(c > 0){
7579                 c = String.fromCharCode(c);
7580                 switch(c){
7581                     case 'b':
7582                         cmd = 'bold';
7583                     break;
7584                     case 'i':
7585                         cmd = 'italic';
7586                     break;
7587                     case 'u':
7588                         cmd = 'underline';
7589                     break;
7590                 }
7591                 if(cmd){
7592                     this.win.focus();
7593                     this.execCmd(cmd);
7594                     this.deferFocus();
7595                     e.preventDefault();
7596                 }
7597             }
7598         }
7599     },
7600
7601     /**
7602      * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated
7603      * to insert text.
7604      * @param {String} text
7605      */
7606     insertAtCursor : function(text){
7607         if(!this.activated){
7608             return;
7609         }
7610         if(Ext.isIE){
7611             this.win.focus();
7612             var doc = this.getDoc(),
7613                 r = doc.selection.createRange();
7614             if(r){
7615                 r.pasteHTML(text);
7616                 this.syncValue();
7617                 this.deferFocus();
7618             }
7619         }else{
7620             this.win.focus();
7621             this.execCmd('InsertHTML', text);
7622             this.deferFocus();
7623         }
7624     },
7625
7626     // private
7627     fixKeys : function(){ // load time branching for fastest keydown performance
7628         if(Ext.isIE){
7629             return function(e){
7630                 var k = e.getKey(),
7631                     doc = this.getDoc(),
7632                         r;
7633                 if(k == e.TAB){
7634                     e.stopEvent();
7635                     r = doc.selection.createRange();
7636                     if(r){
7637                         r.collapse(true);
7638                         r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;');
7639                         this.deferFocus();
7640                     }
7641                 }else if(k == e.ENTER){
7642                     r = doc.selection.createRange();
7643                     if(r){
7644                         var target = r.parentElement();
7645                         if(!target || target.tagName.toLowerCase() != 'li'){
7646                             e.stopEvent();
7647                             r.pasteHTML('<br />');
7648                             r.collapse(false);
7649                             r.select();
7650                         }
7651                     }
7652                 }
7653             };
7654         }else if(Ext.isOpera){
7655             return function(e){
7656                 var k = e.getKey();
7657                 if(k == e.TAB){
7658                     e.stopEvent();
7659                     this.win.focus();
7660                     this.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;');
7661                     this.deferFocus();
7662                 }
7663             };
7664         }else if(Ext.isWebKit){
7665             return function(e){
7666                 var k = e.getKey();
7667                 if(k == e.TAB){
7668                     e.stopEvent();
7669                     this.execCmd('InsertText','\t');
7670                     this.deferFocus();
7671                 }else if(k == e.ENTER){
7672                     e.stopEvent();
7673                     this.execCmd('InsertHtml','<br /><br />');
7674                     this.deferFocus();
7675                 }
7676              };
7677         }
7678     }(),
7679
7680     /**
7681      * Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b>
7682      * @return {Ext.Toolbar}
7683      */
7684     getToolbar : function(){
7685         return this.tb;
7686     },
7687
7688     /**
7689      * Object collection of toolbar tooltips for the buttons in the editor. The key
7690      * is the command id associated with that button and the value is a valid QuickTips object.
7691      * For example:
7692 <pre><code>
7693 {
7694     bold : {
7695         title: 'Bold (Ctrl+B)',
7696         text: 'Make the selected text bold.',
7697         cls: 'x-html-editor-tip'
7698     },
7699     italic : {
7700         title: 'Italic (Ctrl+I)',
7701         text: 'Make the selected text italic.',
7702         cls: 'x-html-editor-tip'
7703     },
7704     ...
7705 </code></pre>
7706     * @type Object
7707      */
7708     buttonTips : {
7709         bold : {
7710             title: 'Bold (Ctrl+B)',
7711             text: 'Make the selected text bold.',
7712             cls: 'x-html-editor-tip'
7713         },
7714         italic : {
7715             title: 'Italic (Ctrl+I)',
7716             text: 'Make the selected text italic.',
7717             cls: 'x-html-editor-tip'
7718         },
7719         underline : {
7720             title: 'Underline (Ctrl+U)',
7721             text: 'Underline the selected text.',
7722             cls: 'x-html-editor-tip'
7723         },
7724         increasefontsize : {
7725             title: 'Grow Text',
7726             text: 'Increase the font size.',
7727             cls: 'x-html-editor-tip'
7728         },
7729         decreasefontsize : {
7730             title: 'Shrink Text',
7731             text: 'Decrease the font size.',
7732             cls: 'x-html-editor-tip'
7733         },
7734         backcolor : {
7735             title: 'Text Highlight Color',
7736             text: 'Change the background color of the selected text.',
7737             cls: 'x-html-editor-tip'
7738         },
7739         forecolor : {
7740             title: 'Font Color',
7741             text: 'Change the color of the selected text.',
7742             cls: 'x-html-editor-tip'
7743         },
7744         justifyleft : {
7745             title: 'Align Text Left',
7746             text: 'Align text to the left.',
7747             cls: 'x-html-editor-tip'
7748         },
7749         justifycenter : {
7750             title: 'Center Text',
7751             text: 'Center text in the editor.',
7752             cls: 'x-html-editor-tip'
7753         },
7754         justifyright : {
7755             title: 'Align Text Right',
7756             text: 'Align text to the right.',
7757             cls: 'x-html-editor-tip'
7758         },
7759         insertunorderedlist : {
7760             title: 'Bullet List',
7761             text: 'Start a bulleted list.',
7762             cls: 'x-html-editor-tip'
7763         },
7764         insertorderedlist : {
7765             title: 'Numbered List',
7766             text: 'Start a numbered list.',
7767             cls: 'x-html-editor-tip'
7768         },
7769         createlink : {
7770             title: 'Hyperlink',
7771             text: 'Make the selected text a hyperlink.',
7772             cls: 'x-html-editor-tip'
7773         },
7774         sourceedit : {
7775             title: 'Source Edit',
7776             text: 'Switch to source editing mode.',
7777             cls: 'x-html-editor-tip'
7778         }
7779     }
7780
7781     // hide stuff that is not compatible
7782     /**
7783      * @event blur
7784      * @hide
7785      */
7786     /**
7787      * @event change
7788      * @hide
7789      */
7790     /**
7791      * @event focus
7792      * @hide
7793      */
7794     /**
7795      * @event specialkey
7796      * @hide
7797      */
7798     /**
7799      * @cfg {String} fieldClass @hide
7800      */
7801     /**
7802      * @cfg {String} focusClass @hide
7803      */
7804     /**
7805      * @cfg {String} autoCreate @hide
7806      */
7807     /**
7808      * @cfg {String} inputType @hide
7809      */
7810     /**
7811      * @cfg {String} invalidClass @hide
7812      */
7813     /**
7814      * @cfg {String} invalidText @hide
7815      */
7816     /**
7817      * @cfg {String} msgFx @hide
7818      */
7819     /**
7820      * @cfg {String} validateOnBlur @hide
7821      */
7822     /**
7823      * @cfg {Boolean} allowDomMove  @hide
7824      */
7825     /**
7826      * @cfg {String} applyTo @hide
7827      */
7828     /**
7829      * @cfg {String} autoHeight  @hide
7830      */
7831     /**
7832      * @cfg {String} autoWidth  @hide
7833      */
7834     /**
7835      * @cfg {String} cls  @hide
7836      */
7837     /**
7838      * @cfg {String} disabled  @hide
7839      */
7840     /**
7841      * @cfg {String} disabledClass  @hide
7842      */
7843     /**
7844      * @cfg {String} msgTarget  @hide
7845      */
7846     /**
7847      * @cfg {String} readOnly  @hide
7848      */
7849     /**
7850      * @cfg {String} style  @hide
7851      */
7852     /**
7853      * @cfg {String} validationDelay  @hide
7854      */
7855     /**
7856      * @cfg {String} validationEvent  @hide
7857      */
7858     /**
7859      * @cfg {String} tabIndex  @hide
7860      */
7861     /**
7862      * @property disabled
7863      * @hide
7864      */
7865     /**
7866      * @method applyToMarkup
7867      * @hide
7868      */
7869     /**
7870      * @method disable
7871      * @hide
7872      */
7873     /**
7874      * @method enable
7875      * @hide
7876      */
7877     /**
7878      * @method validate
7879      * @hide
7880      */
7881     /**
7882      * @event valid
7883      * @hide
7884      */
7885     /**
7886      * @method setDisabled
7887      * @hide
7888      */
7889     /**
7890      * @cfg keys
7891      * @hide
7892      */
7893 });
7894 Ext.reg('htmleditor', Ext.form.HtmlEditor);
7895 /**
7896  * @class Ext.form.TimeField
7897  * @extends Ext.form.ComboBox
7898  * Provides a time input field with a time dropdown and automatic time validation.  Example usage:
7899  * <pre><code>
7900 new Ext.form.TimeField({
7901     minValue: '9:00 AM',
7902     maxValue: '6:00 PM',
7903     increment: 30
7904 });
7905 </code></pre>
7906  * @constructor
7907  * Create a new TimeField
7908  * @param {Object} config
7909  * @xtype timefield
7910  */
7911 Ext.form.TimeField = Ext.extend(Ext.form.ComboBox, {
7912     /**
7913      * @cfg {Date/String} minValue
7914      * The minimum allowed time. Can be either a Javascript date object with a valid time value or a string
7915      * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
7916      */
7917     minValue : undefined,
7918     /**
7919      * @cfg {Date/String} maxValue
7920      * The maximum allowed time. Can be either a Javascript date object with a valid time value or a string
7921      * time in a valid format -- see {@link #format} and {@link #altFormats} (defaults to undefined).
7922      */
7923     maxValue : undefined,
7924     /**
7925      * @cfg {String} minText
7926      * The error text to display when the date in the cell is before minValue (defaults to
7927      * 'The time in this field must be equal to or after {0}').
7928      */
7929     minText : "The time in this field must be equal to or after {0}",
7930     /**
7931      * @cfg {String} maxText
7932      * The error text to display when the time is after maxValue (defaults to
7933      * 'The time in this field must be equal to or before {0}').
7934      */
7935     maxText : "The time in this field must be equal to or before {0}",
7936     /**
7937      * @cfg {String} invalidText
7938      * The error text to display when the time in the field is invalid (defaults to
7939      * '{value} is not a valid time').
7940      */
7941     invalidText : "{0} is not a valid time",
7942     /**
7943      * @cfg {String} format
7944      * The default time format string which can be overriden for localization support.  The format must be
7945      * valid according to {@link Date#parseDate} (defaults to 'g:i A', e.g., '3:15 PM').  For 24-hour time
7946      * format try 'H:i' instead.
7947      */
7948     format : "g:i A",
7949     /**
7950      * @cfg {String} altFormats
7951      * Multiple date formats separated by "|" to try when parsing a user input value and it doesn't match the defined
7952      * format (defaults to 'g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A').
7953      */
7954     altFormats : "g:ia|g:iA|g:i a|g:i A|h:i|g:i|H:i|ga|ha|gA|h a|g a|g A|gi|hi|gia|hia|g|H|gi a|hi a|giA|hiA|gi A|hi A",
7955     /**
7956      * @cfg {Number} increment
7957      * The number of minutes between each time value in the list (defaults to 15).
7958      */
7959     increment: 15,
7960
7961     // private override
7962     mode: 'local',
7963     // private override
7964     triggerAction: 'all',
7965     // private override
7966     typeAhead: false,
7967
7968     // private - This is the date to use when generating time values in the absence of either minValue
7969     // or maxValue.  Using the current date causes DST issues on DST boundary dates, so this is an
7970     // arbitrary "safe" date that can be any date aside from DST boundary dates.
7971     initDate: '1/1/2008',
7972
7973     initDateFormat: 'j/n/Y',
7974
7975     // private
7976     initComponent : function(){
7977         if(Ext.isDefined(this.minValue)){
7978             this.setMinValue(this.minValue, true);
7979         }
7980         if(Ext.isDefined(this.maxValue)){
7981             this.setMaxValue(this.maxValue, true);
7982         }
7983         if(!this.store){
7984             this.generateStore(true);
7985         }
7986         Ext.form.TimeField.superclass.initComponent.call(this);
7987     },
7988
7989     /**
7990      * Replaces any existing {@link #minValue} with the new time and refreshes the store.
7991      * @param {Date/String} value The minimum time that can be selected
7992      */
7993     setMinValue: function(value, /* private */ initial){
7994         this.setLimit(value, true, initial);
7995         return this;
7996     },
7997
7998     /**
7999      * Replaces any existing {@link #maxValue} with the new time and refreshes the store.
8000      * @param {Date/String} value The maximum time that can be selected
8001      */
8002     setMaxValue: function(value, /* private */ initial){
8003         this.setLimit(value, false, initial);
8004         return this;
8005     },
8006
8007     // private
8008     generateStore: function(initial){
8009         var min = this.minValue || new Date(this.initDate).clearTime(),
8010             max = this.maxValue || new Date(this.initDate).clearTime().add('mi', (24 * 60) - 1),
8011             times = [];
8012
8013         while(min <= max){
8014             times.push(min.dateFormat(this.format));
8015             min = min.add('mi', this.increment);
8016         }
8017         this.bindStore(times, initial);
8018     },
8019
8020     // private
8021     setLimit: function(value, isMin, initial){
8022         var d;
8023         if(Ext.isString(value)){
8024             d = this.parseDate(value);
8025         }else if(Ext.isDate(value)){
8026             d = value;
8027         }
8028         if(d){
8029             var val = new Date(this.initDate).clearTime();
8030             val.setHours(d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
8031             this[isMin ? 'minValue' : 'maxValue'] = val;
8032             if(!initial){
8033                 this.generateStore();
8034             }
8035         }
8036     },
8037
8038     // inherited docs
8039     getValue : function(){
8040         var v = Ext.form.TimeField.superclass.getValue.call(this);
8041         return this.formatDate(this.parseDate(v)) || '';
8042     },
8043
8044     // inherited docs
8045     setValue : function(value){
8046         return Ext.form.TimeField.superclass.setValue.call(this, this.formatDate(this.parseDate(value)));
8047     },
8048
8049     // private overrides
8050     validateValue : Ext.form.DateField.prototype.validateValue,
8051
8052     formatDate : Ext.form.DateField.prototype.formatDate,
8053
8054     parseDate: function(value) {
8055         if (!value || Ext.isDate(value)) {
8056             return value;
8057         }
8058
8059         var id = this.initDate + ' ',
8060             idf = this.initDateFormat + ' ',
8061             v = Date.parseDate(id + value, idf + this.format), // *** handle DST. note: this.format is a TIME-only format
8062             af = this.altFormats;
8063
8064         if (!v && af) {
8065             if (!this.altFormatsArray) {
8066                 this.altFormatsArray = af.split("|");
8067             }
8068             for (var i = 0, afa = this.altFormatsArray, len = afa.length; i < len && !v; i++) {
8069                 v = Date.parseDate(id + value, idf + afa[i]);
8070             }
8071         }
8072
8073         return v;
8074     }
8075 });
8076 Ext.reg('timefield', Ext.form.TimeField);/**
8077  * @class Ext.form.SliderField
8078  * @extends Ext.form.Field
8079  * Wraps a {@link Ext.slider.MultiSlider Slider} so it can be used as a form field.
8080  * @constructor
8081  * Creates a new SliderField
8082  * @param {Object} config Configuration options. Note that you can pass in any slider configuration options, as well as
8083  * as any field configuration options.
8084  * @xtype sliderfield
8085  */
8086 Ext.form.SliderField = Ext.extend(Ext.form.Field, {
8087     
8088     /**
8089      * @cfg {Boolean} useTips
8090      * True to use an Ext.slider.Tip to display tips for the value. Defaults to <tt>true</tt>.
8091      */
8092     useTips : true,
8093     
8094     /**
8095      * @cfg {Function} tipText
8096      * A function used to display custom text for the slider tip. Defaults to <tt>null</tt>, which will
8097      * use the default on the plugin.
8098      */
8099     tipText : null,
8100     
8101     // private override
8102     actionMode: 'wrap',
8103     
8104     /**
8105      * Initialize the component.
8106      * @private
8107      */
8108     initComponent : function() {
8109         var cfg = Ext.copyTo({
8110             id: this.id + '-slider'
8111         }, this.initialConfig, ['vertical', 'minValue', 'maxValue', 'decimalPrecision', 'keyIncrement', 'increment', 'clickToChange', 'animate']);
8112         
8113         // only can use it if it exists.
8114         if (this.useTips) {
8115             var plug = this.tipText ? {getText: this.tipText} : {};
8116             cfg.plugins = [new Ext.slider.Tip(plug)];
8117         }
8118         this.slider = new Ext.Slider(cfg);
8119         Ext.form.SliderField.superclass.initComponent.call(this);
8120     },    
8121     
8122     /**
8123      * Set up the hidden field
8124      * @param {Object} ct The container to render to.
8125      * @param {Object} position The position in the container to render to.
8126      * @private
8127      */
8128     onRender : function(ct, position){
8129         this.autoCreate = {
8130             id: this.id,
8131             name: this.name,
8132             type: 'hidden',
8133             tag: 'input'    
8134         };
8135         Ext.form.SliderField.superclass.onRender.call(this, ct, position);
8136         this.wrap = this.el.wrap({cls: 'x-form-field-wrap'});
8137         this.resizeEl = this.positionEl = this.wrap;
8138         this.slider.render(this.wrap);
8139     },
8140     
8141     /**
8142      * Ensure that the slider size is set automatically when the field resizes.
8143      * @param {Object} w The width
8144      * @param {Object} h The height
8145      * @param {Object} aw The adjusted width
8146      * @param {Object} ah The adjusted height
8147      * @private
8148      */
8149     onResize : function(w, h, aw, ah){
8150         Ext.form.SliderField.superclass.onResize.call(this, w, h, aw, ah);
8151         this.slider.setSize(w, h);    
8152     },
8153     
8154     /**
8155      * Initialize any events for this class.
8156      * @private
8157      */
8158     initEvents : function(){
8159         Ext.form.SliderField.superclass.initEvents.call(this);
8160         this.slider.on('change', this.onChange, this);   
8161     },
8162     
8163     /**
8164      * Utility method to set the value of the field when the slider changes.
8165      * @param {Object} slider The slider object.
8166      * @param {Object} v The new value.
8167      * @private
8168      */
8169     onChange : function(slider, v){
8170         this.setValue(v, undefined, true);
8171     },
8172     
8173     /**
8174      * Enable the slider when the field is enabled.
8175      * @private
8176      */
8177     onEnable : function(){
8178         Ext.form.SliderField.superclass.onEnable.call(this);
8179         this.slider.enable();
8180     },
8181     
8182     /**
8183      * Disable the slider when the field is disabled.
8184      * @private
8185      */
8186     onDisable : function(){
8187         Ext.form.SliderField.superclass.onDisable.call(this);
8188         this.slider.disable();    
8189     },
8190     
8191     /**
8192      * Ensure the slider is destroyed when the field is destroyed.
8193      * @private
8194      */
8195     beforeDestroy : function(){
8196         Ext.destroy(this.slider);
8197         Ext.form.SliderField.superclass.beforeDestroy.call(this);
8198     },
8199     
8200     /**
8201      * If a side icon is shown, do alignment to the slider
8202      * @private
8203      */
8204     alignErrorIcon : function(){
8205         this.errorIcon.alignTo(this.slider.el, 'tl-tr', [2, 0]);
8206     },
8207     
8208     /**
8209      * Sets the minimum field value.
8210      * @param {Number} v The new minimum value.
8211      * @return {Ext.form.SliderField} this
8212      */
8213     setMinValue : function(v){
8214         this.slider.setMinValue(v);
8215         return this;    
8216     },
8217     
8218     /**
8219      * Sets the maximum field value.
8220      * @param {Number} v The new maximum value.
8221      * @return {Ext.form.SliderField} this
8222      */
8223     setMaxValue : function(v){
8224         this.slider.setMaxValue(v);
8225         return this;    
8226     },
8227     
8228     /**
8229      * Sets the value for this field.
8230      * @param {Number} v The new value.
8231      * @param {Boolean} animate (optional) Whether to animate the transition. If not specified, it will default to the animate config.
8232      * @return {Ext.form.SliderField} this
8233      */
8234     setValue : function(v, animate, /* private */ silent){
8235         // silent is used if the setValue method is invoked by the slider
8236         // which means we don't need to set the value on the slider.
8237         if(!silent){
8238             this.slider.setValue(v, animate);
8239         }
8240         return Ext.form.SliderField.superclass.setValue.call(this, this.slider.getValue());
8241     },
8242     
8243     /**
8244      * Gets the current value for this field.
8245      * @return {Number} The current value.
8246      */
8247     getValue : function(){
8248         return this.slider.getValue();    
8249     }
8250 });
8251
8252 Ext.reg('sliderfield', Ext.form.SliderField);/**
8253  * @class Ext.form.Label
8254  * @extends Ext.BoxComponent
8255  * Basic Label field.
8256  * @constructor
8257  * Creates a new Label
8258  * @param {Ext.Element/String/Object} config The configuration options.  If an element is passed, it is set as the internal
8259  * element and its id used as the component id.  If a string is passed, it is assumed to be the id of an existing element
8260  * and is used as the component id.  Otherwise, it is assumed to be a standard config object and is applied to the component.
8261  * @xtype label
8262  */
8263 Ext.form.Label = Ext.extend(Ext.BoxComponent, {
8264     /**
8265      * @cfg {String} text The plain text to display within the label (defaults to ''). If you need to include HTML
8266      * tags within the label's innerHTML, use the {@link #html} config instead.
8267      */
8268     /**
8269      * @cfg {String} forId The id of the input element to which this label will be bound via the standard HTML 'for'
8270      * attribute. If not specified, the attribute will not be added to the label.
8271      */
8272     /**
8273      * @cfg {String} html An HTML fragment that will be used as the label's innerHTML (defaults to '').
8274      * Note that if {@link #text} is specified it will take precedence and this value will be ignored.
8275      */
8276
8277     // private
8278     onRender : function(ct, position){
8279         if(!this.el){
8280             this.el = document.createElement('label');
8281             this.el.id = this.getId();
8282             this.el.innerHTML = this.text ? Ext.util.Format.htmlEncode(this.text) : (this.html || '');
8283             if(this.forId){
8284                 this.el.setAttribute('for', this.forId);
8285             }
8286         }
8287         Ext.form.Label.superclass.onRender.call(this, ct, position);
8288     },
8289
8290     /**
8291      * Updates the label's innerHTML with the specified string.
8292      * @param {String} text The new label text
8293      * @param {Boolean} encode (optional) False to skip HTML-encoding the text when rendering it
8294      * to the label (defaults to true which encodes the value). This might be useful if you want to include
8295      * tags in the label's innerHTML rather than rendering them as string literals per the default logic.
8296      * @return {Label} this
8297      */
8298     setText : function(t, encode){
8299         var e = encode === false;
8300         this[!e ? 'text' : 'html'] = t;
8301         delete this[e ? 'text' : 'html'];
8302         if(this.rendered){
8303             this.el.dom.innerHTML = encode !== false ? Ext.util.Format.htmlEncode(t) : t;
8304         }
8305         return this;
8306     }
8307 });
8308
8309 Ext.reg('label', Ext.form.Label);/**
8310  * @class Ext.form.Action
8311  * <p>The subclasses of this class provide actions to perform upon {@link Ext.form.BasicForm Form}s.</p>
8312  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8313  * the Form needs to perform an action such as submit or load. The Configuration options
8314  * listed for this class are set through the Form's action methods: {@link Ext.form.BasicForm#submit submit},
8315  * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}</p>
8316  * <p>The instance of Action which performed the action is passed to the success
8317  * and failure callbacks of the Form's action methods ({@link Ext.form.BasicForm#submit submit},
8318  * {@link Ext.form.BasicForm#load load} and {@link Ext.form.BasicForm#doAction doAction}),
8319  * and to the {@link Ext.form.BasicForm#actioncomplete actioncomplete} and
8320  * {@link Ext.form.BasicForm#actionfailed actionfailed} event handlers.</p>
8321  */
8322 Ext.form.Action = function(form, options){
8323     this.form = form;
8324     this.options = options || {};
8325 };
8326
8327 /**
8328  * Failure type returned when client side validation of the Form fails
8329  * thus aborting a submit action. Client side validation is performed unless
8330  * {@link #clientValidation} is explicitly set to <tt>false</tt>.
8331  * @type {String}
8332  * @static
8333  */
8334 Ext.form.Action.CLIENT_INVALID = 'client';
8335 /**
8336  * <p>Failure type returned when server side processing fails and the {@link #result}'s
8337  * <tt style="font-weight:bold">success</tt> property is set to <tt>false</tt>.</p>
8338  * <p>In the case of a form submission, field-specific error messages may be returned in the
8339  * {@link #result}'s <tt style="font-weight:bold">errors</tt> property.</p>
8340  * @type {String}
8341  * @static
8342  */
8343 Ext.form.Action.SERVER_INVALID = 'server';
8344 /**
8345  * Failure type returned when a communication error happens when attempting
8346  * to send a request to the remote server. The {@link #response} may be examined to
8347  * provide further information.
8348  * @type {String}
8349  * @static
8350  */
8351 Ext.form.Action.CONNECT_FAILURE = 'connect';
8352 /**
8353  * Failure type returned when the response's <tt style="font-weight:bold">success</tt>
8354  * property is set to <tt>false</tt>, or no field values are returned in the response's
8355  * <tt style="font-weight:bold">data</tt> property.
8356  * @type {String}
8357  * @static
8358  */
8359 Ext.form.Action.LOAD_FAILURE = 'load';
8360
8361 Ext.form.Action.prototype = {
8362 /**
8363  * @cfg {String} url The URL that the Action is to invoke.
8364  */
8365 /**
8366  * @cfg {Boolean} reset When set to <tt><b>true</b></tt>, causes the Form to be
8367  * {@link Ext.form.BasicForm.reset reset} on Action success. If specified, this happens
8368  * <b>before</b> the {@link #success} callback is called and before the Form's
8369  * {@link Ext.form.BasicForm.actioncomplete actioncomplete} event fires.
8370  */
8371 /**
8372  * @cfg {String} method The HTTP method to use to access the requested URL. Defaults to the
8373  * {@link Ext.form.BasicForm}'s method, or if that is not specified, the underlying DOM form's method.
8374  */
8375 /**
8376  * @cfg {Mixed} params <p>Extra parameter values to pass. These are added to the Form's
8377  * {@link Ext.form.BasicForm#baseParams} and passed to the specified URL along with the Form's
8378  * input fields.</p>
8379  * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
8380  */
8381 /**
8382  * @cfg {Number} timeout The number of seconds to wait for a server response before
8383  * failing with the {@link #failureType} as {@link #Action.CONNECT_FAILURE}. If not specified,
8384  * defaults to the configured <tt>{@link Ext.form.BasicForm#timeout timeout}</tt> of the
8385  * {@link Ext.form.BasicForm form}.
8386  */
8387 /**
8388  * @cfg {Function} success The function to call when a valid success return packet is recieved.
8389  * The function is passed the following parameters:<ul class="mdetail-params">
8390  * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
8391  * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. The {@link #result}
8392  * property of this object may be examined to perform custom postprocessing.</div></li>
8393  * </ul>
8394  */
8395 /**
8396  * @cfg {Function} failure The function to call when a failure packet was recieved, or when an
8397  * error ocurred in the Ajax communication.
8398  * The function is passed the following parameters:<ul class="mdetail-params">
8399  * <li><b>form</b> : Ext.form.BasicForm<div class="sub-desc">The form that requested the action</div></li>
8400  * <li><b>action</b> : Ext.form.Action<div class="sub-desc">The Action class. If an Ajax
8401  * error ocurred, the failure type will be in {@link #failureType}. The {@link #result}
8402  * property of this object may be examined to perform custom postprocessing.</div></li>
8403  * </ul>
8404  */
8405 /**
8406  * @cfg {Object} scope The scope in which to call the callback functions (The <tt>this</tt> reference
8407  * for the callback functions).
8408  */
8409 /**
8410  * @cfg {String} waitMsg The message to be displayed by a call to {@link Ext.MessageBox#wait}
8411  * during the time the action is being processed.
8412  */
8413 /**
8414  * @cfg {String} waitTitle The title to be displayed by a call to {@link Ext.MessageBox#wait}
8415  * during the time the action is being processed.
8416  */
8417
8418 /**
8419  * @cfg {Boolean} submitEmptyText If set to <tt>true</tt>, the emptyText value will be sent with the form
8420  * when it is submitted.  Defaults to <tt>true</tt>.
8421  */
8422
8423 /**
8424  * The type of action this Action instance performs.
8425  * Currently only "submit" and "load" are supported.
8426  * @type {String}
8427  */
8428     type : 'default',
8429 /**
8430  * The type of failure detected will be one of these: {@link #CLIENT_INVALID},
8431  * {@link #SERVER_INVALID}, {@link #CONNECT_FAILURE}, or {@link #LOAD_FAILURE}.  Usage:
8432  * <pre><code>
8433 var fp = new Ext.form.FormPanel({
8434 ...
8435 buttons: [{
8436     text: 'Save',
8437     formBind: true,
8438     handler: function(){
8439         if(fp.getForm().isValid()){
8440             fp.getForm().submit({
8441                 url: 'form-submit.php',
8442                 waitMsg: 'Submitting your data...',
8443                 success: function(form, action){
8444                     // server responded with success = true
8445                     var result = action.{@link #result};
8446                 },
8447                 failure: function(form, action){
8448                     if (action.{@link #failureType} === Ext.form.Action.{@link #CONNECT_FAILURE}) {
8449                         Ext.Msg.alert('Error',
8450                             'Status:'+action.{@link #response}.status+': '+
8451                             action.{@link #response}.statusText);
8452                     }
8453                     if (action.failureType === Ext.form.Action.{@link #SERVER_INVALID}){
8454                         // server responded with success = false
8455                         Ext.Msg.alert('Invalid', action.{@link #result}.errormsg);
8456                     }
8457                 }
8458             });
8459         }
8460     }
8461 },{
8462     text: 'Reset',
8463     handler: function(){
8464         fp.getForm().reset();
8465     }
8466 }]
8467  * </code></pre>
8468  * @property failureType
8469  * @type {String}
8470  */
8471  /**
8472  * The XMLHttpRequest object used to perform the action.
8473  * @property response
8474  * @type {Object}
8475  */
8476  /**
8477  * The decoded response object containing a boolean <tt style="font-weight:bold">success</tt> property and
8478  * other, action-specific properties.
8479  * @property result
8480  * @type {Object}
8481  */
8482
8483     // interface method
8484     run : function(options){
8485
8486     },
8487
8488     // interface method
8489     success : function(response){
8490
8491     },
8492
8493     // interface method
8494     handleResponse : function(response){
8495
8496     },
8497
8498     // default connection failure
8499     failure : function(response){
8500         this.response = response;
8501         this.failureType = Ext.form.Action.CONNECT_FAILURE;
8502         this.form.afterAction(this, false);
8503     },
8504
8505     // private
8506     // shared code among all Actions to validate that there was a response
8507     // with either responseText or responseXml
8508     processResponse : function(response){
8509         this.response = response;
8510         if(!response.responseText && !response.responseXML){
8511             return true;
8512         }
8513         this.result = this.handleResponse(response);
8514         return this.result;
8515     },
8516
8517     // utility functions used internally
8518     getUrl : function(appendParams){
8519         var url = this.options.url || this.form.url || this.form.el.dom.action;
8520         if(appendParams){
8521             var p = this.getParams();
8522             if(p){
8523                 url = Ext.urlAppend(url, p);
8524             }
8525         }
8526         return url;
8527     },
8528
8529     // private
8530     getMethod : function(){
8531         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
8532     },
8533
8534     // private
8535     getParams : function(){
8536         var bp = this.form.baseParams;
8537         var p = this.options.params;
8538         if(p){
8539             if(typeof p == "object"){
8540                 p = Ext.urlEncode(Ext.applyIf(p, bp));
8541             }else if(typeof p == 'string' && bp){
8542                 p += '&' + Ext.urlEncode(bp);
8543             }
8544         }else if(bp){
8545             p = Ext.urlEncode(bp);
8546         }
8547         return p;
8548     },
8549
8550     // private
8551     createCallback : function(opts){
8552         var opts = opts || {};
8553         return {
8554             success: this.success,
8555             failure: this.failure,
8556             scope: this,
8557             timeout: (opts.timeout*1000) || (this.form.timeout*1000),
8558             upload: this.form.fileUpload ? this.success : undefined
8559         };
8560     }
8561 };
8562
8563 /**
8564  * @class Ext.form.Action.Submit
8565  * @extends Ext.form.Action
8566  * <p>A class which handles submission of data from {@link Ext.form.BasicForm Form}s
8567  * and processes the returned response.</p>
8568  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8569  * {@link Ext.form.BasicForm#submit submit}ting.</p>
8570  * <p><u><b>Response Packet Criteria</b></u></p>
8571  * <p>A response packet may contain:
8572  * <div class="mdetail-params"><ul>
8573  * <li><b><code>success</code></b> property : Boolean
8574  * <div class="sub-desc">The <code>success</code> property is required.</div></li>
8575  * <li><b><code>errors</code></b> property : Object
8576  * <div class="sub-desc"><div class="sub-desc">The <code>errors</code> property,
8577  * which is optional, contains error messages for invalid fields.</div></li>
8578  * </ul></div>
8579  * <p><u><b>JSON Packets</b></u></p>
8580  * <p>By default, response packets are assumed to be JSON, so a typical response
8581  * packet may look like this:</p><pre><code>
8582 {
8583     success: false,
8584     errors: {
8585         clientCode: "Client not found",
8586         portOfLoading: "This field must not be null"
8587     }
8588 }</code></pre>
8589  * <p>Other data may be placed into the response for processing by the {@link Ext.form.BasicForm}'s callback
8590  * or event handler methods. The object decoded from this JSON is available in the
8591  * {@link Ext.form.Action#result result} property.</p>
8592  * <p>Alternatively, if an {@link #errorReader} is specified as an {@link Ext.data.XmlReader XmlReader}:</p><pre><code>
8593     errorReader: new Ext.data.XmlReader({
8594             record : 'field',
8595             success: '@success'
8596         }, [
8597             'id', 'msg'
8598         ]
8599     )
8600 </code></pre>
8601  * <p>then the results may be sent back in XML format:</p><pre><code>
8602 &lt;?xml version="1.0" encoding="UTF-8"?&gt;
8603 &lt;message success="false"&gt;
8604 &lt;errors&gt;
8605     &lt;field&gt;
8606         &lt;id&gt;clientCode&lt;/id&gt;
8607         &lt;msg&gt;&lt;![CDATA[Code not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt;
8608     &lt;/field&gt;
8609     &lt;field&gt;
8610         &lt;id&gt;portOfLoading&lt;/id&gt;
8611         &lt;msg&gt;&lt;![CDATA[Port not found. &lt;br /&gt;&lt;i&gt;This is a test validation message from the server &lt;/i&gt;]]&gt;&lt;/msg&gt;
8612     &lt;/field&gt;
8613 &lt;/errors&gt;
8614 &lt;/message&gt;
8615 </code></pre>
8616  * <p>Other elements may be placed into the response XML for processing by the {@link Ext.form.BasicForm}'s callback
8617  * or event handler methods. The XML document is available in the {@link #errorReader}'s {@link Ext.data.XmlReader#xmlData xmlData} property.</p>
8618  */
8619 Ext.form.Action.Submit = function(form, options){
8620     Ext.form.Action.Submit.superclass.constructor.call(this, form, options);
8621 };
8622
8623 Ext.extend(Ext.form.Action.Submit, Ext.form.Action, {
8624     /**
8625      * @cfg {Ext.data.DataReader} errorReader <p><b>Optional. JSON is interpreted with
8626      * no need for an errorReader.</b></p>
8627      * <p>A Reader which reads a single record from the returned data. The DataReader's
8628      * <b>success</b> property specifies how submission success is determined. The Record's
8629      * data provides the error messages to apply to any invalid form Fields.</p>
8630      */
8631     /**
8632      * @cfg {boolean} clientValidation Determines whether a Form's fields are validated
8633      * in a final call to {@link Ext.form.BasicForm#isValid isValid} prior to submission.
8634      * Pass <tt>false</tt> in the Form's submit options to prevent this. If not defined, pre-submission field validation
8635      * is performed.
8636      */
8637     type : 'submit',
8638
8639     // private
8640     run : function(){
8641         var o = this.options,
8642             method = this.getMethod(),
8643             isGet = method == 'GET';
8644         if(o.clientValidation === false || this.form.isValid()){
8645             if (o.submitEmptyText === false) {
8646                 var fields = this.form.items,
8647                     emptyFields = [],
8648                     setupEmptyFields = function(f){
8649                         if (f.el.getValue() == f.emptyText) {
8650                             emptyFields.push(f);
8651                             f.el.dom.value = "";
8652                         }
8653                         if(f.isComposite && f.rendered){
8654                             f.items.each(setupEmptyFields);
8655                         }
8656                     };
8657                     
8658                 fields.each(setupEmptyFields);
8659             }
8660             Ext.Ajax.request(Ext.apply(this.createCallback(o), {
8661                 form:this.form.el.dom,
8662                 url:this.getUrl(isGet),
8663                 method: method,
8664                 headers: o.headers,
8665                 params:!isGet ? this.getParams() : null,
8666                 isUpload: this.form.fileUpload
8667             }));
8668             if (o.submitEmptyText === false) {
8669                 Ext.each(emptyFields, function(f) {
8670                     if (f.applyEmptyText) {
8671                         f.applyEmptyText();
8672                     }
8673                 });
8674             }
8675         }else if (o.clientValidation !== false){ // client validation failed
8676             this.failureType = Ext.form.Action.CLIENT_INVALID;
8677             this.form.afterAction(this, false);
8678         }
8679     },
8680
8681     // private
8682     success : function(response){
8683         var result = this.processResponse(response);
8684         if(result === true || result.success){
8685             this.form.afterAction(this, true);
8686             return;
8687         }
8688         if(result.errors){
8689             this.form.markInvalid(result.errors);
8690         }
8691         this.failureType = Ext.form.Action.SERVER_INVALID;
8692         this.form.afterAction(this, false);
8693     },
8694
8695     // private
8696     handleResponse : function(response){
8697         if(this.form.errorReader){
8698             var rs = this.form.errorReader.read(response);
8699             var errors = [];
8700             if(rs.records){
8701                 for(var i = 0, len = rs.records.length; i < len; i++) {
8702                     var r = rs.records[i];
8703                     errors[i] = r.data;
8704                 }
8705             }
8706             if(errors.length < 1){
8707                 errors = null;
8708             }
8709             return {
8710                 success : rs.success,
8711                 errors : errors
8712             };
8713         }
8714         return Ext.decode(response.responseText);
8715     }
8716 });
8717
8718
8719 /**
8720  * @class Ext.form.Action.Load
8721  * @extends Ext.form.Action
8722  * <p>A class which handles loading of data from a server into the Fields of an {@link Ext.form.BasicForm}.</p>
8723  * <p>Instances of this class are only created by a {@link Ext.form.BasicForm Form} when
8724  * {@link Ext.form.BasicForm#load load}ing.</p>
8725  * <p><u><b>Response Packet Criteria</b></u></p>
8726  * <p>A response packet <b>must</b> contain:
8727  * <div class="mdetail-params"><ul>
8728  * <li><b><code>success</code></b> property : Boolean</li>
8729  * <li><b><code>data</code></b> property : Object</li>
8730  * <div class="sub-desc">The <code>data</code> property contains the values of Fields to load.
8731  * The individual value object for each Field is passed to the Field's
8732  * {@link Ext.form.Field#setValue setValue} method.</div></li>
8733  * </ul></div>
8734  * <p><u><b>JSON Packets</b></u></p>
8735  * <p>By default, response packets are assumed to be JSON, so for the following form load call:<pre><code>
8736 var myFormPanel = new Ext.form.FormPanel({
8737     title: 'Client and routing info',
8738     items: [{
8739         fieldLabel: 'Client',
8740         name: 'clientName'
8741     }, {
8742         fieldLabel: 'Port of loading',
8743         name: 'portOfLoading'
8744     }, {
8745         fieldLabel: 'Port of discharge',
8746         name: 'portOfDischarge'
8747     }]
8748 });
8749 myFormPanel.{@link Ext.form.FormPanel#getForm getForm}().{@link Ext.form.BasicForm#load load}({
8750     url: '/getRoutingInfo.php',
8751     params: {
8752         consignmentRef: myConsignmentRef
8753     },
8754     failure: function(form, action) {
8755         Ext.Msg.alert("Load failed", action.result.errorMessage);
8756     }
8757 });
8758 </code></pre>
8759  * a <b>success response</b> packet may look like this:</p><pre><code>
8760 {
8761     success: true,
8762     data: {
8763         clientName: "Fred. Olsen Lines",
8764         portOfLoading: "FXT",
8765         portOfDischarge: "OSL"
8766     }
8767 }</code></pre>
8768  * while a <b>failure response</b> packet may look like this:</p><pre><code>
8769 {
8770     success: false,
8771     errorMessage: "Consignment reference not found"
8772 }</code></pre>
8773  * <p>Other data may be placed into the response for processing the {@link Ext.form.BasicForm Form}'s
8774  * callback or event handler methods. The object decoded from this JSON is available in the
8775  * {@link Ext.form.Action#result result} property.</p>
8776  */
8777 Ext.form.Action.Load = function(form, options){
8778     Ext.form.Action.Load.superclass.constructor.call(this, form, options);
8779     this.reader = this.form.reader;
8780 };
8781
8782 Ext.extend(Ext.form.Action.Load, Ext.form.Action, {
8783     // private
8784     type : 'load',
8785
8786     // private
8787     run : function(){
8788         Ext.Ajax.request(Ext.apply(
8789                 this.createCallback(this.options), {
8790                     method:this.getMethod(),
8791                     url:this.getUrl(false),
8792                     headers: this.options.headers,
8793                     params:this.getParams()
8794         }));
8795     },
8796
8797     // private
8798     success : function(response){
8799         var result = this.processResponse(response);
8800         if(result === true || !result.success || !result.data){
8801             this.failureType = Ext.form.Action.LOAD_FAILURE;
8802             this.form.afterAction(this, false);
8803             return;
8804         }
8805         this.form.clearInvalid();
8806         this.form.setValues(result.data);
8807         this.form.afterAction(this, true);
8808     },
8809
8810     // private
8811     handleResponse : function(response){
8812         if(this.form.reader){
8813             var rs = this.form.reader.read(response);
8814             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
8815             return {
8816                 success : rs.success,
8817                 data : data
8818             };
8819         }
8820         return Ext.decode(response.responseText);
8821     }
8822 });
8823
8824
8825
8826 /**
8827  * @class Ext.form.Action.DirectLoad
8828  * @extends Ext.form.Action.Load
8829  * <p>Provides Ext.direct support for loading form data.</p>
8830  * <p>This example illustrates usage of Ext.Direct to <b>load</b> a form through Ext.Direct.</p>
8831  * <pre><code>
8832 var myFormPanel = new Ext.form.FormPanel({
8833     // configs for FormPanel
8834     title: 'Basic Information',
8835     renderTo: document.body,
8836     width: 300, height: 160,
8837     padding: 10,
8838
8839     // configs apply to child items
8840     defaults: {anchor: '100%'},
8841     defaultType: 'textfield',
8842     items: [{
8843         fieldLabel: 'Name',
8844         name: 'name'
8845     },{
8846         fieldLabel: 'Email',
8847         name: 'email'
8848     },{
8849         fieldLabel: 'Company',
8850         name: 'company'
8851     }],
8852
8853     // configs for BasicForm
8854     api: {
8855         // The server-side method to call for load() requests
8856         load: Profile.getBasicInfo,
8857         // The server-side must mark the submit handler as a 'formHandler'
8858         submit: Profile.updateBasicInfo
8859     },
8860     // specify the order for the passed params
8861     paramOrder: ['uid', 'foo']
8862 });
8863
8864 // load the form
8865 myFormPanel.getForm().load({
8866     // pass 2 arguments to server side getBasicInfo method (len=2)
8867     params: {
8868         foo: 'bar',
8869         uid: 34
8870     }
8871 });
8872  * </code></pre>
8873  * The data packet sent to the server will resemble something like:
8874  * <pre><code>
8875 [
8876     {
8877         "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
8878         "data":[34,"bar"] // note the order of the params
8879     }
8880 ]
8881  * </code></pre>
8882  * The form will process a data packet returned by the server that is similar
8883  * to the following format:
8884  * <pre><code>
8885 [
8886     {
8887         "action":"Profile","method":"getBasicInfo","type":"rpc","tid":2,
8888         "result":{
8889             "success":true,
8890             "data":{
8891                 "name":"Fred Flintstone",
8892                 "company":"Slate Rock and Gravel",
8893                 "email":"fred.flintstone@slaterg.com"
8894             }
8895         }
8896     }
8897 ]
8898  * </code></pre>
8899  */
8900 Ext.form.Action.DirectLoad = Ext.extend(Ext.form.Action.Load, {
8901     constructor: function(form, opts) {
8902         Ext.form.Action.DirectLoad.superclass.constructor.call(this, form, opts);
8903     },
8904     type : 'directload',
8905
8906     run : function(){
8907         var args = this.getParams();
8908         args.push(this.success, this);
8909         this.form.api.load.apply(window, args);
8910     },
8911
8912     getParams : function() {
8913         var buf = [], o = {};
8914         var bp = this.form.baseParams;
8915         var p = this.options.params;
8916         Ext.apply(o, p, bp);
8917         var paramOrder = this.form.paramOrder;
8918         if(paramOrder){
8919             for(var i = 0, len = paramOrder.length; i < len; i++){
8920                 buf.push(o[paramOrder[i]]);
8921             }
8922         }else if(this.form.paramsAsHash){
8923             buf.push(o);
8924         }
8925         return buf;
8926     },
8927     // Direct actions have already been processed and therefore
8928     // we can directly set the result; Direct Actions do not have
8929     // a this.response property.
8930     processResponse : function(result) {
8931         this.result = result;
8932         return result;
8933     },
8934
8935     success : function(response, trans){
8936         if(trans.type == Ext.Direct.exceptions.SERVER){
8937             response = {};
8938         }
8939         Ext.form.Action.DirectLoad.superclass.success.call(this, response);
8940     }
8941 });
8942
8943 /**
8944  * @class Ext.form.Action.DirectSubmit
8945  * @extends Ext.form.Action.Submit
8946  * <p>Provides Ext.direct support for submitting form data.</p>
8947  * <p>This example illustrates usage of Ext.Direct to <b>submit</b> a form through Ext.Direct.</p>
8948  * <pre><code>
8949 var myFormPanel = new Ext.form.FormPanel({
8950     // configs for FormPanel
8951     title: 'Basic Information',
8952     renderTo: document.body,
8953     width: 300, height: 160,
8954     padding: 10,
8955     buttons:[{
8956         text: 'Submit',
8957         handler: function(){
8958             myFormPanel.getForm().submit({
8959                 params: {
8960                     foo: 'bar',
8961                     uid: 34
8962                 }
8963             });
8964         }
8965     }],
8966
8967     // configs apply to child items
8968     defaults: {anchor: '100%'},
8969     defaultType: 'textfield',
8970     items: [{
8971         fieldLabel: 'Name',
8972         name: 'name'
8973     },{
8974         fieldLabel: 'Email',
8975         name: 'email'
8976     },{
8977         fieldLabel: 'Company',
8978         name: 'company'
8979     }],
8980
8981     // configs for BasicForm
8982     api: {
8983         // The server-side method to call for load() requests
8984         load: Profile.getBasicInfo,
8985         // The server-side must mark the submit handler as a 'formHandler'
8986         submit: Profile.updateBasicInfo
8987     },
8988     // specify the order for the passed params
8989     paramOrder: ['uid', 'foo']
8990 });
8991  * </code></pre>
8992  * The data packet sent to the server will resemble something like:
8993  * <pre><code>
8994 {
8995     "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
8996     "result":{
8997         "success":true,
8998         "id":{
8999             "extAction":"Profile","extMethod":"updateBasicInfo",
9000             "extType":"rpc","extTID":"6","extUpload":"false",
9001             "name":"Aaron Conran","email":"aaron@extjs.com","company":"Ext JS, LLC"
9002         }
9003     }
9004 }
9005  * </code></pre>
9006  * The form will process a data packet returned by the server that is similar
9007  * to the following:
9008  * <pre><code>
9009 // sample success packet (batched requests)
9010 [
9011     {
9012         "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":3,
9013         "result":{
9014             "success":true
9015         }
9016     }
9017 ]
9018
9019 // sample failure packet (one request)
9020 {
9021         "action":"Profile","method":"updateBasicInfo","type":"rpc","tid":"6",
9022         "result":{
9023             "errors":{
9024                 "email":"already taken"
9025             },
9026             "success":false,
9027             "foo":"bar"
9028         }
9029 }
9030  * </code></pre>
9031  * Also see the discussion in {@link Ext.form.Action.DirectLoad}.
9032  */
9033 Ext.form.Action.DirectSubmit = Ext.extend(Ext.form.Action.Submit, {
9034     constructor : function(form, opts) {
9035         Ext.form.Action.DirectSubmit.superclass.constructor.call(this, form, opts);
9036     },
9037     type : 'directsubmit',
9038     // override of Submit
9039     run : function(){
9040         var o = this.options;
9041         if(o.clientValidation === false || this.form.isValid()){
9042             // tag on any additional params to be posted in the
9043             // form scope
9044             this.success.params = this.getParams();
9045             this.form.api.submit(this.form.el.dom, this.success, this);
9046         }else if (o.clientValidation !== false){ // client validation failed
9047             this.failureType = Ext.form.Action.CLIENT_INVALID;
9048             this.form.afterAction(this, false);
9049         }
9050     },
9051
9052     getParams : function() {
9053         var o = {};
9054         var bp = this.form.baseParams;
9055         var p = this.options.params;
9056         Ext.apply(o, p, bp);
9057         return o;
9058     },
9059     // Direct actions have already been processed and therefore
9060     // we can directly set the result; Direct Actions do not have
9061     // a this.response property.
9062     processResponse : function(result) {
9063         this.result = result;
9064         return result;
9065     },
9066
9067     success : function(response, trans){
9068         if(trans.type == Ext.Direct.exceptions.SERVER){
9069             response = {};
9070         }
9071         Ext.form.Action.DirectSubmit.superclass.success.call(this, response);
9072     }
9073 });
9074
9075 Ext.form.Action.ACTION_TYPES = {
9076     'load' : Ext.form.Action.Load,
9077     'submit' : Ext.form.Action.Submit,
9078     'directload' : Ext.form.Action.DirectLoad,
9079     'directsubmit' : Ext.form.Action.DirectSubmit
9080 };
9081 /**
9082  * @class Ext.form.VTypes
9083  * <p>This is a singleton object which contains a set of commonly used field validation functions.
9084  * The validations provided are basic and intended to be easily customizable and extended.</p>
9085  * <p>To add custom VTypes specify the <code>{@link Ext.form.TextField#vtype vtype}</code> validation
9086  * test function, and optionally specify any corresponding error text to display and any keystroke
9087  * filtering mask to apply. For example:</p>
9088  * <pre><code>
9089 // custom Vtype for vtype:'time'
9090 var timeTest = /^([1-9]|1[0-9]):([0-5][0-9])(\s[a|p]m)$/i;
9091 Ext.apply(Ext.form.VTypes, {
9092     //  vtype validation function
9093     time: function(val, field) {
9094         return timeTest.test(val);
9095     },
9096     // vtype Text property: The error text to display when the validation function returns false
9097     timeText: 'Not a valid time.  Must be in the format "12:34 PM".',
9098     // vtype Mask property: The keystroke filter mask
9099     timeMask: /[\d\s:amp]/i
9100 });
9101  * </code></pre>
9102  * Another example:
9103  * <pre><code>
9104 // custom Vtype for vtype:'IPAddress'
9105 Ext.apply(Ext.form.VTypes, {
9106     IPAddress:  function(v) {
9107         return /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(v);
9108     },
9109     IPAddressText: 'Must be a numeric IP address',
9110     IPAddressMask: /[\d\.]/i
9111 });
9112  * </code></pre>
9113  * @singleton
9114  */
9115 Ext.form.VTypes = function(){
9116     // closure these in so they are only created once.
9117     var alpha = /^[a-zA-Z_]+$/,
9118         alphanum = /^[a-zA-Z0-9_]+$/,
9119         email = /^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/,
9120         url = /(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i;
9121
9122     // All these messages and functions are configurable
9123     return {
9124         /**
9125          * The function used to validate email addresses.  Note that this is a very basic validation -- complete
9126          * validation per the email RFC specifications is very complex and beyond the scope of this class, although
9127          * this function can be overridden if a more comprehensive validation scheme is desired.  See the validation
9128          * section of the <a href="http://en.wikipedia.org/wiki/E-mail_address">Wikipedia article on email addresses</a>
9129          * for additional information.  This implementation is intended to validate the following emails:<tt>
9130          * 'barney@example.de', 'barney.rubble@example.com', 'barney-rubble@example.coop', 'barney+rubble@example.com'
9131          * </tt>.
9132          * @param {String} value The email address
9133          * @return {Boolean} true if the RegExp test passed, and false if not.
9134          */
9135         'email' : function(v){
9136             return email.test(v);
9137         },
9138         /**
9139          * The error text to display when the email validation function returns false.  Defaults to:
9140          * <tt>'This field should be an e-mail address in the format "user@example.com"'</tt>
9141          * @type String
9142          */
9143         'emailText' : 'This field should be an e-mail address in the format "user@example.com"',
9144         /**
9145          * The keystroke filter mask to be applied on email input.  See the {@link #email} method for
9146          * information about more complex email validation. Defaults to:
9147          * <tt>/[a-z0-9_\.\-@]/i</tt>
9148          * @type RegExp
9149          */
9150         'emailMask' : /[a-z0-9_\.\-@\+]/i,
9151
9152         /**
9153          * The function used to validate URLs
9154          * @param {String} value The URL
9155          * @return {Boolean} true if the RegExp test passed, and false if not.
9156          */
9157         'url' : function(v){
9158             return url.test(v);
9159         },
9160         /**
9161          * The error text to display when the url validation function returns false.  Defaults to:
9162          * <tt>'This field should be a URL in the format "http:/'+'/www.example.com"'</tt>
9163          * @type String
9164          */
9165         'urlText' : 'This field should be a URL in the format "http:/'+'/www.example.com"',
9166
9167         /**
9168          * The function used to validate alpha values
9169          * @param {String} value The value
9170          * @return {Boolean} true if the RegExp test passed, and false if not.
9171          */
9172         'alpha' : function(v){
9173             return alpha.test(v);
9174         },
9175         /**
9176          * The error text to display when the alpha validation function returns false.  Defaults to:
9177          * <tt>'This field should only contain letters and _'</tt>
9178          * @type String
9179          */
9180         'alphaText' : 'This field should only contain letters and _',
9181         /**
9182          * The keystroke filter mask to be applied on alpha input.  Defaults to:
9183          * <tt>/[a-z_]/i</tt>
9184          * @type RegExp
9185          */
9186         'alphaMask' : /[a-z_]/i,
9187
9188         /**
9189          * The function used to validate alphanumeric values
9190          * @param {String} value The value
9191          * @return {Boolean} true if the RegExp test passed, and false if not.
9192          */
9193         'alphanum' : function(v){
9194             return alphanum.test(v);
9195         },
9196         /**
9197          * The error text to display when the alphanumeric validation function returns false.  Defaults to:
9198          * <tt>'This field should only contain letters, numbers and _'</tt>
9199          * @type String
9200          */
9201         'alphanumText' : 'This field should only contain letters, numbers and _',
9202         /**
9203          * The keystroke filter mask to be applied on alphanumeric input.  Defaults to:
9204          * <tt>/[a-z0-9_]/i</tt>
9205          * @type RegExp
9206          */
9207         'alphanumMask' : /[a-z0-9_]/i
9208     };
9209 }();