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