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