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