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