+ /**
+ * Retrieve a tool by id.
+ * @param {String} id
+ * @return {Object} tool
+ */
+ getTool : function(id) {
+ return this.tools[id];
+ }
+
+/**
+ * @cfg {String} autoEl @hide
+ */
+});
+Ext.reg('panel', Ext.Panel);
+/**
+ * @class Ext.Editor
+ * @extends Ext.Component
+ * A base editor field that handles displaying/hiding on demand and has some built-in sizing and event handling logic.
+ * @constructor
+ * Create a new Editor
+ * @param {Object} config The config object
+ * @xtype editor
+ */
+Ext.Editor = function(field, config){
+ if(field.field){
+ this.field = Ext.create(field.field, 'textfield');
+ config = Ext.apply({}, field); // copy so we don't disturb original config
+ delete config.field;
+ }else{
+ this.field = field;
+ }
+ Ext.Editor.superclass.constructor.call(this, config);
+};
+
+Ext.extend(Ext.Editor, Ext.Component, {
+ /**
+ * @cfg {Ext.form.Field} field
+ * The Field object (or descendant) or config object for field
+ */
+ /**
+ * @cfg {Boolean} allowBlur
+ * True to {@link #completeEdit complete the editing process} if in edit mode when the
+ * field is blurred. Defaults to <tt>true</tt>.
+ */
+ allowBlur: true,
+ /**
+ * @cfg {Boolean/String} autoSize
+ * True for the editor to automatically adopt the size of the underlying field, "width" to adopt the width only,
+ * or "height" to adopt the height only, "none" to always use the field dimensions. (defaults to false)
+ */
+ /**
+ * @cfg {Boolean} revertInvalid
+ * True to automatically revert the field value and cancel the edit when the user completes an edit and the field
+ * validation fails (defaults to true)
+ */
+ /**
+ * @cfg {Boolean} ignoreNoChange
+ * True to skip the edit completion process (no save, no events fired) if the user completes an edit and
+ * the value has not changed (defaults to false). Applies only to string values - edits for other data types
+ * will never be ignored.
+ */
+ /**
+ * @cfg {Boolean} hideEl
+ * False to keep the bound element visible while the editor is displayed (defaults to true)
+ */
+ /**
+ * @cfg {Mixed} value
+ * The data value of the underlying field (defaults to "")
+ */
+ value : "",
+ /**
+ * @cfg {String} alignment
+ * The position to align to (see {@link Ext.Element#alignTo} for more details, defaults to "c-c?").
+ */
+ alignment: "c-c?",
+ /**
+ * @cfg {Array} offsets
+ * The offsets to use when aligning (see {@link Ext.Element#alignTo} for more details. Defaults to <tt>[0, 0]</tt>.
+ */
+ offsets: [0, 0],
+ /**
+ * @cfg {Boolean/String} shadow "sides" for sides/bottom only, "frame" for 4-way shadow, and "drop"
+ * for bottom-right shadow (defaults to "frame")
+ */
+ shadow : "frame",
+ /**
+ * @cfg {Boolean} constrain True to constrain the editor to the viewport
+ */
+ constrain : false,
+ /**
+ * @cfg {Boolean} swallowKeys Handle the keydown/keypress events so they don't propagate (defaults to true)
+ */
+ swallowKeys : true,
+ /**
+ * @cfg {Boolean} completeOnEnter True to complete the edit when the enter key is pressed. Defaults to <tt>true</tt>.
+ */
+ completeOnEnter : true,
+ /**
+ * @cfg {Boolean} cancelOnEsc True to cancel the edit when the escape key is pressed. Defaults to <tt>true</tt>.
+ */
+ cancelOnEsc : true,
+ /**
+ * @cfg {Boolean} updateEl True to update the innerHTML of the bound element when the update completes (defaults to false)
+ */
+ updateEl : false,
+
+ initComponent : function(){
+ Ext.Editor.superclass.initComponent.call(this);
+ this.addEvents(
+ /**
+ * @event beforestartedit
+ * Fires when editing is initiated, but before the value changes. Editing can be canceled by returning
+ * false from the handler of this event.
+ * @param {Editor} this
+ * @param {Ext.Element} boundEl The underlying element bound to this editor
+ * @param {Mixed} value The field value being set
+ */
+ "beforestartedit",
+ /**
+ * @event startedit
+ * Fires when this editor is displayed
+ * @param {Ext.Element} boundEl The underlying element bound to this editor
+ * @param {Mixed} value The starting field value
+ */
+ "startedit",
+ /**
+ * @event beforecomplete
+ * Fires after a change has been made to the field, but before the change is reflected in the underlying
+ * field. Saving the change to the field can be canceled by returning false from the handler of this event.
+ * Note that if the value has not changed and ignoreNoChange = true, the editing will still end but this
+ * event will not fire since no edit actually occurred.
+ * @param {Editor} this
+ * @param {Mixed} value The current field value
+ * @param {Mixed} startValue The original field value
+ */
+ "beforecomplete",
+ /**
+ * @event complete
+ * Fires after editing is complete and any changed value has been written to the underlying field.
+ * @param {Editor} this
+ * @param {Mixed} value The current field value
+ * @param {Mixed} startValue The original field value
+ */
+ "complete",
+ /**
+ * @event canceledit
+ * Fires after editing has been canceled and the editor's value has been reset.
+ * @param {Editor} this
+ * @param {Mixed} value The user-entered field value that was discarded
+ * @param {Mixed} startValue The original field value that was set back into the editor after cancel
+ */
+ "canceledit",
+ /**
+ * @event specialkey
+ * Fires when any key related to navigation (arrows, tab, enter, esc, etc.) is pressed. You can check
+ * {@link Ext.EventObject#getKey} to determine which key was pressed.
+ * @param {Ext.form.Field} this
+ * @param {Ext.EventObject} e The event object
+ */
+ "specialkey"
+ );
+ },
+
+ // private
+ onRender : function(ct, position){
+ this.el = new Ext.Layer({
+ shadow: this.shadow,
+ cls: "x-editor",
+ parentEl : ct,
+ shim : this.shim,
+ shadowOffset: this.shadowOffset || 4,
+ id: this.id,
+ constrain: this.constrain
+ });
+ if(this.zIndex){
+ this.el.setZIndex(this.zIndex);
+ }
+ this.el.setStyle("overflow", Ext.isGecko ? "auto" : "hidden");
+ if(this.field.msgTarget != 'title'){
+ this.field.msgTarget = 'qtip';
+ }
+ this.field.inEditor = true;
+ this.mon(this.field, {
+ scope: this,
+ blur: this.onBlur,
+ specialkey: this.onSpecialKey
+ });
+ if(this.field.grow){
+ this.mon(this.field, "autosize", this.el.sync, this.el, {delay:1});
+ }
+ this.field.render(this.el).show();
+ this.field.getEl().dom.name = '';
+ if(this.swallowKeys){
+ this.field.el.swallowEvent([
+ 'keypress', // *** Opera
+ 'keydown' // *** all other browsers
+ ]);
+ }
+ },
+
+ // private
+ onSpecialKey : function(field, e){
+ var key = e.getKey(),
+ complete = this.completeOnEnter && key == e.ENTER,
+ cancel = this.cancelOnEsc && key == e.ESC;
+ if(complete || cancel){
+ e.stopEvent();
+ if(complete){
+ this.completeEdit();
+ }else{
+ this.cancelEdit();
+ }
+ if(field.triggerBlur){
+ field.triggerBlur();
+ }
+ }
+ this.fireEvent('specialkey', field, e);
+ },
+
+ /**
+ * Starts the editing process and shows the editor.
+ * @param {Mixed} el The element to edit
+ * @param {String} value (optional) A value to initialize the editor with. If a value is not provided, it defaults
+ * to the innerHTML of el.
+ */
+ startEdit : function(el, value){
+ if(this.editing){
+ this.completeEdit();
+ }
+ this.boundEl = Ext.get(el);
+ var v = value !== undefined ? value : this.boundEl.dom.innerHTML;
+ if(!this.rendered){
+ this.render(this.parentEl || document.body);
+ }
+ if(this.fireEvent("beforestartedit", this, this.boundEl, v) !== false){
+ this.startValue = v;
+ this.field.reset();
+ this.field.setValue(v);
+ this.realign(true);
+ this.editing = true;
+ this.show();
+ }
+ },
+
+ // private
+ doAutoSize : function(){
+ if(this.autoSize){
+ var sz = this.boundEl.getSize(),
+ fs = this.field.getSize();
+
+ switch(this.autoSize){
+ case "width":
+ this.setSize(sz.width, fs.height);
+ break;
+ case "height":
+ this.setSize(fs.width, sz.height);
+ break;
+ case "none":
+ this.setSize(fs.width, fs.height);
+ break;
+ default:
+ this.setSize(sz.width, sz.height);
+ }
+ }
+ },
+
+ /**
+ * Sets the height and width of this editor.
+ * @param {Number} width The new width
+ * @param {Number} height The new height
+ */
+ setSize : function(w, h){
+ delete this.field.lastSize;
+ this.field.setSize(w, h);
+ if(this.el){
+ if(Ext.isGecko2 || Ext.isOpera){
+ // prevent layer scrollbars
+ this.el.setSize(w, h);
+ }
+ this.el.sync();
+ }
+ },
+
+ /**
+ * Realigns the editor to the bound field based on the current alignment config value.
+ * @param {Boolean} autoSize (optional) True to size the field to the dimensions of the bound element.
+ */
+ realign : function(autoSize){
+ if(autoSize === true){
+ this.doAutoSize();
+ }
+ this.el.alignTo(this.boundEl, this.alignment, this.offsets);
+ },
+
+ /**
+ * Ends the editing process, persists the changed value to the underlying field, and hides the editor.
+ * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after edit (defaults to false)
+ */
+ completeEdit : function(remainVisible){
+ if(!this.editing){
+ return;
+ }
+ // Assert combo values first
+ if (this.field.assertValue) {
+ this.field.assertValue();
+ }
+ var v = this.getValue();
+ if(!this.field.isValid()){
+ if(this.revertInvalid !== false){
+ this.cancelEdit(remainVisible);
+ }
+ return;
+ }
+ if(String(v) === String(this.startValue) && this.ignoreNoChange){
+ this.hideEdit(remainVisible);
+ return;
+ }
+ if(this.fireEvent("beforecomplete", this, v, this.startValue) !== false){
+ v = this.getValue();
+ if(this.updateEl && this.boundEl){
+ this.boundEl.update(v);
+ }
+ this.hideEdit(remainVisible);
+ this.fireEvent("complete", this, v, this.startValue);
+ }
+ },
+
+ // private
+ onShow : function(){
+ this.el.show();
+ if(this.hideEl !== false){
+ this.boundEl.hide();
+ }
+ this.field.show().focus(false, true);
+ this.fireEvent("startedit", this.boundEl, this.startValue);
+ },
+
+ /**
+ * Cancels the editing process and hides the editor without persisting any changes. The field value will be
+ * reverted to the original starting value.
+ * @param {Boolean} remainVisible Override the default behavior and keep the editor visible after
+ * cancel (defaults to false)
+ */
+ cancelEdit : function(remainVisible){
+ if(this.editing){
+ var v = this.getValue();
+ this.setValue(this.startValue);
+ this.hideEdit(remainVisible);
+ this.fireEvent("canceledit", this, v, this.startValue);
+ }
+ },
+
+ // private
+ hideEdit: function(remainVisible){
+ if(remainVisible !== true){
+ this.editing = false;
+ this.hide();
+ }
+ },
+
+ // private
+ onBlur : function(){
+ // selectSameEditor flag allows the same editor to be started without onBlur firing on itself
+ if(this.allowBlur === true && this.editing && this.selectSameEditor !== true){
+ this.completeEdit();
+ }
+ },
+
+ // private
+ onHide : function(){
+ if(this.editing){
+ this.completeEdit();
+ return;
+ }
+ this.field.blur();
+ if(this.field.collapse){
+ this.field.collapse();
+ }
+ this.el.hide();
+ if(this.hideEl !== false){
+ this.boundEl.show();
+ }
+ },
+
+ /**
+ * Sets the data value of the editor
+ * @param {Mixed} value Any valid value supported by the underlying field
+ */
+ setValue : function(v){
+ this.field.setValue(v);
+ },
+
+ /**
+ * Gets the data value of the editor
+ * @return {Mixed} The data value
+ */
+ getValue : function(){
+ return this.field.getValue();
+ },
+
+ beforeDestroy : function(){
+ Ext.destroyMembers(this, 'field');
+
+ delete this.parentEl;
+ delete this.boundEl;
+ }
+});
+Ext.reg('editor', Ext.Editor);
+/**
+ * @class Ext.ColorPalette
+ * @extends Ext.Component
+ * Simple color palette class for choosing colors. The palette can be rendered to any container.<br />
+ * Here's an example of typical usage:
+ * <pre><code>
+var cp = new Ext.ColorPalette({value:'993300'}); // initial selected color
+cp.render('my-div');
+
+cp.on('select', function(palette, selColor){
+ // do something with selColor
+});
+</code></pre>
+ * @constructor
+ * Create a new ColorPalette
+ * @param {Object} config The config object
+ * @xtype colorpalette
+ */
+Ext.ColorPalette = Ext.extend(Ext.Component, {
+ /**
+ * @cfg {String} tpl An existing XTemplate instance to be used in place of the default template for rendering the component.
+ */
+ /**
+ * @cfg {String} itemCls
+ * The CSS class to apply to the containing element (defaults to 'x-color-palette')
+ */
+ itemCls : 'x-color-palette',
+ /**
+ * @cfg {String} value
+ * The initial color to highlight (should be a valid 6-digit color hex code without the # symbol). Note that
+ * the hex codes are case-sensitive.
+ */
+ value : null,
+ /**
+ * @cfg {String} clickEvent
+ * The DOM event that will cause a color to be selected. This can be any valid event name (dblclick, contextmenu).
+ * Defaults to <tt>'click'</tt>.
+ */
+ clickEvent :'click',
+ // private
+ ctype : 'Ext.ColorPalette',
+
+ /**
+ * @cfg {Boolean} allowReselect If set to true then reselecting a color that is already selected fires the {@link #select} event
+ */
+ allowReselect : false,
+
+ /**
+ * <p>An array of 6-digit color hex code strings (without the # symbol). This array can contain any number
+ * of colors, and each hex code should be unique. The width of the palette is controlled via CSS by adjusting
+ * the width property of the 'x-color-palette' class (or assigning a custom class), so you can balance the number
+ * of colors with the width setting until the box is symmetrical.</p>
+ * <p>You can override individual colors if needed:</p>
+ * <pre><code>
+var cp = new Ext.ColorPalette();
+cp.colors[0] = 'FF0000'; // change the first box to red
+</code></pre>
+
+Or you can provide a custom array of your own for complete control:
+<pre><code>
+var cp = new Ext.ColorPalette();
+cp.colors = ['000000', '993300', '333300'];
+</code></pre>
+ * @type Array
+ */
+ colors : [
+ '000000', '993300', '333300', '003300', '003366', '000080', '333399', '333333',
+ '800000', 'FF6600', '808000', '008000', '008080', '0000FF', '666699', '808080',
+ 'FF0000', 'FF9900', '99CC00', '339966', '33CCCC', '3366FF', '800080', '969696',
+ 'FF00FF', 'FFCC00', 'FFFF00', '00FF00', '00FFFF', '00CCFF', '993366', 'C0C0C0',
+ 'FF99CC', 'FFCC99', 'FFFF99', 'CCFFCC', 'CCFFFF', '99CCFF', 'CC99FF', 'FFFFFF'
+ ],
+
+ /**
+ * @cfg {Function} handler
+ * Optional. A function that will handle the select event of this palette.
+ * The handler is passed the following parameters:<div class="mdetail-params"><ul>
+ * <li><code>palette</code> : ColorPalette<div class="sub-desc">The {@link #palette Ext.ColorPalette}.</div></li>
+ * <li><code>color</code> : String<div class="sub-desc">The 6-digit color hex code (without the # symbol).</div></li>
+ * </ul></div>
+ */
+ /**
+ * @cfg {Object} scope
+ * The scope (<tt><b>this</b></tt> reference) in which the <code>{@link #handler}</code>
+ * function will be called. Defaults to this ColorPalette instance.
+ */
+
+ // private
+ initComponent : function(){
+ Ext.ColorPalette.superclass.initComponent.call(this);
+ this.addEvents(
+ /**
+ * @event select
+ * Fires when a color is selected
+ * @param {ColorPalette} this
+ * @param {String} color The 6-digit color hex code (without the # symbol)
+ */
+ 'select'
+ );
+
+ if(this.handler){
+ this.on('select', this.handler, this.scope, true);
+ }
+ },
+
+ // private
+ onRender : function(container, position){
+ this.autoEl = {
+ tag: 'div',
+ cls: this.itemCls
+ };
+ Ext.ColorPalette.superclass.onRender.call(this, container, position);
+ var t = this.tpl || new Ext.XTemplate(
+ '<tpl for="."><a href="#" class="color-{.}" hidefocus="on"><em><span style="background:#{.}" unselectable="on"> </span></em></a></tpl>'
+ );
+ t.overwrite(this.el, this.colors);
+ this.mon(this.el, this.clickEvent, this.handleClick, this, {delegate: 'a'});
+ if(this.clickEvent != 'click'){
+ this.mon(this.el, 'click', Ext.emptyFn, this, {delegate: 'a', preventDefault: true});
+ }
+ },
+
+ // private
+ afterRender : function(){
+ Ext.ColorPalette.superclass.afterRender.call(this);
+ if(this.value){
+ var s = this.value;
+ this.value = null;
+ this.select(s);
+ }
+ },
+
+ // private
+ handleClick : function(e, t){
+ e.preventDefault();
+ if(!this.disabled){
+ var c = t.className.match(/(?:^|\s)color-(.{6})(?:\s|$)/)[1];
+ this.select(c.toUpperCase());
+ }
+ },
+
+ /**
+ * Selects the specified color in the palette (fires the {@link #select} event)
+ * @param {String} color A valid 6-digit color hex code (# will be stripped if included)
+ */
+ select : function(color){
+ color = color.replace('#', '');
+ if(color != this.value || this.allowReselect){
+ var el = this.el;
+ if(this.value){
+ el.child('a.color-'+this.value).removeClass('x-color-palette-sel');
+ }
+ el.child('a.color-'+color).addClass('x-color-palette-sel');
+ this.value = color;
+ this.fireEvent('select', this, color);
+ }
+ }
+
+ /**
+ * @cfg {String} autoEl @hide
+ */
+});
+Ext.reg('colorpalette', Ext.ColorPalette);
+/**
+ * @class Ext.DatePicker
+ * @extends Ext.Component
+ * <p>A popup date picker. This class is used by the {@link Ext.form.DateField DateField} class
+ * to allow browsing and selection of valid dates.</p>
+ * <p>All the string values documented below may be overridden by including an Ext locale file in
+ * your page.</p>
+ * @constructor
+ * Create a new DatePicker
+ * @param {Object} config The config object
+ * @xtype datepicker
+ */
+Ext.DatePicker = Ext.extend(Ext.BoxComponent, {
+ /**
+ * @cfg {String} todayText
+ * The text to display on the button that selects the current date (defaults to <code>'Today'</code>)
+ */
+ todayText : 'Today',
+ /**
+ * @cfg {String} okText
+ * The text to display on the ok button (defaults to <code>' OK '</code> to give the user extra clicking room)
+ */
+ okText : ' OK ',
+ /**
+ * @cfg {String} cancelText
+ * The text to display on the cancel button (defaults to <code>'Cancel'</code>)
+ */
+ cancelText : 'Cancel',
+ /**
+ * @cfg {Function} handler
+ * Optional. A function that will handle the select event of this picker.
+ * The handler is passed the following parameters:<div class="mdetail-params"><ul>
+ * <li><code>picker</code> : DatePicker<div class="sub-desc">This DatePicker.</div></li>
+ * <li><code>date</code> : Date<div class="sub-desc">The selected date.</div></li>
+ * </ul></div>
+ */
+ /**
+ * @cfg {Object} scope
+ * The scope (<code><b>this</b></code> reference) in which the <code>{@link #handler}</code>
+ * function will be called. Defaults to this DatePicker instance.
+ */
+ /**
+ * @cfg {String} todayTip
+ * A string used to format the message for displaying in a tooltip over the button that
+ * selects the current date. Defaults to <code>'{0} (Spacebar)'</code> where
+ * the <code>{0}</code> token is replaced by today's date.
+ */
+ todayTip : '{0} (Spacebar)',
+ /**
+ * @cfg {String} minText
+ * The error text to display if the minDate validation fails (defaults to <code>'This date is before the minimum date'</code>)
+ */
+ minText : 'This date is before the minimum date',
+ /**
+ * @cfg {String} maxText
+ * The error text to display if the maxDate validation fails (defaults to <code>'This date is after the maximum date'</code>)
+ */
+ maxText : 'This date is after the maximum date',
+ /**
+ * @cfg {String} format
+ * The default date format string which can be overriden for localization support. The format must be
+ * valid according to {@link Date#parseDate} (defaults to <code>'m/d/y'</code>).
+ */
+ format : 'm/d/y',
+ /**
+ * @cfg {String} disabledDaysText
+ * The tooltip to display when the date falls on a disabled day (defaults to <code>'Disabled'</code>)
+ */
+ disabledDaysText : 'Disabled',
+ /**
+ * @cfg {String} disabledDatesText
+ * The tooltip text to display when the date falls on a disabled date (defaults to <code>'Disabled'</code>)
+ */
+ disabledDatesText : 'Disabled',
+ /**
+ * @cfg {Array} monthNames
+ * An array of textual month names which can be overriden for localization support (defaults to Date.monthNames)
+ */
+ monthNames : Date.monthNames,
+ /**
+ * @cfg {Array} dayNames
+ * An array of textual day names which can be overriden for localization support (defaults to Date.dayNames)
+ */
+ dayNames : Date.dayNames,
+ /**
+ * @cfg {String} nextText
+ * The next month navigation button tooltip (defaults to <code>'Next Month (Control+Right)'</code>)
+ */
+ nextText : 'Next Month (Control+Right)',
+ /**
+ * @cfg {String} prevText
+ * The previous month navigation button tooltip (defaults to <code>'Previous Month (Control+Left)'</code>)
+ */
+ prevText : 'Previous Month (Control+Left)',
+ /**
+ * @cfg {String} monthYearText
+ * The header month selector tooltip (defaults to <code>'Choose a month (Control+Up/Down to move years)'</code>)
+ */
+ monthYearText : 'Choose a month (Control+Up/Down to move years)',
+ /**
+ * @cfg {Number} startDay
+ * Day index at which the week should begin, 0-based (defaults to 0, which is Sunday)
+ */
+ startDay : 0,
+ /**
+ * @cfg {Boolean} showToday
+ * False to hide the footer area containing the Today button and disable the keyboard handler for spacebar
+ * that selects the current date (defaults to <code>true</code>).
+ */
+ showToday : true,
+ /**
+ * @cfg {Date} minDate
+ * Minimum allowable date (JavaScript date object, defaults to null)
+ */
+ /**
+ * @cfg {Date} maxDate
+ * Maximum allowable date (JavaScript date object, defaults to null)
+ */
+ /**
+ * @cfg {Array} disabledDays
+ * An array of days to disable, 0-based. For example, [0, 6] disables Sunday and Saturday (defaults to null).
+ */
+ /**
+ * @cfg {RegExp} disabledDatesRE
+ * JavaScript regular expression used to disable a pattern of dates (defaults to null). The {@link #disabledDates}
+ * config will generate this regex internally, but if you specify disabledDatesRE it will take precedence over the
+ * disabledDates value.
+ */
+ /**
+ * @cfg {Array} disabledDates
+ * An array of 'dates' to disable, as strings. These strings will be used to build a dynamic regular
+ * expression so they are very powerful. Some examples:
+ * <ul>
+ * <li>['03/08/2003', '09/16/2003'] would disable those exact dates</li>
+ * <li>['03/08', '09/16'] would disable those days for every year</li>
+ * <li>['^03/08'] would only match the beginning (useful if you are using short years)</li>
+ * <li>['03/../2006'] would disable every day in March 2006</li>
+ * <li>['^03'] would disable every day in every March</li>
+ * </ul>
+ * Note that the format of the dates included in the array should exactly match the {@link #format} config.
+ * In order to support regular expressions, if you are using a date format that has '.' in it, you will have to
+ * escape the dot when restricting dates. For example: ['03\\.08\\.03'].
+ */
+
+ // private
+ // Set by other components to stop the picker focus being updated when the value changes.
+ focusOnSelect: true,
+
+ // default value used to initialise each date in the DatePicker
+ // (note: 12 noon was chosen because it steers well clear of all DST timezone changes)
+ initHour: 12, // 24-hour format
+
+ // private
+ initComponent : function(){
+ Ext.DatePicker.superclass.initComponent.call(this);
+
+ this.value = this.value ?
+ this.value.clearTime(true) : new Date().clearTime();
+
+ this.addEvents(
+ /**
+ * @event select
+ * Fires when a date is selected
+ * @param {DatePicker} this DatePicker
+ * @param {Date} date The selected date
+ */
+ 'select'
+ );
+
+ if(this.handler){
+ this.on('select', this.handler, this.scope || this);
+ }
+
+ this.initDisabledDays();
+ },
+
+ // private
+ initDisabledDays : function(){
+ if(!this.disabledDatesRE && this.disabledDates){
+ var dd = this.disabledDates,
+ len = dd.length - 1,
+ re = '(?:';
+
+ Ext.each(dd, function(d, i){
+ re += Ext.isDate(d) ? '^' + Ext.escapeRe(d.dateFormat(this.format)) + '$' : dd[i];
+ if(i != len){
+ re += '|';
+ }
+ }, this);
+ this.disabledDatesRE = new RegExp(re + ')');
+ }
+ },
+
+ /**
+ * Replaces any existing disabled dates with new values and refreshes the DatePicker.
+ * @param {Array/RegExp} disabledDates An array of date strings (see the {@link #disabledDates} config
+ * for details on supported values), or a JavaScript regular expression used to disable a pattern of dates.
+ */
+ setDisabledDates : function(dd){
+ if(Ext.isArray(dd)){
+ this.disabledDates = dd;
+ this.disabledDatesRE = null;
+ }else{
+ this.disabledDatesRE = dd;
+ }
+ this.initDisabledDays();
+ this.update(this.value, true);
+ },
+
+ /**
+ * Replaces any existing disabled days (by index, 0-6) with new values and refreshes the DatePicker.
+ * @param {Array} disabledDays An array of disabled day indexes. See the {@link #disabledDays} config
+ * for details on supported values.
+ */
+ setDisabledDays : function(dd){
+ this.disabledDays = dd;
+ this.update(this.value, true);
+ },
+
+ /**
+ * Replaces any existing {@link #minDate} with the new value and refreshes the DatePicker.
+ * @param {Date} value The minimum date that can be selected
+ */
+ setMinDate : function(dt){
+ this.minDate = dt;
+ this.update(this.value, true);
+ },
+
+ /**
+ * Replaces any existing {@link #maxDate} with the new value and refreshes the DatePicker.
+ * @param {Date} value The maximum date that can be selected
+ */
+ setMaxDate : function(dt){
+ this.maxDate = dt;
+ this.update(this.value, true);
+ },
+
+ /**
+ * Sets the value of the date field
+ * @param {Date} value The date to set
+ */
+ setValue : function(value){
+ this.value = value.clearTime(true);
+ this.update(this.value);
+ },
+
+ /**
+ * Gets the current selected value of the date field
+ * @return {Date} The selected date
+ */
+ getValue : function(){
+ return this.value;
+ },
+
+ // private
+ focus : function(){
+ this.update(this.activeDate);
+ },
+
+ // private
+ onEnable: function(initial){
+ Ext.DatePicker.superclass.onEnable.call(this);
+ this.doDisabled(false);
+ this.update(initial ? this.value : this.activeDate);
+ if(Ext.isIE){
+ this.el.repaint();
+ }
+
+ },
+
+ // private
+ onDisable : function(){
+ Ext.DatePicker.superclass.onDisable.call(this);
+ this.doDisabled(true);
+ if(Ext.isIE && !Ext.isIE8){
+ /* Really strange problem in IE6/7, when disabled, have to explicitly
+ * repaint each of the nodes to get them to display correctly, simply
+ * calling repaint on the main element doesn't appear to be enough.
+ */
+ Ext.each([].concat(this.textNodes, this.el.query('th span')), function(el){
+ Ext.fly(el).repaint();
+ });
+ }
+ },
+
+ // private
+ doDisabled : function(disabled){
+ this.keyNav.setDisabled(disabled);
+ this.prevRepeater.setDisabled(disabled);
+ this.nextRepeater.setDisabled(disabled);
+ if(this.showToday){
+ this.todayKeyListener.setDisabled(disabled);
+ this.todayBtn.setDisabled(disabled);
+ }
+ },
+
+ // private
+ onRender : function(container, position){
+ var m = [
+ '<table cellspacing="0">',
+ '<tr><td class="x-date-left"><a href="#" title="', this.prevText ,'"> </a></td><td class="x-date-middle" align="center"></td><td class="x-date-right"><a href="#" title="', this.nextText ,'"> </a></td></tr>',
+ '<tr><td colspan="3"><table class="x-date-inner" cellspacing="0"><thead><tr>'],
+ dn = this.dayNames,
+ i;
+ for(i = 0; i < 7; i++){
+ var d = this.startDay+i;
+ if(d > 6){
+ d = d-7;
+ }
+ m.push('<th><span>', dn[d].substr(0,1), '</span></th>');
+ }
+ m[m.length] = '</tr></thead><tbody><tr>';
+ for(i = 0; i < 42; i++) {
+ if(i % 7 === 0 && i !== 0){
+ m[m.length] = '</tr><tr>';
+ }
+ m[m.length] = '<td><a href="#" hidefocus="on" class="x-date-date" tabIndex="1"><em><span></span></em></a></td>';
+ }
+ m.push('</tr></tbody></table></td></tr>',
+ this.showToday ? '<tr><td colspan="3" class="x-date-bottom" align="center"></td></tr>' : '',
+ '</table><div class="x-date-mp"></div>');
+
+ var el = document.createElement('div');
+ el.className = 'x-date-picker';
+ el.innerHTML = m.join('');
+
+ container.dom.insertBefore(el, position);
+
+ this.el = Ext.get(el);
+ this.eventEl = Ext.get(el.firstChild);
+
+ this.prevRepeater = new Ext.util.ClickRepeater(this.el.child('td.x-date-left a'), {
+ handler: this.showPrevMonth,
+ scope: this,
+ preventDefault:true,
+ stopDefault:true
+ });
+
+ this.nextRepeater = new Ext.util.ClickRepeater(this.el.child('td.x-date-right a'), {
+ handler: this.showNextMonth,
+ scope: this,
+ preventDefault:true,
+ stopDefault:true
+ });
+
+ this.monthPicker = this.el.down('div.x-date-mp');
+ this.monthPicker.enableDisplayMode('block');
+
+ this.keyNav = new Ext.KeyNav(this.eventEl, {
+ 'left' : function(e){
+ if(e.ctrlKey){
+ this.showPrevMonth();
+ }else{
+ this.update(this.activeDate.add('d', -1));
+ }
+ },
+
+ 'right' : function(e){
+ if(e.ctrlKey){
+ this.showNextMonth();
+ }else{
+ this.update(this.activeDate.add('d', 1));
+ }
+ },
+
+ 'up' : function(e){
+ if(e.ctrlKey){
+ this.showNextYear();
+ }else{
+ this.update(this.activeDate.add('d', -7));
+ }
+ },
+
+ 'down' : function(e){
+ if(e.ctrlKey){
+ this.showPrevYear();
+ }else{
+ this.update(this.activeDate.add('d', 7));
+ }
+ },
+
+ 'pageUp' : function(e){
+ this.showNextMonth();
+ },
+
+ 'pageDown' : function(e){
+ this.showPrevMonth();
+ },
+
+ 'enter' : function(e){
+ e.stopPropagation();
+ return true;
+ },
+
+ scope : this
+ });
+
+ this.el.unselectable();
+
+ this.cells = this.el.select('table.x-date-inner tbody td');
+ this.textNodes = this.el.query('table.x-date-inner tbody span');
+
+ this.mbtn = new Ext.Button({
+ text: ' ',
+ tooltip: this.monthYearText,
+ renderTo: this.el.child('td.x-date-middle', true)
+ });
+ this.mbtn.el.child('em').addClass('x-btn-arrow');
+
+ if(this.showToday){
+ this.todayKeyListener = this.eventEl.addKeyListener(Ext.EventObject.SPACE, this.selectToday, this);
+ var today = (new Date()).dateFormat(this.format);
+ this.todayBtn = new Ext.Button({
+ renderTo: this.el.child('td.x-date-bottom', true),
+ text: String.format(this.todayText, today),
+ tooltip: String.format(this.todayTip, today),
+ handler: this.selectToday,
+ scope: this
+ });
+ }
+ this.mon(this.eventEl, 'mousewheel', this.handleMouseWheel, this);
+ this.mon(this.eventEl, 'click', this.handleDateClick, this, {delegate: 'a.x-date-date'});
+ this.mon(this.mbtn, 'click', this.showMonthPicker, this);
+ this.onEnable(true);
+ },
+
+ // private
+ createMonthPicker : function(){
+ if(!this.monthPicker.dom.firstChild){
+ var buf = ['<table border="0" cellspacing="0">'];
+ for(var i = 0; i < 6; i++){
+ buf.push(
+ '<tr><td class="x-date-mp-month"><a href="#">', Date.getShortMonthName(i), '</a></td>',
+ '<td class="x-date-mp-month x-date-mp-sep"><a href="#">', Date.getShortMonthName(i + 6), '</a></td>',
+ i === 0 ?
+ '<td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-prev"></a></td><td class="x-date-mp-ybtn" align="center"><a class="x-date-mp-next"></a></td></tr>' :
+ '<td class="x-date-mp-year"><a href="#"></a></td><td class="x-date-mp-year"><a href="#"></a></td></tr>'
+ );
+ }
+ buf.push(
+ '<tr class="x-date-mp-btns"><td colspan="4"><button type="button" class="x-date-mp-ok">',
+ this.okText,
+ '</button><button type="button" class="x-date-mp-cancel">',
+ this.cancelText,
+ '</button></td></tr>',
+ '</table>'
+ );
+ this.monthPicker.update(buf.join(''));
+
+ this.mon(this.monthPicker, 'click', this.onMonthClick, this);
+ this.mon(this.monthPicker, 'dblclick', this.onMonthDblClick, this);
+
+ this.mpMonths = this.monthPicker.select('td.x-date-mp-month');
+ this.mpYears = this.monthPicker.select('td.x-date-mp-year');
+
+ this.mpMonths.each(function(m, a, i){
+ i += 1;
+ if((i%2) === 0){
+ m.dom.xmonth = 5 + Math.round(i * 0.5);
+ }else{
+ m.dom.xmonth = Math.round((i-1) * 0.5);
+ }
+ });
+ }
+ },
+
+ // private
+ showMonthPicker : function(){
+ if(!this.disabled){
+ this.createMonthPicker();
+ var size = this.el.getSize();
+ this.monthPicker.setSize(size);
+ this.monthPicker.child('table').setSize(size);
+
+ this.mpSelMonth = (this.activeDate || this.value).getMonth();
+ this.updateMPMonth(this.mpSelMonth);
+ this.mpSelYear = (this.activeDate || this.value).getFullYear();
+ this.updateMPYear(this.mpSelYear);
+
+ this.monthPicker.slideIn('t', {duration:0.2});
+ }
+ },
+
+ // private
+ updateMPYear : function(y){
+ this.mpyear = y;
+ var ys = this.mpYears.elements;
+ for(var i = 1; i <= 10; i++){
+ var td = ys[i-1], y2;
+ if((i%2) === 0){
+ y2 = y + Math.round(i * 0.5);
+ td.firstChild.innerHTML = y2;
+ td.xyear = y2;
+ }else{
+ y2 = y - (5-Math.round(i * 0.5));
+ td.firstChild.innerHTML = y2;
+ td.xyear = y2;
+ }
+ this.mpYears.item(i-1)[y2 == this.mpSelYear ? 'addClass' : 'removeClass']('x-date-mp-sel');
+ }
+ },
+
+ // private
+ updateMPMonth : function(sm){
+ this.mpMonths.each(function(m, a, i){
+ m[m.dom.xmonth == sm ? 'addClass' : 'removeClass']('x-date-mp-sel');
+ });
+ },
+
+ // private
+ selectMPMonth : function(m){
+
+ },
+
+ // private
+ onMonthClick : function(e, t){
+ e.stopEvent();
+ var el = new Ext.Element(t), pn;
+ if(el.is('button.x-date-mp-cancel')){
+ this.hideMonthPicker();
+ }
+ else if(el.is('button.x-date-mp-ok')){
+ var d = new Date(this.mpSelYear, this.mpSelMonth, (this.activeDate || this.value).getDate());
+ if(d.getMonth() != this.mpSelMonth){
+ // 'fix' the JS rolling date conversion if needed
+ d = new Date(this.mpSelYear, this.mpSelMonth, 1).getLastDateOfMonth();
+ }
+ this.update(d);
+ this.hideMonthPicker();
+ }
+ else if((pn = el.up('td.x-date-mp-month', 2))){
+ this.mpMonths.removeClass('x-date-mp-sel');
+ pn.addClass('x-date-mp-sel');
+ this.mpSelMonth = pn.dom.xmonth;
+ }
+ else if((pn = el.up('td.x-date-mp-year', 2))){
+ this.mpYears.removeClass('x-date-mp-sel');
+ pn.addClass('x-date-mp-sel');
+ this.mpSelYear = pn.dom.xyear;
+ }
+ else if(el.is('a.x-date-mp-prev')){
+ this.updateMPYear(this.mpyear-10);
+ }
+ else if(el.is('a.x-date-mp-next')){
+ this.updateMPYear(this.mpyear+10);
+ }
+ },
+
+ // private
+ onMonthDblClick : function(e, t){
+ e.stopEvent();
+ var el = new Ext.Element(t), pn;
+ if((pn = el.up('td.x-date-mp-month', 2))){
+ this.update(new Date(this.mpSelYear, pn.dom.xmonth, (this.activeDate || this.value).getDate()));
+ this.hideMonthPicker();
+ }
+ else if((pn = el.up('td.x-date-mp-year', 2))){
+ this.update(new Date(pn.dom.xyear, this.mpSelMonth, (this.activeDate || this.value).getDate()));
+ this.hideMonthPicker();
+ }
+ },
+
+ // private
+ hideMonthPicker : function(disableAnim){
+ if(this.monthPicker){
+ if(disableAnim === true){
+ this.monthPicker.hide();
+ }else{
+ this.monthPicker.slideOut('t', {duration:0.2});
+ }
+ }
+ },
+
+ // private
+ showPrevMonth : function(e){
+ this.update(this.activeDate.add('mo', -1));
+ },
+
+ // private
+ showNextMonth : function(e){
+ this.update(this.activeDate.add('mo', 1));
+ },
+
+ // private
+ showPrevYear : function(){
+ this.update(this.activeDate.add('y', -1));
+ },
+
+ // private
+ showNextYear : function(){
+ this.update(this.activeDate.add('y', 1));
+ },
+
+ // private
+ handleMouseWheel : function(e){
+ e.stopEvent();
+ if(!this.disabled){
+ var delta = e.getWheelDelta();
+ if(delta > 0){
+ this.showPrevMonth();
+ } else if(delta < 0){
+ this.showNextMonth();
+ }
+ }
+ },
+
+ // private
+ handleDateClick : function(e, t){
+ e.stopEvent();
+ if(!this.disabled && t.dateValue && !Ext.fly(t.parentNode).hasClass('x-date-disabled')){
+ this.cancelFocus = this.focusOnSelect === false;
+ this.setValue(new Date(t.dateValue));
+ delete this.cancelFocus;
+ this.fireEvent('select', this, this.value);
+ }
+ },
+
+ // private
+ selectToday : function(){
+ if(this.todayBtn && !this.todayBtn.disabled){
+ this.setValue(new Date().clearTime());
+ this.fireEvent('select', this, this.value);
+ }
+ },
+
+ // private
+ update : function(date, forceRefresh){
+ if(this.rendered){
+ var vd = this.activeDate, vis = this.isVisible();
+ this.activeDate = date;
+ if(!forceRefresh && vd && this.el){
+ var t = date.getTime();
+ if(vd.getMonth() == date.getMonth() && vd.getFullYear() == date.getFullYear()){
+ this.cells.removeClass('x-date-selected');
+ this.cells.each(function(c){
+ if(c.dom.firstChild.dateValue == t){
+ c.addClass('x-date-selected');
+ if(vis && !this.cancelFocus){
+ Ext.fly(c.dom.firstChild).focus(50);
+ }
+ return false;
+ }
+ }, this);
+ return;
+ }
+ }
+ var days = date.getDaysInMonth(),
+ firstOfMonth = date.getFirstDateOfMonth(),
+ startingPos = firstOfMonth.getDay()-this.startDay;
+
+ if(startingPos < 0){
+ startingPos += 7;
+ }
+ days += startingPos;
+
+ var pm = date.add('mo', -1),
+ prevStart = pm.getDaysInMonth()-startingPos,
+ cells = this.cells.elements,
+ textEls = this.textNodes,
+ // convert everything to numbers so it's fast
+ d = (new Date(pm.getFullYear(), pm.getMonth(), prevStart, this.initHour)),
+ today = new Date().clearTime().getTime(),
+ sel = date.clearTime(true).getTime(),
+ min = this.minDate ? this.minDate.clearTime(true) : Number.NEGATIVE_INFINITY,
+ max = this.maxDate ? this.maxDate.clearTime(true) : Number.POSITIVE_INFINITY,
+ ddMatch = this.disabledDatesRE,
+ ddText = this.disabledDatesText,
+ ddays = this.disabledDays ? this.disabledDays.join('') : false,
+ ddaysText = this.disabledDaysText,
+ format = this.format;
+
+ if(this.showToday){
+ var td = new Date().clearTime(),
+ disable = (td < min || td > max ||
+ (ddMatch && format && ddMatch.test(td.dateFormat(format))) ||
+ (ddays && ddays.indexOf(td.getDay()) != -1));
+
+ if(!this.disabled){
+ this.todayBtn.setDisabled(disable);
+ this.todayKeyListener[disable ? 'disable' : 'enable']();
+ }
+ }
+
+ var setCellClass = function(cal, cell){
+ cell.title = '';
+ var t = d.clearTime(true).getTime();
+ cell.firstChild.dateValue = t;
+ if(t == today){
+ cell.className += ' x-date-today';
+ cell.title = cal.todayText;
+ }
+ if(t == sel){
+ cell.className += ' x-date-selected';
+ if(vis){
+ Ext.fly(cell.firstChild).focus(50);
+ }
+ }
+ // disabling
+ if(t < min) {
+ cell.className = ' x-date-disabled';
+ cell.title = cal.minText;
+ return;
+ }
+ if(t > max) {
+ cell.className = ' x-date-disabled';
+ cell.title = cal.maxText;
+ return;
+ }
+ if(ddays){
+ if(ddays.indexOf(d.getDay()) != -1){
+ cell.title = ddaysText;
+ cell.className = ' x-date-disabled';
+ }
+ }
+ if(ddMatch && format){
+ var fvalue = d.dateFormat(format);
+ if(ddMatch.test(fvalue)){
+ cell.title = ddText.replace('%0', fvalue);
+ cell.className = ' x-date-disabled';
+ }
+ }
+ };
+
+ var i = 0;
+ for(; i < startingPos; i++) {
+ textEls[i].innerHTML = (++prevStart);
+ d.setDate(d.getDate()+1);
+ cells[i].className = 'x-date-prevday';
+ setCellClass(this, cells[i]);
+ }
+ for(; i < days; i++){
+ var intDay = i - startingPos + 1;
+ textEls[i].innerHTML = (intDay);
+ d.setDate(d.getDate()+1);
+ cells[i].className = 'x-date-active';
+ setCellClass(this, cells[i]);
+ }
+ var extraDays = 0;
+ for(; i < 42; i++) {
+ textEls[i].innerHTML = (++extraDays);
+ d.setDate(d.getDate()+1);
+ cells[i].className = 'x-date-nextday';
+ setCellClass(this, cells[i]);
+ }
+
+ this.mbtn.setText(this.monthNames[date.getMonth()] + ' ' + date.getFullYear());
+
+ if(!this.internalRender){
+ var main = this.el.dom.firstChild,
+ w = main.offsetWidth;
+ this.el.setWidth(w + this.el.getBorderWidth('lr'));
+ Ext.fly(main).setWidth(w);
+ this.internalRender = true;
+ // opera does not respect the auto grow header center column
+ // then, after it gets a width opera refuses to recalculate
+ // without a second pass
+ if(Ext.isOpera && !this.secondPass){
+ main.rows[0].cells[1].style.width = (w - (main.rows[0].cells[0].offsetWidth+main.rows[0].cells[2].offsetWidth)) + 'px';
+ this.secondPass = true;
+ this.update.defer(10, this, [date]);
+ }
+ }
+ }
+ },
+
+ // private
+ beforeDestroy : function() {
+ if(this.rendered){
+ Ext.destroy(
+ this.keyNav,
+ this.monthPicker,
+ this.eventEl,
+ this.mbtn,
+ this.nextRepeater,
+ this.prevRepeater,
+ this.cells.el,
+ this.todayBtn
+ );
+ delete this.textNodes;
+ delete this.cells.elements;
+ }
+ }
+
+ /**
+ * @cfg {String} autoEl @hide
+ */
+});
+
+Ext.reg('datepicker', Ext.DatePicker);
+/**
+ * @class Ext.LoadMask
+ * A simple utility class for generically masking elements while loading data. If the {@link #store}
+ * config option is specified, the masking will be automatically synchronized with the store's loading
+ * process and the mask element will be cached for reuse. For all other elements, this mask will replace the
+ * element's Updater load indicator and will be destroyed after the initial load.
+ * <p>Example usage:</p>
+ *<pre><code>
+// Basic mask:
+var myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
+myMask.show();
+</code></pre>
+ * @constructor
+ * Create a new LoadMask
+ * @param {Mixed} el The element or DOM node, or its id
+ * @param {Object} config The config object
+ */
+Ext.LoadMask = function(el, config){
+ this.el = Ext.get(el);
+ Ext.apply(this, config);
+ if(this.store){
+ this.store.on({
+ scope: this,
+ beforeload: this.onBeforeLoad,
+ load: this.onLoad,
+ exception: this.onLoad
+ });
+ this.removeMask = Ext.value(this.removeMask, false);
+ }else{
+ var um = this.el.getUpdater();
+ um.showLoadIndicator = false; // disable the default indicator
+ um.on({
+ scope: this,
+ beforeupdate: this.onBeforeLoad,
+ update: this.onLoad,
+ failure: this.onLoad
+ });
+ this.removeMask = Ext.value(this.removeMask, true);
+ }
+};
+
+Ext.LoadMask.prototype = {
+ /**
+ * @cfg {Ext.data.Store} store
+ * Optional Store to which the mask is bound. The mask is displayed when a load request is issued, and
+ * hidden on either load sucess, or load fail.
+ */
+ /**
+ * @cfg {Boolean} removeMask
+ * True to create a single-use mask that is automatically destroyed after loading (useful for page loads),
+ * False to persist the mask element reference for multiple uses (e.g., for paged data widgets). Defaults to false.
+ */
+ /**
+ * @cfg {String} msg
+ * The text to display in a centered loading message box (defaults to 'Loading...')
+ */
+ msg : 'Loading...',
+ /**
+ * @cfg {String} msgCls
+ * The CSS class to apply to the loading message element (defaults to "x-mask-loading")
+ */
+ msgCls : 'x-mask-loading',
+
+ /**
+ * Read-only. True if the mask is currently disabled so that it will not be displayed (defaults to false)
+ * @type Boolean
+ */
+ disabled: false,
+
+ /**
+ * Disables the mask to prevent it from being displayed
+ */
+ disable : function(){
+ this.disabled = true;
+ },
+
+ /**
+ * Enables the mask so that it can be displayed
+ */
+ enable : function(){
+ this.disabled = false;
+ },
+
+ // private
+ onLoad : function(){
+ this.el.unmask(this.removeMask);
+ },
+
+ // private
+ onBeforeLoad : function(){
+ if(!this.disabled){
+ this.el.mask(this.msg, this.msgCls);
+ }
+ },
+
+ /**
+ * Show this LoadMask over the configured Element.
+ */
+ show: function(){
+ this.onBeforeLoad();
+ },
+
+ /**
+ * Hide this LoadMask.
+ */
+ hide: function(){
+ this.onLoad();
+ },
+
+ // private
+ destroy : function(){
+ if(this.store){
+ this.store.un('beforeload', this.onBeforeLoad, this);
+ this.store.un('load', this.onLoad, this);
+ this.store.un('exception', this.onLoad, this);
+ }else{
+ var um = this.el.getUpdater();
+ um.un('beforeupdate', this.onBeforeLoad, this);
+ um.un('update', this.onLoad, this);
+ um.un('failure', this.onLoad, this);
+ }
+ }
+};Ext.ns('Ext.slider');
+
+/**
+ * @class Ext.slider.Thumb
+ * @extends Object
+ * Represents a single thumb element on a Slider. This would not usually be created manually and would instead
+ * be created internally by an {@link Ext.slider.MultiSlider Ext.Slider}.
+ */
+Ext.slider.Thumb = Ext.extend(Object, {
+
+ /**
+ * @constructor
+ * @cfg {Ext.slider.MultiSlider} slider The Slider to render to (required)
+ */
+ constructor: function(config) {
+ /**
+ * @property slider
+ * @type Ext.slider.MultiSlider
+ * The slider this thumb is contained within
+ */
+ Ext.apply(this, config || {}, {
+ cls: 'x-slider-thumb',
+
+ /**
+ * @cfg {Boolean} constrain True to constrain the thumb so that it cannot overlap its siblings
+ */
+ constrain: false
+ });
+
+ Ext.slider.Thumb.superclass.constructor.call(this, config);
+
+ if (this.slider.vertical) {
+ Ext.apply(this, Ext.slider.Thumb.Vertical);
+ }
+ },
+
+ /**
+ * Renders the thumb into a slider
+ */
+ render: function() {
+ this.el = this.slider.innerEl.insertFirst({cls: this.cls});
+
+ this.initEvents();
+ },
+
+ /**
+ * Enables the thumb if it is currently disabled
+ */
+ enable: function() {
+ this.disabled = false;
+ this.el.removeClass(this.slider.disabledClass);
+ },
+
+ /**
+ * Disables the thumb if it is currently enabled
+ */
+ disable: function() {
+ this.disabled = true;
+ this.el.addClass(this.slider.disabledClass);
+ },
+
+ /**
+ * Sets up an Ext.dd.DragTracker for this thumb
+ */
+ initEvents: function() {
+ var el = this.el;
+
+ el.addClassOnOver('x-slider-thumb-over');
+
+ this.tracker = new Ext.dd.DragTracker({
+ onBeforeStart: this.onBeforeDragStart.createDelegate(this),
+ onStart : this.onDragStart.createDelegate(this),
+ onDrag : this.onDrag.createDelegate(this),
+ onEnd : this.onDragEnd.createDelegate(this),
+ tolerance : 3,
+ autoStart : 300
+ });
+
+ this.tracker.initEl(el);
+ },
+
+ /**
+ * @private
+ * This is tied into the internal Ext.dd.DragTracker. If the slider is currently disabled,
+ * this returns false to disable the DragTracker too.
+ * @return {Boolean} False if the slider is currently disabled
+ */
+ onBeforeDragStart : function(e) {
+ if (this.disabled) {
+ return false;
+ } else {
+ this.slider.promoteThumb(this);
+ return true;
+ }
+ },
+
+ /**
+ * @private
+ * This is tied into the internal Ext.dd.DragTracker's onStart template method. Adds the drag CSS class
+ * to the thumb and fires the 'dragstart' event
+ */
+ onDragStart: function(e){
+ this.el.addClass('x-slider-thumb-drag');
+ this.dragging = true;
+ this.dragStartValue = this.value;
+
+ this.slider.fireEvent('dragstart', this.slider, e, this);
+ },
+
+ /**
+ * @private
+ * This is tied into the internal Ext.dd.DragTracker's onDrag template method. This is called every time
+ * the DragTracker detects a drag movement. It updates the Slider's value using the position of the drag
+ */
+ onDrag: function(e) {
+ var slider = this.slider,
+ index = this.index,
+ newValue = this.getNewValue();
+
+ if (this.constrain) {
+ var above = slider.thumbs[index + 1],
+ below = slider.thumbs[index - 1];
+
+ if (below != undefined && newValue <= below.value) newValue = below.value;
+ if (above != undefined && newValue >= above.value) newValue = above.value;
+ }
+
+ slider.setValue(index, newValue, false);
+ slider.fireEvent('drag', slider, e, this);
+ },
+
+ getNewValue: function() {
+ var slider = this.slider,
+ pos = slider.innerEl.translatePoints(this.tracker.getXY());
+
+ return Ext.util.Format.round(slider.reverseValue(pos.left), slider.decimalPrecision);
+ },
+
+ /**
+ * @private
+ * This is tied to the internal Ext.dd.DragTracker's onEnd template method. Removes the drag CSS class and
+ * fires the 'changecomplete' event with the new value
+ */
+ onDragEnd: function(e) {
+ var slider = this.slider,
+ value = this.value;
+
+ this.el.removeClass('x-slider-thumb-drag');
+
+ this.dragging = false;
+ slider.fireEvent('dragend', slider, e);
+
+ if (this.dragStartValue != value) {
+ slider.fireEvent('changecomplete', slider, value, this);
+ }
+ }
+});
+
+/**
+ * @class Ext.slider.MultiSlider
+ * @extends Ext.BoxComponent
+ * Slider which supports vertical or horizontal orientation, keyboard adjustments, configurable snapping, axis clicking and animation. Can be added as an item to any container. Example usage:
+<pre>
+new Ext.Slider({
+ renderTo: Ext.getBody(),
+ width: 200,
+ value: 50,
+ increment: 10,
+ minValue: 0,
+ maxValue: 100
+});
+</pre>
+ * Sliders can be created with more than one thumb handle by passing an array of values instead of a single one:
+<pre>
+new Ext.Slider({
+ renderTo: Ext.getBody(),
+ width: 200,
+ values: [25, 50, 75],
+ minValue: 0,
+ maxValue: 100,
+
+ //this defaults to true, setting to false allows the thumbs to pass each other
+ {@link #constrainThumbs}: false
+});
+</pre>
+ */
+Ext.slider.MultiSlider = Ext.extend(Ext.BoxComponent, {
+ /**
+ * @cfg {Number} value The value to initialize the slider with. Defaults to minValue.
+ */
+ /**
+ * @cfg {Boolean} vertical Orient the Slider vertically rather than horizontally, defaults to false.
+ */
+ vertical: false,
+ /**
+ * @cfg {Number} minValue The minimum value for the Slider. Defaults to 0.
+ */
+ minValue: 0,
+ /**
+ * @cfg {Number} maxValue The maximum value for the Slider. Defaults to 100.
+ */
+ maxValue: 100,
+ /**
+ * @cfg {Number/Boolean} decimalPrecision.
+ * <p>The number of decimal places to which to round the Slider's value. Defaults to 0.</p>
+ * <p>To disable rounding, configure as <tt><b>false</b></tt>.</p>
+ */
+ decimalPrecision: 0,
+ /**
+ * @cfg {Number} keyIncrement How many units to change the Slider when adjusting with keyboard navigation. Defaults to 1. If the increment config is larger, it will be used instead.
+ */
+ keyIncrement: 1,
+ /**
+ * @cfg {Number} increment How many units to change the slider when adjusting by drag and drop. Use this option to enable 'snapping'.
+ */
+ increment: 0,
+
+ /**
+ * @private
+ * @property clickRange
+ * @type Array
+ * Determines whether or not a click to the slider component is considered to be a user request to change the value. Specified as an array of [top, bottom],
+ * the click event's 'top' property is compared to these numbers and the click only considered a change request if it falls within them. e.g. if the 'top'
+ * value of the click event is 4 or 16, the click is not considered a change request as it falls outside of the [5, 15] range
+ */
+ clickRange: [5,15],
+
+ /**
+ * @cfg {Boolean} clickToChange Determines whether or not clicking on the Slider axis will change the slider. Defaults to true
+ */
+ clickToChange : true,
+ /**
+ * @cfg {Boolean} animate Turn on or off animation. Defaults to true
+ */
+ animate: true,
+
+ /**
+ * True while the thumb is in a drag operation
+ * @type Boolean
+ */
+ dragging: false,
+
+ /**
+ * @cfg {Boolean} constrainThumbs True to disallow thumbs from overlapping one another. Defaults to true
+ */
+ constrainThumbs: true,
+
+ /**
+ * @private
+ * @property topThumbZIndex
+ * @type Number
+ * The number used internally to set the z index of the top thumb (see promoteThumb for details)
+ */
+ topThumbZIndex: 10000,
+
+ // private override
+ initComponent : function(){
+ if(!Ext.isDefined(this.value)){
+ this.value = this.minValue;
+ }
+
+ /**
+ * @property thumbs
+ * @type Array
+ * Array containing references to each thumb
+ */
+ this.thumbs = [];
+
+ Ext.slider.MultiSlider.superclass.initComponent.call(this);
+
+ this.keyIncrement = Math.max(this.increment, this.keyIncrement);
+ this.addEvents(
+ /**
+ * @event beforechange
+ * Fires before the slider value is changed. By returning false from an event handler,
+ * you can cancel the event and prevent the slider from changing.
+ * @param {Ext.Slider} slider The slider
+ * @param {Number} newValue The new value which the slider is being changed to.
+ * @param {Number} oldValue The old value which the slider was previously.
+ */
+ 'beforechange',
+
+ /**
+ * @event change
+ * Fires when the slider value is changed.
+ * @param {Ext.Slider} slider The slider
+ * @param {Number} newValue The new value which the slider has been changed to.
+ * @param {Ext.slider.Thumb} thumb The thumb that was changed
+ */
+ 'change',
+
+ /**
+ * @event changecomplete
+ * Fires when the slider value is changed by the user and any drag operations have completed.
+ * @param {Ext.Slider} slider The slider
+ * @param {Number} newValue The new value which the slider has been changed to.
+ * @param {Ext.slider.Thumb} thumb The thumb that was changed
+ */
+ 'changecomplete',
+
+ /**
+ * @event dragstart
+ * Fires after a drag operation has started.
+ * @param {Ext.Slider} slider The slider
+ * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
+ */
+ 'dragstart',
+
+ /**
+ * @event drag
+ * Fires continuously during the drag operation while the mouse is moving.
+ * @param {Ext.Slider} slider The slider
+ * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
+ */
+ 'drag',
+
+ /**
+ * @event dragend
+ * Fires after the drag operation has completed.
+ * @param {Ext.Slider} slider The slider
+ * @param {Ext.EventObject} e The event fired from Ext.dd.DragTracker
+ */
+ 'dragend'
+ );
+
+ /**
+ * @property values
+ * @type Array
+ * Array of values to initalize the thumbs with
+ */
+ if (this.values == undefined || Ext.isEmpty(this.values)) this.values = [0];
+
+ var values = this.values;
+
+ for (var i=0; i < values.length; i++) {
+ this.addThumb(values[i]);
+ }
+
+ if(this.vertical){
+ Ext.apply(this, Ext.slider.Vertical);
+ }
+ },
+
+ /**
+ * Creates a new thumb and adds it to the slider
+ * @param {Number} value The initial value to set on the thumb. Defaults to 0
+ */
+ addThumb: function(value) {
+ var thumb = new Ext.slider.Thumb({
+ value : value,
+ slider : this,
+ index : this.thumbs.length,
+ constrain: this.constrainThumbs
+ });
+ this.thumbs.push(thumb);
+
+ //render the thumb now if needed
+ if (this.rendered) thumb.render();
+ },
+
+ /**
+ * @private
+ * Moves the given thumb above all other by increasing its z-index. This is called when as drag
+ * any thumb, so that the thumb that was just dragged is always at the highest z-index. This is
+ * required when the thumbs are stacked on top of each other at one of the ends of the slider's
+ * range, which can result in the user not being able to move any of them.
+ * @param {Ext.slider.Thumb} topThumb The thumb to move to the top
+ */
+ promoteThumb: function(topThumb) {
+ var thumbs = this.thumbs,
+ zIndex, thumb;
+
+ for (var i = 0, j = thumbs.length; i < j; i++) {
+ thumb = thumbs[i];
+
+ if (thumb == topThumb) {
+ zIndex = this.topThumbZIndex;
+ } else {
+ zIndex = '';
+ }
+
+ thumb.el.setStyle('zIndex', zIndex);
+ }
+ },
+
+ // private override
+ onRender : function() {
+ this.autoEl = {
+ cls: 'x-slider ' + (this.vertical ? 'x-slider-vert' : 'x-slider-horz'),
+ cn : {
+ cls: 'x-slider-end',
+ cn : {
+ cls:'x-slider-inner',
+ cn : [{tag:'a', cls:'x-slider-focus', href:"#", tabIndex: '-1', hidefocus:'on'}]
+ }
+ }
+ };
+
+ Ext.slider.MultiSlider.superclass.onRender.apply(this, arguments);
+
+ this.endEl = this.el.first();
+ this.innerEl = this.endEl.first();
+ this.focusEl = this.innerEl.child('.x-slider-focus');
+
+ //render each thumb
+ for (var i=0; i < this.thumbs.length; i++) {
+ this.thumbs[i].render();
+ }
+
+ //calculate the size of half a thumb
+ var thumb = this.innerEl.child('.x-slider-thumb');
+ this.halfThumb = (this.vertical ? thumb.getHeight() : thumb.getWidth()) / 2;
+
+ this.initEvents();
+ },
+
+ /**
+ * @private
+ * Adds keyboard and mouse listeners on this.el. Ignores click events on the internal focus element.
+ * Creates a new DragTracker which is used to control what happens when the user drags the thumb around.
+ */
+ initEvents : function(){
+ this.mon(this.el, {
+ scope : this,
+ mousedown: this.onMouseDown,
+ keydown : this.onKeyDown
+ });
+
+ this.focusEl.swallowEvent("click", true);
+ },
+
+ /**
+ * @private
+ * Mousedown handler for the slider. If the clickToChange is enabled and the click was not on the draggable 'thumb',
+ * this calculates the new value of the slider and tells the implementation (Horizontal or Vertical) to move the thumb
+ * @param {Ext.EventObject} e The click event
+ */
+ onMouseDown : function(e){
+ if(this.disabled){
+ return;
+ }
+
+ //see if the click was on any of the thumbs
+ var thumbClicked = false;
+ for (var i=0; i < this.thumbs.length; i++) {
+ thumbClicked = thumbClicked || e.target == this.thumbs[i].el.dom;
+ }
+
+ if (this.clickToChange && !thumbClicked) {
+ var local = this.innerEl.translatePoints(e.getXY());
+ this.onClickChange(local);
+ }
+ this.focus();
+ },
+
+ /**
+ * @private
+ * Moves the thumb to the indicated position. Note that a Vertical implementation is provided in Ext.slider.Vertical.
+ * Only changes the value if the click was within this.clickRange.
+ * @param {Object} local Object containing top and left values for the click event.
+ */
+ onClickChange : function(local) {
+ if (local.top > this.clickRange[0] && local.top < this.clickRange[1]) {
+ //find the nearest thumb to the click event
+ var thumb = this.getNearest(local, 'left'),
+ index = thumb.index;
+
+ this.setValue(index, Ext.util.Format.round(this.reverseValue(local.left), this.decimalPrecision), undefined, true);
+ }
+ },
+
+ /**
+ * @private
+ * Returns the nearest thumb to a click event, along with its distance
+ * @param {Object} local Object containing top and left values from a click event
+ * @param {String} prop The property of local to compare on. Use 'left' for horizontal sliders, 'top' for vertical ones
+ * @return {Object} The closest thumb object and its distance from the click event
+ */
+ getNearest: function(local, prop) {
+ var localValue = prop == 'top' ? this.innerEl.getHeight() - local[prop] : local[prop],
+ clickValue = this.reverseValue(localValue),
+ nearestDistance = (this.maxValue - this.minValue) + 5, //add a small fudge for the end of the slider
+ index = 0,
+ nearest = null;
+
+ for (var i=0; i < this.thumbs.length; i++) {
+ var thumb = this.thumbs[i],
+ value = thumb.value,
+ dist = Math.abs(value - clickValue);
+
+ if (Math.abs(dist <= nearestDistance)) {
+ nearest = thumb;
+ index = i;
+ nearestDistance = dist;
+ }
+ }
+ return nearest;
+ },
+
+ /**
+ * @private
+ * Handler for any keypresses captured by the slider. If the key is UP or RIGHT, the thumb is moved along to the right
+ * by this.keyIncrement. If DOWN or LEFT it is moved left. Pressing CTRL moves the slider to the end in either direction
+ * @param {Ext.EventObject} e The Event object
+ */
+ onKeyDown : function(e){
+ if(this.disabled){e.preventDefault();return;}
+ var k = e.getKey();
+ switch(k){
+ case e.UP:
+ case e.RIGHT:
+ e.stopEvent();
+ if(e.ctrlKey){
+ this.setValue(this.maxValue, undefined, true);
+ }else{
+ this.setValue(this.value+this.keyIncrement, undefined, true);
+ }
+ break;
+ case e.DOWN:
+ case e.LEFT:
+ e.stopEvent();
+ if(e.ctrlKey){
+ this.setValue(this.minValue, undefined, true);
+ }else{
+ this.setValue(this.value-this.keyIncrement, undefined, true);
+ }
+ break;
+ default:
+ e.preventDefault();
+ }
+ },
+
+ /**
+ * @private
+ * If using snapping, this takes a desired new value and returns the closest snapped
+ * value to it
+ * @param {Number} value The unsnapped value
+ * @return {Number} The value of the nearest snap target
+ */
+ doSnap : function(value){
+ if (!(this.increment && value)) {
+ return value;
+ }
+ var newValue = value,
+ inc = this.increment,
+ m = value % inc;
+ if (m != 0) {
+ newValue -= m;
+ if (m * 2 >= inc) {
+ newValue += inc;
+ } else if (m * 2 < -inc) {
+ newValue -= inc;
+ }
+ }
+ return newValue.constrain(this.minValue, this.maxValue);
+ },
+
+ // private
+ afterRender : function(){
+ Ext.slider.MultiSlider.superclass.afterRender.apply(this, arguments);
+
+ for (var i=0; i < this.thumbs.length; i++) {
+ var thumb = this.thumbs[i];
+
+ if (thumb.value !== undefined) {
+ var v = this.normalizeValue(thumb.value);
+
+ if (v !== thumb.value) {
+ // delete this.value;
+ this.setValue(i, v, false);
+ } else {
+ this.moveThumb(i, this.translateValue(v), false);
+ }
+ }
+ };
+ },
+
+ /**
+ * @private
+ * Returns the ratio of pixels to mapped values. e.g. if the slider is 200px wide and maxValue - minValue is 100,
+ * the ratio is 2
+ * @return {Number} The ratio of pixels to mapped values
+ */
+ getRatio : function(){
+ var w = this.innerEl.getWidth(),
+ v = this.maxValue - this.minValue;
+ return v == 0 ? w : (w/v);
+ },
+
+ /**
+ * @private
+ * Returns a snapped, constrained value when given a desired value
+ * @param {Number} value Raw number value
+ * @return {Number} The raw value rounded to the correct d.p. and constrained within the set max and min values
+ */
+ normalizeValue : function(v){
+ v = this.doSnap(v);
+ v = Ext.util.Format.round(v, this.decimalPrecision);
+ v = v.constrain(this.minValue, this.maxValue);
+ return v;
+ },
+
+ /**
+ * Sets the minimum value for the slider instance. If the current value is less than the
+ * minimum value, the current value will be changed.
+ * @param {Number} val The new minimum value
+ */
+ setMinValue : function(val){
+ this.minValue = val;
+ this.syncThumb();
+
+ for (var i=0, j = this.thumbs.length; i < j; i++) {
+ if (this.thumbs[i].value < val) this.thumbs[i].value = val;
+ }
+ },
+
+ /**
+ * Sets the maximum value for the slider instance. If the current value is more than the
+ * maximum value, the current value will be changed.
+ * @param {Number} val The new maximum value
+ */
+ setMaxValue : function(val){
+ this.maxValue = val;
+ this.syncThumb();
+
+ for (var i=0; i < this.thumbs.length; i++) {
+ if (this.thumbs[i].value > val) this.thumbs[i].value = val;
+ }
+ },
+
+ /**
+ * Programmatically sets the value of the Slider. Ensures that the value is constrained within
+ * the minValue and maxValue.
+ * @param {Number} index Index of the thumb to move
+ * @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
+ * @param {Boolean} animate Turn on or off animation, defaults to true
+ */
+ setValue : function(index, v, animate, changeComplete) {
+ var thumb = this.thumbs[index],
+ el = thumb.el;
+
+ v = this.normalizeValue(v);
+
+ if (v !== thumb.value && this.fireEvent('beforechange', this, v, thumb.value) !== false) {
+ thumb.value = v;
+ this.moveThumb(index, this.translateValue(v), animate !== false);
+ this.fireEvent('change', this, v, thumb);
+ if(changeComplete){
+ this.fireEvent('changecomplete', this, v, thumb);
+ }
+ }
+ },
+
+ /**
+ * @private
+ */
+ translateValue : function(v) {
+ var ratio = this.getRatio();
+ return (v * ratio) - (this.minValue * ratio) - this.halfThumb;
+ },
+
+ /**
+ * @private
+ * Given a pixel location along the slider, returns the mapped slider value for that pixel.
+ * E.g. if we have a slider 200px wide with minValue = 100 and maxValue = 500, reverseValue(50)
+ * returns 200
+ * @param {Number} pos The position along the slider to return a mapped value for
+ * @return {Number} The mapped value for the given position
+ */
+ reverseValue : function(pos){
+ var ratio = this.getRatio();
+ return (pos + (this.minValue * ratio)) / ratio;
+ },
+
+ /**
+ * @private
+ * @param {Number} index Index of the thumb to move
+ */
+ moveThumb: function(index, v, animate){
+ var thumb = this.thumbs[index].el;
+
+ if(!animate || this.animate === false){
+ thumb.setLeft(v);
+ }else{
+ thumb.shift({left: v, stopFx: true, duration:.35});
+ }
+ },
+
+ // private
+ focus : function(){
+ this.focusEl.focus(10);
+ },
+
+ // private
+ onResize : function(w, h){
+ var thumbs = this.thumbs,
+ len = thumbs.length,
+ i = 0;
+
+ /*
+ * If we happen to be animating during a resize, the position of the thumb will likely be off
+ * when the animation stops. As such, just stop any animations before syncing the thumbs.
+ */
+ for(; i < len; ++i){
+ thumbs[i].el.stopFx();
+ }
+ this.innerEl.setWidth(w - (this.el.getPadding('l') + this.endEl.getPadding('r')));
+ this.syncThumb();
+ Ext.slider.MultiSlider.superclass.onResize.apply(this, arguments);
+ },
+
+ //private
+ onDisable: function(){
+ Ext.slider.MultiSlider.superclass.onDisable.call(this);
+
+ for (var i=0; i < this.thumbs.length; i++) {
+ var thumb = this.thumbs[i],
+ el = thumb.el;
+
+ thumb.disable();
+
+ if(Ext.isIE){
+ //IE breaks when using overflow visible and opacity other than 1.
+ //Create a place holder for the thumb and display it.
+ var xy = el.getXY();
+ el.hide();
+
+ this.innerEl.addClass(this.disabledClass).dom.disabled = true;
+
+ if (!this.thumbHolder) {
+ this.thumbHolder = this.endEl.createChild({cls: 'x-slider-thumb ' + this.disabledClass});
+ }
+
+ this.thumbHolder.show().setXY(xy);
+ }
+ }
+ },
+
+ //private
+ onEnable: function(){
+ Ext.slider.MultiSlider.superclass.onEnable.call(this);
+
+ for (var i=0; i < this.thumbs.length; i++) {
+ var thumb = this.thumbs[i],
+ el = thumb.el;
+
+ thumb.enable();
+
+ if (Ext.isIE) {
+ this.innerEl.removeClass(this.disabledClass).dom.disabled = false;
+
+ if (this.thumbHolder) this.thumbHolder.hide();
+
+ el.show();
+ this.syncThumb();
+ }
+ }
+ },
+
+ /**
+ * Synchronizes the thumb position to the proper proportion of the total component width based
+ * on the current slider {@link #value}. This will be called automatically when the Slider
+ * is resized by a layout, but if it is rendered auto width, this method can be called from
+ * another resize handler to sync the Slider if necessary.
+ */
+ syncThumb : function() {
+ if (this.rendered) {
+ for (var i=0; i < this.thumbs.length; i++) {
+ this.moveThumb(i, this.translateValue(this.thumbs[i].value));
+ }
+ }
+ },
+
+ /**
+ * Returns the current value of the slider
+ * @param {Number} index The index of the thumb to return a value for
+ * @return {Number} The current value of the slider
+ */
+ getValue : function(index) {
+ return this.thumbs[index].value;
+ },
+
+ /**
+ * Returns an array of values - one for the location of each thumb
+ * @return {Array} The set of thumb values
+ */
+ getValues: function() {
+ var values = [];
+
+ for (var i=0; i < this.thumbs.length; i++) {
+ values.push(this.thumbs[i].value);
+ }
+
+ return values;
+ },
+
+ // private
+ beforeDestroy : function(){
+ Ext.destroyMembers(this, 'endEl', 'innerEl', 'thumb', 'halfThumb', 'focusEl', 'tracker', 'thumbHolder');
+ Ext.slider.MultiSlider.superclass.beforeDestroy.call(this);
+ }
+});
+
+Ext.reg('multislider', Ext.slider.MultiSlider);
+
+/**
+ * @class Ext.slider.SingleSlider
+ * @extends Ext.slider.MultiSlider
+ * Slider which supports vertical or horizontal orientation, keyboard adjustments,
+ * configurable snapping, axis clicking and animation. Can be added as an item to
+ * any container. Example usage:
+<pre><code>
+new Ext.slider.SingleSlider({
+ renderTo: Ext.getBody(),
+ width: 200,
+ value: 50,
+ increment: 10,
+ minValue: 0,
+ maxValue: 100
+});
+</code></pre>
+ * The class Ext.slider.SingleSlider is aliased to Ext.Slider for backwards compatibility.
+ */
+Ext.slider.SingleSlider = Ext.extend(Ext.slider.MultiSlider, {
+ constructor: function(config) {
+ config = config || {};
+
+ Ext.applyIf(config, {
+ values: [config.value || 0]
+ });
+
+ Ext.slider.SingleSlider.superclass.constructor.call(this, config);
+ },
+
+ /**
+ * Returns the current value of the slider
+ * @return {Number} The current value of the slider
+ */
+ getValue: function() {
+ //just returns the value of the first thumb, which should be the only one in a single slider
+ return Ext.slider.SingleSlider.superclass.getValue.call(this, 0);
+ },
+
+ /**
+ * Programmatically sets the value of the Slider. Ensures that the value is constrained within
+ * the minValue and maxValue.
+ * @param {Number} value The value to set the slider to. (This will be constrained within minValue and maxValue)
+ * @param {Boolean} animate Turn on or off animation, defaults to true
+ */
+ setValue: function(value, animate) {
+ var args = Ext.toArray(arguments),
+ len = args.length;
+
+ //this is to maintain backwards compatiblity for sliders with only one thunb. Usually you must pass the thumb
+ //index to setValue, but if we only have one thumb we inject the index here first if given the multi-slider
+ //signature without the required index. The index will always be 0 for a single slider
+ if (len == 1 || (len <= 3 && typeof arguments[1] != 'number')) {
+ args.unshift(0);
+ }
+
+ return Ext.slider.SingleSlider.superclass.setValue.apply(this, args);
+ },
+
+ /**
+ * Synchronizes the thumb position to the proper proportion of the total component width based
+ * on the current slider {@link #value}. This will be called automatically when the Slider
+ * is resized by a layout, but if it is rendered auto width, this method can be called from
+ * another resize handler to sync the Slider if necessary.
+ */
+ syncThumb : function() {
+ return Ext.slider.SingleSlider.superclass.syncThumb.apply(this, [0].concat(arguments));
+ },
+
+ // private
+ getNearest : function(){
+ // Since there's only 1 thumb, it's always the nearest
+ return this.thumbs[0];
+ }
+});
+
+//backwards compatibility
+Ext.Slider = Ext.slider.SingleSlider;
+
+Ext.reg('slider', Ext.slider.SingleSlider);
+
+// private class to support vertical sliders
+Ext.slider.Vertical = {
+ onResize : function(w, h){
+ this.innerEl.setHeight(h - (this.el.getPadding('t') + this.endEl.getPadding('b')));
+ this.syncThumb();
+ },
+
+ getRatio : function(){
+ var h = this.innerEl.getHeight(),
+ v = this.maxValue - this.minValue;
+ return h/v;
+ },
+
+ moveThumb: function(index, v, animate) {
+ var thumb = this.thumbs[index],
+ el = thumb.el;
+
+ if (!animate || this.animate === false) {
+ el.setBottom(v);
+ } else {
+ el.shift({bottom: v, stopFx: true, duration:.35});
+ }
+ },
+
+ onClickChange : function(local) {
+ if (local.left > this.clickRange[0] && local.left < this.clickRange[1]) {
+ var thumb = this.getNearest(local, 'top'),
+ index = thumb.index,
+ value = this.minValue + this.reverseValue(this.innerEl.getHeight() - local.top);
+
+ this.setValue(index, Ext.util.Format.round(value, this.decimalPrecision), undefined, true);
+ }
+ }
+};
+
+//private class to support vertical dragging of thumbs within a slider
+Ext.slider.Thumb.Vertical = {
+ getNewValue: function() {
+ var slider = this.slider,
+ innerEl = slider.innerEl,
+ pos = innerEl.translatePoints(this.tracker.getXY()),
+ bottom = innerEl.getHeight() - pos.top;
+
+ return slider.minValue + Ext.util.Format.round(bottom / slider.getRatio(), slider.decimalPrecision);
+ }
+};
+/**
+ * @class Ext.ProgressBar
+ * @extends Ext.BoxComponent
+ * <p>An updateable progress bar component. The progress bar supports two different modes: manual and automatic.</p>
+ * <p>In manual mode, you are responsible for showing, updating (via {@link #updateProgress}) and clearing the
+ * progress bar as needed from your own code. This method is most appropriate when you want to show progress
+ * throughout an operation that has predictable points of interest at which you can update the control.</p>
+ * <p>In automatic mode, you simply call {@link #wait} and let the progress bar run indefinitely, only clearing it
+ * once the operation is complete. You can optionally have the progress bar wait for a specific amount of time
+ * and then clear itself. Automatic mode is most appropriate for timed operations or asynchronous operations in
+ * which you have no need for indicating intermediate progress.</p>
+ * @cfg {Float} value A floating point value between 0 and 1 (e.g., .5, defaults to 0)
+ * @cfg {String} text The progress bar text (defaults to '')
+ * @cfg {Mixed} textEl The element to render the progress text to (defaults to the progress
+ * bar's internal text element)
+ * @cfg {String} id The progress bar element's id (defaults to an auto-generated id)
+ * @xtype progress
+ */
+Ext.ProgressBar = Ext.extend(Ext.BoxComponent, {
+ /**
+ * @cfg {String} baseCls
+ * The base CSS class to apply to the progress bar's wrapper element (defaults to 'x-progress')
+ */
+ baseCls : 'x-progress',
+
+ /**
+ * @cfg {Boolean} animate
+ * True to animate the progress bar during transitions (defaults to false)
+ */
+ animate : false,
+
+ // private
+ waitTimer : null,
+
+ // private
+ initComponent : function(){
+ Ext.ProgressBar.superclass.initComponent.call(this);
+ this.addEvents(
+ /**
+ * @event update
+ * Fires after each update interval
+ * @param {Ext.ProgressBar} this
+ * @param {Number} The current progress value
+ * @param {String} The current progress text
+ */
+ "update"
+ );
+ },
+
+ // private
+ onRender : function(ct, position){
+ var tpl = new Ext.Template(
+ '<div class="{cls}-wrap">',
+ '<div class="{cls}-inner">',
+ '<div class="{cls}-bar">',
+ '<div class="{cls}-text">',
+ '<div> </div>',
+ '</div>',
+ '</div>',
+ '<div class="{cls}-text {cls}-text-back">',
+ '<div> </div>',
+ '</div>',
+ '</div>',
+ '</div>'
+ );
+
+ this.el = position ? tpl.insertBefore(position, {cls: this.baseCls}, true)
+ : tpl.append(ct, {cls: this.baseCls}, true);
+
+ if(this.id){
+ this.el.dom.id = this.id;
+ }
+ var inner = this.el.dom.firstChild;
+ this.progressBar = Ext.get(inner.firstChild);
+
+ if(this.textEl){
+ //use an external text el
+ this.textEl = Ext.get(this.textEl);
+ delete this.textTopEl;
+ }else{
+ //setup our internal layered text els
+ this.textTopEl = Ext.get(this.progressBar.dom.firstChild);
+ var textBackEl = Ext.get(inner.childNodes[1]);
+ this.textTopEl.setStyle("z-index", 99).addClass('x-hidden');
+ this.textEl = new Ext.CompositeElement([this.textTopEl.dom.firstChild, textBackEl.dom.firstChild]);
+ this.textEl.setWidth(inner.offsetWidth);
+ }
+ this.progressBar.setHeight(inner.offsetHeight);
+ },
+
+ // private
+ afterRender : function(){
+ Ext.ProgressBar.superclass.afterRender.call(this);
+ if(this.value){
+ this.updateProgress(this.value, this.text);
+ }else{
+ this.updateText(this.text);
+ }
+ },
+
+ /**
+ * Updates the progress bar value, and optionally its text. If the text argument is not specified,
+ * any existing text value will be unchanged. To blank out existing text, pass ''. Note that even
+ * if the progress bar value exceeds 1, it will never automatically reset -- you are responsible for
+ * determining when the progress is complete and calling {@link #reset} to clear and/or hide the control.
+ * @param {Float} value (optional) A floating point value between 0 and 1 (e.g., .5, defaults to 0)
+ * @param {String} text (optional) The string to display in the progress text element (defaults to '')
+ * @param {Boolean} animate (optional) Whether to animate the transition of the progress bar. If this value is
+ * not specified, the default for the class is used (default to false)
+ * @return {Ext.ProgressBar} this
+ */
+ updateProgress : function(value, text, animate){
+ this.value = value || 0;
+ if(text){
+ this.updateText(text);
+ }
+ if(this.rendered && !this.isDestroyed){
+ var w = Math.floor(value*this.el.dom.firstChild.offsetWidth);
+ this.progressBar.setWidth(w, animate === true || (animate !== false && this.animate));
+ if(this.textTopEl){
+ //textTopEl should be the same width as the bar so overflow will clip as the bar moves
+ this.textTopEl.removeClass('x-hidden').setWidth(w);
+ }
+ }
+ this.fireEvent('update', this, value, text);
+ return this;
+ },
+
+ /**
+ * Initiates an auto-updating progress bar. A duration can be specified, in which case the progress
+ * bar will automatically reset after a fixed amount of time and optionally call a callback function
+ * if specified. If no duration is passed in, then the progress bar will run indefinitely and must
+ * be manually cleared by calling {@link #reset}. The wait method accepts a config object with
+ * the following properties:
+ * <pre>
+Property Type Description
+---------- ------------ ----------------------------------------------------------------------
+duration Number The length of time in milliseconds that the progress bar should
+ run before resetting itself (defaults to undefined, in which case it
+ will run indefinitely until reset is called)
+interval Number The length of time in milliseconds between each progress update
+ (defaults to 1000 ms)
+animate Boolean Whether to animate the transition of the progress bar. If this value is
+ not specified, the default for the class is used.
+increment Number The number of progress update segments to display within the progress
+ bar (defaults to 10). If the bar reaches the end and is still
+ updating, it will automatically wrap back to the beginning.
+text String Optional text to display in the progress bar element (defaults to '').
+fn Function A callback function to execute after the progress bar finishes auto-
+ updating. The function will be called with no arguments. This function
+ will be ignored if duration is not specified since in that case the
+ progress bar can only be stopped programmatically, so any required function
+ should be called by the same code after it resets the progress bar.
+scope Object The scope that is passed to the callback function (only applies when
+ duration and fn are both passed).
+</pre>
+ *
+ * Example usage:
+ * <pre><code>
+var p = new Ext.ProgressBar({
+ renderTo: 'my-el'
+});
+
+//Wait for 5 seconds, then update the status el (progress bar will auto-reset)
+p.wait({
+ interval: 100, //bar will move fast!
+ duration: 5000,
+ increment: 15,
+ text: 'Updating...',
+ scope: this,
+ fn: function(){
+ Ext.fly('status').update('Done!');
+ }
+});
+
+//Or update indefinitely until some async action completes, then reset manually
+p.wait();
+myAction.on('complete', function(){
+ p.reset();
+ Ext.fly('status').update('Done!');
+});
+</code></pre>
+ * @param {Object} config (optional) Configuration options
+ * @return {Ext.ProgressBar} this
+ */
+ wait : function(o){
+ if(!this.waitTimer){
+ var scope = this;
+ o = o || {};
+ this.updateText(o.text);
+ this.waitTimer = Ext.TaskMgr.start({
+ run: function(i){
+ var inc = o.increment || 10;
+ i -= 1;
+ this.updateProgress(((((i+inc)%inc)+1)*(100/inc))*0.01, null, o.animate);
+ },
+ interval: o.interval || 1000,
+ duration: o.duration,
+ onStop: function(){
+ if(o.fn){
+ o.fn.apply(o.scope || this);
+ }
+ this.reset();
+ },
+ scope: scope
+ });
+ }
+ return this;
+ },
+
+ /**
+ * Returns true if the progress bar is currently in a {@link #wait} operation
+ * @return {Boolean} True if waiting, else false
+ */
+ isWaiting : function(){
+ return this.waitTimer !== null;
+ },
+
+ /**
+ * Updates the progress bar text. If specified, textEl will be updated, otherwise the progress
+ * bar itself will display the updated text.
+ * @param {String} text (optional) The string to display in the progress text element (defaults to '')
+ * @return {Ext.ProgressBar} this
+ */
+ updateText : function(text){
+ this.text = text || ' ';
+ if(this.rendered){
+ this.textEl.update(this.text);
+ }
+ return this;
+ },
+
+ /**
+ * Synchronizes the inner bar width to the proper proportion of the total componet width based
+ * on the current progress {@link #value}. This will be called automatically when the ProgressBar
+ * is resized by a layout, but if it is rendered auto width, this method can be called from
+ * another resize handler to sync the ProgressBar if necessary.
+ */
+ syncProgressBar : function(){
+ if(this.value){
+ this.updateProgress(this.value, this.text);
+ }
+ return this;
+ },
+
+ /**
+ * Sets the size of the progress bar.
+ * @param {Number} width The new width in pixels
+ * @param {Number} height The new height in pixels
+ * @return {Ext.ProgressBar} this
+ */
+ setSize : function(w, h){
+ Ext.ProgressBar.superclass.setSize.call(this, w, h);
+ if(this.textTopEl){
+ var inner = this.el.dom.firstChild;
+ this.textEl.setSize(inner.offsetWidth, inner.offsetHeight);
+ }
+ this.syncProgressBar();
+ return this;
+ },
+
+ /**
+ * Resets the progress bar value to 0 and text to empty string. If hide = true, the progress
+ * bar will also be hidden (using the {@link #hideMode} property internally).
+ * @param {Boolean} hide (optional) True to hide the progress bar (defaults to false)
+ * @return {Ext.ProgressBar} this
+ */
+ reset : function(hide){
+ this.updateProgress(0);
+ if(this.textTopEl){
+ this.textTopEl.addClass('x-hidden');
+ }
+ this.clearTimer();
+ if(hide === true){
+ this.hide();
+ }
+ return this;
+ },
+
+ // private
+ clearTimer : function(){
+ if(this.waitTimer){
+ this.waitTimer.onStop = null; //prevent recursion
+ Ext.TaskMgr.stop(this.waitTimer);
+ this.waitTimer = null;
+ }
+ },
+
+ onDestroy: function(){
+ this.clearTimer();
+ if(this.rendered){
+ if(this.textEl.isComposite){
+ this.textEl.clear();
+ }
+ Ext.destroyMembers(this, 'textEl', 'progressBar', 'textTopEl');
+ }
+ Ext.ProgressBar.superclass.onDestroy.call(this);
+ }
+});
+Ext.reg('progress', Ext.ProgressBar);/*
+ * These classes are derivatives of the similarly named classes in the YUI Library.
+ * The original license:
+ * Copyright (c) 2006, Yahoo! Inc. All rights reserved.
+ * Code licensed under the BSD License:
+ * http://developer.yahoo.net/yui/license.txt
+ */
+
+(function() {
+
+var Event=Ext.EventManager;
+var Dom=Ext.lib.Dom;
+
+/**
+ * @class Ext.dd.DragDrop
+ * Defines the interface and base operation of items that that can be
+ * dragged or can be drop targets. It was designed to be extended, overriding
+ * the event handlers for startDrag, onDrag, onDragOver and onDragOut.
+ * Up to three html elements can be associated with a DragDrop instance:
+ * <ul>
+ * <li>linked element: the element that is passed into the constructor.
+ * This is the element which defines the boundaries for interaction with
+ * other DragDrop objects.</li>
+ * <li>handle element(s): The drag operation only occurs if the element that
+ * was clicked matches a handle element. By default this is the linked
+ * element, but there are times that you will want only a portion of the
+ * linked element to initiate the drag operation, and the setHandleElId()
+ * method provides a way to define this.</li>
+ * <li>drag element: this represents the element that would be moved along
+ * with the cursor during a drag operation. By default, this is the linked
+ * element itself as in {@link Ext.dd.DD}. setDragElId() lets you define
+ * a separate element that would be moved, as in {@link Ext.dd.DDProxy}.
+ * </li>
+ * </ul>
+ * This class should not be instantiated until the onload event to ensure that
+ * the associated elements are available.
+ * The following would define a DragDrop obj that would interact with any
+ * other DragDrop obj in the "group1" group:
+ * <pre>
+ * dd = new Ext.dd.DragDrop("div1", "group1");
+ * </pre>
+ * Since none of the event handlers have been implemented, nothing would
+ * actually happen if you were to run the code above. Normally you would
+ * override this class or one of the default implementations, but you can
+ * also override the methods you want on an instance of the class...
+ * <pre>
+ * dd.onDragDrop = function(e, id) {
+ * alert("dd was dropped on " + id);
+ * }
+ * </pre>
+ * @constructor
+ * @param {String} id of the element that is linked to this instance
+ * @param {String} sGroup the group of related DragDrop objects
+ * @param {object} config an object containing configurable attributes
+ * Valid properties for DragDrop:
+ * padding, isTarget, maintainOffset, primaryButtonOnly
+ */
+Ext.dd.DragDrop = function(id, sGroup, config) {
+ if(id) {
+ this.init(id, sGroup, config);
+ }
+};
+
+Ext.dd.DragDrop.prototype = {
+
+ /**
+ * Set to false to enable a DragDrop object to fire drag events while dragging
+ * over its own Element. Defaults to true - DragDrop objects do not by default
+ * fire drag events to themselves.
+ * @property ignoreSelf
+ * @type Boolean
+ */
+
+ /**
+ * The id of the element associated with this object. This is what we
+ * refer to as the "linked element" because the size and position of
+ * this element is used to determine when the drag and drop objects have
+ * interacted.
+ * @property id
+ * @type String
+ */
+ id: null,
+
+ /**
+ * Configuration attributes passed into the constructor
+ * @property config
+ * @type object
+ */
+ config: null,
+
+ /**
+ * The id of the element that will be dragged. By default this is same
+ * as the linked element, but could be changed to another element. Ex:
+ * Ext.dd.DDProxy
+ * @property dragElId
+ * @type String
+ * @private
+ */
+ dragElId: null,
+
+ /**
+ * The ID of the element that initiates the drag operation. By default
+ * this is the linked element, but could be changed to be a child of this
+ * element. This lets us do things like only starting the drag when the
+ * header element within the linked html element is clicked.
+ * @property handleElId
+ * @type String
+ * @private
+ */
+ handleElId: null,
+
+ /**
+ * An object who's property names identify HTML tags to be considered invalid as drag handles.
+ * A non-null property value identifies the tag as invalid. Defaults to the
+ * following value which prevents drag operations from being initiated by <a> elements:<pre><code>
+{
+ A: "A"
+}</code></pre>
+ * @property invalidHandleTypes
+ * @type Object
+ */
+ invalidHandleTypes: null,
+
+ /**
+ * An object who's property names identify the IDs of elements to be considered invalid as drag handles.
+ * A non-null property value identifies the ID as invalid. For example, to prevent
+ * dragging from being initiated on element ID "foo", use:<pre><code>
+{
+ foo: true
+}</code></pre>
+ * @property invalidHandleIds
+ * @type Object
+ */
+ invalidHandleIds: null,
+
+ /**
+ * An Array of CSS class names for elements to be considered in valid as drag handles.
+ * @property invalidHandleClasses
+ * @type Array
+ */
+ invalidHandleClasses: null,
+
+ /**
+ * The linked element's absolute X position at the time the drag was
+ * started
+ * @property startPageX
+ * @type int
+ * @private
+ */
+ startPageX: 0,
+
+ /**
+ * The linked element's absolute X position at the time the drag was
+ * started
+ * @property startPageY
+ * @type int
+ * @private
+ */
+ startPageY: 0,
+
+ /**
+ * The group defines a logical collection of DragDrop objects that are
+ * related. Instances only get events when interacting with other
+ * DragDrop object in the same group. This lets us define multiple
+ * groups using a single DragDrop subclass if we want.
+ * @property groups
+ * @type object An object in the format {'group1':true, 'group2':true}
+ */
+ groups: null,
+
+ /**
+ * Individual drag/drop instances can be locked. This will prevent
+ * onmousedown start drag.
+ * @property locked
+ * @type boolean
+ * @private
+ */
+ locked: false,
+
+ /**
+ * Lock this instance
+ * @method lock
+ */
+ lock: function() {
+ this.locked = true;
+ },
+
+ /**
+ * When set to true, other DD objects in cooperating DDGroups do not receive
+ * notification events when this DD object is dragged over them. Defaults to false.
+ * @property moveOnly
+ * @type boolean
+ */
+ moveOnly: false,
+
+ /**
+ * Unlock this instace
+ * @method unlock
+ */
+ unlock: function() {
+ this.locked = false;
+ },
+
+ /**
+ * By default, all instances can be a drop target. This can be disabled by
+ * setting isTarget to false.
+ * @property isTarget
+ * @type boolean
+ */
+ isTarget: true,
+
+ /**
+ * The padding configured for this drag and drop object for calculating
+ * the drop zone intersection with this object.
+ * @property padding
+ * @type int[] An array containing the 4 padding values: [top, right, bottom, left]
+ */
+ padding: null,
+
+ /**
+ * Cached reference to the linked element
+ * @property _domRef
+ * @private
+ */
+ _domRef: null,
+
+ /**
+ * Internal typeof flag
+ * @property __ygDragDrop
+ * @private
+ */
+ __ygDragDrop: true,
+
+ /**
+ * Set to true when horizontal contraints are applied
+ * @property constrainX
+ * @type boolean
+ * @private
+ */
+ constrainX: false,
+
+ /**
+ * Set to true when vertical contraints are applied
+ * @property constrainY
+ * @type boolean
+ * @private
+ */
+ constrainY: false,
+
+ /**
+ * The left constraint
+ * @property minX
+ * @type int
+ * @private
+ */
+ minX: 0,
+
+ /**
+ * The right constraint
+ * @property maxX
+ * @type int
+ * @private
+ */
+ maxX: 0,
+
+ /**
+ * The up constraint
+ * @property minY
+ * @type int
+ * @private
+ */
+ minY: 0,
+
+ /**
+ * The down constraint
+ * @property maxY
+ * @type int
+ * @private
+ */
+ maxY: 0,
+
+ /**
+ * Maintain offsets when we resetconstraints. Set to true when you want
+ * the position of the element relative to its parent to stay the same
+ * when the page changes
+ *
+ * @property maintainOffset
+ * @type boolean
+ */
+ maintainOffset: false,
+
+ /**
+ * Array of pixel locations the element will snap to if we specified a
+ * horizontal graduation/interval. This array is generated automatically
+ * when you define a tick interval.
+ * @property xTicks
+ * @type int[]
+ */
+ xTicks: null,
+
+ /**
+ * Array of pixel locations the element will snap to if we specified a
+ * vertical graduation/interval. This array is generated automatically
+ * when you define a tick interval.
+ * @property yTicks
+ * @type int[]
+ */
+ yTicks: null,
+
+ /**
+ * By default the drag and drop instance will only respond to the primary
+ * button click (left button for a right-handed mouse). Set to true to
+ * allow drag and drop to start with any mouse click that is propogated
+ * by the browser
+ * @property primaryButtonOnly
+ * @type boolean
+ */
+ primaryButtonOnly: true,
+
+ /**
+ * The available property is false until the linked dom element is accessible.
+ * @property available
+ * @type boolean
+ */
+ available: false,
+
+ /**
+ * By default, drags can only be initiated if the mousedown occurs in the
+ * region the linked element is. This is done in part to work around a
+ * bug in some browsers that mis-report the mousedown if the previous
+ * mouseup happened outside of the window. This property is set to true
+ * if outer handles are defined.
+ *
+ * @property hasOuterHandles
+ * @type boolean
+ * @default false
+ */
+ hasOuterHandles: false,
+
+ /**
+ * Code that executes immediately before the startDrag event
+ * @method b4StartDrag
+ * @private
+ */
+ b4StartDrag: function(x, y) { },
+
+ /**
+ * Abstract method called after a drag/drop object is clicked
+ * and the drag or mousedown time thresholds have beeen met.
+ * @method startDrag
+ * @param {int} X click location
+ * @param {int} Y click location
+ */
+ startDrag: function(x, y) { /* override this */ },
+
+ /**
+ * Code that executes immediately before the onDrag event
+ * @method b4Drag
+ * @private
+ */
+ b4Drag: function(e) { },
+
+ /**
+ * Abstract method called during the onMouseMove event while dragging an
+ * object.
+ * @method onDrag
+ * @param {Event} e the mousemove event
+ */
+ onDrag: function(e) { /* override this */ },
+
+ /**
+ * Abstract method called when this element fist begins hovering over
+ * another DragDrop obj
+ * @method onDragEnter
+ * @param {Event} e the mousemove event
+ * @param {String|DragDrop[]} id In POINT mode, the element
+ * id this is hovering over. In INTERSECT mode, an array of one or more
+ * dragdrop items being hovered over.
+ */
+ onDragEnter: function(e, id) { /* override this */ },
+
+ /**
+ * Code that executes immediately before the onDragOver event
+ * @method b4DragOver
+ * @private
+ */
+ b4DragOver: function(e) { },
+
+ /**
+ * Abstract method called when this element is hovering over another
+ * DragDrop obj
+ * @method onDragOver
+ * @param {Event} e the mousemove event
+ * @param {String|DragDrop[]} id In POINT mode, the element
+ * id this is hovering over. In INTERSECT mode, an array of dd items
+ * being hovered over.
+ */
+ onDragOver: function(e, id) { /* override this */ },
+
+ /**
+ * Code that executes immediately before the onDragOut event
+ * @method b4DragOut
+ * @private
+ */
+ b4DragOut: function(e) { },
+
+ /**
+ * Abstract method called when we are no longer hovering over an element
+ * @method onDragOut
+ * @param {Event} e the mousemove event
+ * @param {String|DragDrop[]} id In POINT mode, the element
+ * id this was hovering over. In INTERSECT mode, an array of dd items
+ * that the mouse is no longer over.
+ */
+ onDragOut: function(e, id) { /* override this */ },
+
+ /**
+ * Code that executes immediately before the onDragDrop event
+ * @method b4DragDrop
+ * @private
+ */
+ b4DragDrop: function(e) { },
+
+ /**
+ * Abstract method called when this item is dropped on another DragDrop
+ * obj
+ * @method onDragDrop
+ * @param {Event} e the mouseup event
+ * @param {String|DragDrop[]} id In POINT mode, the element
+ * id this was dropped on. In INTERSECT mode, an array of dd items this
+ * was dropped on.
+ */
+ onDragDrop: function(e, id) { /* override this */ },
+
+ /**
+ * Abstract method called when this item is dropped on an area with no
+ * drop target
+ * @method onInvalidDrop
+ * @param {Event} e the mouseup event
+ */
+ onInvalidDrop: function(e) { /* override this */ },
+
+ /**
+ * Code that executes immediately before the endDrag event
+ * @method b4EndDrag
+ * @private
+ */
+ b4EndDrag: function(e) { },
+
+ /**
+ * Fired when we are done dragging the object
+ * @method endDrag
+ * @param {Event} e the mouseup event
+ */
+ endDrag: function(e) { /* override this */ },
+
+ /**
+ * Code executed immediately before the onMouseDown event
+ * @method b4MouseDown
+ * @param {Event} e the mousedown event
+ * @private
+ */
+ b4MouseDown: function(e) { },
+
+ /**
+ * Event handler that fires when a drag/drop obj gets a mousedown
+ * @method onMouseDown
+ * @param {Event} e the mousedown event
+ */
+ onMouseDown: function(e) { /* override this */ },
+
+ /**
+ * Event handler that fires when a drag/drop obj gets a mouseup
+ * @method onMouseUp
+ * @param {Event} e the mouseup event
+ */
+ onMouseUp: function(e) { /* override this */ },
+
+ /**
+ * Override the onAvailable method to do what is needed after the initial
+ * position was determined.
+ * @method onAvailable
+ */
+ onAvailable: function () {
+ },
+
+ /**
+ * Provides default constraint padding to "constrainTo" elements (defaults to {left: 0, right:0, top:0, bottom:0}).
+ * @type Object
+ */
+ defaultPadding : {left:0, right:0, top:0, bottom:0},
+
+ /**
+ * Initializes the drag drop object's constraints to restrict movement to a certain element.
+ *
+ * Usage:
+ <pre><code>
+ var dd = new Ext.dd.DDProxy("dragDiv1", "proxytest",
+ { dragElId: "existingProxyDiv" });
+ dd.startDrag = function(){
+ this.constrainTo("parent-id");
+ };
+ </code></pre>
+ * Or you can initalize it using the {@link Ext.Element} object:
+ <pre><code>
+ Ext.get("dragDiv1").initDDProxy("proxytest", {dragElId: "existingProxyDiv"}, {
+ startDrag : function(){
+ this.constrainTo("parent-id");
+ }
+ });
+ </code></pre>
+ * @param {Mixed} constrainTo The element to constrain to.
+ * @param {Object/Number} pad (optional) Pad provides a way to specify "padding" of the constraints,
+ * and can be either a number for symmetrical padding (4 would be equal to {left:4, right:4, top:4, bottom:4}) or
+ * an object containing the sides to pad. For example: {right:10, bottom:10}
+ * @param {Boolean} inContent (optional) Constrain the draggable in the content box of the element (inside padding and borders)
+ */
+ constrainTo : function(constrainTo, pad, inContent){
+ if(Ext.isNumber(pad)){
+ pad = {left: pad, right:pad, top:pad, bottom:pad};
+ }
+ pad = pad || this.defaultPadding;
+ var b = Ext.get(this.getEl()).getBox(),
+ ce = Ext.get(constrainTo),
+ s = ce.getScroll(),
+ c,
+ cd = ce.dom;
+ if(cd == document.body){
+ c = { x: s.left, y: s.top, width: Ext.lib.Dom.getViewWidth(), height: Ext.lib.Dom.getViewHeight()};
+ }else{
+ var xy = ce.getXY();
+ c = {x : xy[0], y: xy[1], width: cd.clientWidth, height: cd.clientHeight};
+ }
+
+
+ var topSpace = b.y - c.y,
+ leftSpace = b.x - c.x;
+
+ this.resetConstraints();
+ this.setXConstraint(leftSpace - (pad.left||0), // left
+ c.width - leftSpace - b.width - (pad.right||0), //right
+ this.xTickSize
+ );
+ this.setYConstraint(topSpace - (pad.top||0), //top
+ c.height - topSpace - b.height - (pad.bottom||0), //bottom
+ this.yTickSize
+ );
+ },
+
+ /**
+ * Returns a reference to the linked element
+ * @method getEl
+ * @return {HTMLElement} the html element
+ */
+ getEl: function() {
+ if (!this._domRef) {
+ this._domRef = Ext.getDom(this.id);
+ }
+
+ return this._domRef;
+ },
+
+ /**
+ * Returns a reference to the actual element to drag. By default this is
+ * the same as the html element, but it can be assigned to another
+ * element. An example of this can be found in Ext.dd.DDProxy
+ * @method getDragEl
+ * @return {HTMLElement} the html element
+ */
+ getDragEl: function() {
+ return Ext.getDom(this.dragElId);
+ },
+
+ /**
+ * Sets up the DragDrop object. Must be called in the constructor of any
+ * Ext.dd.DragDrop subclass
+ * @method init
+ * @param id the id of the linked element
+ * @param {String} sGroup the group of related items
+ * @param {object} config configuration attributes
+ */
+ init: function(id, sGroup, config) {
+ this.initTarget(id, sGroup, config);
+ Event.on(this.id, "mousedown", this.handleMouseDown, this);
+ // Event.on(this.id, "selectstart", Event.preventDefault);
+ },
+
+ /**
+ * Initializes Targeting functionality only... the object does not
+ * get a mousedown handler.
+ * @method initTarget
+ * @param id the id of the linked element
+ * @param {String} sGroup the group of related items
+ * @param {object} config configuration attributes
+ */
+ initTarget: function(id, sGroup, config) {
+
+ // configuration attributes
+ this.config = config || {};
+
+ // create a local reference to the drag and drop manager
+ this.DDM = Ext.dd.DDM;
+ // initialize the groups array
+ this.groups = {};
+
+ // assume that we have an element reference instead of an id if the
+ // parameter is not a string
+ if (typeof id !== "string") {
+ id = Ext.id(id);
+ }
+
+ // set the id
+ this.id = id;
+
+ // add to an interaction group
+ this.addToGroup((sGroup) ? sGroup : "default");
+
+ // We don't want to register this as the handle with the manager
+ // so we just set the id rather than calling the setter.
+ this.handleElId = id;
+
+ // the linked element is the element that gets dragged by default
+ this.setDragElId(id);
+
+ // by default, clicked anchors will not start drag operations.
+ this.invalidHandleTypes = { A: "A" };
+ this.invalidHandleIds = {};
+ this.invalidHandleClasses = [];
+
+ this.applyConfig();
+
+ this.handleOnAvailable();
+ },
+
+ /**
+ * Applies the configuration parameters that were passed into the constructor.
+ * This is supposed to happen at each level through the inheritance chain. So
+ * a DDProxy implentation will execute apply config on DDProxy, DD, and
+ * DragDrop in order to get all of the parameters that are available in
+ * each object.
+ * @method applyConfig
+ */
+ applyConfig: function() {
+
+ // configurable properties:
+ // padding, isTarget, maintainOffset, primaryButtonOnly
+ this.padding = this.config.padding || [0, 0, 0, 0];
+ this.isTarget = (this.config.isTarget !== false);
+ this.maintainOffset = (this.config.maintainOffset);
+ this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
+
+ },
+
+ /**
+ * Executed when the linked element is available
+ * @method handleOnAvailable
+ * @private
+ */
+ handleOnAvailable: function() {
+ this.available = true;
+ this.resetConstraints();
+ this.onAvailable();
+ },
+
+ /**
+ * Configures the padding for the target zone in px. Effectively expands
+ * (or reduces) the virtual object size for targeting calculations.
+ * Supports css-style shorthand; if only one parameter is passed, all sides
+ * will have that padding, and if only two are passed, the top and bottom
+ * will have the first param, the left and right the second.
+ * @method setPadding
+ * @param {int} iTop Top pad
+ * @param {int} iRight Right pad
+ * @param {int} iBot Bot pad
+ * @param {int} iLeft Left pad
+ */
+ setPadding: function(iTop, iRight, iBot, iLeft) {
+ // this.padding = [iLeft, iRight, iTop, iBot];
+ if (!iRight && 0 !== iRight) {
+ this.padding = [iTop, iTop, iTop, iTop];
+ } else if (!iBot && 0 !== iBot) {
+ this.padding = [iTop, iRight, iTop, iRight];
+ } else {
+ this.padding = [iTop, iRight, iBot, iLeft];
+ }
+ },
+
+ /**
+ * Stores the initial placement of the linked element.
+ * @method setInitPosition
+ * @param {int} diffX the X offset, default 0
+ * @param {int} diffY the Y offset, default 0
+ */
+ setInitPosition: function(diffX, diffY) {
+ var el = this.getEl();
+
+ if (!this.DDM.verifyEl(el)) {
+ return;
+ }
+
+ var dx = diffX || 0;
+ var dy = diffY || 0;
+
+ var p = Dom.getXY( el );
+
+ this.initPageX = p[0] - dx;
+ this.initPageY = p[1] - dy;
+
+ this.lastPageX = p[0];
+ this.lastPageY = p[1];
+
+ this.setStartPosition(p);
+ },
+
+ /**
+ * Sets the start position of the element. This is set when the obj
+ * is initialized, the reset when a drag is started.
+ * @method setStartPosition
+ * @param pos current position (from previous lookup)
+ * @private
+ */
+ setStartPosition: function(pos) {
+ var p = pos || Dom.getXY( this.getEl() );
+ this.deltaSetXY = null;
+
+ this.startPageX = p[0];
+ this.startPageY = p[1];
+ },
+
+ /**
+ * Add this instance to a group of related drag/drop objects. All
+ * instances belong to at least one group, and can belong to as many
+ * groups as needed.
+ * @method addToGroup
+ * @param sGroup {string} the name of the group
+ */
+ addToGroup: function(sGroup) {
+ this.groups[sGroup] = true;
+ this.DDM.regDragDrop(this, sGroup);
+ },
+
+ /**
+ * Remove's this instance from the supplied interaction group
+ * @method removeFromGroup
+ * @param {string} sGroup The group to drop
+ */
+ removeFromGroup: function(sGroup) {
+ if (this.groups[sGroup]) {
+ delete this.groups[sGroup];
+ }
+
+ this.DDM.removeDDFromGroup(this, sGroup);
+ },
+
+ /**
+ * Allows you to specify that an element other than the linked element
+ * will be moved with the cursor during a drag
+ * @method setDragElId
+ * @param id {string} the id of the element that will be used to initiate the drag
+ */
+ setDragElId: function(id) {
+ this.dragElId = id;
+ },
+
+ /**
+ * Allows you to specify a child of the linked element that should be
+ * used to initiate the drag operation. An example of this would be if
+ * you have a content div with text and links. Clicking anywhere in the
+ * content area would normally start the drag operation. Use this method
+ * to specify that an element inside of the content div is the element
+ * that starts the drag operation.
+ * @method setHandleElId
+ * @param id {string} the id of the element that will be used to
+ * initiate the drag.
+ */
+ setHandleElId: function(id) {
+ if (typeof id !== "string") {
+ id = Ext.id(id);
+ }
+ this.handleElId = id;
+ this.DDM.regHandle(this.id, id);
+ },
+
+ /**
+ * Allows you to set an element outside of the linked element as a drag
+ * handle
+ * @method setOuterHandleElId
+ * @param id the id of the element that will be used to initiate the drag
+ */
+ setOuterHandleElId: function(id) {
+ if (typeof id !== "string") {
+ id = Ext.id(id);
+ }
+ Event.on(id, "mousedown",
+ this.handleMouseDown, this);
+ this.setHandleElId(id);
+
+ this.hasOuterHandles = true;
+ },
+
+ /**
+ * Remove all drag and drop hooks for this element
+ * @method unreg
+ */
+ unreg: function() {
+ Event.un(this.id, "mousedown",
+ this.handleMouseDown);
+ this._domRef = null;
+ this.DDM._remove(this);
+ },
+
+ destroy : function(){
+ this.unreg();
+ },
+
+ /**
+ * Returns true if this instance is locked, or the drag drop mgr is locked
+ * (meaning that all drag/drop is disabled on the page.)
+ * @method isLocked
+ * @return {boolean} true if this obj or all drag/drop is locked, else
+ * false
+ */
+ isLocked: function() {
+ return (this.DDM.isLocked() || this.locked);
+ },
+
+ /**
+ * Fired when this object is clicked
+ * @method handleMouseDown
+ * @param {Event} e
+ * @param {Ext.dd.DragDrop} oDD the clicked dd object (this dd obj)
+ * @private
+ */
+ handleMouseDown: function(e, oDD){
+ if (this.primaryButtonOnly && e.button != 0) {
+ return;
+ }
+
+ if (this.isLocked()) {
+ return;
+ }
+
+ this.DDM.refreshCache(this.groups);
+
+ var pt = new Ext.lib.Point(Ext.lib.Event.getPageX(e), Ext.lib.Event.getPageY(e));
+ if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
+ } else {
+ if (this.clickValidator(e)) {
+
+ // set the initial element position
+ this.setStartPosition();
+
+ this.b4MouseDown(e);
+ this.onMouseDown(e);
+
+ this.DDM.handleMouseDown(e, this);
+
+ this.DDM.stopEvent(e);
+ } else {
+
+
+ }
+ }
+ },
+
+ clickValidator: function(e) {
+ var target = e.getTarget();
+ return ( this.isValidHandleChild(target) &&
+ (this.id == this.handleElId ||
+ this.DDM.handleWasClicked(target, this.id)) );
+ },
+
+ /**
+ * Allows you to specify a tag name that should not start a drag operation
+ * when clicked. This is designed to facilitate embedding links within a
+ * drag handle that do something other than start the drag.
+ * @method addInvalidHandleType
+ * @param {string} tagName the type of element to exclude
+ */
+ addInvalidHandleType: function(tagName) {
+ var type = tagName.toUpperCase();
+ this.invalidHandleTypes[type] = type;
+ },
+
+ /**
+ * Lets you to specify an element id for a child of a drag handle
+ * that should not initiate a drag
+ * @method addInvalidHandleId
+ * @param {string} id the element id of the element you wish to ignore
+ */
+ addInvalidHandleId: function(id) {
+ if (typeof id !== "string") {
+ id = Ext.id(id);
+ }
+ this.invalidHandleIds[id] = id;
+ },
+
+ /**
+ * Lets you specify a css class of elements that will not initiate a drag
+ * @method addInvalidHandleClass
+ * @param {string} cssClass the class of the elements you wish to ignore
+ */
+ addInvalidHandleClass: function(cssClass) {
+ this.invalidHandleClasses.push(cssClass);
+ },
+
+ /**
+ * Unsets an excluded tag name set by addInvalidHandleType
+ * @method removeInvalidHandleType
+ * @param {string} tagName the type of element to unexclude
+ */
+ removeInvalidHandleType: function(tagName) {
+ var type = tagName.toUpperCase();
+ // this.invalidHandleTypes[type] = null;
+ delete this.invalidHandleTypes[type];
+ },
+
+ /**
+ * Unsets an invalid handle id
+ * @method removeInvalidHandleId
+ * @param {string} id the id of the element to re-enable
+ */
+ removeInvalidHandleId: function(id) {
+ if (typeof id !== "string") {
+ id = Ext.id(id);
+ }
+ delete this.invalidHandleIds[id];
+ },
+
+ /**
+ * Unsets an invalid css class
+ * @method removeInvalidHandleClass
+ * @param {string} cssClass the class of the element(s) you wish to
+ * re-enable
+ */
+ removeInvalidHandleClass: function(cssClass) {
+ for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
+ if (this.invalidHandleClasses[i] == cssClass) {
+ delete this.invalidHandleClasses[i];
+ }
+ }
+ },
+
+ /**
+ * Checks the tag exclusion list to see if this click should be ignored
+ * @method isValidHandleChild
+ * @param {HTMLElement} node the HTMLElement to evaluate
+ * @return {boolean} true if this is a valid tag type, false if not
+ */
+ isValidHandleChild: function(node) {
+
+ var valid = true;
+ // var n = (node.nodeName == "#text") ? node.parentNode : node;
+ var nodeName;
+ try {
+ nodeName = node.nodeName.toUpperCase();
+ } catch(e) {
+ nodeName = node.nodeName;
+ }
+ valid = valid && !this.invalidHandleTypes[nodeName];
+ valid = valid && !this.invalidHandleIds[node.id];
+
+ for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
+ valid = !Ext.fly(node).hasClass(this.invalidHandleClasses[i]);
+ }
+
+
+ return valid;
+
+ },
+
+ /**
+ * Create the array of horizontal tick marks if an interval was specified
+ * in setXConstraint().
+ * @method setXTicks
+ * @private
+ */
+ setXTicks: function(iStartX, iTickSize) {
+ this.xTicks = [];
+ this.xTickSize = iTickSize;
+
+ var tickMap = {};
+
+ for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
+ if (!tickMap[i]) {
+ this.xTicks[this.xTicks.length] = i;
+ tickMap[i] = true;
+ }
+ }
+
+ for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
+ if (!tickMap[i]) {
+ this.xTicks[this.xTicks.length] = i;
+ tickMap[i] = true;
+ }
+ }
+
+ this.xTicks.sort(this.DDM.numericSort) ;
+ },
+
+ /**
+ * Create the array of vertical tick marks if an interval was specified in
+ * setYConstraint().
+ * @method setYTicks
+ * @private
+ */
+ setYTicks: function(iStartY, iTickSize) {
+ this.yTicks = [];
+ this.yTickSize = iTickSize;
+
+ var tickMap = {};
+
+ for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
+ if (!tickMap[i]) {
+ this.yTicks[this.yTicks.length] = i;
+ tickMap[i] = true;
+ }
+ }
+
+ for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
+ if (!tickMap[i]) {
+ this.yTicks[this.yTicks.length] = i;
+ tickMap[i] = true;
+ }
+ }
+
+ this.yTicks.sort(this.DDM.numericSort) ;
+ },
+
+ /**
+ * By default, the element can be dragged any place on the screen. Use
+ * this method to limit the horizontal travel of the element. Pass in
+ * 0,0 for the parameters if you want to lock the drag to the y axis.
+ * @method setXConstraint
+ * @param {int} iLeft the number of pixels the element can move to the left
+ * @param {int} iRight the number of pixels the element can move to the
+ * right
+ * @param {int} iTickSize optional parameter for specifying that the
+ * element
+ * should move iTickSize pixels at a time.
+ */
+ setXConstraint: function(iLeft, iRight, iTickSize) {
+ this.leftConstraint = iLeft;
+ this.rightConstraint = iRight;
+
+ this.minX = this.initPageX - iLeft;
+ this.maxX = this.initPageX + iRight;
+ if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
+
+ this.constrainX = true;
+ },
+
+ /**
+ * Clears any constraints applied to this instance. Also clears ticks
+ * since they can't exist independent of a constraint at this time.
+ * @method clearConstraints
+ */
+ clearConstraints: function() {
+ this.constrainX = false;
+ this.constrainY = false;
+ this.clearTicks();
+ },
+
+ /**
+ * Clears any tick interval defined for this instance
+ * @method clearTicks
+ */
+ clearTicks: function() {
+ this.xTicks = null;
+ this.yTicks = null;
+ this.xTickSize = 0;
+ this.yTickSize = 0;
+ },
+
+ /**
+ * By default, the element can be dragged any place on the screen. Set
+ * this to limit the vertical travel of the element. Pass in 0,0 for the
+ * parameters if you want to lock the drag to the x axis.
+ * @method setYConstraint
+ * @param {int} iUp the number of pixels the element can move up
+ * @param {int} iDown the number of pixels the element can move down
+ * @param {int} iTickSize optional parameter for specifying that the
+ * element should move iTickSize pixels at a time.
+ */
+ setYConstraint: function(iUp, iDown, iTickSize) {
+ this.topConstraint = iUp;
+ this.bottomConstraint = iDown;
+
+ this.minY = this.initPageY - iUp;
+ this.maxY = this.initPageY + iDown;
+ if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
+
+ this.constrainY = true;
+
+ },
+
+ /**
+ * resetConstraints must be called if you manually reposition a dd element.
+ * @method resetConstraints
+ * @param {boolean} maintainOffset
+ */
+ resetConstraints: function() {
+ // Maintain offsets if necessary
+ if (this.initPageX || this.initPageX === 0) {
+ // figure out how much this thing has moved
+ var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
+ var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
+
+ this.setInitPosition(dx, dy);
+
+ // This is the first time we have detected the element's position
+ } else {
+ this.setInitPosition();
+ }
+
+ if (this.constrainX) {
+ this.setXConstraint( this.leftConstraint,
+ this.rightConstraint,
+ this.xTickSize );
+ }
+
+ if (this.constrainY) {
+ this.setYConstraint( this.topConstraint,
+ this.bottomConstraint,
+ this.yTickSize );
+ }
+ },
+
+ /**
+ * Normally the drag element is moved pixel by pixel, but we can specify
+ * that it move a number of pixels at a time. This method resolves the
+ * location when we have it set up like this.
+ * @method getTick
+ * @param {int} val where we want to place the object
+ * @param {int[]} tickArray sorted array of valid points
+ * @return {int} the closest tick
+ * @private
+ */
+ getTick: function(val, tickArray) {
+ if (!tickArray) {
+ // If tick interval is not defined, it is effectively 1 pixel,
+ // so we return the value passed to us.
+ return val;
+ } else if (tickArray[0] >= val) {
+ // The value is lower than the first tick, so we return the first
+ // tick.
+ return tickArray[0];
+ } else {
+ for (var i=0, len=tickArray.length; i<len; ++i) {
+ var next = i + 1;
+ if (tickArray[next] && tickArray[next] >= val) {
+ var diff1 = val - tickArray[i];
+ var diff2 = tickArray[next] - val;
+ return (diff2 > diff1) ? tickArray[i] : tickArray[next];
+ }
+ }
+
+ // The value is larger than the last tick, so we return the last
+ // tick.
+ return tickArray[tickArray.length - 1];
+ }
+ },
+
+ /**
+ * toString method
+ * @method toString
+ * @return {string} string representation of the dd obj
+ */
+ toString: function() {
+ return ("DragDrop " + this.id);
+ }
+
+};
+
+})();
+/*!
+ * The drag and drop utility provides a framework for building drag and drop
+ * applications. In addition to enabling drag and drop for specific elements,
+ * the drag and drop elements are tracked by the manager class, and the
+ * interactions between the various elements are tracked during the drag and
+ * the implementing code is notified about these important moments.
+ */
+
+// Only load the library once. Rewriting the manager class would orphan
+// existing drag and drop instances.
+if (!Ext.dd.DragDropMgr) {
+
+/**
+ * @class Ext.dd.DragDropMgr
+ * DragDropMgr is a singleton that tracks the element interaction for
+ * all DragDrop items in the window. Generally, you will not call
+ * this class directly, but it does have helper methods that could
+ * be useful in your DragDrop implementations.
+ * @singleton
+ */
+Ext.dd.DragDropMgr = function() {
+
+ var Event = Ext.EventManager;
+
+ return {
+
+ /**
+ * Two dimensional Array of registered DragDrop objects. The first
+ * dimension is the DragDrop item group, the second the DragDrop
+ * object.
+ * @property ids
+ * @type String[]
+ * @private
+ * @static
+ */
+ ids: {},
+
+ /**
+ * Array of element ids defined as drag handles. Used to determine
+ * if the element that generated the mousedown event is actually the
+ * handle and not the html element itself.
+ * @property handleIds
+ * @type String[]
+ * @private
+ * @static
+ */
+ handleIds: {},
+
+ /**
+ * the DragDrop object that is currently being dragged
+ * @property dragCurrent
+ * @type DragDrop
+ * @private
+ * @static
+ **/
+ dragCurrent: null,
+
+ /**
+ * the DragDrop object(s) that are being hovered over
+ * @property dragOvers
+ * @type Array
+ * @private
+ * @static
+ */
+ dragOvers: {},
+
+ /**
+ * the X distance between the cursor and the object being dragged
+ * @property deltaX
+ * @type int
+ * @private
+ * @static
+ */
+ deltaX: 0,
+
+ /**
+ * the Y distance between the cursor and the object being dragged
+ * @property deltaY
+ * @type int
+ * @private
+ * @static
+ */
+ deltaY: 0,
+
+ /**
+ * Flag to determine if we should prevent the default behavior of the
+ * events we define. By default this is true, but this can be set to
+ * false if you need the default behavior (not recommended)
+ * @property preventDefault
+ * @type boolean
+ * @static
+ */
+ preventDefault: true,
+
+ /**
+ * Flag to determine if we should stop the propagation of the events
+ * we generate. This is true by default but you may want to set it to
+ * false if the html element contains other features that require the
+ * mouse click.
+ * @property stopPropagation
+ * @type boolean
+ * @static
+ */
+ stopPropagation: true,
+
+ /**
+ * Internal flag that is set to true when drag and drop has been
+ * intialized
+ * @property initialized
+ * @private
+ * @static
+ */
+ initialized: false,
+
+ /**
+ * All drag and drop can be disabled.
+ * @property locked
+ * @private
+ * @static
+ */
+ locked: false,
+
+ /**
+ * Called the first time an element is registered.
+ * @method init
+ * @private
+ * @static
+ */
+ init: function() {
+ this.initialized = true;
+ },
+
+ /**
+ * In point mode, drag and drop interaction is defined by the
+ * location of the cursor during the drag/drop
+ * @property POINT
+ * @type int
+ * @static
+ */
+ POINT: 0,
+
+ /**
+ * In intersect mode, drag and drop interaction is defined by the
+ * overlap of two or more drag and drop objects.
+ * @property INTERSECT
+ * @type int
+ * @static
+ */
+ INTERSECT: 1,
+
+ /**
+ * The current drag and drop mode. Default: POINT
+ * @property mode
+ * @type int
+ * @static
+ */
+ mode: 0,
+
+ /**
+ * Runs method on all drag and drop objects
+ * @method _execOnAll
+ * @private
+ * @static
+ */
+ _execOnAll: function(sMethod, args) {
+ for (var i in this.ids) {
+ for (var j in this.ids[i]) {
+ var oDD = this.ids[i][j];
+ if (! this.isTypeOfDD(oDD)) {
+ continue;
+ }
+ oDD[sMethod].apply(oDD, args);
+ }
+ }
+ },
+
+ /**
+ * Drag and drop initialization. Sets up the global event handlers
+ * @method _onLoad
+ * @private
+ * @static
+ */
+ _onLoad: function() {
+
+ this.init();
+
+
+ Event.on(document, "mouseup", this.handleMouseUp, this, true);
+ Event.on(document, "mousemove", this.handleMouseMove, this, true);
+ Event.on(window, "unload", this._onUnload, this, true);
+ Event.on(window, "resize", this._onResize, this, true);
+ // Event.on(window, "mouseout", this._test);
+
+ },
+
+ /**
+ * Reset constraints on all drag and drop objs
+ * @method _onResize
+ * @private
+ * @static
+ */
+ _onResize: function(e) {
+ this._execOnAll("resetConstraints", []);
+ },
+
+ /**
+ * Lock all drag and drop functionality
+ * @method lock
+ * @static
+ */
+ lock: function() { this.locked = true; },
+
+ /**
+ * Unlock all drag and drop functionality
+ * @method unlock
+ * @static
+ */
+ unlock: function() { this.locked = false; },
+
+ /**
+ * Is drag and drop locked?
+ * @method isLocked
+ * @return {boolean} True if drag and drop is locked, false otherwise.
+ * @static
+ */
+ isLocked: function() { return this.locked; },
+
+ /**
+ * Location cache that is set for all drag drop objects when a drag is
+ * initiated, cleared when the drag is finished.
+ * @property locationCache
+ * @private
+ * @static
+ */
+ locationCache: {},
+
+ /**
+ * Set useCache to false if you want to force object the lookup of each
+ * drag and drop linked element constantly during a drag.
+ * @property useCache
+ * @type boolean
+ * @static
+ */
+ useCache: true,
+
+ /**
+ * The number of pixels that the mouse needs to move after the
+ * mousedown before the drag is initiated. Default=3;
+ * @property clickPixelThresh
+ * @type int
+ * @static
+ */
+ clickPixelThresh: 3,
+
+ /**
+ * The number of milliseconds after the mousedown event to initiate the
+ * drag if we don't get a mouseup event. Default=350
+ * @property clickTimeThresh
+ * @type int
+ * @static
+ */
+ clickTimeThresh: 350,
+
+ /**
+ * Flag that indicates that either the drag pixel threshold or the
+ * mousdown time threshold has been met
+ * @property dragThreshMet
+ * @type boolean
+ * @private
+ * @static
+ */
+ dragThreshMet: false,
+
+ /**
+ * Timeout used for the click time threshold
+ * @property clickTimeout
+ * @type Object
+ * @private
+ * @static
+ */
+ clickTimeout: null,
+
+ /**
+ * The X position of the mousedown event stored for later use when a
+ * drag threshold is met.
+ * @property startX
+ * @type int
+ * @private
+ * @static
+ */
+ startX: 0,
+
+ /**
+ * The Y position of the mousedown event stored for later use when a
+ * drag threshold is met.
+ * @property startY
+ * @type int
+ * @private
+ * @static
+ */
+ startY: 0,
+
+ /**
+ * Each DragDrop instance must be registered with the DragDropMgr.
+ * This is executed in DragDrop.init()
+ * @method regDragDrop
+ * @param {DragDrop} oDD the DragDrop object to register
+ * @param {String} sGroup the name of the group this element belongs to
+ * @static
+ */
+ regDragDrop: function(oDD, sGroup) {
+ if (!this.initialized) { this.init(); }
+
+ if (!this.ids[sGroup]) {
+ this.ids[sGroup] = {};
+ }
+ this.ids[sGroup][oDD.id] = oDD;
+ },
+
+ /**
+ * Removes the supplied dd instance from the supplied group. Executed
+ * by DragDrop.removeFromGroup, so don't call this function directly.
+ * @method removeDDFromGroup
+ * @private
+ * @static
+ */
+ removeDDFromGroup: function(oDD, sGroup) {
+ if (!this.ids[sGroup]) {
+ this.ids[sGroup] = {};
+ }
+
+ var obj = this.ids[sGroup];
+ if (obj && obj[oDD.id]) {
+ delete obj[oDD.id];
+ }
+ },
+
+ /**
+ * Unregisters a drag and drop item. This is executed in
+ * DragDrop.unreg, use that method instead of calling this directly.
+ * @method _remove
+ * @private
+ * @static
+ */
+ _remove: function(oDD) {
+ for (var g in oDD.groups) {
+ if (g && this.ids[g] && this.ids[g][oDD.id]) {
+ delete this.ids[g][oDD.id];
+ }
+ }
+ delete this.handleIds[oDD.id];
+ },
+
+ /**
+ * Each DragDrop handle element must be registered. This is done
+ * automatically when executing DragDrop.setHandleElId()
+ * @method regHandle
+ * @param {String} sDDId the DragDrop id this element is a handle for
+ * @param {String} sHandleId the id of the element that is the drag
+ * handle
+ * @static
+ */
+ regHandle: function(sDDId, sHandleId) {
+ if (!this.handleIds[sDDId]) {
+ this.handleIds[sDDId] = {};
+ }
+ this.handleIds[sDDId][sHandleId] = sHandleId;
+ },
+
+ /**
+ * Utility function to determine if a given element has been
+ * registered as a drag drop item.
+ * @method isDragDrop
+ * @param {String} id the element id to check
+ * @return {boolean} true if this element is a DragDrop item,
+ * false otherwise
+ * @static
+ */
+ isDragDrop: function(id) {
+ return ( this.getDDById(id) ) ? true : false;
+ },
+
+ /**
+ * Returns the drag and drop instances that are in all groups the
+ * passed in instance belongs to.
+ * @method getRelated
+ * @param {DragDrop} p_oDD the obj to get related data for
+ * @param {boolean} bTargetsOnly if true, only return targetable objs
+ * @return {DragDrop[]} the related instances
+ * @static
+ */
+ getRelated: function(p_oDD, bTargetsOnly) {
+ var oDDs = [];
+ for (var i in p_oDD.groups) {
+ for (var j in this.ids[i]) {
+ var dd = this.ids[i][j];
+ if (! this.isTypeOfDD(dd)) {
+ continue;
+ }
+ if (!bTargetsOnly || dd.isTarget) {
+ oDDs[oDDs.length] = dd;
+ }
+ }
+ }
+
+ return oDDs;
+ },
+
+ /**
+ * Returns true if the specified dd target is a legal target for
+ * the specifice drag obj
+ * @method isLegalTarget
+ * @param {DragDrop} oDD the drag obj
+ * @param {DragDrop} oTargetDD the target
+ * @return {boolean} true if the target is a legal target for the
+ * dd obj
+ * @static
+ */
+ isLegalTarget: function (oDD, oTargetDD) {
+ var targets = this.getRelated(oDD, true);
+ for (var i=0, len=targets.length;i<len;++i) {
+ if (targets[i].id == oTargetDD.id) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ /**
+ * My goal is to be able to transparently determine if an object is
+ * typeof DragDrop, and the exact subclass of DragDrop. typeof
+ * returns "object", oDD.constructor.toString() always returns
+ * "DragDrop" and not the name of the subclass. So for now it just
+ * evaluates a well-known variable in DragDrop.
+ * @method isTypeOfDD
+ * @param {Object} the object to evaluate
+ * @return {boolean} true if typeof oDD = DragDrop
+ * @static
+ */
+ isTypeOfDD: function (oDD) {
+ return (oDD && oDD.__ygDragDrop);
+ },
+
+ /**
+ * Utility function to determine if a given element has been
+ * registered as a drag drop handle for the given Drag Drop object.
+ * @method isHandle
+ * @param {String} id the element id to check
+ * @return {boolean} true if this element is a DragDrop handle, false
+ * otherwise
+ * @static
+ */
+ isHandle: function(sDDId, sHandleId) {
+ return ( this.handleIds[sDDId] &&
+ this.handleIds[sDDId][sHandleId] );
+ },
+
+ /**
+ * Returns the DragDrop instance for a given id
+ * @method getDDById
+ * @param {String} id the id of the DragDrop object
+ * @return {DragDrop} the drag drop object, null if it is not found
+ * @static
+ */
+ getDDById: function(id) {
+ for (var i in this.ids) {
+ if (this.ids[i][id]) {
+ return this.ids[i][id];
+ }
+ }
+ return null;
+ },
+
+ /**
+ * Fired after a registered DragDrop object gets the mousedown event.
+ * Sets up the events required to track the object being dragged
+ * @method handleMouseDown
+ * @param {Event} e the event
+ * @param oDD the DragDrop object being dragged
+ * @private
+ * @static
+ */
+ handleMouseDown: function(e, oDD) {
+ if(Ext.QuickTips){
+ Ext.QuickTips.disable();
+ }
+ if(this.dragCurrent){
+ // the original browser mouseup wasn't handled (e.g. outside FF browser window)
+ // so clean up first to avoid breaking the next drag
+ this.handleMouseUp(e);
+ }
+
+ this.currentTarget = e.getTarget();
+ this.dragCurrent = oDD;
+
+ var el = oDD.getEl();
+
+ // track start position
+ this.startX = e.getPageX();
+ this.startY = e.getPageY();
+
+ this.deltaX = this.startX - el.offsetLeft;
+ this.deltaY = this.startY - el.offsetTop;
+
+ this.dragThreshMet = false;
+
+ this.clickTimeout = setTimeout(
+ function() {
+ var DDM = Ext.dd.DDM;
+ DDM.startDrag(DDM.startX, DDM.startY);
+ },
+ this.clickTimeThresh );
+ },
+
+ /**
+ * Fired when either the drag pixel threshol or the mousedown hold
+ * time threshold has been met.
+ * @method startDrag
+ * @param x {int} the X position of the original mousedown
+ * @param y {int} the Y position of the original mousedown
+ * @static
+ */
+ startDrag: function(x, y) {
+ clearTimeout(this.clickTimeout);
+ if (this.dragCurrent) {
+ this.dragCurrent.b4StartDrag(x, y);
+ this.dragCurrent.startDrag(x, y);
+ }
+ this.dragThreshMet = true;
+ },
+
+ /**
+ * Internal function to handle the mouseup event. Will be invoked
+ * from the context of the document.
+ * @method handleMouseUp
+ * @param {Event} e the event
+ * @private
+ * @static
+ */
+ handleMouseUp: function(e) {
+
+ if(Ext.QuickTips){
+ Ext.QuickTips.enable();
+ }
+ if (! this.dragCurrent) {
+ return;
+ }
+
+ clearTimeout(this.clickTimeout);
+
+ if (this.dragThreshMet) {
+ this.fireEvents(e, true);
+ } else {
+ }
+
+ this.stopDrag(e);
+
+ this.stopEvent(e);
+ },
+
+ /**
+ * Utility to stop event propagation and event default, if these
+ * features are turned on.
+ * @method stopEvent
+ * @param {Event} e the event as returned by this.getEvent()
+ * @static
+ */
+ stopEvent: function(e){
+ if(this.stopPropagation) {
+ e.stopPropagation();
+ }
+
+ if (this.preventDefault) {
+ e.preventDefault();
+ }
+ },
+
+ /**
+ * Internal function to clean up event handlers after the drag
+ * operation is complete
+ * @method stopDrag
+ * @param {Event} e the event
+ * @private
+ * @static
+ */
+ stopDrag: function(e) {
+ // Fire the drag end event for the item that was dragged
+ if (this.dragCurrent) {
+ if (this.dragThreshMet) {
+ this.dragCurrent.b4EndDrag(e);
+ this.dragCurrent.endDrag(e);
+ }
+
+ this.dragCurrent.onMouseUp(e);
+ }
+
+ this.dragCurrent = null;
+ this.dragOvers = {};
+ },
+
+ /**
+ * Internal function to handle the mousemove event. Will be invoked
+ * from the context of the html element.
+ *
+ * @TODO figure out what we can do about mouse events lost when the
+ * user drags objects beyond the window boundary. Currently we can
+ * detect this in internet explorer by verifying that the mouse is
+ * down during the mousemove event. Firefox doesn't give us the
+ * button state on the mousemove event.
+ * @method handleMouseMove
+ * @param {Event} e the event
+ * @private
+ * @static
+ */
+ handleMouseMove: function(e) {
+ if (! this.dragCurrent) {
+ return true;
+ }
+ // var button = e.which || e.button;
+
+ // check for IE mouseup outside of page boundary
+ if (Ext.isIE && (e.button !== 0 && e.button !== 1 && e.button !== 2)) {
+ this.stopEvent(e);
+ return this.handleMouseUp(e);
+ }
+
+ if (!this.dragThreshMet) {
+ var diffX = Math.abs(this.startX - e.getPageX());
+ var diffY = Math.abs(this.startY - e.getPageY());
+ if (diffX > this.clickPixelThresh ||
+ diffY > this.clickPixelThresh) {
+ this.startDrag(this.startX, this.startY);
+ }
+ }
+
+ if (this.dragThreshMet) {
+ this.dragCurrent.b4Drag(e);
+ this.dragCurrent.onDrag(e);
+ if(!this.dragCurrent.moveOnly){
+ this.fireEvents(e, false);
+ }
+ }
+
+ this.stopEvent(e);
+
+ return true;
+ },
+
+ /**
+ * Iterates over all of the DragDrop elements to find ones we are
+ * hovering over or dropping on
+ * @method fireEvents
+ * @param {Event} e the event
+ * @param {boolean} isDrop is this a drop op or a mouseover op?
+ * @private
+ * @static
+ */
+ fireEvents: function(e, isDrop) {
+ var dc = this.dragCurrent;
+
+ // If the user did the mouse up outside of the window, we could
+ // get here even though we have ended the drag.
+ if (!dc || dc.isLocked()) {
+ return;
+ }
+
+ var pt = e.getPoint();
+
+ // cache the previous dragOver array
+ var oldOvers = [];
+
+ var outEvts = [];
+ var overEvts = [];
+ var dropEvts = [];
+ var enterEvts = [];
+
+ // Check to see if the object(s) we were hovering over is no longer
+ // being hovered over so we can fire the onDragOut event
+ for (var i in this.dragOvers) {
+
+ var ddo = this.dragOvers[i];
+
+ if (! this.isTypeOfDD(ddo)) {
+ continue;
+ }
+
+ if (! this.isOverTarget(pt, ddo, this.mode)) {
+ outEvts.push( ddo );
+ }
+
+ oldOvers[i] = true;
+ delete this.dragOvers[i];
+ }
+
+ for (var sGroup in dc.groups) {
+
+ if ("string" != typeof sGroup) {
+ continue;
+ }
+
+ for (i in this.ids[sGroup]) {
+ var oDD = this.ids[sGroup][i];
+ if (! this.isTypeOfDD(oDD)) {
+ continue;
+ }
+
+ if (oDD.isTarget && !oDD.isLocked() && ((oDD != dc) || (dc.ignoreSelf === false))) {
+ if (this.isOverTarget(pt, oDD, this.mode)) {
+ // look for drop interactions
+ if (isDrop) {
+ dropEvts.push( oDD );
+ // look for drag enter and drag over interactions
+ } else {
+
+ // initial drag over: dragEnter fires
+ if (!oldOvers[oDD.id]) {
+ enterEvts.push( oDD );
+ // subsequent drag overs: dragOver fires
+ } else {
+ overEvts.push( oDD );
+ }
+
+ this.dragOvers[oDD.id] = oDD;
+ }
+ }
+ }
+ }
+ }
+
+ if (this.mode) {
+ if (outEvts.length) {
+ dc.b4DragOut(e, outEvts);
+ dc.onDragOut(e, outEvts);
+ }
+
+ if (enterEvts.length) {
+ dc.onDragEnter(e, enterEvts);
+ }
+
+ if (overEvts.length) {
+ dc.b4DragOver(e, overEvts);
+ dc.onDragOver(e, overEvts);
+ }
+
+ if (dropEvts.length) {
+ dc.b4DragDrop(e, dropEvts);
+ dc.onDragDrop(e, dropEvts);
+ }
+
+ } else {
+ // fire dragout events
+ var len = 0;
+ for (i=0, len=outEvts.length; i<len; ++i) {
+ dc.b4DragOut(e, outEvts[i].id);
+ dc.onDragOut(e, outEvts[i].id);
+ }
+
+ // fire enter events
+ for (i=0,len=enterEvts.length; i<len; ++i) {
+ // dc.b4DragEnter(e, oDD.id);
+ dc.onDragEnter(e, enterEvts[i].id);
+ }
+
+ // fire over events
+ for (i=0,len=overEvts.length; i<len; ++i) {
+ dc.b4DragOver(e, overEvts[i].id);
+ dc.onDragOver(e, overEvts[i].id);
+ }
+
+ // fire drop events
+ for (i=0, len=dropEvts.length; i<len; ++i) {
+ dc.b4DragDrop(e, dropEvts[i].id);
+ dc.onDragDrop(e, dropEvts[i].id);
+ }
+
+ }
+
+ // notify about a drop that did not find a target
+ if (isDrop && !dropEvts.length) {
+ dc.onInvalidDrop(e);
+ }
+
+ },
+
+ /**
+ * Helper function for getting the best match from the list of drag
+ * and drop objects returned by the drag and drop events when we are
+ * in INTERSECT mode. It returns either the first object that the
+ * cursor is over, or the object that has the greatest overlap with
+ * the dragged element.
+ * @method getBestMatch
+ * @param {DragDrop[]} dds The array of drag and drop objects
+ * targeted
+ * @return {DragDrop} The best single match
+ * @static
+ */
+ getBestMatch: function(dds) {
+ var winner = null;
+ // Return null if the input is not what we expect
+ //if (!dds || !dds.length || dds.length == 0) {
+ // winner = null;
+ // If there is only one item, it wins
+ //} else if (dds.length == 1) {
+
+ var len = dds.length;
+
+ if (len == 1) {
+ winner = dds[0];
+ } else {
+ // Loop through the targeted items
+ for (var i=0; i<len; ++i) {
+ var dd = dds[i];
+ // If the cursor is over the object, it wins. If the
+ // cursor is over multiple matches, the first one we come
+ // to wins.
+ if (dd.cursorIsOver) {
+ winner = dd;
+ break;
+ // Otherwise the object with the most overlap wins
+ } else {
+ if (!winner ||
+ winner.overlap.getArea() < dd.overlap.getArea()) {
+ winner = dd;
+ }
+ }
+ }
+ }
+
+ return winner;
+ },
+
+ /**
+ * Refreshes the cache of the top-left and bottom-right points of the
+ * drag and drop objects in the specified group(s). This is in the
+ * format that is stored in the drag and drop instance, so typical
+ * usage is:
+ * <code>
+ * Ext.dd.DragDropMgr.refreshCache(ddinstance.groups);
+ * </code>
+ * Alternatively:
+ * <code>
+ * Ext.dd.DragDropMgr.refreshCache({group1:true, group2:true});
+ * </code>
+ * @TODO this really should be an indexed array. Alternatively this
+ * method could accept both.
+ * @method refreshCache
+ * @param {Object} groups an associative array of groups to refresh
+ * @static
+ */
+ refreshCache: function(groups) {
+ for (var sGroup in groups) {
+ if ("string" != typeof sGroup) {
+ continue;
+ }
+ for (var i in this.ids[sGroup]) {
+ var oDD = this.ids[sGroup][i];
+
+ if (this.isTypeOfDD(oDD)) {
+ // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
+ var loc = this.getLocation(oDD);
+ if (loc) {
+ this.locationCache[oDD.id] = loc;
+ } else {
+ delete this.locationCache[oDD.id];
+ // this will unregister the drag and drop object if
+ // the element is not in a usable state
+ // oDD.unreg();
+ }
+ }
+ }
+ }
+ },
+
+ /**
+ * This checks to make sure an element exists and is in the DOM. The
+ * main purpose is to handle cases where innerHTML is used to remove
+ * drag and drop objects from the DOM. IE provides an 'unspecified
+ * error' when trying to access the offsetParent of such an element
+ * @method verifyEl
+ * @param {HTMLElement} el the element to check
+ * @return {boolean} true if the element looks usable
+ * @static
+ */
+ verifyEl: function(el) {
+ if (el) {
+ var parent;
+ if(Ext.isIE){
+ try{
+ parent = el.offsetParent;
+ }catch(e){}
+ }else{
+ parent = el.offsetParent;
+ }
+ if (parent) {
+ return true;
+ }
+ }
+
+ return false;
+ },
+
+ /**
+ * Returns a Region object containing the drag and drop element's position
+ * and size, including the padding configured for it
+ * @method getLocation
+ * @param {DragDrop} oDD the drag and drop object to get the
+ * location for
+ * @return {Ext.lib.Region} a Region object representing the total area
+ * the element occupies, including any padding
+ * the instance is configured for.
+ * @static
+ */
+ getLocation: function(oDD) {
+ if (! this.isTypeOfDD(oDD)) {
+ return null;
+ }
+
+ var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
+
+ try {
+ pos= Ext.lib.Dom.getXY(el);
+ } catch (e) { }
+
+ if (!pos) {
+ return null;
+ }
+
+ x1 = pos[0];
+ x2 = x1 + el.offsetWidth;
+ y1 = pos[1];
+ y2 = y1 + el.offsetHeight;
+
+ t = y1 - oDD.padding[0];
+ r = x2 + oDD.padding[1];
+ b = y2 + oDD.padding[2];
+ l = x1 - oDD.padding[3];
+
+ return new Ext.lib.Region( t, r, b, l );
+ },
+
+ /**
+ * Checks the cursor location to see if it over the target
+ * @method isOverTarget
+ * @param {Ext.lib.Point} pt The point to evaluate
+ * @param {DragDrop} oTarget the DragDrop object we are inspecting
+ * @return {boolean} true if the mouse is over the target
+ * @private
+ * @static
+ */
+ isOverTarget: function(pt, oTarget, intersect) {
+ // use cache if available
+ var loc = this.locationCache[oTarget.id];
+ if (!loc || !this.useCache) {
+ loc = this.getLocation(oTarget);
+ this.locationCache[oTarget.id] = loc;
+
+ }
+
+ if (!loc) {
+ return false;
+ }
+
+ oTarget.cursorIsOver = loc.contains( pt );
+
+ // DragDrop is using this as a sanity check for the initial mousedown
+ // in this case we are done. In POINT mode, if the drag obj has no
+ // contraints, we are also done. Otherwise we need to evaluate the
+ // location of the target as related to the actual location of the
+ // dragged element.
+ var dc = this.dragCurrent;
+ if (!dc || !dc.getTargetCoord ||
+ (!intersect && !dc.constrainX && !dc.constrainY)) {
+ return oTarget.cursorIsOver;
+ }
+
+ oTarget.overlap = null;
+
+ // Get the current location of the drag element, this is the
+ // location of the mouse event less the delta that represents
+ // where the original mousedown happened on the element. We
+ // need to consider constraints and ticks as well.
+ var pos = dc.getTargetCoord(pt.x, pt.y);
+
+ var el = dc.getDragEl();
+ var curRegion = new Ext.lib.Region( pos.y,
+ pos.x + el.offsetWidth,
+ pos.y + el.offsetHeight,
+ pos.x );
+
+ var overlap = curRegion.intersect(loc);
+
+ if (overlap) {
+ oTarget.overlap = overlap;
+ return (intersect) ? true : oTarget.cursorIsOver;
+ } else {
+ return false;
+ }
+ },
+
+ /**
+ * unload event handler
+ * @method _onUnload
+ * @private
+ * @static
+ */
+ _onUnload: function(e, me) {
+ Ext.dd.DragDropMgr.unregAll();
+ },
+
+ /**
+ * Cleans up the drag and drop events and objects.
+ * @method unregAll
+ * @private
+ * @static
+ */
+ unregAll: function() {
+
+ if (this.dragCurrent) {
+ this.stopDrag();
+ this.dragCurrent = null;
+ }
+
+ this._execOnAll("unreg", []);
+
+ for (var i in this.elementCache) {
+ delete this.elementCache[i];
+ }
+
+ this.elementCache = {};
+ this.ids = {};
+ },
+
+ /**
+ * A cache of DOM elements
+ * @property elementCache
+ * @private
+ * @static
+ */
+ elementCache: {},
+
+ /**
+ * Get the wrapper for the DOM element specified
+ * @method getElWrapper
+ * @param {String} id the id of the element to get
+ * @return {Ext.dd.DDM.ElementWrapper} the wrapped element
+ * @private
+ * @deprecated This wrapper isn't that useful
+ * @static
+ */
+ getElWrapper: function(id) {
+ var oWrapper = this.elementCache[id];
+ if (!oWrapper || !oWrapper.el) {
+ oWrapper = this.elementCache[id] =
+ new this.ElementWrapper(Ext.getDom(id));
+ }
+ return oWrapper;
+ },
+
+ /**
+ * Returns the actual DOM element
+ * @method getElement
+ * @param {String} id the id of the elment to get
+ * @return {Object} The element
+ * @deprecated use Ext.lib.Ext.getDom instead
+ * @static
+ */
+ getElement: function(id) {
+ return Ext.getDom(id);
+ },
+
+ /**
+ * Returns the style property for the DOM element (i.e.,
+ * document.getElById(id).style)
+ * @method getCss
+ * @param {String} id the id of the elment to get
+ * @return {Object} The style property of the element
+ * @deprecated use Ext.lib.Dom instead
+ * @static
+ */
+ getCss: function(id) {
+ var el = Ext.getDom(id);
+ return (el) ? el.style : null;
+ },
+
+ /**
+ * Inner class for cached elements
+ * @class Ext.dd.DragDropMgr.ElementWrapper
+ * @for DragDropMgr
+ * @private
+ * @deprecated
+ */
+ ElementWrapper: function(el) {
+ /**
+ * The element
+ * @property el
+ */
+ this.el = el || null;
+ /**
+ * The element id
+ * @property id
+ */
+ this.id = this.el && el.id;
+ /**
+ * A reference to the style property
+ * @property css
+ */
+ this.css = this.el && el.style;
+ },
+
+ /**
+ * Returns the X position of an html element
+ * @method getPosX
+ * @param el the element for which to get the position
+ * @return {int} the X coordinate
+ * @for DragDropMgr
+ * @deprecated use Ext.lib.Dom.getX instead
+ * @static
+ */
+ getPosX: function(el) {
+ return Ext.lib.Dom.getX(el);
+ },
+
+ /**
+ * Returns the Y position of an html element
+ * @method getPosY
+ * @param el the element for which to get the position
+ * @return {int} the Y coordinate
+ * @deprecated use Ext.lib.Dom.getY instead
+ * @static
+ */
+ getPosY: function(el) {
+ return Ext.lib.Dom.getY(el);
+ },
+
+ /**
+ * Swap two nodes. In IE, we use the native method, for others we
+ * emulate the IE behavior
+ * @method swapNode
+ * @param n1 the first node to swap
+ * @param n2 the other node to swap
+ * @static
+ */
+ swapNode: function(n1, n2) {
+ if (n1.swapNode) {
+ n1.swapNode(n2);
+ } else {
+ var p = n2.parentNode;
+ var s = n2.nextSibling;
+
+ if (s == n1) {
+ p.insertBefore(n1, n2);
+ } else if (n2 == n1.nextSibling) {
+ p.insertBefore(n2, n1);
+ } else {
+ n1.parentNode.replaceChild(n2, n1);
+ p.insertBefore(n1, s);
+ }
+ }
+ },
+
+ /**
+ * Returns the current scroll position
+ * @method getScroll
+ * @private
+ * @static
+ */
+ getScroll: function () {
+ var t, l, dde=document.documentElement, db=document.body;
+ if (dde && (dde.scrollTop || dde.scrollLeft)) {
+ t = dde.scrollTop;
+ l = dde.scrollLeft;
+ } else if (db) {
+ t = db.scrollTop;
+ l = db.scrollLeft;
+ } else {
+
+ }
+ return { top: t, left: l };
+ },
+
+ /**
+ * Returns the specified element style property
+ * @method getStyle
+ * @param {HTMLElement} el the element
+ * @param {string} styleProp the style property
+ * @return {string} The value of the style property
+ * @deprecated use Ext.lib.Dom.getStyle
+ * @static
+ */
+ getStyle: function(el, styleProp) {
+ return Ext.fly(el).getStyle(styleProp);
+ },
+
+ /**
+ * Gets the scrollTop
+ * @method getScrollTop
+ * @return {int} the document's scrollTop
+ * @static
+ */
+ getScrollTop: function () {
+ return this.getScroll().top;
+ },
+
+ /**
+ * Gets the scrollLeft
+ * @method getScrollLeft
+ * @return {int} the document's scrollTop
+ * @static
+ */
+ getScrollLeft: function () {
+ return this.getScroll().left;
+ },
+
+ /**
+ * Sets the x/y position of an element to the location of the
+ * target element.
+ * @method moveToEl
+ * @param {HTMLElement} moveEl The element to move
+ * @param {HTMLElement} targetEl The position reference element
+ * @static
+ */
+ moveToEl: function (moveEl, targetEl) {
+ var aCoord = Ext.lib.Dom.getXY(targetEl);
+ Ext.lib.Dom.setXY(moveEl, aCoord);
+ },
+
+ /**
+ * Numeric array sort function
+ * @method numericSort
+ * @static
+ */
+ numericSort: function(a, b) {
+ return (a - b);
+ },
+
+ /**
+ * Internal counter
+ * @property _timeoutCount
+ * @private
+ * @static
+ */
+ _timeoutCount: 0,
+
+ /**
+ * Trying to make the load order less important. Without this we get
+ * an error if this file is loaded before the Event Utility.
+ * @method _addListeners
+ * @private
+ * @static
+ */
+ _addListeners: function() {
+ var DDM = Ext.dd.DDM;
+ if ( Ext.lib.Event && document ) {
+ DDM._onLoad();
+ } else {
+ if (DDM._timeoutCount > 2000) {
+ } else {
+ setTimeout(DDM._addListeners, 10);
+ if (document && document.body) {
+ DDM._timeoutCount += 1;
+ }
+ }
+ }
+ },
+
+ /**
+ * Recursively searches the immediate parent and all child nodes for
+ * the handle element in order to determine wheter or not it was
+ * clicked.
+ * @method handleWasClicked
+ * @param node the html element to inspect
+ * @static
+ */
+ handleWasClicked: function(node, id) {
+ if (this.isHandle(id, node.id)) {
+ return true;
+ } else {
+ // check to see if this is a text node child of the one we want
+ var p = node.parentNode;
+
+ while (p) {
+ if (this.isHandle(id, p.id)) {
+ return true;
+ } else {
+ p = p.parentNode;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ };
+
+}();
+
+// shorter alias, save a few bytes
+Ext.dd.DDM = Ext.dd.DragDropMgr;
+Ext.dd.DDM._addListeners();
+
+}
+
+/**
+ * @class Ext.dd.DD
+ * A DragDrop implementation where the linked element follows the
+ * mouse cursor during a drag.
+ * @extends Ext.dd.DragDrop
+ * @constructor
+ * @param {String} id the id of the linked element
+ * @param {String} sGroup the group of related DragDrop items
+ * @param {object} config an object containing configurable attributes
+ * Valid properties for DD:
+ * scroll
+ */
+Ext.dd.DD = function(id, sGroup, config) {
+ if (id) {
+ this.init(id, sGroup, config);
+ }
+};
+
+Ext.extend(Ext.dd.DD, Ext.dd.DragDrop, {
+
+ /**
+ * When set to true, the utility automatically tries to scroll the browser
+ * window when a drag and drop element is dragged near the viewport boundary.
+ * Defaults to true.
+ * @property scroll
+ * @type boolean
+ */
+ scroll: true,
+
+ /**
+ * Sets the pointer offset to the distance between the linked element's top
+ * left corner and the location the element was clicked
+ * @method autoOffset
+ * @param {int} iPageX the X coordinate of the click
+ * @param {int} iPageY the Y coordinate of the click
+ */
+ autoOffset: function(iPageX, iPageY) {
+ var x = iPageX - this.startPageX;
+ var y = iPageY - this.startPageY;
+ this.setDelta(x, y);
+ },
+
+ /**
+ * Sets the pointer offset. You can call this directly to force the
+ * offset to be in a particular location (e.g., pass in 0,0 to set it
+ * to the center of the object)
+ * @method setDelta
+ * @param {int} iDeltaX the distance from the left
+ * @param {int} iDeltaY the distance from the top
+ */
+ setDelta: function(iDeltaX, iDeltaY) {
+ this.deltaX = iDeltaX;
+ this.deltaY = iDeltaY;
+ },
+
+ /**
+ * Sets the drag element to the location of the mousedown or click event,
+ * maintaining the cursor location relative to the location on the element
+ * that was clicked. Override this if you want to place the element in a
+ * location other than where the cursor is.
+ * @method setDragElPos
+ * @param {int} iPageX the X coordinate of the mousedown or drag event
+ * @param {int} iPageY the Y coordinate of the mousedown or drag event
+ */
+ setDragElPos: function(iPageX, iPageY) {
+ // the first time we do this, we are going to check to make sure
+ // the element has css positioning
+
+ var el = this.getDragEl();
+ this.alignElWithMouse(el, iPageX, iPageY);
+ },
+
+ /**
+ * Sets the element to the location of the mousedown or click event,
+ * maintaining the cursor location relative to the location on the element
+ * that was clicked. Override this if you want to place the element in a
+ * location other than where the cursor is.
+ * @method alignElWithMouse
+ * @param {HTMLElement} el the element to move
+ * @param {int} iPageX the X coordinate of the mousedown or drag event
+ * @param {int} iPageY the Y coordinate of the mousedown or drag event
+ */
+ alignElWithMouse: function(el, iPageX, iPageY) {
+ var oCoord = this.getTargetCoord(iPageX, iPageY);
+ var fly = el.dom ? el : Ext.fly(el, '_dd');
+ if (!this.deltaSetXY) {
+ var aCoord = [oCoord.x, oCoord.y];
+ fly.setXY(aCoord);
+ var newLeft = fly.getLeft(true);
+ var newTop = fly.getTop(true);
+ this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
+ } else {
+ fly.setLeftTop(oCoord.x + this.deltaSetXY[0], oCoord.y + this.deltaSetXY[1]);
+ }
+
+ this.cachePosition(oCoord.x, oCoord.y);
+ this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
+ return oCoord;
+ },
+
+ /**
+ * Saves the most recent position so that we can reset the constraints and
+ * tick marks on-demand. We need to know this so that we can calculate the
+ * number of pixels the element is offset from its original position.
+ * @method cachePosition
+ * @param iPageX the current x position (optional, this just makes it so we
+ * don't have to look it up again)
+ * @param iPageY the current y position (optional, this just makes it so we
+ * don't have to look it up again)
+ */
+ cachePosition: function(iPageX, iPageY) {
+ if (iPageX) {
+ this.lastPageX = iPageX;
+ this.lastPageY = iPageY;
+ } else {
+ var aCoord = Ext.lib.Dom.getXY(this.getEl());
+ this.lastPageX = aCoord[0];
+ this.lastPageY = aCoord[1];
+ }
+ },
+
+ /**
+ * Auto-scroll the window if the dragged object has been moved beyond the
+ * visible window boundary.
+ * @method autoScroll
+ * @param {int} x the drag element's x position
+ * @param {int} y the drag element's y position
+ * @param {int} h the height of the drag element
+ * @param {int} w the width of the drag element
+ * @private
+ */
+ autoScroll: function(x, y, h, w) {
+
+ if (this.scroll) {
+ // The client height
+ var clientH = Ext.lib.Dom.getViewHeight();
+
+ // The client width
+ var clientW = Ext.lib.Dom.getViewWidth();
+
+ // The amt scrolled down
+ var st = this.DDM.getScrollTop();
+
+ // The amt scrolled right
+ var sl = this.DDM.getScrollLeft();
+
+ // Location of the bottom of the element
+ var bot = h + y;
+
+ // Location of the right of the element
+ var right = w + x;
+
+ // The distance from the cursor to the bottom of the visible area,
+ // adjusted so that we don't scroll if the cursor is beyond the
+ // element drag constraints
+ var toBot = (clientH + st - y - this.deltaY);
+
+ // The distance from the cursor to the right of the visible area
+ var toRight = (clientW + sl - x - this.deltaX);
+
+
+ // How close to the edge the cursor must be before we scroll
+ // var thresh = (document.all) ? 100 : 40;
+ var thresh = 40;
+
+ // How many pixels to scroll per autoscroll op. This helps to reduce
+ // clunky scrolling. IE is more sensitive about this ... it needs this
+ // value to be higher.
+ var scrAmt = (document.all) ? 80 : 30;
+
+ // Scroll down if we are near the bottom of the visible page and the
+ // obj extends below the crease
+ if ( bot > clientH && toBot < thresh ) {
+ window.scrollTo(sl, st + scrAmt);
+ }
+
+ // Scroll up if the window is scrolled down and the top of the object
+ // goes above the top border
+ if ( y < st && st > 0 && y - st < thresh ) {
+ window.scrollTo(sl, st - scrAmt);
+ }
+
+ // Scroll right if the obj is beyond the right border and the cursor is
+ // near the border.
+ if ( right > clientW && toRight < thresh ) {
+ window.scrollTo(sl + scrAmt, st);
+ }
+
+ // Scroll left if the window has been scrolled to the right and the obj
+ // extends past the left border
+ if ( x < sl && sl > 0 && x - sl < thresh ) {
+ window.scrollTo(sl - scrAmt, st);
+ }
+ }
+ },
+
+ /**
+ * Finds the location the element should be placed if we want to move
+ * it to where the mouse location less the click offset would place us.
+ * @method getTargetCoord
+ * @param {int} iPageX the X coordinate of the click
+ * @param {int} iPageY the Y coordinate of the click
+ * @return an object that contains the coordinates (Object.x and Object.y)
+ * @private
+ */
+ getTargetCoord: function(iPageX, iPageY) {
+ var x = iPageX - this.deltaX;
+ var y = iPageY - this.deltaY;
+
+ if (this.constrainX) {
+ if (x < this.minX) { x = this.minX; }
+ if (x > this.maxX) { x = this.maxX; }
+ }
+
+ if (this.constrainY) {
+ if (y < this.minY) { y = this.minY; }
+ if (y > this.maxY) { y = this.maxY; }
+ }
+
+ x = this.getTick(x, this.xTicks);
+ y = this.getTick(y, this.yTicks);
+
+
+ return {x:x, y:y};
+ },
+
+ /**
+ * Sets up config options specific to this class. Overrides
+ * Ext.dd.DragDrop, but all versions of this method through the
+ * inheritance chain are called
+ */
+ applyConfig: function() {
+ Ext.dd.DD.superclass.applyConfig.call(this);
+ this.scroll = (this.config.scroll !== false);
+ },
+
+ /**
+ * Event that fires prior to the onMouseDown event. Overrides
+ * Ext.dd.DragDrop.
+ */
+ b4MouseDown: function(e) {
+ // this.resetConstraints();
+ this.autoOffset(e.getPageX(),
+ e.getPageY());
+ },
+
+ /**
+ * Event that fires prior to the onDrag event. Overrides
+ * Ext.dd.DragDrop.
+ */
+ b4Drag: function(e) {
+ this.setDragElPos(e.getPageX(),
+ e.getPageY());
+ },
+
+ toString: function() {
+ return ("DD " + this.id);
+ }
+
+ //////////////////////////////////////////////////////////////////////////
+ // Debugging ygDragDrop events that can be overridden
+ //////////////////////////////////////////////////////////////////////////
+ /*
+ startDrag: function(x, y) {
+ },
+
+ onDrag: function(e) {
+ },
+
+ onDragEnter: function(e, id) {
+ },
+
+ onDragOver: function(e, id) {
+ },
+
+ onDragOut: function(e, id) {
+ },
+
+ onDragDrop: function(e, id) {
+ },
+
+ endDrag: function(e) {
+ }
+
+ */
+
+});
+/**
+ * @class Ext.dd.DDProxy
+ * A DragDrop implementation that inserts an empty, bordered div into
+ * the document that follows the cursor during drag operations. At the time of
+ * the click, the frame div is resized to the dimensions of the linked html
+ * element, and moved to the exact location of the linked element.
+ *
+ * References to the "frame" element refer to the single proxy element that
+ * was created to be dragged in place of all DDProxy elements on the
+ * page.
+ *
+ * @extends Ext.dd.DD
+ * @constructor
+ * @param {String} id the id of the linked html element
+ * @param {String} sGroup the group of related DragDrop objects
+ * @param {object} config an object containing configurable attributes
+ * Valid properties for DDProxy in addition to those in DragDrop:
+ * resizeFrame, centerFrame, dragElId
+ */
+Ext.dd.DDProxy = function(id, sGroup, config) {
+ if (id) {
+ this.init(id, sGroup, config);
+ this.initFrame();
+ }
+};
+
+/**
+ * The default drag frame div id
+ * @property Ext.dd.DDProxy.dragElId
+ * @type String
+ * @static
+ */
+Ext.dd.DDProxy.dragElId = "ygddfdiv";
+
+Ext.extend(Ext.dd.DDProxy, Ext.dd.DD, {
+
+ /**
+ * By default we resize the drag frame to be the same size as the element
+ * we want to drag (this is to get the frame effect). We can turn it off
+ * if we want a different behavior.
+ * @property resizeFrame
+ * @type boolean
+ */
+ resizeFrame: true,
+
+ /**
+ * By default the frame is positioned exactly where the drag element is, so
+ * we use the cursor offset provided by Ext.dd.DD. Another option that works only if
+ * you do not have constraints on the obj is to have the drag frame centered
+ * around the cursor. Set centerFrame to true for this effect.
+ * @property centerFrame
+ * @type boolean
+ */
+ centerFrame: false,
+
+ /**
+ * Creates the proxy element if it does not yet exist
+ * @method createFrame
+ */
+ createFrame: function() {
+ var self = this;
+ var body = document.body;
+
+ if (!body || !body.firstChild) {
+ setTimeout( function() { self.createFrame(); }, 50 );
+ return;
+ }
+
+ var div = this.getDragEl();
+
+ if (!div) {
+ div = document.createElement("div");
+ div.id = this.dragElId;
+ var s = div.style;
+
+ s.position = "absolute";
+ s.visibility = "hidden";
+ s.cursor = "move";
+ s.border = "2px solid #aaa";
+ s.zIndex = 999;
+
+ // appendChild can blow up IE if invoked prior to the window load event
+ // while rendering a table. It is possible there are other scenarios
+ // that would cause this to happen as well.
+ body.insertBefore(div, body.firstChild);
+ }
+ },
+
+ /**
+ * Initialization for the drag frame element. Must be called in the
+ * constructor of all subclasses
+ * @method initFrame
+ */
+ initFrame: function() {
+ this.createFrame();
+ },
+
+ applyConfig: function() {
+ Ext.dd.DDProxy.superclass.applyConfig.call(this);
+
+ this.resizeFrame = (this.config.resizeFrame !== false);
+ this.centerFrame = (this.config.centerFrame);
+ this.setDragElId(this.config.dragElId || Ext.dd.DDProxy.dragElId);
+ },
+
+ /**
+ * Resizes the drag frame to the dimensions of the clicked object, positions
+ * it over the object, and finally displays it
+ * @method showFrame
+ * @param {int} iPageX X click position
+ * @param {int} iPageY Y click position
+ * @private
+ */
+ showFrame: function(iPageX, iPageY) {
+ var el = this.getEl();
+ var dragEl = this.getDragEl();
+ var s = dragEl.style;
+
+ this._resizeProxy();
+
+ if (this.centerFrame) {
+ this.setDelta( Math.round(parseInt(s.width, 10)/2),
+ Math.round(parseInt(s.height, 10)/2) );
+ }
+
+ this.setDragElPos(iPageX, iPageY);
+
+ Ext.fly(dragEl).show();
+ },
+
+ /**
+ * The proxy is automatically resized to the dimensions of the linked
+ * element when a drag is initiated, unless resizeFrame is set to false
+ * @method _resizeProxy
+ * @private
+ */
+ _resizeProxy: function() {
+ if (this.resizeFrame) {
+ var el = this.getEl();
+ Ext.fly(this.getDragEl()).setSize(el.offsetWidth, el.offsetHeight);
+ }
+ },
+
+ // overrides Ext.dd.DragDrop
+ b4MouseDown: function(e) {
+ var x = e.getPageX();
+ var y = e.getPageY();
+ this.autoOffset(x, y);
+ this.setDragElPos(x, y);
+ },
+
+ // overrides Ext.dd.DragDrop
+ b4StartDrag: function(x, y) {
+ // show the drag frame
+ this.showFrame(x, y);
+ },
+
+ // overrides Ext.dd.DragDrop
+ b4EndDrag: function(e) {
+ Ext.fly(this.getDragEl()).hide();
+ },
+
+ // overrides Ext.dd.DragDrop
+ // By default we try to move the element to the last location of the frame.
+ // This is so that the default behavior mirrors that of Ext.dd.DD.
+ endDrag: function(e) {
+
+ var lel = this.getEl();
+ var del = this.getDragEl();
+
+ // Show the drag frame briefly so we can get its position
+ del.style.visibility = "";
+
+ this.beforeMove();
+ // Hide the linked element before the move to get around a Safari
+ // rendering bug.
+ lel.style.visibility = "hidden";
+ Ext.dd.DDM.moveToEl(lel, del);
+ del.style.visibility = "hidden";
+ lel.style.visibility = "";
+
+ this.afterDrag();
+ },
+
+ beforeMove : function(){
+
+ },
+
+ afterDrag : function(){
+
+ },
+
+ toString: function() {
+ return ("DDProxy " + this.id);
+ }
+
+});
+/**
+ * @class Ext.dd.DDTarget
+ * A DragDrop implementation that does not move, but can be a drop
+ * target. You would get the same result by simply omitting implementation
+ * for the event callbacks, but this way we reduce the processing cost of the
+ * event listener and the callbacks.
+ * @extends Ext.dd.DragDrop
+ * @constructor
+ * @param {String} id the id of the element that is a drop target
+ * @param {String} sGroup the group of related DragDrop objects
+ * @param {object} config an object containing configurable attributes
+ * Valid properties for DDTarget in addition to those in
+ * DragDrop:
+ * none
+ */
+Ext.dd.DDTarget = function(id, sGroup, config) {
+ if (id) {
+ this.initTarget(id, sGroup, config);
+ }
+};
+
+// Ext.dd.DDTarget.prototype = new Ext.dd.DragDrop();
+Ext.extend(Ext.dd.DDTarget, Ext.dd.DragDrop, {
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ getDragEl: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ isValidHandleChild: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ startDrag: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ endDrag: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onDrag: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onDragDrop: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onDragEnter: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onDragOut: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onDragOver: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onInvalidDrop: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onMouseDown: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ onMouseUp: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ setXConstraint: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ setYConstraint: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ resetConstraints: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ clearConstraints: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ clearTicks: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ setInitPosition: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ setDragElId: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ setHandleElId: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ setOuterHandleElId: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ addInvalidHandleClass: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ addInvalidHandleId: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ addInvalidHandleType: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ removeInvalidHandleClass: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ removeInvalidHandleId: Ext.emptyFn,
+ /**
+ * @hide
+ * Overridden and disabled. A DDTarget does not support being dragged.
+ * @method
+ */
+ removeInvalidHandleType: Ext.emptyFn,
+
+ toString: function() {
+ return ("DDTarget " + this.id);
+ }
+});/**
+ * @class Ext.dd.DragTracker
+ * @extends Ext.util.Observable
+ * A DragTracker listens for drag events on an Element and fires events at the start and end of the drag,
+ * as well as during the drag. This is useful for components such as {@link Ext.Slider}, where there is
+ * an element that can be dragged around to change the Slider's value.
+ * DragTracker provides a series of template methods that should be overridden to provide functionality
+ * in response to detected drag operations. These are onBeforeStart, onStart, onDrag and onEnd.
+ * See {@link Ext.Slider}'s initEvents function for an example implementation.
+ */
+Ext.dd.DragTracker = Ext.extend(Ext.util.Observable, {
+ /**
+ * @cfg {Boolean} active
+ * Defaults to <tt>false</tt>.
+ */
+ active: false,
+ /**
+ * @cfg {Number} tolerance
+ * Number of pixels the drag target must be moved before dragging is considered to have started. Defaults to <tt>5</tt>.
+ */
+ tolerance: 5,
+ /**
+ * @cfg {Boolean/Number} autoStart
+ * Defaults to <tt>false</tt>. Specify <tt>true</tt> to defer trigger start by 1000 ms.
+ * Specify a Number for the number of milliseconds to defer trigger start.
+ */
+ autoStart: false,
+
+ constructor : function(config){
+ Ext.apply(this, config);
+ this.addEvents(
+ /**
+ * @event mousedown
+ * @param {Object} this
+ * @param {Object} e event object
+ */
+ 'mousedown',
+ /**
+ * @event mouseup
+ * @param {Object} this
+ * @param {Object} e event object
+ */
+ 'mouseup',
+ /**
+ * @event mousemove
+ * @param {Object} this
+ * @param {Object} e event object
+ */
+ 'mousemove',
+ /**
+ * @event dragstart
+ * @param {Object} this
+ * @param {Object} startXY the page coordinates of the event
+ */
+ 'dragstart',
+ /**
+ * @event dragend
+ * @param {Object} this
+ * @param {Object} e event object
+ */
+ 'dragend',
+ /**
+ * @event drag
+ * @param {Object} this
+ * @param {Object} e event object
+ */
+ 'drag'
+ );
+
+ this.dragRegion = new Ext.lib.Region(0,0,0,0);
+
+ if(this.el){
+ this.initEl(this.el);
+ }
+ Ext.dd.DragTracker.superclass.constructor.call(this, config);
+ },
+
+ initEl: function(el){
+ this.el = Ext.get(el);
+ el.on('mousedown', this.onMouseDown, this,
+ this.delegate ? {delegate: this.delegate} : undefined);
+ },
+
+ destroy : function(){
+ this.el.un('mousedown', this.onMouseDown, this);
+ },
+
+ onMouseDown: function(e, target){
+ if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){
+ this.startXY = this.lastXY = e.getXY();
+ this.dragTarget = this.delegate ? target : this.el.dom;
+ if(this.preventDefault !== false){
+ e.preventDefault();
+ }
+ var doc = Ext.getDoc();
+ doc.on('mouseup', this.onMouseUp, this);
+ doc.on('mousemove', this.onMouseMove, this);
+ doc.on('selectstart', this.stopSelect, this);
+ if(this.autoStart){
+ this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this);
+ }
+ }
+ },
+
+ onMouseMove: function(e, target){
+ // HACK: IE hack to see if button was released outside of window. */
+ if(this.active && Ext.isIE && !e.browserEvent.button){
+ e.preventDefault();
+ this.onMouseUp(e);
+ return;
+ }
+
+ e.preventDefault();
+ var xy = e.getXY(), s = this.startXY;
+ this.lastXY = xy;
+ if(!this.active){
+ if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){
+ this.triggerStart();
+ }else{
+ return;
+ }
+ }
+ this.fireEvent('mousemove', this, e);
+ this.onDrag(e);
+ this.fireEvent('drag', this, e);
+ },
+
+ onMouseUp: function(e) {
+ var doc = Ext.getDoc();
+ doc.un('mousemove', this.onMouseMove, this);
+ doc.un('mouseup', this.onMouseUp, this);
+ doc.un('selectstart', this.stopSelect, this);
+ e.preventDefault();
+ this.clearStart();
+ var wasActive = this.active;
+ this.active = false;
+ delete this.elRegion;
+ this.fireEvent('mouseup', this, e);
+ if(wasActive){
+ this.onEnd(e);
+ this.fireEvent('dragend', this, e);
+ }
+ },
+
+ triggerStart: function(isTimer) {
+ this.clearStart();
+ this.active = true;
+ this.onStart(this.startXY);
+ this.fireEvent('dragstart', this, this.startXY);
+ },
+
+ clearStart : function() {
+ if(this.timer){
+ clearTimeout(this.timer);
+ delete this.timer;
+ }
+ },
+
+ stopSelect : function(e) {
+ e.stopEvent();
+ return false;
+ },
+
+ /**
+ * Template method which should be overridden by each DragTracker instance. Called when the user first clicks and
+ * holds the mouse button down. Return false to disallow the drag
+ * @param {Ext.EventObject} e The event object
+ */
+ onBeforeStart : function(e) {
+
+ },
+
+ /**
+ * Template method which should be overridden by each DragTracker instance. Called when a drag operation starts
+ * (e.g. the user has moved the tracked element beyond the specified tolerance)
+ * @param {Array} xy x and y co-ordinates of the original location of the tracked element
+ */
+ onStart : function(xy) {
+
+ },
+
+ /**
+ * Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected.
+ * @param {Ext.EventObject} e The event object
+ */
+ onDrag : function(e) {
+
+ },
+
+ /**
+ * Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed
+ * (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button)
+ * @param {Ext.EventObject} e The event object
+ */
+ onEnd : function(e) {
+
+ },
+
+ /**
+ * Returns the drag target
+ * @return {Ext.Element} The element currently being tracked
+ */
+ getDragTarget : function(){
+ return this.dragTarget;
+ },
+
+ getDragCt : function(){
+ return this.el;
+ },
+
+ getXY : function(constrain){
+ return constrain ?
+ this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY;
+ },
+
+ getOffset : function(constrain){
+ var xy = this.getXY(constrain);
+ var s = this.startXY;
+ return [s[0]-xy[0], s[1]-xy[1]];
+ },
+
+ constrainModes: {
+ 'point' : function(xy){
+
+ if(!this.elRegion){
+ this.elRegion = this.getDragCt().getRegion();
+ }
+
+ var dr = this.dragRegion;
+
+ dr.left = xy[0];
+ dr.top = xy[1];
+ dr.right = xy[0];
+ dr.bottom = xy[1];
+
+ dr.constrainTo(this.elRegion);
+
+ return [dr.left, dr.top];
+ }
+ }
+});/**
+ * @class Ext.dd.ScrollManager
+ * <p>Provides automatic scrolling of overflow regions in the page during drag operations.</p>
+ * <p>The ScrollManager configs will be used as the defaults for any scroll container registered with it,
+ * but you can also override most of the configs per scroll container by adding a
+ * <tt>ddScrollConfig</tt> object to the target element that contains these properties: {@link #hthresh},
+ * {@link #vthresh}, {@link #increment} and {@link #frequency}. Example usage:
+ * <pre><code>
+var el = Ext.get('scroll-ct');
+el.ddScrollConfig = {
+ vthresh: 50,
+ hthresh: -1,
+ frequency: 100,
+ increment: 200
+};
+Ext.dd.ScrollManager.register(el);
+</code></pre>
+ * <b>Note: This class uses "Point Mode" and is untested in "Intersect Mode".</b>
+ * @singleton
+ */
+Ext.dd.ScrollManager = function(){
+ var ddm = Ext.dd.DragDropMgr;
+ var els = {};
+ var dragEl = null;
+ var proc = {};
+
+ var onStop = function(e){
+ dragEl = null;
+ clearProc();
+ };
+
+ var triggerRefresh = function(){
+ if(ddm.dragCurrent){
+ ddm.refreshCache(ddm.dragCurrent.groups);
+ }
+ };
+
+ var doScroll = function(){
+ if(ddm.dragCurrent){
+ var dds = Ext.dd.ScrollManager;
+ var inc = proc.el.ddScrollConfig ?
+ proc.el.ddScrollConfig.increment : dds.increment;
+ if(!dds.animate){
+ if(proc.el.scroll(proc.dir, inc)){
+ triggerRefresh();
+ }
+ }else{
+ proc.el.scroll(proc.dir, inc, true, dds.animDuration, triggerRefresh);
+ }
+ }
+ };
+
+ var clearProc = function(){
+ if(proc.id){
+ clearInterval(proc.id);
+ }
+ proc.id = 0;
+ proc.el = null;
+ proc.dir = "";
+ };
+
+ var startProc = function(el, dir){
+ clearProc();
+ proc.el = el;
+ proc.dir = dir;
+ var freq = (el.ddScrollConfig && el.ddScrollConfig.frequency) ?
+ el.ddScrollConfig.frequency : Ext.dd.ScrollManager.frequency;
+ proc.id = setInterval(doScroll, freq);
+ };
+
+ var onFire = function(e, isDrop){
+ if(isDrop || !ddm.dragCurrent){ return; }
+ var dds = Ext.dd.ScrollManager;
+ if(!dragEl || dragEl != ddm.dragCurrent){
+ dragEl = ddm.dragCurrent;
+ // refresh regions on drag start
+ dds.refreshCache();
+ }
+
+ var xy = Ext.lib.Event.getXY(e);
+ var pt = new Ext.lib.Point(xy[0], xy[1]);
+ for(var id in els){
+ var el = els[id], r = el._region;
+ var c = el.ddScrollConfig ? el.ddScrollConfig : dds;
+ if(r && r.contains(pt) && el.isScrollable()){
+ if(r.bottom - pt.y <= c.vthresh){
+ if(proc.el != el){
+ startProc(el, "down");
+ }
+ return;
+ }else if(r.right - pt.x <= c.hthresh){
+ if(proc.el != el){
+ startProc(el, "left");
+ }
+ return;
+ }else if(pt.y - r.top <= c.vthresh){
+ if(proc.el != el){
+ startProc(el, "up");
+ }
+ return;
+ }else if(pt.x - r.left <= c.hthresh){
+ if(proc.el != el){
+ startProc(el, "right");
+ }
+ return;
+ }
+ }
+ }
+ clearProc();
+ };
+
+ ddm.fireEvents = ddm.fireEvents.createSequence(onFire, ddm);
+ ddm.stopDrag = ddm.stopDrag.createSequence(onStop, ddm);
+
+ return {
+ /**
+ * Registers new overflow element(s) to auto scroll
+ * @param {Mixed/Array} el The id of or the element to be scrolled or an array of either
+ */
+ register : function(el){
+ if(Ext.isArray(el)){
+ for(var i = 0, len = el.length; i < len; i++) {
+ this.register(el[i]);
+ }
+ }else{
+ el = Ext.get(el);
+ els[el.id] = el;
+ }
+ },
+
+ /**
+ * Unregisters overflow element(s) so they are no longer scrolled
+ * @param {Mixed/Array} el The id of or the element to be removed or an array of either
+ */
+ unregister : function(el){
+ if(Ext.isArray(el)){
+ for(var i = 0, len = el.length; i < len; i++) {
+ this.unregister(el[i]);
+ }
+ }else{
+ el = Ext.get(el);
+ delete els[el.id];
+ }
+ },
+
+ /**
+ * The number of pixels from the top or bottom edge of a container the pointer needs to be to
+ * trigger scrolling (defaults to 25)
+ * @type Number
+ */
+ vthresh : 25,
+ /**
+ * The number of pixels from the right or left edge of a container the pointer needs to be to
+ * trigger scrolling (defaults to 25)
+ * @type Number
+ */
+ hthresh : 25,
+
+ /**
+ * The number of pixels to scroll in each scroll increment (defaults to 50)
+ * @type Number
+ */
+ increment : 100,
+
+ /**
+ * The frequency of scrolls in milliseconds (defaults to 500)
+ * @type Number
+ */
+ frequency : 500,
+
+ /**
+ * True to animate the scroll (defaults to true)
+ * @type Boolean
+ */
+ animate: true,
+
+ /**
+ * The animation duration in seconds -
+ * MUST BE less than Ext.dd.ScrollManager.frequency! (defaults to .4)
+ * @type Number
+ */
+ animDuration: .4,
+
+ /**
+ * Manually trigger a cache refresh.
+ */
+ refreshCache : function(){
+ for(var id in els){
+ if(typeof els[id] == 'object'){ // for people extending the object prototype
+ els[id]._region = els[id].getRegion();
+ }
+ }
+ }
+ };
+}();/**
+ * @class Ext.dd.Registry
+ * Provides easy access to all drag drop components that are registered on a page. Items can be retrieved either
+ * directly by DOM node id, or by passing in the drag drop event that occurred and looking up the event target.
+ * @singleton
+ */
+Ext.dd.Registry = function(){
+ var elements = {};
+ var handles = {};
+ var autoIdSeed = 0;
+
+ var getId = function(el, autogen){
+ if(typeof el == "string"){
+ return el;
+ }
+ var id = el.id;
+ if(!id && autogen !== false){
+ id = "extdd-" + (++autoIdSeed);
+ el.id = id;
+ }
+ return id;
+ };
+
+ return {
+ /**
+ * Resgister a drag drop element
+ * @param {String/HTMLElement} element The id or DOM node to register
+ * @param {Object} data (optional) An custom data object that will be passed between the elements that are involved
+ * in drag drop operations. You can populate this object with any arbitrary properties that your own code
+ * knows how to interpret, plus there are some specific properties known to the Registry that should be
+ * populated in the data object (if applicable):
+ * <pre>
+Value Description<br />
+--------- ------------------------------------------<br />
+handles Array of DOM nodes that trigger dragging<br />
+ for the element being registered<br />
+isHandle True if the element passed in triggers<br />
+ dragging itself, else false
+</pre>
+ */
+ register : function(el, data){
+ data = data || {};
+ if(typeof el == "string"){
+ el = document.getElementById(el);
+ }
+ data.ddel = el;
+ elements[getId(el)] = data;
+ if(data.isHandle !== false){
+ handles[data.ddel.id] = data;
+ }
+ if(data.handles){
+ var hs = data.handles;
+ for(var i = 0, len = hs.length; i < len; i++){
+ handles[getId(hs[i])] = data;
+ }
+ }
+ },
+
+ /**
+ * Unregister a drag drop element
+ * @param {String/HTMLElement} element The id or DOM node to unregister
+ */
+ unregister : function(el){
+ var id = getId(el, false);
+ var data = elements[id];
+ if(data){
+ delete elements[id];
+ if(data.handles){
+ var hs = data.handles;
+ for(var i = 0, len = hs.length; i < len; i++){
+ delete handles[getId(hs[i], false)];
+ }
+ }
+ }
+ },
+
+ /**
+ * Returns the handle registered for a DOM Node by id
+ * @param {String/HTMLElement} id The DOM node or id to look up
+ * @return {Object} handle The custom handle data
+ */
+ getHandle : function(id){
+ if(typeof id != "string"){ // must be element?
+ id = id.id;
+ }
+ return handles[id];
+ },
+
+ /**
+ * Returns the handle that is registered for the DOM node that is the target of the event
+ * @param {Event} e The event
+ * @return {Object} handle The custom handle data
+ */
+ getHandleFromEvent : function(e){
+ var t = Ext.lib.Event.getTarget(e);
+ return t ? handles[t.id] : null;
+ },
+
+ /**
+ * Returns a custom data object that is registered for a DOM node by id
+ * @param {String/HTMLElement} id The DOM node or id to look up
+ * @return {Object} data The custom data
+ */
+ getTarget : function(id){
+ if(typeof id != "string"){ // must be element?
+ id = id.id;
+ }
+ return elements[id];
+ },
+
+ /**
+ * Returns a custom data object that is registered for the DOM node that is the target of the event
+ * @param {Event} e The event
+ * @return {Object} data The custom data
+ */
+ getTargetFromEvent : function(e){
+ var t = Ext.lib.Event.getTarget(e);
+ return t ? elements[t.id] || handles[t.id] : null;
+ }
+ };
+}();/**
+ * @class Ext.dd.StatusProxy
+ * A specialized drag proxy that supports a drop status icon, {@link Ext.Layer} styles and auto-repair. This is the
+ * default drag proxy used by all Ext.dd components.
+ * @constructor
+ * @param {Object} config
+ */
+Ext.dd.StatusProxy = function(config){
+ Ext.apply(this, config);
+ this.id = this.id || Ext.id();
+ this.el = new Ext.Layer({
+ dh: {
+ id: this.id, tag: "div", cls: "x-dd-drag-proxy "+this.dropNotAllowed, children: [
+ {tag: "div", cls: "x-dd-drop-icon"},
+ {tag: "div", cls: "x-dd-drag-ghost"}
+ ]
+ },
+ shadow: !config || config.shadow !== false
+ });
+ this.ghost = Ext.get(this.el.dom.childNodes[1]);
+ this.dropStatus = this.dropNotAllowed;
+};
+
+Ext.dd.StatusProxy.prototype = {
+ /**
+ * @cfg {String} dropAllowed
+ * The CSS class to apply to the status element when drop is allowed (defaults to "x-dd-drop-ok").
+ */
+ dropAllowed : "x-dd-drop-ok",
+ /**
+ * @cfg {String} dropNotAllowed
+ * The CSS class to apply to the status element when drop is not allowed (defaults to "x-dd-drop-nodrop").
+ */
+ dropNotAllowed : "x-dd-drop-nodrop",
+
+ /**
+ * Updates the proxy's visual element to indicate the status of whether or not drop is allowed
+ * over the current target element.
+ * @param {String} cssClass The css class for the new drop status indicator image
+ */
+ setStatus : function(cssClass){
+ cssClass = cssClass || this.dropNotAllowed;
+ if(this.dropStatus != cssClass){
+ this.el.replaceClass(this.dropStatus, cssClass);
+ this.dropStatus = cssClass;
+ }
+ },
+
+ /**
+ * Resets the status indicator to the default dropNotAllowed value
+ * @param {Boolean} clearGhost True to also remove all content from the ghost, false to preserve it
+ */
+ reset : function(clearGhost){
+ this.el.dom.className = "x-dd-drag-proxy " + this.dropNotAllowed;
+ this.dropStatus = this.dropNotAllowed;
+ if(clearGhost){
+ this.ghost.update("");
+ }
+ },
+
+ /**
+ * Updates the contents of the ghost element
+ * @param {String/HTMLElement} html The html that will replace the current innerHTML of the ghost element, or a
+ * DOM node to append as the child of the ghost element (in which case the innerHTML will be cleared first).
+ */
+ update : function(html){
+ if(typeof html == "string"){
+ this.ghost.update(html);
+ }else{
+ this.ghost.update("");
+ html.style.margin = "0";
+ this.ghost.dom.appendChild(html);
+ }
+ var el = this.ghost.dom.firstChild;
+ if(el){
+ Ext.fly(el).setStyle('float', 'none');
+ }
+ },
+
+ /**
+ * Returns the underlying proxy {@link Ext.Layer}
+ * @return {Ext.Layer} el
+ */
+ getEl : function(){
+ return this.el;
+ },
+
+ /**
+ * Returns the ghost element
+ * @return {Ext.Element} el
+ */
+ getGhost : function(){
+ return this.ghost;
+ },
+
+ /**
+ * Hides the proxy
+ * @param {Boolean} clear True to reset the status and clear the ghost contents, false to preserve them
+ */
+ hide : function(clear){
+ this.el.hide();
+ if(clear){
+ this.reset(true);
+ }
+ },
+
+ /**
+ * Stops the repair animation if it's currently running
+ */
+ stop : function(){
+ if(this.anim && this.anim.isAnimated && this.anim.isAnimated()){
+ this.anim.stop();
+ }
+ },
+
+ /**
+ * Displays this proxy
+ */
+ show : function(){
+ this.el.show();
+ },
+
+ /**
+ * Force the Layer to sync its shadow and shim positions to the element
+ */
+ sync : function(){
+ this.el.sync();
+ },
+
+ /**
+ * Causes the proxy to return to its position of origin via an animation. Should be called after an
+ * invalid drop operation by the item being dragged.
+ * @param {Array} xy The XY position of the element ([x, y])
+ * @param {Function} callback The function to call after the repair is complete.
+ * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
+ */
+ repair : function(xy, callback, scope){
+ this.callback = callback;
+ this.scope = scope;
+ if(xy && this.animRepair !== false){
+ this.el.addClass("x-dd-drag-repair");
+ this.el.hideUnders(true);
+ this.anim = this.el.shift({
+ duration: this.repairDuration || .5,
+ easing: 'easeOut',
+ xy: xy,
+ stopFx: true,
+ callback: this.afterRepair,
+ scope: this
+ });
+ }else{
+ this.afterRepair();
+ }
+ },
+
+ // private
+ afterRepair : function(){
+ this.hide(true);
+ if(typeof this.callback == "function"){
+ this.callback.call(this.scope || this);
+ }
+ this.callback = null;
+ this.scope = null;
+ },
+
+ destroy: function(){
+ Ext.destroy(this.ghost, this.el);
+ }
+};/**
+ * @class Ext.dd.DragSource
+ * @extends Ext.dd.DDProxy
+ * A simple class that provides the basic implementation needed to make any element draggable.
+ * @constructor
+ * @param {Mixed} el The container element
+ * @param {Object} config
+ */
+Ext.dd.DragSource = function(el, config){
+ this.el = Ext.get(el);
+ if(!this.dragData){
+ this.dragData = {};
+ }
+
+ Ext.apply(this, config);
+
+ if(!this.proxy){
+ this.proxy = new Ext.dd.StatusProxy();
+ }
+ Ext.dd.DragSource.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
+ {dragElId : this.proxy.id, resizeFrame: false, isTarget: false, scroll: this.scroll === true});
+
+ this.dragging = false;
+};
+
+Ext.extend(Ext.dd.DragSource, Ext.dd.DDProxy, {
+ /**
+ * @cfg {String} ddGroup
+ * A named drag drop group to which this object belongs. If a group is specified, then this object will only
+ * interact with other drag drop objects in the same group (defaults to undefined).
+ */
+ /**
+ * @cfg {String} dropAllowed
+ * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
+ */
+ dropAllowed : "x-dd-drop-ok",
+ /**
+ * @cfg {String} dropNotAllowed
+ * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
+ */
+ dropNotAllowed : "x-dd-drop-nodrop",
+
+ /**
+ * Returns the data object associated with this drag source
+ * @return {Object} data An object containing arbitrary data
+ */
+ getDragData : function(e){
+ return this.dragData;
+ },
+
+ // private
+ onDragEnter : function(e, id){
+ var target = Ext.dd.DragDropMgr.getDDById(id);
+ this.cachedTarget = target;
+ if(this.beforeDragEnter(target, e, id) !== false){
+ if(target.isNotifyTarget){
+ var status = target.notifyEnter(this, e, this.dragData);
+ this.proxy.setStatus(status);
+ }else{
+ this.proxy.setStatus(this.dropAllowed);
+ }
+
+ if(this.afterDragEnter){
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * when the dragged item enters the drop target by providing an implementation.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @method afterDragEnter
+ */
+ this.afterDragEnter(target, e, id);
+ }
+ }
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * before the dragged item enters the drop target and optionally cancel the onDragEnter.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @return {Boolean} isValid True if the drag event is valid, else false to cancel
+ */
+ beforeDragEnter : function(target, e, id){
+ return true;
+ },
+
+ // private
+ alignElWithMouse: function() {
+ Ext.dd.DragSource.superclass.alignElWithMouse.apply(this, arguments);
+ this.proxy.sync();
+ },
+
+ // private
+ onDragOver : function(e, id){
+ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
+ if(this.beforeDragOver(target, e, id) !== false){
+ if(target.isNotifyTarget){
+ var status = target.notifyOver(this, e, this.dragData);
+ this.proxy.setStatus(status);
+ }
+
+ if(this.afterDragOver){
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * while the dragged item is over the drop target by providing an implementation.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @method afterDragOver
+ */
+ this.afterDragOver(target, e, id);
+ }
+ }
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * while the dragged item is over the drop target and optionally cancel the onDragOver.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @return {Boolean} isValid True if the drag event is valid, else false to cancel
+ */
+ beforeDragOver : function(target, e, id){
+ return true;
+ },
+
+ // private
+ onDragOut : function(e, id){
+ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
+ if(this.beforeDragOut(target, e, id) !== false){
+ if(target.isNotifyTarget){
+ target.notifyOut(this, e, this.dragData);
+ }
+ this.proxy.reset();
+ if(this.afterDragOut){
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * after the dragged item is dragged out of the target without dropping.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @method afterDragOut
+ */
+ this.afterDragOut(target, e, id);
+ }
+ }
+ this.cachedTarget = null;
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action before the dragged
+ * item is dragged out of the target without dropping, and optionally cancel the onDragOut.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @return {Boolean} isValid True if the drag event is valid, else false to cancel
+ */
+ beforeDragOut : function(target, e, id){
+ return true;
+ },
+
+ // private
+ onDragDrop : function(e, id){
+ var target = this.cachedTarget || Ext.dd.DragDropMgr.getDDById(id);
+ if(this.beforeDragDrop(target, e, id) !== false){
+ if(target.isNotifyTarget){
+ if(target.notifyDrop(this, e, this.dragData)){ // valid drop?
+ this.onValidDrop(target, e, id);
+ }else{
+ this.onInvalidDrop(target, e, id);
+ }
+ }else{
+ this.onValidDrop(target, e, id);
+ }
+
+ if(this.afterDragDrop){
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * after a valid drag drop has occurred by providing an implementation.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dropped element
+ * @method afterDragDrop
+ */
+ this.afterDragDrop(target, e, id);
+ }
+ }
+ delete this.cachedTarget;
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action before the dragged
+ * item is dropped onto the target and optionally cancel the onDragDrop.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @return {Boolean} isValid True if the drag drop event is valid, else false to cancel
+ */
+ beforeDragDrop : function(target, e, id){
+ return true;
+ },
+
+ // private
+ onValidDrop : function(target, e, id){
+ this.hideProxy();
+ if(this.afterValidDrop){
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * after a valid drop has occurred by providing an implementation.
+ * @param {Object} target The target DD
+ * @param {Event} e The event object
+ * @param {String} id The id of the dropped element
+ * @method afterInvalidDrop
+ */
+ this.afterValidDrop(target, e, id);
+ }
+ },
+
+ // private
+ getRepairXY : function(e, data){
+ return this.el.getXY();
+ },
+
+ // private
+ onInvalidDrop : function(target, e, id){
+ this.beforeInvalidDrop(target, e, id);
+ if(this.cachedTarget){
+ if(this.cachedTarget.isNotifyTarget){
+ this.cachedTarget.notifyOut(this, e, this.dragData);
+ }
+ this.cacheTarget = null;
+ }
+ this.proxy.repair(this.getRepairXY(e, this.dragData), this.afterRepair, this);
+
+ if(this.afterInvalidDrop){
+ /**
+ * An empty function by default, but provided so that you can perform a custom action
+ * after an invalid drop has occurred by providing an implementation.
+ * @param {Event} e The event object
+ * @param {String} id The id of the dropped element
+ * @method afterInvalidDrop
+ */
+ this.afterInvalidDrop(e, id);
+ }
+ },
+
+ // private
+ afterRepair : function(){
+ if(Ext.enableFx){
+ this.el.highlight(this.hlColor || "c3daf9");
+ }
+ this.dragging = false;
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action after an invalid
+ * drop has occurred.
+ * @param {Ext.dd.DragDrop} target The drop target
+ * @param {Event} e The event object
+ * @param {String} id The id of the dragged element
+ * @return {Boolean} isValid True if the invalid drop should proceed, else false to cancel
+ */
+ beforeInvalidDrop : function(target, e, id){
+ return true;
+ },
+
+ // private
+ handleMouseDown : function(e){
+ if(this.dragging) {
+ return;
+ }
+ var data = this.getDragData(e);
+ if(data && this.onBeforeDrag(data, e) !== false){
+ this.dragData = data;
+ this.proxy.stop();
+ Ext.dd.DragSource.superclass.handleMouseDown.apply(this, arguments);
+ }
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action before the initial
+ * drag event begins and optionally cancel it.
+ * @param {Object} data An object containing arbitrary data to be shared with drop targets
+ * @param {Event} e The event object
+ * @return {Boolean} isValid True if the drag event is valid, else false to cancel
+ */
+ onBeforeDrag : function(data, e){
+ return true;
+ },
+
+ /**
+ * An empty function by default, but provided so that you can perform a custom action once the initial
+ * drag event has begun. The drag cannot be canceled from this function.
+ * @param {Number} x The x position of the click on the dragged object
+ * @param {Number} y The y position of the click on the dragged object
+ */
+ onStartDrag : Ext.emptyFn,
+
+ // private override
+ startDrag : function(x, y){
+ this.proxy.reset();
+ this.dragging = true;
+ this.proxy.update("");
+ this.onInitDrag(x, y);
+ this.proxy.show();
+ },
+
+ // private
+ onInitDrag : function(x, y){
+ var clone = this.el.dom.cloneNode(true);
+ clone.id = Ext.id(); // prevent duplicate ids
+ this.proxy.update(clone);
+ this.onStartDrag(x, y);
+ return true;
+ },
+
+ /**
+ * Returns the drag source's underlying {@link Ext.dd.StatusProxy}
+ * @return {Ext.dd.StatusProxy} proxy The StatusProxy
+ */
+ getProxy : function(){
+ return this.proxy;
+ },
+
+ /**
+ * Hides the drag source's {@link Ext.dd.StatusProxy}
+ */
+ hideProxy : function(){
+ this.proxy.hide();
+ this.proxy.reset(true);
+ this.dragging = false;
+ },
+
+ // private
+ triggerCacheRefresh : function(){
+ Ext.dd.DDM.refreshCache(this.groups);
+ },
+
+ // private - override to prevent hiding
+ b4EndDrag: function(e) {
+ },
+
+ // private - override to prevent moving
+ endDrag : function(e){
+ this.onEndDrag(this.dragData, e);
+ },
+
+ // private
+ onEndDrag : function(data, e){
+ },
+
+ // private - pin to cursor
+ autoOffset : function(x, y) {
+ this.setDelta(-12, -20);
+ },
+
+ destroy: function(){
+ Ext.dd.DragSource.superclass.destroy.call(this);
+ Ext.destroy(this.proxy);
+ }
+});/**
+ * @class Ext.dd.DropTarget
+ * @extends Ext.dd.DDTarget
+ * A simple class that provides the basic implementation needed to make any element a drop target that can have
+ * draggable items dropped onto it. The drop has no effect until an implementation of notifyDrop is provided.
+ * @constructor
+ * @param {Mixed} el The container element
+ * @param {Object} config
+ */
+Ext.dd.DropTarget = function(el, config){
+ this.el = Ext.get(el);
+
+ Ext.apply(this, config);
+
+ if(this.containerScroll){
+ Ext.dd.ScrollManager.register(this.el);
+ }
+
+ Ext.dd.DropTarget.superclass.constructor.call(this, this.el.dom, this.ddGroup || this.group,
+ {isTarget: true});
+
+};
+
+Ext.extend(Ext.dd.DropTarget, Ext.dd.DDTarget, {
+ /**
+ * @cfg {String} ddGroup
+ * A named drag drop group to which this object belongs. If a group is specified, then this object will only
+ * interact with other drag drop objects in the same group (defaults to undefined).
+ */
+ /**
+ * @cfg {String} overClass
+ * The CSS class applied to the drop target element while the drag source is over it (defaults to "").
+ */
+ /**
+ * @cfg {String} dropAllowed
+ * The CSS class returned to the drag source when drop is allowed (defaults to "x-dd-drop-ok").
+ */
+ dropAllowed : "x-dd-drop-ok",
+ /**
+ * @cfg {String} dropNotAllowed
+ * The CSS class returned to the drag source when drop is not allowed (defaults to "x-dd-drop-nodrop").
+ */
+ dropNotAllowed : "x-dd-drop-nodrop",
+
+ // private
+ isTarget : true,
+
+ // private
+ isNotifyTarget : true,
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the source is now over the
+ * target. This default implementation adds the CSS class specified by overClass (if any) to the drop element
+ * and returns the dropAllowed config value. This method should be overridden if drop validation is required.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {String} status The CSS class that communicates the drop status back to the source so that the
+ * underlying {@link Ext.dd.StatusProxy} can be updated
+ */
+ notifyEnter : function(dd, e, data){
+ if(this.overClass){
+ this.el.addClass(this.overClass);
+ }
+ return this.dropAllowed;
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the target.
+ * This method will be called on every mouse movement while the drag source is over the drop target.
+ * This default implementation simply returns the dropAllowed config value.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {String} status The CSS class that communicates the drop status back to the source so that the
+ * underlying {@link Ext.dd.StatusProxy} can be updated
+ */
+ notifyOver : function(dd, e, data){
+ return this.dropAllowed;
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the source has been dragged
+ * out of the target without dropping. This default implementation simply removes the CSS class specified by
+ * overClass (if any) from the drop element.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ */
+ notifyOut : function(dd, e, data){
+ if(this.overClass){
+ this.el.removeClass(this.overClass);
+ }
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls once to notify this drop target that the dragged item has
+ * been dropped on it. This method has no default implementation and returns false, so you must provide an
+ * implementation that does something to process the drop event and returns true so that the drag source's
+ * repair action does not run.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {Boolean} True if the drop was valid, else false
+ */
+ notifyDrop : function(dd, e, data){
+ return false;
+ }
+});/**
+ * @class Ext.dd.DragZone
+ * @extends Ext.dd.DragSource
+ * <p>This class provides a container DD instance that allows dragging of multiple child source nodes.</p>
+ * <p>This class does not move the drag target nodes, but a proxy element which may contain
+ * any DOM structure you wish. The DOM element to show in the proxy is provided by either a
+ * provided implementation of {@link #getDragData}, or by registered draggables registered with {@link Ext.dd.Registry}</p>
+ * <p>If you wish to provide draggability for an arbitrary number of DOM nodes, each of which represent some
+ * application object (For example nodes in a {@link Ext.DataView DataView}) then use of this class
+ * is the most efficient way to "activate" those nodes.</p>
+ * <p>By default, this class requires that draggable child nodes are registered with {@link Ext.dd.Registry}.
+ * However a simpler way to allow a DragZone to manage any number of draggable elements is to configure
+ * the DragZone with an implementation of the {@link #getDragData} method which interrogates the passed
+ * mouse event to see if it has taken place within an element, or class of elements. This is easily done
+ * by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
+ * {@link Ext.DomQuery} selector. For example, to make the nodes of a DataView draggable, use the following
+ * technique. Knowledge of the use of the DataView is required:</p><pre><code>
+myDataView.on('render', function(v) {
+ myDataView.dragZone = new Ext.dd.DragZone(v.getEl(), {
+
+// On receipt of a mousedown event, see if it is within a DataView node.
+// Return a drag data object if so.
+ getDragData: function(e) {
+
+// Use the DataView's own itemSelector (a mandatory property) to
+// test if the mousedown is within one of the DataView's nodes.
+ var sourceEl = e.getTarget(v.itemSelector, 10);
+
+// If the mousedown is within a DataView node, clone the node to produce
+// a ddel element for use by the drag proxy. Also add application data
+// to the returned data object.
+ if (sourceEl) {
+ d = sourceEl.cloneNode(true);
+ d.id = Ext.id();
+ return {
+ ddel: d,
+ sourceEl: sourceEl,
+ repairXY: Ext.fly(sourceEl).getXY(),
+ sourceStore: v.store,
+ draggedRecord: v.{@link Ext.DataView#getRecord getRecord}(sourceEl)
+ }
+ }
+ },
+
+// Provide coordinates for the proxy to slide back to on failed drag.
+// This is the original XY coordinates of the draggable element captured
+// in the getDragData method.
+ getRepairXY: function() {
+ return this.dragData.repairXY;
+ }
+ });
+});</code></pre>
+ * See the {@link Ext.dd.DropZone DropZone} documentation for details about building a DropZone which
+ * cooperates with this DragZone.
+ * @constructor
+ * @param {Mixed} el The container element
+ * @param {Object} config
+ */
+Ext.dd.DragZone = function(el, config){
+ Ext.dd.DragZone.superclass.constructor.call(this, el, config);
+ if(this.containerScroll){
+ Ext.dd.ScrollManager.register(this.el);
+ }
+};
+
+Ext.extend(Ext.dd.DragZone, Ext.dd.DragSource, {
+ /**
+ * This property contains the data representing the dragged object. This data is set up by the implementation
+ * of the {@link #getDragData} method. It must contain a <tt>ddel</tt> property, but can contain
+ * any other data according to the application's needs.
+ * @type Object
+ * @property dragData
+ */
+ /**
+ * @cfg {Boolean} containerScroll True to register this container with the Scrollmanager
+ * for auto scrolling during drag operations.
+ */
+ /**
+ * @cfg {String} hlColor The color to use when visually highlighting the drag source in the afterRepair
+ * method after a failed drop (defaults to "c3daf9" - light blue)
+ */
+
+ /**
+ * Called when a mousedown occurs in this container. Looks in {@link Ext.dd.Registry}
+ * for a valid target to drag based on the mouse down. Override this method
+ * to provide your own lookup logic (e.g. finding a child by class name). Make sure your returned
+ * object has a "ddel" attribute (with an HTML Element) for other functions to work.
+ * @param {EventObject} e The mouse down event
+ * @return {Object} The dragData
+ */
+ getDragData : function(e){
+ return Ext.dd.Registry.getHandleFromEvent(e);
+ },
+
+ /**
+ * Called once drag threshold has been reached to initialize the proxy element. By default, it clones the
+ * this.dragData.ddel
+ * @param {Number} x The x position of the click on the dragged object
+ * @param {Number} y The y position of the click on the dragged object
+ * @return {Boolean} true to continue the drag, false to cancel
+ */
+ onInitDrag : function(x, y){
+ this.proxy.update(this.dragData.ddel.cloneNode(true));
+ this.onStartDrag(x, y);
+ return true;
+ },
+
+ /**
+ * Called after a repair of an invalid drop. By default, highlights this.dragData.ddel
+ */
+ afterRepair : function(){
+ if(Ext.enableFx){
+ Ext.Element.fly(this.dragData.ddel).highlight(this.hlColor || "c3daf9");
+ }
+ this.dragging = false;
+ },
+
+ /**
+ * Called before a repair of an invalid drop to get the XY to animate to. By default returns
+ * the XY of this.dragData.ddel
+ * @param {EventObject} e The mouse up event
+ * @return {Array} The xy location (e.g. [100, 200])
+ */
+ getRepairXY : function(e){
+ return Ext.Element.fly(this.dragData.ddel).getXY();
+ }
+});/**
+ * @class Ext.dd.DropZone
+ * @extends Ext.dd.DropTarget
+ * <p>This class provides a container DD instance that allows dropping on multiple child target nodes.</p>
+ * <p>By default, this class requires that child nodes accepting drop are registered with {@link Ext.dd.Registry}.
+ * However a simpler way to allow a DropZone to manage any number of target elements is to configure the
+ * DropZone with an implementation of {@link #getTargetFromEvent} which interrogates the passed
+ * mouse event to see if it has taken place within an element, or class of elements. This is easily done
+ * by using the event's {@link Ext.EventObject#getTarget getTarget} method to identify a node based on a
+ * {@link Ext.DomQuery} selector.</p>
+ * <p>Once the DropZone has detected through calling getTargetFromEvent, that the mouse is over
+ * a drop target, that target is passed as the first parameter to {@link #onNodeEnter}, {@link #onNodeOver},
+ * {@link #onNodeOut}, {@link #onNodeDrop}. You may configure the instance of DropZone with implementations
+ * of these methods to provide application-specific behaviour for these events to update both
+ * application state, and UI state.</p>
+ * <p>For example to make a GridPanel a cooperating target with the example illustrated in
+ * {@link Ext.dd.DragZone DragZone}, the following technique might be used:</p><pre><code>
+myGridPanel.on('render', function() {
+ myGridPanel.dropZone = new Ext.dd.DropZone(myGridPanel.getView().scroller, {
+
+// If the mouse is over a grid row, return that node. This is
+// provided as the "target" parameter in all "onNodeXXXX" node event handling functions
+ getTargetFromEvent: function(e) {
+ return e.getTarget(myGridPanel.getView().rowSelector);
+ },
+
+// On entry into a target node, highlight that node.
+ onNodeEnter : function(target, dd, e, data){
+ Ext.fly(target).addClass('my-row-highlight-class');
+ },
+
+// On exit from a target node, unhighlight that node.
+ onNodeOut : function(target, dd, e, data){
+ Ext.fly(target).removeClass('my-row-highlight-class');
+ },
+
+// While over a target node, return the default drop allowed class which
+// places a "tick" icon into the drag proxy.
+ onNodeOver : function(target, dd, e, data){
+ return Ext.dd.DropZone.prototype.dropAllowed;
+ },
+
+// On node drop we can interrogate the target to find the underlying
+// application object that is the real target of the dragged data.
+// In this case, it is a Record in the GridPanel's Store.
+// We can use the data set up by the DragZone's getDragData method to read
+// any data we decided to attach in the DragZone's getDragData method.
+ onNodeDrop : function(target, dd, e, data){
+ var rowIndex = myGridPanel.getView().findRowIndex(target);
+ var r = myGridPanel.getStore().getAt(rowIndex);
+ Ext.Msg.alert('Drop gesture', 'Dropped Record id ' + data.draggedRecord.id +
+ ' on Record id ' + r.id);
+ return true;
+ }
+ });
+}
+</code></pre>
+ * See the {@link Ext.dd.DragZone DragZone} documentation for details about building a DragZone which
+ * cooperates with this DropZone.
+ * @constructor
+ * @param {Mixed} el The container element
+ * @param {Object} config
+ */
+Ext.dd.DropZone = function(el, config){
+ Ext.dd.DropZone.superclass.constructor.call(this, el, config);
+};
+
+Ext.extend(Ext.dd.DropZone, Ext.dd.DropTarget, {
+ /**
+ * Returns a custom data object associated with the DOM node that is the target of the event. By default
+ * this looks up the event target in the {@link Ext.dd.Registry}, although you can override this method to
+ * provide your own custom lookup.
+ * @param {Event} e The event
+ * @return {Object} data The custom data
+ */
+ getTargetFromEvent : function(e){
+ return Ext.dd.Registry.getTargetFromEvent(e);
+ },
+
+ /**
+ * Called when the DropZone determines that a {@link Ext.dd.DragSource} has entered a drop node
+ * that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
+ * This method has no default implementation and should be overridden to provide
+ * node-specific processing if necessary.
+ * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
+ * {@link #getTargetFromEvent} for this node)
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ */
+ onNodeEnter : function(n, dd, e, data){
+
+ },
+
+ /**
+ * Called while the DropZone determines that a {@link Ext.dd.DragSource} is over a drop node
+ * that has either been registered or detected by a configured implementation of {@link #getTargetFromEvent}.
+ * The default implementation returns this.dropNotAllowed, so it should be
+ * overridden to provide the proper feedback.
+ * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
+ * {@link #getTargetFromEvent} for this node)
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {String} status The CSS class that communicates the drop status back to the source so that the
+ * underlying {@link Ext.dd.StatusProxy} can be updated
+ */
+ onNodeOver : function(n, dd, e, data){
+ return this.dropAllowed;
+ },
+
+ /**
+ * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dragged out of
+ * the drop node without dropping. This method has no default implementation and should be overridden to provide
+ * node-specific processing if necessary.
+ * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
+ * {@link #getTargetFromEvent} for this node)
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ */
+ onNodeOut : function(n, dd, e, data){
+
+ },
+
+ /**
+ * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped onto
+ * the drop node. The default implementation returns false, so it should be overridden to provide the
+ * appropriate processing of the drop event and return true so that the drag source's repair action does not run.
+ * @param {Object} nodeData The custom data associated with the drop node (this is the same value returned from
+ * {@link #getTargetFromEvent} for this node)
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {Boolean} True if the drop was valid, else false
+ */
+ onNodeDrop : function(n, dd, e, data){
+ return false;
+ },
+
+ /**
+ * Called while the DropZone determines that a {@link Ext.dd.DragSource} is being dragged over it,
+ * but not over any of its registered drop nodes. The default implementation returns this.dropNotAllowed, so
+ * it should be overridden to provide the proper feedback if necessary.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {String} status The CSS class that communicates the drop status back to the source so that the
+ * underlying {@link Ext.dd.StatusProxy} can be updated
+ */
+ onContainerOver : function(dd, e, data){
+ return this.dropNotAllowed;
+ },
+
+ /**
+ * Called when the DropZone determines that a {@link Ext.dd.DragSource} has been dropped on it,
+ * but not on any of its registered drop nodes. The default implementation returns false, so it should be
+ * overridden to provide the appropriate processing of the drop event if you need the drop zone itself to
+ * be able to accept drops. It should return true when valid so that the drag source's repair action does not run.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {Boolean} True if the drop was valid, else false
+ */
+ onContainerDrop : function(dd, e, data){
+ return false;
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source is now over
+ * the zone. The default implementation returns this.dropNotAllowed and expects that only registered drop
+ * nodes can process drag drop operations, so if you need the drop zone itself to be able to process drops
+ * you should override this method and provide a custom implementation.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {String} status The CSS class that communicates the drop status back to the source so that the
+ * underlying {@link Ext.dd.StatusProxy} can be updated
+ */
+ notifyEnter : function(dd, e, data){
+ return this.dropNotAllowed;
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls continuously while it is being dragged over the drop zone.
+ * This method will be called on every mouse movement while the drag source is over the drop zone.
+ * It will call {@link #onNodeOver} while the drag source is over a registered node, and will also automatically
+ * delegate to the appropriate node-specific methods as necessary when the drag source enters and exits
+ * registered nodes ({@link #onNodeEnter}, {@link #onNodeOut}). If the drag source is not currently over a
+ * registered node, it will call {@link #onContainerOver}.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {String} status The CSS class that communicates the drop status back to the source so that the
+ * underlying {@link Ext.dd.StatusProxy} can be updated
+ */
+ notifyOver : function(dd, e, data){
+ var n = this.getTargetFromEvent(e);
+ if(!n){ // not over valid drop target
+ if(this.lastOverNode){
+ this.onNodeOut(this.lastOverNode, dd, e, data);
+ this.lastOverNode = null;
+ }
+ return this.onContainerOver(dd, e, data);
+ }
+ if(this.lastOverNode != n){
+ if(this.lastOverNode){
+ this.onNodeOut(this.lastOverNode, dd, e, data);
+ }
+ this.onNodeEnter(n, dd, e, data);
+ this.lastOverNode = n;
+ }
+ return this.onNodeOver(n, dd, e, data);
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the source has been dragged
+ * out of the zone without dropping. If the drag source is currently over a registered node, the notification
+ * will be delegated to {@link #onNodeOut} for node-specific handling, otherwise it will be ignored.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop target
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag zone
+ */
+ notifyOut : function(dd, e, data){
+ if(this.lastOverNode){
+ this.onNodeOut(this.lastOverNode, dd, e, data);
+ this.lastOverNode = null;
+ }
+ },
+
+ /**
+ * The function a {@link Ext.dd.DragSource} calls once to notify this drop zone that the dragged item has
+ * been dropped on it. The drag zone will look up the target node based on the event passed in, and if there
+ * is a node registered for that event, it will delegate to {@link #onNodeDrop} for node-specific handling,
+ * otherwise it will call {@link #onContainerDrop}.
+ * @param {Ext.dd.DragSource} source The drag source that was dragged over this drop zone
+ * @param {Event} e The event
+ * @param {Object} data An object containing arbitrary data supplied by the drag source
+ * @return {Boolean} True if the drop was valid, else false
+ */
+ notifyDrop : function(dd, e, data){
+ if(this.lastOverNode){
+ this.onNodeOut(this.lastOverNode, dd, e, data);
+ this.lastOverNode = null;
+ }
+ var n = this.getTargetFromEvent(e);
+ return n ?
+ this.onNodeDrop(n, dd, e, data) :
+ this.onContainerDrop(dd, e, data);
+ },
+
+ // private
+ triggerCacheRefresh : function(){
+ Ext.dd.DDM.refreshCache(this.groups);
+ }
+});/**
+ * @class Ext.Element
+ */
+Ext.Element.addMethods({
+ /**
+ * Initializes a {@link Ext.dd.DD} drag drop object for this element.
+ * @param {String} group The group the DD object is member of
+ * @param {Object} config The DD config object
+ * @param {Object} overrides An object containing methods to override/implement on the DD object
+ * @return {Ext.dd.DD} The DD object
+ */
+ initDD : function(group, config, overrides){
+ var dd = new Ext.dd.DD(Ext.id(this.dom), group, config);
+ return Ext.apply(dd, overrides);
+ },
+
+ /**
+ * Initializes a {@link Ext.dd.DDProxy} object for this element.
+ * @param {String} group The group the DDProxy object is member of
+ * @param {Object} config The DDProxy config object
+ * @param {Object} overrides An object containing methods to override/implement on the DDProxy object
+ * @return {Ext.dd.DDProxy} The DDProxy object
+ */
+ initDDProxy : function(group, config, overrides){
+ var dd = new Ext.dd.DDProxy(Ext.id(this.dom), group, config);
+ return Ext.apply(dd, overrides);
+ },
+
+ /**
+ * Initializes a {@link Ext.dd.DDTarget} object for this element.
+ * @param {String} group The group the DDTarget object is member of
+ * @param {Object} config The DDTarget config object
+ * @param {Object} overrides An object containing methods to override/implement on the DDTarget object
+ * @return {Ext.dd.DDTarget} The DDTarget object
+ */
+ initDDTarget : function(group, config, overrides){
+ var dd = new Ext.dd.DDTarget(Ext.id(this.dom), group, config);
+ return Ext.apply(dd, overrides);
+ }
+});
+/**
+ * @class Ext.data.Api
+ * @extends Object
+ * Ext.data.Api is a singleton designed to manage the data API including methods
+ * for validating a developer's DataProxy API. Defines variables for CRUD actions
+ * create, read, update and destroy in addition to a mapping of RESTful HTTP methods
+ * GET, POST, PUT and DELETE to CRUD actions.
+ * @singleton
+ */
+Ext.data.Api = (function() {
+
+ // private validActions. validActions is essentially an inverted hash of Ext.data.Api.actions, where value becomes the key.
+ // Some methods in this singleton (e.g.: getActions, getVerb) will loop through actions with the code <code>for (var verb in this.actions)</code>
+ // For efficiency, some methods will first check this hash for a match. Those methods which do acces validActions will cache their result here.
+ // We cannot pre-define this hash since the developer may over-ride the actions at runtime.
+ var validActions = {};
+
+ return {
+ /**
+ * Defined actions corresponding to remote actions:
+ * <pre><code>
+actions: {
+ create : 'create', // Text representing the remote-action to create records on server.
+ read : 'read', // Text representing the remote-action to read/load data from server.
+ update : 'update', // Text representing the remote-action to update records on server.
+ destroy : 'destroy' // Text representing the remote-action to destroy records on server.
+}
+ * </code></pre>
+ * @property actions
+ * @type Object
+ */
+ actions : {
+ create : 'create',
+ read : 'read',
+ update : 'update',
+ destroy : 'destroy'
+ },
+
+ /**
+ * Defined {CRUD action}:{HTTP method} pairs to associate HTTP methods with the
+ * corresponding actions for {@link Ext.data.DataProxy#restful RESTful proxies}.
+ * Defaults to:
+ * <pre><code>
+restActions : {
+ create : 'POST',
+ read : 'GET',
+ update : 'PUT',
+ destroy : 'DELETE'
+},
+ * </code></pre>
+ */
+ restActions : {
+ create : 'POST',
+ read : 'GET',
+ update : 'PUT',
+ destroy : 'DELETE'
+ },
+
+ /**
+ * Returns true if supplied action-name is a valid API action defined in <code>{@link #actions}</code> constants
+ * @param {String} action Action to test for availability.
+ * @return {Boolean}
+ */
+ isAction : function(action) {
+ return (Ext.data.Api.actions[action]) ? true : false;
+ },
+
+ /**
+ * Returns the actual CRUD action KEY "create", "read", "update" or "destroy" from the supplied action-name. This method is used internally and shouldn't generally
+ * need to be used directly. The key/value pair of Ext.data.Api.actions will often be identical but this is not necessarily true. A developer can override this naming
+ * convention if desired. However, the framework internally calls methods based upon the KEY so a way of retreiving the the words "create", "read", "update" and "destroy" is
+ * required. This method will cache discovered KEYS into the private validActions hash.
+ * @param {String} name The runtime name of the action.
+ * @return {String||null} returns the action-key, or verb of the user-action or null if invalid.
+ * @nodoc
+ */
+ getVerb : function(name) {
+ if (validActions[name]) {
+ return validActions[name]; // <-- found in cache. return immediately.
+ }
+ for (var verb in this.actions) {
+ if (this.actions[verb] === name) {
+ validActions[name] = verb;
+ break;
+ }
+ }
+ return (validActions[name] !== undefined) ? validActions[name] : null;
+ },
+
+ /**
+ * Returns true if the supplied API is valid; that is, check that all keys match defined actions
+ * otherwise returns an array of mistakes.
+ * @return {String[]|true}
+ */
+ isValid : function(api){
+ var invalid = [];
+ var crud = this.actions; // <-- cache a copy of the actions.
+ for (var action in api) {
+ if (!(action in crud)) {
+ invalid.push(action);
+ }
+ }
+ return (!invalid.length) ? true : invalid;
+ },
+
+ /**
+ * Returns true if the supplied verb upon the supplied proxy points to a unique url in that none of the other api-actions
+ * point to the same url. The question is important for deciding whether to insert the "xaction" HTTP parameter within an
+ * Ajax request. This method is used internally and shouldn't generally need to be called directly.
+ * @param {Ext.data.DataProxy} proxy
+ * @param {String} verb
+ * @return {Boolean}
+ */
+ hasUniqueUrl : function(proxy, verb) {
+ var url = (proxy.api[verb]) ? proxy.api[verb].url : null;
+ var unique = true;
+ for (var action in proxy.api) {
+ if ((unique = (action === verb) ? true : (proxy.api[action].url != url) ? true : false) === false) {
+ break;
+ }
+ }
+ return unique;
+ },
+
+ /**
+ * This method is used internally by <tt>{@link Ext.data.DataProxy DataProxy}</tt> and should not generally need to be used directly.
+ * Each action of a DataProxy api can be initially defined as either a String or an Object. When specified as an object,
+ * one can explicitly define the HTTP method (GET|POST) to use for each CRUD action. This method will prepare the supplied API, setting
+ * each action to the Object form. If your API-actions do not explicitly define the HTTP method, the "method" configuration-parameter will
+ * be used. If the method configuration parameter is not specified, POST will be used.
+ <pre><code>
+new Ext.data.HttpProxy({
+ method: "POST", // <-- default HTTP method when not specified.
+ api: {
+ create: 'create.php',
+ load: 'read.php',
+ save: 'save.php',
+ destroy: 'destroy.php'
+ }
+});
+
+// Alternatively, one can use the object-form to specify the API
+new Ext.data.HttpProxy({
+ api: {
+ load: {url: 'read.php', method: 'GET'},
+ create: 'create.php',
+ destroy: 'destroy.php',
+ save: 'update.php'
+ }
+});
+ </code></pre>
+ *
+ * @param {Ext.data.DataProxy} proxy
+ */
+ prepare : function(proxy) {
+ if (!proxy.api) {
+ proxy.api = {}; // <-- No api? create a blank one.
+ }
+ for (var verb in this.actions) {
+ var action = this.actions[verb];
+ proxy.api[action] = proxy.api[action] || proxy.url || proxy.directFn;
+ if (typeof(proxy.api[action]) == 'string') {
+ proxy.api[action] = {
+ url: proxy.api[action],
+ method: (proxy.restful === true) ? Ext.data.Api.restActions[action] : undefined
+ };
+ }
+ }
+ },
+
+ /**
+ * Prepares a supplied Proxy to be RESTful. Sets the HTTP method for each api-action to be one of
+ * GET, POST, PUT, DELETE according to the defined {@link #restActions}.
+ * @param {Ext.data.DataProxy} proxy
+ */
+ restify : function(proxy) {
+ proxy.restful = true;
+ for (var verb in this.restActions) {
+ proxy.api[this.actions[verb]].method ||
+ (proxy.api[this.actions[verb]].method = this.restActions[verb]);
+ }
+ // TODO: perhaps move this interceptor elsewhere? like into DataProxy, perhaps? Placed here
+ // to satisfy initial 3.0 final release of REST features.
+ proxy.onWrite = proxy.onWrite.createInterceptor(function(action, o, response, rs) {
+ var reader = o.reader;
+ var res = new Ext.data.Response({
+ action: action,
+ raw: response
+ });
+
+ switch (response.status) {
+ case 200: // standard 200 response, send control back to HttpProxy#onWrite by returning true from this intercepted #onWrite
+ return true;
+ break;
+ case 201: // entity created but no response returned
+ if (Ext.isEmpty(res.raw.responseText)) {
+ res.success = true;
+ } else {
+ //if the response contains data, treat it like a 200
+ return true;
+ }
+ break;
+ case 204: // no-content. Create a fake response.
+ res.success = true;
+ res.data = null;
+ break;
+ default:
+ return true;
+ break;
+ }
+ if (res.success === true) {
+ this.fireEvent("write", this, action, res.data, res, rs, o.request.arg);
+ } else {
+ this.fireEvent('exception', this, 'remote', action, o, res, rs);
+ }
+ o.request.callback.call(o.request.scope, res.data, res, res.success);
+
+ return false; // <-- false to prevent intercepted function from running.
+ }, proxy);
+ }
+ };
+})();
+
+/**
+ * Ext.data.Response
+ * Experimental. Do not use directly.
+ */
+Ext.data.Response = function(params, response) {
+ Ext.apply(this, params, {
+ raw: response
+ });
+};
+Ext.data.Response.prototype = {
+ message : null,
+ success : false,
+ status : null,
+ root : null,
+ raw : null,
+
+ getMessage : function() {
+ return this.message;
+ },
+ getSuccess : function() {
+ return this.success;
+ },
+ getStatus : function() {
+ return this.status;
+ },
+ getRoot : function() {
+ return this.root;
+ },
+ getRawResponse : function() {
+ return this.raw;
+ }
+};
+
+/**
+ * @class Ext.data.Api.Error
+ * @extends Ext.Error
+ * Error class for Ext.data.Api errors
+ */
+Ext.data.Api.Error = Ext.extend(Ext.Error, {
+ constructor : function(message, arg) {
+ this.arg = arg;
+ Ext.Error.call(this, message);
+ },
+ name: 'Ext.data.Api'
+});
+Ext.apply(Ext.data.Api.Error.prototype, {
+ lang: {
+ 'action-url-undefined': 'No fallback url defined for this action. When defining a DataProxy api, please be sure to define an url for each CRUD action in Ext.data.Api.actions or define a default url in addition to your api-configuration.',
+ 'invalid': 'received an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions',
+ 'invalid-url': 'Invalid url. Please review your proxy configuration.',
+ 'execute': 'Attempted to execute an unknown action. Valid API actions are defined in Ext.data.Api.actions"'
+ }
+});
+
+
+
+/**
+ * @class Ext.data.SortTypes
+ * @singleton
+ * Defines the default sorting (casting?) comparison functions used when sorting data.
+ */
+Ext.data.SortTypes = {
+ /**
+ * Default sort that does nothing
+ * @param {Mixed} s The value being converted
+ * @return {Mixed} The comparison value
+ */
+ none : function(s){
+ return s;
+ },
+
+ /**
+ * The regular expression used to strip tags
+ * @type {RegExp}
+ * @property
+ */
+ stripTagsRE : /<\/?[^>]+>/gi,
+
+ /**
+ * Strips all HTML tags to sort on text only
+ * @param {Mixed} s The value being converted
+ * @return {String} The comparison value
+ */
+ asText : function(s){
+ return String(s).replace(this.stripTagsRE, "");
+ },
+
+ /**
+ * Strips all HTML tags to sort on text only - Case insensitive
+ * @param {Mixed} s The value being converted
+ * @return {String} The comparison value
+ */
+ asUCText : function(s){
+ return String(s).toUpperCase().replace(this.stripTagsRE, "");
+ },
+
+ /**
+ * Case insensitive string
+ * @param {Mixed} s The value being converted
+ * @return {String} The comparison value
+ */
+ asUCString : function(s) {
+ return String(s).toUpperCase();
+ },
+
+ /**
+ * Date sorting
+ * @param {Mixed} s The value being converted
+ * @return {Number} The comparison value
+ */
+ asDate : function(s) {
+ if(!s){
+ return 0;
+ }
+ if(Ext.isDate(s)){
+ return s.getTime();
+ }
+ return Date.parse(String(s));
+ },
+
+ /**
+ * Float sorting
+ * @param {Mixed} s The value being converted
+ * @return {Float} The comparison value
+ */
+ asFloat : function(s) {
+ var val = parseFloat(String(s).replace(/,/g, ""));
+ return isNaN(val) ? 0 : val;
+ },
+
+ /**
+ * Integer sorting
+ * @param {Mixed} s The value being converted
+ * @return {Number} The comparison value
+ */
+ asInt : function(s) {
+ var val = parseInt(String(s).replace(/,/g, ""), 10);
+ return isNaN(val) ? 0 : val;
+ }
+};/**
+ * @class Ext.data.Record
+ * <p>Instances of this class encapsulate both Record <em>definition</em> information, and Record
+ * <em>value</em> information for use in {@link Ext.data.Store} objects, or any code which needs
+ * to access Records cached in an {@link Ext.data.Store} object.</p>
+ * <p>Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
+ * Instances are usually only created by {@link Ext.data.Reader} implementations when processing unformatted data
+ * objects.</p>
+ * <p>Note that an instance of a Record class may only belong to one {@link Ext.data.Store Store} at a time.
+ * In order to copy data from one Store to another, use the {@link #copy} method to create an exact
+ * copy of the Record, and insert the new instance into the other Store.</p>
+ * <p>When serializing a Record for submission to the server, be aware that it contains many private
+ * properties, and also a reference to its owning Store which in turn holds references to its Records.
+ * This means that a whole Record may not be encoded using {@link Ext.util.JSON.encode}. Instead, use the
+ * <code>{@link #data}</code> and <code>{@link #id}</code> properties.</p>
+ * <p>Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.</p>
+ * @constructor
+ * <p>This constructor should not be used to create Record objects. Instead, use {@link #create} to
+ * generate a subclass of Ext.data.Record configured with information about its constituent fields.<p>
+ * <p><b>The generated constructor has the same signature as this constructor.</b></p>
+ * @param {Object} data (Optional) An object, the properties of which provide values for the new Record's
+ * fields. If not specified the <code>{@link Ext.data.Field#defaultValue defaultValue}</code>
+ * for each field will be assigned.
+ * @param {Object} id (Optional) The id of the Record. The id is used by the
+ * {@link Ext.data.Store} object which owns the Record to index its collection
+ * of Records (therefore this id should be unique within each store). If an
+ * <code>id</code> is not specified a <b><code>{@link #phantom}</code></b>
+ * Record will be created with an {@link #Record.id automatically generated id}.
+ */
+Ext.data.Record = function(data, id){
+ // if no id, call the auto id method
+ this.id = (id || id === 0) ? id : Ext.data.Record.id(this);
+ this.data = data || {};
+};
+
+/**
+ * Generate a constructor for a specific Record layout.
+ * @param {Array} o An Array of <b>{@link Ext.data.Field Field}</b> definition objects.
+ * The constructor generated by this method may be used to create new Record instances. The data
+ * object must contain properties named after the {@link Ext.data.Field field}
+ * <b><tt>{@link Ext.data.Field#name}s</tt></b>. Example usage:<pre><code>
+// create a Record constructor from a description of the fields
+var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
+ {{@link Ext.data.Field#name name}: 'title', {@link Ext.data.Field#mapping mapping}: 'topic_title'},
+ {name: 'author', mapping: 'username', allowBlank: false},
+ {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
+ {name: 'lastPost', mapping: 'post_time', type: 'date'},
+ {name: 'lastPoster', mapping: 'user2'},
+ {name: 'excerpt', mapping: 'post_text', allowBlank: false},
+ // In the simplest case, if no properties other than <tt>name</tt> are required,
+ // a field definition may consist of just a String for the field name.
+ 'signature'
+]);
+
+// create Record instance
+var myNewRecord = new TopicRecord(
+ {
+ title: 'Do my job please',
+ author: 'noobie',
+ totalPosts: 1,
+ lastPost: new Date(),
+ lastPoster: 'Animal',
+ excerpt: 'No way dude!',
+ signature: ''
+ },
+ id // optionally specify the id of the record otherwise {@link #Record.id one is auto-assigned}
+);
+myStore.{@link Ext.data.Store#add add}(myNewRecord);
+</code></pre>
+ * @method create
+ * @return {Function} A constructor which is used to create new Records according
+ * to the definition. The constructor has the same signature as {@link #Record}.
+ * @static
+ */
+Ext.data.Record.create = function(o){
+ var f = Ext.extend(Ext.data.Record, {});
+ var p = f.prototype;
+ p.fields = new Ext.util.MixedCollection(false, function(field){
+ return field.name;
+ });
+ for(var i = 0, len = o.length; i < len; i++){
+ p.fields.add(new Ext.data.Field(o[i]));
+ }
+ f.getField = function(name){
+ return p.fields.get(name);
+ };
+ return f;
+};
+
+Ext.data.Record.PREFIX = 'ext-record';
+Ext.data.Record.AUTO_ID = 1;
+Ext.data.Record.EDIT = 'edit';
+Ext.data.Record.REJECT = 'reject';
+Ext.data.Record.COMMIT = 'commit';
+
+
+/**
+ * Generates a sequential id. This method is typically called when a record is {@link #create}d
+ * and {@link #Record no id has been specified}. The returned id takes the form:
+ * <tt>{PREFIX}-{AUTO_ID}</tt>.<div class="mdetail-params"><ul>
+ * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.PREFIX</tt>
+ * (defaults to <tt>'ext-record'</tt>)</p></li>
+ * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.AUTO_ID</tt>
+ * (defaults to <tt>1</tt> initially)</p></li>
+ * </ul></div>
+ * @param {Record} rec The record being created. The record does not exist, it's a {@link #phantom}.
+ * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
+ */
+Ext.data.Record.id = function(rec) {
+ rec.phantom = true;
+ return [Ext.data.Record.PREFIX, '-', Ext.data.Record.AUTO_ID++].join('');
+};
+
+Ext.data.Record.prototype = {
+ /**
+ * <p><b>This property is stored in the Record definition's <u>prototype</u></b></p>
+ * A MixedCollection containing the defined {@link Ext.data.Field Field}s for this Record. Read-only.
+ * @property fields
+ * @type Ext.util.MixedCollection
+ */
+ /**
+ * An object hash representing the data for this Record. Every field name in the Record definition
+ * is represented by a property of that name in this object. Note that unless you specified a field
+ * with {@link Ext.data.Field#name name} "id" in the Record definition, this will <b>not</b> contain
+ * an <tt>id</tt> property.
+ * @property data
+ * @type {Object}
+ */
+ /**
+ * The unique ID of the Record {@link #Record as specified at construction time}.
+ * @property id
+ * @type {Object}
+ */
+ /**
+ * <p><b>Only present if this Record was created by an {@link Ext.data.XmlReader XmlReader}</b>.</p>
+ * <p>The XML element which was the source of the data for this Record.</p>
+ * @property node
+ * @type {XMLElement}
+ */
+ /**
+ * <p><b>Only present if this Record was created by an {@link Ext.data.ArrayReader ArrayReader} or a {@link Ext.data.JsonReader JsonReader}</b>.</p>
+ * <p>The Array or object which was the source of the data for this Record.</p>
+ * @property json
+ * @type {Array|Object}
+ */
+ /**
+ * Readonly flag - true if this Record has been modified.
+ * @type Boolean
+ */
+ dirty : false,
+ editing : false,
+ error : null,
+ /**
+ * This object contains a key and value storing the original values of all modified
+ * fields or is null if no fields have been modified.
+ * @property modified
+ * @type {Object}
+ */
+ modified : null,
+ /**
+ * <tt>true</tt> when the record does not yet exist in a server-side database (see
+ * {@link #markDirty}). Any record which has a real database pk set as its id property
+ * is NOT a phantom -- it's real.
+ * @property phantom
+ * @type {Boolean}
+ */
+ phantom : false,
+
+ // private
+ join : function(store){
+ /**
+ * The {@link Ext.data.Store} to which this Record belongs.
+ * @property store
+ * @type {Ext.data.Store}
+ */
+ this.store = store;
+ },
+
+ /**
+ * Set the {@link Ext.data.Field#name named field} to the specified value. For example:
+ * <pre><code>
+// record has a field named 'firstname'
+var Employee = Ext.data.Record.{@link #create}([
+ {name: 'firstname'},
+ ...
+]);
+
+// update the 2nd record in the store:
+var rec = myStore.{@link Ext.data.Store#getAt getAt}(1);
+
+// set the value (shows dirty flag):
+rec.set('firstname', 'Betty');
+
+// commit the change (removes dirty flag):
+rec.{@link #commit}();
+
+// update the record in the store, bypass setting dirty flag,
+// and do not store the change in the {@link Ext.data.Store#getModifiedRecords modified records}
+rec.{@link #data}['firstname'] = 'Wilma'; // updates record, but not the view
+rec.{@link #commit}(); // updates the view
+ * </code></pre>
+ * <b>Notes</b>:<div class="mdetail-params"><ul>
+ * <li>If the store has a writer and <code>autoSave=true</code>, each set()
+ * will execute an XHR to the server.</li>
+ * <li>Use <code>{@link #beginEdit}</code> to prevent the store's <code>update</code>
+ * event firing while using set().</li>
+ * <li>Use <code>{@link #endEdit}</code> to have the store's <code>update</code>
+ * event fire.</li>
+ * </ul></div>
+ * @param {String} name The {@link Ext.data.Field#name name of the field} to set.
+ * @param {String/Object/Array} value The value to set the field to.
+ */
+ set : function(name, value){
+ var encode = Ext.isPrimitive(value) ? String : Ext.encode;
+ if(encode(this.data[name]) == encode(value)) {
+ return;
+ }
+ this.dirty = true;
+ if(!this.modified){
+ this.modified = {};
+ }
+ if(this.modified[name] === undefined){
+ this.modified[name] = this.data[name];
+ }
+ this.data[name] = value;
+ if(!this.editing){
+ this.afterEdit();
+ }
+ },
+
+ // private
+ afterEdit : function(){
+ if (this.store != undefined && typeof this.store.afterEdit == "function") {
+ this.store.afterEdit(this);
+ }
+ },
+
+ // private
+ afterReject : function(){
+ if(this.store){
+ this.store.afterReject(this);
+ }
+ },
+
+ // private
+ afterCommit : function(){
+ if(this.store){
+ this.store.afterCommit(this);
+ }
+ },
+
+ /**
+ * Get the value of the {@link Ext.data.Field#name named field}.
+ * @param {String} name The {@link Ext.data.Field#name name of the field} to get the value of.
+ * @return {Object} The value of the field.
+ */
+ get : function(name){
+ return this.data[name];
+ },
+
+ /**
+ * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
+ * are relayed to the containing store.
+ * See also: <code>{@link #endEdit}</code> and <code>{@link #cancelEdit}</code>.
+ */
+ beginEdit : function(){
+ this.editing = true;
+ this.modified = this.modified || {};
+ },
+
+ /**
+ * Cancels all changes made in the current edit operation.
+ */
+ cancelEdit : function(){
+ this.editing = false;
+ delete this.modified;
+ },
+
+ /**
+ * End an edit. If any data was modified, the containing store is notified
+ * (ie, the store's <code>update</code> event will fire).
+ */
+ endEdit : function(){
+ this.editing = false;
+ if(this.dirty){
+ this.afterEdit();
+ }
+ },
+
+ /**
+ * Usually called by the {@link Ext.data.Store} which owns the Record.
+ * Rejects all changes made to the Record since either creation, or the last commit operation.
+ * Modified fields are reverted to their original values.
+ * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
+ * to have their code notified of reject operations.</p>
+ * @param {Boolean} silent (optional) True to skip notification of the owning
+ * store of the change (defaults to false)
+ */
+ reject : function(silent){
+ var m = this.modified;
+ for(var n in m){
+ if(typeof m[n] != "function"){
+ this.data[n] = m[n];
+ }
+ }
+ this.dirty = false;
+ delete this.modified;
+ this.editing = false;
+ if(silent !== true){
+ this.afterReject();
+ }
+ },
+
+ /**
+ * Usually called by the {@link Ext.data.Store} which owns the Record.
+ * Commits all changes made to the Record since either creation, or the last commit operation.
+ * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
+ * to have their code notified of commit operations.</p>
+ * @param {Boolean} silent (optional) True to skip notification of the owning
+ * store of the change (defaults to false)
+ */
+ commit : function(silent){
+ this.dirty = false;
+ delete this.modified;
+ this.editing = false;
+ if(silent !== true){
+ this.afterCommit();
+ }
+ },
+
+ /**
+ * Gets a hash of only the fields that have been modified since this Record was created or commited.
+ * @return Object
+ */
+ getChanges : function(){
+ var m = this.modified, cs = {};
+ for(var n in m){
+ if(m.hasOwnProperty(n)){
+ cs[n] = this.data[n];
+ }
+ }
+ return cs;
+ },
+
+ // private
+ hasError : function(){
+ return this.error !== null;
+ },
+
+ // private
+ clearError : function(){
+ this.error = null;
+ },
+
+ /**
+ * Creates a copy (clone) of this Record.
+ * @param {String} id (optional) A new Record id, defaults to the id
+ * of the record being copied. See <code>{@link #id}</code>.
+ * To generate a phantom record with a new id use:<pre><code>
+var rec = record.copy(); // clone the record
+Ext.data.Record.id(rec); // automatically generate a unique sequential id
+ * </code></pre>
+ * @return {Record}
+ */
+ copy : function(newId) {
+ return new this.constructor(Ext.apply({}, this.data), newId || this.id);
+ },
+
+ /**
+ * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
+ * since the load or last commit.
+ * @param {String} fieldName {@link Ext.data.Field.{@link Ext.data.Field#name}
+ * @return {Boolean}
+ */
+ isModified : function(fieldName){
+ return !!(this.modified && this.modified.hasOwnProperty(fieldName));
+ },
+
+ /**
+ * By default returns <tt>false</tt> if any {@link Ext.data.Field field} within the
+ * record configured with <tt>{@link Ext.data.Field#allowBlank} = false</tt> returns
+ * <tt>true</tt> from an {@link Ext}.{@link Ext#isEmpty isempty} test.
+ * @return {Boolean}
+ */
+ isValid : function() {
+ return this.fields.find(function(f) {
+ return (f.allowBlank === false && Ext.isEmpty(this.data[f.name])) ? true : false;
+ },this) ? false : true;
+ },
+
+ /**
+ * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>. This method
+ * is used interally when adding <code>{@link #phantom}</code> records to a
+ * {@link Ext.data.Store#writer writer enabled store}.</p>
+ * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
+ * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
+ * have a create action composed for it during {@link Ext.data.Store#save store save}
+ * operations.</p>
+ */
+ markDirty : function(){
+ this.dirty = true;
+ if(!this.modified){
+ this.modified = {};
+ }
+ this.fields.each(function(f) {
+ this.modified[f.name] = this.data[f.name];
+ },this);
+ }
+};
+/**
+ * @class Ext.StoreMgr
+ * @extends Ext.util.MixedCollection
+ * The default global group of stores.
+ * @singleton
+ */
+Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), {
+ /**
+ * @cfg {Object} listeners @hide
+ */
+
+ /**
+ * Registers one or more Stores with the StoreMgr. You do not normally need to register stores
+ * manually. Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered.
+ * @param {Ext.data.Store} store1 A Store instance
+ * @param {Ext.data.Store} store2 (optional)
+ * @param {Ext.data.Store} etc... (optional)
+ */
+ register : function(){
+ for(var i = 0, s; (s = arguments[i]); i++){
+ this.add(s);
+ }
+ },
+
+ /**
+ * Unregisters one or more Stores with the StoreMgr
+ * @param {String/Object} id1 The id of the Store, or a Store instance
+ * @param {String/Object} id2 (optional)
+ * @param {String/Object} etc... (optional)
+ */
+ unregister : function(){
+ for(var i = 0, s; (s = arguments[i]); i++){
+ this.remove(this.lookup(s));
+ }
+ },
+
+ /**
+ * Gets a registered Store by id
+ * @param {String/Object} id The id of the Store, or a Store instance
+ * @return {Ext.data.Store}
+ */
+ lookup : function(id){
+ if(Ext.isArray(id)){
+ var fields = ['field1'], expand = !Ext.isArray(id[0]);
+ if(!expand){
+ for(var i = 2, len = id[0].length; i <= len; ++i){
+ fields.push('field' + i);
+ }
+ }
+ return new Ext.data.ArrayStore({
+ fields: fields,
+ data: id,
+ expandData: expand,
+ autoDestroy: true,
+ autoCreated: true
+
+ });
+ }
+ return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id);
+ },
+
+ // getKey implementation for MixedCollection
+ getKey : function(o){
+ return o.storeId;
+ }
+});/**
+ * @class Ext.data.Store
+ * @extends Ext.util.Observable
+ * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
+ * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
+ * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
+ * <p><u>Retrieving Data</u></p>
+ * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
+ * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
+ * <li>{@link #data} to automatically pass in data</li>
+ * <li>{@link #loadData} to manually pass in data</li>
+ * </ul></div></p>
+ * <p><u>Reading Data</u></p>
+ * <p>A Store object has no inherent knowledge of the format of the data object (it could be
+ * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
+ * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
+ * object.</p>
+ * <p><u>Store Types</u></p>
+ * <p>There are several implementations of Store available which are customized for use with
+ * a specific DataReader implementation. Here is an example using an ArrayStore which implicitly
+ * creates a reader commensurate to an Array data object.</p>
+ * <pre><code>
+var myStore = new Ext.data.ArrayStore({
+ fields: ['fullname', 'first'],
+ idIndex: 0 // id for each record will be the first element
+});
+ * </code></pre>
+ * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
+ * <pre><code>
+// create a {@link Ext.data.Record Record} constructor:
+var rt = Ext.data.Record.create([
+ {name: 'fullname'},
+ {name: 'first'}
+]);
+var myStore = new Ext.data.Store({
+ // explicitly create reader
+ reader: new Ext.data.ArrayReader(
+ {
+ idIndex: 0 // id for each record will be the first element
+ },
+ rt // recordType
+ )
+});
+ * </code></pre>
+ * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
+ * <pre><code>
+var myData = [
+ [1, 'Fred Flintstone', 'Fred'], // note that id for the record is the first element
+ [2, 'Barney Rubble', 'Barney']
+];
+myStore.loadData(myData);
+ * </code></pre>
+ * <p>Records are cached and made available through accessor functions. An example of adding
+ * a record to the store:</p>
+ * <pre><code>
+var defaultData = {
+ fullname: 'Full Name',
+ first: 'First Name'
+};
+var recId = 100; // provide unique id for the record
+var r = new myStore.recordType(defaultData, ++recId); // create new record
+myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
+ * </code></pre>
+ * <p><u>Writing Data</u></p>
+ * <p>And <b>new in Ext version 3</b>, use the new {@link Ext.data.DataWriter DataWriter} to create an automated, <a href="http://extjs.com/deploy/dev/examples/writer/writer.html">Writable Store</a>
+ * along with <a href="http://extjs.com/deploy/dev/examples/restful/restful.html">RESTful features.</a>
+ * @constructor
+ * Creates a new Store.
+ * @param {Object} config A config object containing the objects needed for the Store to access data,
+ * and read the data into Records.
+ * @xtype store
+ */
+Ext.data.Store = Ext.extend(Ext.util.Observable, {
+ /**
+ * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
+ * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
+ * assignment.</p>
+ */
+ /**
+ * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
+ * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
+ * Typically this option, or the <code>{@link #data}</code> option will be specified.
+ */
+ /**
+ * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
+ * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
+ * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
+ * be passed to the store's {@link #load} method.
+ */
+ /**
+ * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
+ * access to a data object. See <code>{@link #url}</code>.
+ */
+ /**
+ * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
+ * Typically this option, or the <code>{@link #url}</code> option will be specified.
+ */
+ /**
+ * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
+ * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
+ * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
+ */
+ /**
+ * @cfg {Ext.data.DataWriter} writer
+ * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
+ * to the server-side database.</p>
+ * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
+ * events on the store are monitored in order to remotely {@link #createRecords create records},
+ * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
+ * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
+ * <br><p>Sample implementation:
+ * <pre><code>
+var writer = new {@link Ext.data.JsonWriter}({
+ encode: true,
+ writeAllFields: true // write all fields, not just those that changed
+});
+
+// Typical Store collecting the Proxy, Reader and Writer together.
+var store = new Ext.data.Store({
+ storeId: 'user',
+ root: 'records',
+ proxy: proxy,
+ reader: reader,
+ writer: writer, // <-- plug a DataWriter into the store just as you would a Reader
+ paramsAsHash: true,
+ autoSave: false // <-- false to delay executing create, update, destroy requests
+ // until specifically told to do so.
+});
+ * </code></pre></p>
+ */
+ writer : undefined,
+ /**
+ * @cfg {Object} baseParams
+ * <p>An object containing properties which are to be sent as parameters
+ * for <i>every</i> HTTP request.</p>
+ * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
+ * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
+ * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
+ * for more details.</p>
+ * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
+ * method.
+ * @property
+ */
+ /**
+ * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
+ * {@link #load} operation. Note that for local sorting, the <tt>direction</tt> property is
+ * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
+ * For example:<pre><code>
+sortInfo: {
+ field: 'fieldName',
+ direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
+}
+</code></pre>
+ */
+ /**
+ * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
+ * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
+ * in place (defaults to <tt>false</tt>).
+ * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
+ * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
+ * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
+ * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
+ * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
+ * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
+ * </ul></div></p>
+ */
+ remoteSort : false,
+
+ /**
+ * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
+ * to is destroyed (defaults to <tt>false</tt>).
+ * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
+ */
+ autoDestroy : false,
+
+ /**
+ * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
+ * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
+ * for the accessor method to retrieve the modified records.
+ */
+ pruneModifiedRecords : false,
+
+ /**
+ * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
+ * for the details of what this may contain. This may be useful for accessing any params which were used
+ * to load the current Record cache.
+ * @property
+ */
+ lastOptions : null,
+
+ /**
+ * @cfg {Boolean} autoSave
+ * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
+ * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
+ * to send all modifiedRecords to the server.</p>
+ * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
+ */
+ autoSave : true,
+
+ /**
+ * @cfg {Boolean} batch
+ * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
+ * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
+ * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
+ * to <tt>false</tt>.</p>
+ * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
+ * generated for each record.</p>
+ */
+ batch : true,
+
+ /**
+ * @cfg {Boolean} restful
+ * Defaults to <tt>false</tt>. Set to <tt>true</tt> to have the Store and the set
+ * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
+ * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
+ * action is described in {@link Ext.data.Api#restActions}. For additional information
+ * see {@link Ext.data.DataProxy#restful}.
+ * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
+ * internally be set to <tt>false</tt>.</p>
+ */
+ restful: false,
+
+ /**
+ * @cfg {Object} paramNames
+ * <p>An object containing properties which specify the names of the paging and
+ * sorting parameters passed to remote servers when loading blocks of data. By default, this
+ * object takes the following form:</p><pre><code>
+{
+ start : 'start', // The parameter name which specifies the start row
+ limit : 'limit', // The parameter name which specifies number of rows to return
+ sort : 'sort', // The parameter name which specifies the column to sort on
+ dir : 'dir' // The parameter name which specifies the sort direction
+}
+</code></pre>
+ * <p>The server must produce the requested data block upon receipt of these parameter names.
+ * If different parameter names are required, this property can be overriden using a configuration
+ * property.</p>
+ * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
+ * the parameter names to use in its {@link #load requests}.
+ */
+ paramNames : undefined,
+
+ /**
+ * @cfg {Object} defaultParamNames
+ * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
+ * for all stores, this object should be changed on the store prototype.
+ */
+ defaultParamNames : {
+ start : 'start',
+ limit : 'limit',
+ sort : 'sort',
+ dir : 'dir'
+ },
+
+ /**
+ * @property isDestroyed
+ * @type Boolean
+ * True if the store has been destroyed already. Read only
+ */
+ isDestroyed: false,
+
+ /**
+ * @property hasMultiSort
+ * @type Boolean
+ * True if this store is currently sorted by more than one field/direction combination.
+ */
+ hasMultiSort: false,
+
+ // private
+ batchKey : '_ext_batch_',
+
+ constructor : function(config){
+ this.data = new Ext.util.MixedCollection(false);
+ this.data.getKey = function(o){
+ return o.id;
+ };
+
+
+ // temporary removed-records cache
+ this.removed = [];
+
+ if(config && config.data){
+ this.inlineData = config.data;
+ delete config.data;
+ }
+
+ Ext.apply(this, config);
+
+ /**
+ * See the <code>{@link #baseParams corresponding configuration option}</code>
+ * for a description of this property.
+ * To modify this property see <code>{@link #setBaseParam}</code>.
+ * @property
+ */
+ this.baseParams = Ext.isObject(this.baseParams) ? this.baseParams : {};
+
+ this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
+
+ if((this.url || this.api) && !this.proxy){
+ this.proxy = new Ext.data.HttpProxy({url: this.url, api: this.api});
+ }
+ // If Store is RESTful, so too is the DataProxy
+ if (this.restful === true && this.proxy) {
+ // When operating RESTfully, a unique transaction is generated for each record.
+ // TODO might want to allow implemention of faux REST where batch is possible using RESTful routes only.
+ this.batch = false;
+ Ext.data.Api.restify(this.proxy);
+ }
+
+ if(this.reader){ // reader passed
+ if(!this.recordType){
+ this.recordType = this.reader.recordType;
+ }
+ if(this.reader.onMetaChange){
+ this.reader.onMetaChange = this.reader.onMetaChange.createSequence(this.onMetaChange, this);
+ }
+ if (this.writer) { // writer passed
+ if (this.writer instanceof(Ext.data.DataWriter) === false) { // <-- config-object instead of instance.
+ this.writer = this.buildWriter(this.writer);
+ }
+ this.writer.meta = this.reader.meta;
+ this.pruneModifiedRecords = true;
+ }
+ }
+
+ /**
+ * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
+ * {@link Ext.data.DataReader Reader}. Read-only.
+ * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
+ * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
+ * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
+ * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
+ // create the data store
+ var store = new Ext.data.ArrayStore({
+ autoDestroy: true,
+ fields: [
+ {name: 'company'},
+ {name: 'price', type: 'float'},
+ {name: 'change', type: 'float'},
+ {name: 'pctChange', type: 'float'},
+ {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
+ ]
+ });
+ store.loadData(myData);
+
+ // create the Grid
+ var grid = new Ext.grid.EditorGridPanel({
+ store: store,
+ colModel: new Ext.grid.ColumnModel({
+ columns: [
+ {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
+ {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
+ {header: 'Change', renderer: change, dataIndex: 'change'},
+ {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
+ {header: 'Last Updated', width: 85,
+ renderer: Ext.util.Format.dateRenderer('m/d/Y'),
+ dataIndex: 'lastChange'}
+ ],
+ defaults: {
+ sortable: true,
+ width: 75
+ }
+ }),
+ autoExpandColumn: 'company', // match the id specified in the column model
+ height:350,
+ width:600,
+ title:'Array Grid',
+ tbar: [{
+ text: 'Add Record',
+ handler : function(){
+ var defaultData = {
+ change: 0,
+ company: 'New Company',
+ lastChange: (new Date()).clearTime(),
+ pctChange: 0,
+ price: 10
+ };
+ var recId = 3; // provide unique id
+ var p = new store.recordType(defaultData, recId); // create new record
+ grid.stopEditing();
+ store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
+ grid.startEditing(0, 0);
+ }
+ }]
+ });
+ * </code></pre>
+ * @property recordType
+ * @type Function
+ */
+
+ if(this.recordType){
+ /**
+ * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
+ * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
+ * @property fields
+ * @type Ext.util.MixedCollection
+ */
+ this.fields = this.recordType.prototype.fields;
+ }
+ this.modified = [];
+
+ this.addEvents(
+ /**
+ * @event datachanged
+ * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
+ * widget that is using this Store as a Record cache should refresh its view.
+ * @param {Store} this
+ */
+ 'datachanged',
+ /**
+ * @event metachange
+ * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
+ * @param {Store} this
+ * @param {Object} meta The JSON metadata
+ */
+ 'metachange',
+ /**
+ * @event add
+ * Fires when Records have been {@link #add}ed to the Store
+ * @param {Store} this
+ * @param {Ext.data.Record[]} records The array of Records added
+ * @param {Number} index The index at which the record(s) were added
+ */
+ 'add',
+ /**
+ * @event remove
+ * Fires when a Record has been {@link #remove}d from the Store
+ * @param {Store} this
+ * @param {Ext.data.Record} record The Record that was removed
+ * @param {Number} index The index at which the record was removed
+ */
+ 'remove',
+ /**
+ * @event update
+ * Fires when a Record has been updated
+ * @param {Store} this
+ * @param {Ext.data.Record} record The Record that was updated
+ * @param {String} operation The update operation being performed. Value may be one of:
+ * <pre><code>
+ Ext.data.Record.EDIT
+ Ext.data.Record.REJECT
+ Ext.data.Record.COMMIT
+ * </code></pre>
+ */
+ 'update',
+ /**
+ * @event clear
+ * Fires when the data cache has been cleared.
+ * @param {Store} this
+ * @param {Record[]} The records that were cleared.
+ */
+ 'clear',
+ /**
+ * @event exception
+ * <p>Fires if an exception occurs in the Proxy during a remote request.
+ * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
+ * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
+ * for additional details.
+ * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
+ * for description.
+ */
+ 'exception',
+ /**
+ * @event beforeload
+ * Fires before a request is made for a new data object. If the beforeload handler returns
+ * <tt>false</tt> the {@link #load} action will be canceled.
+ * @param {Store} this
+ * @param {Object} options The loading options that were specified (see {@link #load} for details)
+ */
+ 'beforeload',
+ /**
+ * @event load
+ * Fires after a new set of Records has been loaded.
+ * @param {Store} this
+ * @param {Ext.data.Record[]} records The Records that were loaded
+ * @param {Object} options The loading options that were specified (see {@link #load} for details)
+ */
+ 'load',
+ /**
+ * @event loadexception
+ * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
+ * event instead.</p>
+ * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
+ * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
+ * for additional details.
+ * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
+ * for description.
+ */
+ 'loadexception',
+ /**
+ * @event beforewrite
+ * @param {Ext.data.Store} store
+ * @param {String} action [Ext.data.Api.actions.create|update|destroy]
+ * @param {Record/Record[]} rs The Record(s) being written.
+ * @param {Object} options The loading options that were specified. Edit <code>options.params</code> to add Http parameters to the request. (see {@link #save} for details)
+ * @param {Object} arg The callback's arg object passed to the {@link #request} function
+ */
+ 'beforewrite',
+ /**
+ * @event write
+ * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
+ * Success of the action is determined in the <code>result['successProperty']</code>property (<b>NOTE</b> for RESTful stores,
+ * a simple 20x response is sufficient for the actions "destroy" and "update". The "create" action should should return 200 along with a database pk).
+ * @param {Ext.data.Store} store
+ * @param {String} action [Ext.data.Api.actions.create|update|destroy]
+ * @param {Object} result The 'data' picked-out out of the response for convenience.
+ * @param {Ext.Direct.Transaction} res
+ * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
+ */
+ 'write',
+ /**
+ * @event beforesave
+ * Fires before a save action is called. A save encompasses destroying records, updating records and creating records.
+ * @param {Ext.data.Store} store
+ * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
+ * with an array of records for each action.
+ */
+ 'beforesave',
+ /**
+ * @event save
+ * Fires after a save is completed. A save encompasses destroying records, updating records and creating records.
+ * @param {Ext.data.Store} store
+ * @param {Number} batch The identifier for the batch that was saved.
+ * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
+ * with an array of records for each action.
+ */
+ 'save'
+
+ );
+
+ if(this.proxy){
+ // TODO remove deprecated loadexception with ext-3.0.1
+ this.relayEvents(this.proxy, ['loadexception', 'exception']);
+ }
+ // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
+ if (this.writer) {
+ this.on({
+ scope: this,
+ add: this.createRecords,
+ remove: this.destroyRecord,
+ update: this.updateRecord,
+ clear: this.onClear
+ });
+ }
+
+ this.sortToggle = {};
+ if(this.sortField){
+ this.setDefaultSort(this.sortField, this.sortDir);
+ }else if(this.sortInfo){
+ this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
+ }
+
+ Ext.data.Store.superclass.constructor.call(this);
+
+ if(this.id){
+ this.storeId = this.id;
+ delete this.id;
+ }
+ if(this.storeId){
+ Ext.StoreMgr.register(this);
+ }
+ if(this.inlineData){
+ this.loadData(this.inlineData);
+ delete this.inlineData;
+ }else if(this.autoLoad){
+ this.load.defer(10, this, [
+ typeof this.autoLoad == 'object' ?
+ this.autoLoad : undefined]);
+ }
+ // used internally to uniquely identify a batch
+ this.batchCounter = 0;
+ this.batches = {};
+ },
+
+ /**
+ * builds a DataWriter instance when Store constructor is provided with a writer config-object instead of an instace.
+ * @param {Object} config Writer configuration
+ * @return {Ext.data.DataWriter}
+ * @private
+ */
+ buildWriter : function(config) {
+ var klass = undefined,
+ type = (config.format || 'json').toLowerCase();
+ switch (type) {
+ case 'json':
+ klass = Ext.data.JsonWriter;
+ break;
+ case 'xml':
+ klass = Ext.data.XmlWriter;
+ break;
+ default:
+ klass = Ext.data.JsonWriter;
+ }
+ return new klass(config);
+ },
+
+ /**
+ * Destroys the store.
+ */
+ destroy : function(){
+ if(!this.isDestroyed){
+ if(this.storeId){
+ Ext.StoreMgr.unregister(this);
+ }
+ this.clearData();
+ this.data = null;
+ Ext.destroy(this.proxy);
+ this.reader = this.writer = null;
+ this.purgeListeners();
+ this.isDestroyed = true;
+ }
+ },
+
+ /**
+ * Add Records to the Store and fires the {@link #add} event. To add Records
+ * to the store from a remote source use <code>{@link #load}({add:true})</code>.
+ * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
+ * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
+ * to add to the cache. See {@link #recordType}.
+ */
+ add : function(records){
+ records = [].concat(records);
+ if(records.length < 1){
+ return;
+ }
+ for(var i = 0, len = records.length; i < len; i++){
+ records[i].join(this);
+ }
+ var index = this.data.length;
+ this.data.addAll(records);
+ if(this.snapshot){
+ this.snapshot.addAll(records);
+ }
+ this.fireEvent('add', this, records, index);
+ },
+
+ /**
+ * (Local sort only) Inserts the passed Record into the Store at the index where it
+ * should go based on the current sort information.
+ * @param {Ext.data.Record} record
+ */
+ addSorted : function(record){
+ var index = this.findInsertIndex(record);
+ this.insert(index, record);
+ },
+
+ /**
+ * Remove Records from the Store and fires the {@link #remove} event.
+ * @param {Ext.data.Record/Ext.data.Record[]} record The record object or array of records to remove from the cache.
+ */
+ remove : function(record){
+ if(Ext.isArray(record)){
+ Ext.each(record, function(r){
+ this.remove(r);
+ }, this);
+ }
+ var index = this.data.indexOf(record);
+ if(index > -1){
+ record.join(null);
+ this.data.removeAt(index);
+ }
+ if(this.pruneModifiedRecords){
+ this.modified.remove(record);
+ }
+ if(this.snapshot){
+ this.snapshot.remove(record);
+ }
+ if(index > -1){
+ this.fireEvent('remove', this, record, index);
+ }
+ },
+
+ /**
+ * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
+ * @param {Number} index The index of the record to remove.
+ */
+ removeAt : function(index){
+ this.remove(this.getAt(index));
+ },
+
+ /**
+ * Remove all Records from the Store and fires the {@link #clear} event.
+ * @param {Boolean} silent [false] Defaults to <tt>false</tt>. Set <tt>true</tt> to not fire clear event.
+ */
+ removeAll : function(silent){
+ var items = [];
+ this.each(function(rec){
+ items.push(rec);
+ });
+ this.clearData();
+ if(this.snapshot){
+ this.snapshot.clear();
+ }
+ if(this.pruneModifiedRecords){
+ this.modified = [];
+ }
+ if (silent !== true) { // <-- prevents write-actions when we just want to clear a store.
+ this.fireEvent('clear', this, items);
+ }
+ },
+
+ // private
+ onClear: function(store, records){
+ Ext.each(records, function(rec, index){
+ this.destroyRecord(this, rec, index);
+ }, this);
+ },
+
+ /**
+ * Inserts Records into the Store at the given index and fires the {@link #add} event.
+ * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
+ * @param {Number} index The start index at which to insert the passed Records.
+ * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
+ */
+ insert : function(index, records){
+ records = [].concat(records);
+ for(var i = 0, len = records.length; i < len; i++){
+ this.data.insert(index, records[i]);
+ records[i].join(this);
+ }
+ if(this.snapshot){
+ this.snapshot.addAll(records);
+ }
+ this.fireEvent('add', this, records, index);
+ },
+
+ /**
+ * Get the index within the cache of the passed Record.
+ * @param {Ext.data.Record} record The Ext.data.Record object to find.
+ * @return {Number} The index of the passed Record. Returns -1 if not found.
+ */
+ indexOf : function(record){
+ return this.data.indexOf(record);
+ },
+
+ /**
+ * Get the index within the cache of the Record with the passed id.
+ * @param {String} id The id of the Record to find.
+ * @return {Number} The index of the Record. Returns -1 if not found.
+ */
+ indexOfId : function(id){
+ return this.data.indexOfKey(id);
+ },
+
+ /**
+ * Get the Record with the specified id.
+ * @param {String} id The id of the Record to find.
+ * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
+ */
+ getById : function(id){
+ return (this.snapshot || this.data).key(id);
+ },
+
+ /**
+ * Get the Record at the specified index.
+ * @param {Number} index The index of the Record to find.
+ * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
+ */
+ getAt : function(index){
+ return this.data.itemAt(index);
+ },
+
+ /**
+ * Returns a range of Records between specified indices.
+ * @param {Number} startIndex (optional) The starting index (defaults to 0)
+ * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
+ * @return {Ext.data.Record[]} An array of Records
+ */
+ getRange : function(start, end){
+ return this.data.getRange(start, end);
+ },
+
+ // private
+ storeOptions : function(o){
+ o = Ext.apply({}, o);
+ delete o.callback;
+ delete o.scope;
+ this.lastOptions = o;
+ },
+
+ // private
+ clearData: function(){
+ this.data.each(function(rec) {
+ rec.join(null);
+ });
+ this.data.clear();
+ },
+
+ /**
+ * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
+ * <br><p>Notes:</p><div class="mdetail-params"><ul>
+ * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
+ * loaded. To perform any post-processing where information from the load call is required, specify
+ * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
+ * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
+ * properties in the <code>options.params</code> property to establish the initial position within the
+ * dataset, and the number of Records to cache on each read from the Proxy.</li>
+ * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
+ * will be automatically included with the posted parameters according to the specified
+ * <code>{@link #paramNames}</code>.</li>
+ * </ul></div>
+ * @param {Object} options An object containing properties which control loading options:<ul>
+ * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
+ * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
+ * <code>{@link #baseParams}</code> of the same name.</p>
+ * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
+ * <li><b>callback</b> : Function<div class="sub-desc"><p>A function to be called after the Records
+ * have been loaded. The callback is called after the load event is fired, and is passed the following arguments:<ul>
+ * <li>r : Ext.data.Record[] An Array of Records loaded.</li>
+ * <li>options : Options object from the load call.</li>
+ * <li>success : Boolean success indicator.</li></ul></p></div></li>
+ * <li><b>scope</b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
+ * to the Store object)</p></div></li>
+ * <li><b>add</b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
+ * replace the current cache. <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
+ * </ul>
+ * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
+ * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
+ */
+ load : function(options) {
+ options = Ext.apply({}, options);
+ this.storeOptions(options);
+ if(this.sortInfo && this.remoteSort){
+ var pn = this.paramNames;
+ options.params = Ext.apply({}, options.params);
+ options.params[pn.sort] = this.sortInfo.field;
+ options.params[pn.dir] = this.sortInfo.direction;
+ }
+ try {
+ return this.execute('read', null, options); // <-- null represents rs. No rs for load actions.
+ } catch(e) {
+ this.handleException(e);
+ return false;
+ }
+ },
+
+ /**
+ * updateRecord Should not be used directly. This method will be called automatically if a Writer is set.
+ * Listens to 'update' event.
+ * @param {Object} store
+ * @param {Object} record
+ * @param {Object} action
+ * @private
+ */
+ updateRecord : function(store, record, action) {
+ if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid()))) {
+ this.save();
+ }
+ },
+
+ /**
+ * Should not be used directly. Store#add will call this automatically if a Writer is set
+ * @param {Object} store
+ * @param {Object} rs
+ * @param {Object} index
+ * @private
+ */
+ createRecords : function(store, rs, index) {
+ for (var i = 0, len = rs.length; i < len; i++) {
+ if (rs[i].phantom && rs[i].isValid()) {
+ rs[i].markDirty(); // <-- Mark new records dirty
+ this.modified.push(rs[i]); // <-- add to modified
+ }
+ }
+ if (this.autoSave === true) {
+ this.save();
+ }
+ },
+
+ /**
+ * Destroys a Record. Should not be used directly. It's called by Store#remove if a Writer is set.
+ * @param {Store} store this
+ * @param {Ext.data.Record} record
+ * @param {Number} index
+ * @private
+ */
+ destroyRecord : function(store, record, index) {
+ if (this.modified.indexOf(record) != -1) { // <-- handled already if @cfg pruneModifiedRecords == true
+ this.modified.remove(record);
+ }
+ if (!record.phantom) {
+ this.removed.push(record);
+
+ // since the record has already been removed from the store but the server request has not yet been executed,
+ // must keep track of the last known index this record existed. If a server error occurs, the record can be
+ // put back into the store. @see Store#createCallback where the record is returned when response status === false
+ record.lastIndex = index;
+
+ if (this.autoSave === true) {
+ this.save();
+ }
+ }
+ },
+
+ /**
+ * This method should generally not be used directly. This method is called internally
+ * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
+ * {@link #remove}, or {@link #update} events fire.
+ * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
+ * @param {Record/Record[]} rs
+ * @param {Object} options
+ * @throws Error
+ * @private
+ */
+ execute : function(action, rs, options, /* private */ batch) {
+ // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
+ if (!Ext.data.Api.isAction(action)) {
+ throw new Ext.data.Api.Error('execute', action);
+ }
+ // make sure options has a fresh, new params hash
+ options = Ext.applyIf(options||{}, {
+ params: {}
+ });
+ if(batch !== undefined){
+ this.addToBatch(batch);
+ }
+ // have to separate before-events since load has a different signature than create,destroy and save events since load does not
+ // include the rs (record resultset) parameter. Capture return values from the beforeaction into doRequest flag.
+ var doRequest = true;
+
+ if (action === 'read') {
+ doRequest = this.fireEvent('beforeload', this, options);
+ Ext.applyIf(options.params, this.baseParams);
+ }
+ else {
+ // if Writer is configured as listful, force single-record rs to be [{}] instead of {}
+ // TODO Move listful rendering into DataWriter where the @cfg is defined. Should be easy now.
+ if (this.writer.listful === true && this.restful !== true) {
+ rs = (Ext.isArray(rs)) ? rs : [rs];
+ }
+ // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
+ else if (Ext.isArray(rs) && rs.length == 1) {
+ rs = rs.shift();
+ }
+ // Write the action to options.params
+ if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
+ this.writer.apply(options.params, this.baseParams, action, rs);
+ }
+ }
+ if (doRequest !== false) {
+ // Send request to proxy.
+ if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
+ options.params.xaction = action; // <-- really old, probaby unecessary.
+ }
+ // Note: Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.
+ // We'll flip it now and send the value into DataProxy#request, since it's the value which maps to
+ // the user's configured DataProxy#api
+ // TODO Refactor all Proxies to accept an instance of Ext.data.Request (not yet defined) instead of this looooooong list
+ // of params. This method is an artifact from Ext2.
+ this.proxy.request(Ext.data.Api.actions[action], rs, options.params, this.reader, this.createCallback(action, rs, batch), this, options);
+ }
+ return doRequest;
+ },
+
+ /**
+ * Saves all pending changes to the store. If the commensurate Ext.data.Api.actions action is not configured, then
+ * the configured <code>{@link #url}</code> will be used.
+ * <pre>
+ * change url
+ * --------------- --------------------
+ * removed records Ext.data.Api.actions.destroy
+ * phantom records Ext.data.Api.actions.create
+ * {@link #getModifiedRecords modified records} Ext.data.Api.actions.update
+ * </pre>
+ * @TODO: Create extensions of Error class and send associated Record with thrown exceptions.
+ * e.g.: Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
+ * @return {Number} batch Returns a number to uniquely identify the "batch" of saves occurring. -1 will be returned
+ * if there are no items to save or the save was cancelled.
+ */
+ save : function() {
+ if (!this.writer) {
+ throw new Ext.data.Store.Error('writer-undefined');
+ }
+
+ var queue = [],
+ len,
+ trans,
+ batch,
+ data = {};
+ // DESTROY: First check for removed records. Records in this.removed are guaranteed non-phantoms. @see Store#remove
+ if(this.removed.length){
+ queue.push(['destroy', this.removed]);
+ }
+
+ // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
+ var rs = [].concat(this.getModifiedRecords());
+ if(rs.length){
+ // CREATE: Next check for phantoms within rs. splice-off and execute create.
+ var phantoms = [];
+ for(var i = rs.length-1; i >= 0; i--){
+ if(rs[i].phantom === true){
+ var rec = rs.splice(i, 1).shift();
+ if(rec.isValid()){
+ phantoms.push(rec);
+ }
+ }else if(!rs[i].isValid()){ // <-- while we're here, splice-off any !isValid real records
+ rs.splice(i,1);
+ }
+ }
+ // If we have valid phantoms, create them...
+ if(phantoms.length){
+ queue.push(['create', phantoms]);
+ }
+
+ // UPDATE: And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
+ if(rs.length){
+ queue.push(['update', rs]);
+ }
+ }
+ len = queue.length;
+ if(len){
+ batch = ++this.batchCounter;
+ for(var i = 0; i < len; ++i){
+ trans = queue[i];
+ data[trans[0]] = trans[1];
+ }
+ if(this.fireEvent('beforesave', this, data) !== false){
+ for(var i = 0; i < len; ++i){
+ trans = queue[i];
+ this.doTransaction(trans[0], trans[1], batch);
+ }
+ return batch;
+ }
+ }
+ return -1;
+ },
+
+ // private. Simply wraps call to Store#execute in try/catch. Defers to Store#handleException on error. Loops if batch: false
+ doTransaction : function(action, rs, batch) {
+ function transaction(records) {
+ try{
+ this.execute(action, records, undefined, batch);
+ }catch (e){
+ this.handleException(e);
+ }
+ }
+ if(this.batch === false){
+ for(var i = 0, len = rs.length; i < len; i++){
+ transaction.call(this, rs[i]);
+ }
+ }else{
+ transaction.call(this, rs);
+ }
+ },
+
+ // private
+ addToBatch : function(batch){
+ var b = this.batches,
+ key = this.batchKey + batch,
+ o = b[key];
+
+ if(!o){
+ b[key] = o = {
+ id: batch,
+ count: 0,
+ data: {}
+ };
+ }
+ ++o.count;
+ },
+
+ removeFromBatch : function(batch, action, data){
+ var b = this.batches,
+ key = this.batchKey + batch,
+ o = b[key],
+ data,
+ arr;
+
+
+ if(o){
+ arr = o.data[action] || [];
+ o.data[action] = arr.concat(data);
+ if(o.count === 1){
+ data = o.data;
+ delete b[key];
+ this.fireEvent('save', this, batch, data);
+ }else{
+ --o.count;
+ }
+ }
+ },
+
+ // @private callback-handler for remote CRUD actions
+ // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
+ createCallback : function(action, rs, batch) {
+ var actions = Ext.data.Api.actions;
+ return (action == 'read') ? this.loadRecords : function(data, response, success) {
+ // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
+ this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, [].concat(data));
+ // If success === false here, exception will have been called in DataProxy
+ if (success === true) {
+ this.fireEvent('write', this, action, data, response, rs);
+ }
+ this.removeFromBatch(batch, action, data);
+ };
+ },
+
+ // Clears records from modified array after an exception event.
+ // NOTE: records are left marked dirty. Do we want to commit them even though they were not updated/realized?
+ // TODO remove this method?
+ clearModified : function(rs) {
+ if (Ext.isArray(rs)) {
+ for (var n=rs.length-1;n>=0;n--) {
+ this.modified.splice(this.modified.indexOf(rs[n]), 1);
+ }
+ } else {
+ this.modified.splice(this.modified.indexOf(rs), 1);
+ }
+ },
+
+ // remap record ids in MixedCollection after records have been realized. @see Store#onCreateRecords, @see DataReader#realize
+ reMap : function(record) {
+ if (Ext.isArray(record)) {
+ for (var i = 0, len = record.length; i < len; i++) {
+ this.reMap(record[i]);
+ }
+ } else {
+ delete this.data.map[record._phid];
+ this.data.map[record.id] = record;
+ var index = this.data.keys.indexOf(record._phid);
+ this.data.keys.splice(index, 1, record.id);
+ delete record._phid;
+ }
+ },
+
+ // @protected onCreateRecord proxy callback for create action
+ onCreateRecords : function(success, rs, data) {
+ if (success === true) {
+ try {
+ this.reader.realize(rs, data);
+ this.reMap(rs);
+ }
+ catch (e) {
+ this.handleException(e);
+ if (Ext.isArray(rs)) {
+ // Recurse to run back into the try {}. DataReader#realize splices-off the rs until empty.
+ this.onCreateRecords(success, rs, data);
+ }
+ }
+ }
+ },
+
+ // @protected, onUpdateRecords proxy callback for update action
+ onUpdateRecords : function(success, rs, data) {
+ if (success === true) {
+ try {
+ this.reader.update(rs, data);
+ } catch (e) {
+ this.handleException(e);
+ if (Ext.isArray(rs)) {
+ // Recurse to run back into the try {}. DataReader#update splices-off the rs until empty.
+ this.onUpdateRecords(success, rs, data);
+ }
+ }
+ }
+ },
+
+ // @protected onDestroyRecords proxy callback for destroy action
+ onDestroyRecords : function(success, rs, data) {
+ // splice each rec out of this.removed
+ rs = (rs instanceof Ext.data.Record) ? [rs] : [].concat(rs);
+ for (var i=0,len=rs.length;i<len;i++) {
+ this.removed.splice(this.removed.indexOf(rs[i]), 1);
+ }
+ if (success === false) {
+ // put records back into store if remote destroy fails.
+ // @TODO: Might want to let developer decide.
+ for (i=rs.length-1;i>=0;i--) {
+ this.insert(rs[i].lastIndex, rs[i]); // <-- lastIndex set in Store#destroyRecord
+ }
+ }
+ },
+
+ // protected handleException. Possibly temporary until Ext framework has an exception-handler.
+ handleException : function(e) {
+ // @see core/Error.js
+ Ext.handleError(e);
+ },
+
+ /**
+ * <p>Reloads the Record cache from the configured Proxy using the configured
+ * {@link Ext.data.Reader Reader} and the options from the last load operation
+ * performed.</p>
+ * <p><b>Note</b>: see the Important note in {@link #load}.</p>
+ * @param {Object} options <p>(optional) An <tt>Object</tt> containing
+ * {@link #load loading options} which may override the {@link #lastOptions options}
+ * used in the last {@link #load} operation. See {@link #load} for details
+ * (defaults to <tt>null</tt>, in which case the {@link #lastOptions} are
+ * used).</p>
+ * <br><p>To add new params to the existing params:</p><pre><code>
+lastOptions = myStore.lastOptions;
+Ext.apply(lastOptions.params, {
+ myNewParam: true
+});
+myStore.reload(lastOptions);
+ * </code></pre>
+ */
+ reload : function(options){
+ this.load(Ext.applyIf(options||{}, this.lastOptions));
+ },
+
+ // private
+ // Called as a callback by the Reader during a load operation.
+ loadRecords : function(o, options, success){
+ if (this.isDestroyed === true) {
+ return;
+ }
+ if(!o || success === false){
+ if(success !== false){
+ this.fireEvent('load', this, [], options);
+ }
+ if(options.callback){
+ options.callback.call(options.scope || this, [], options, false, o);
+ }
+ return;
+ }
+ var r = o.records, t = o.totalRecords || r.length;
+ if(!options || options.add !== true){
+ if(this.pruneModifiedRecords){
+ this.modified = [];
+ }
+ for(var i = 0, len = r.length; i < len; i++){
+ r[i].join(this);
+ }
+ if(this.snapshot){
+ this.data = this.snapshot;
+ delete this.snapshot;
+ }
+ this.clearData();
+ this.data.addAll(r);
+ this.totalLength = t;
+ this.applySort();
+ this.fireEvent('datachanged', this);
+ }else{
+ this.totalLength = Math.max(t, this.data.length+r.length);
+ this.add(r);
+ }
+ this.fireEvent('load', this, r, options);
+ if(options.callback){
+ options.callback.call(options.scope || this, r, options, true);
+ }
+ },
+
+ /**
+ * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
+ * which understands the format of the data must have been configured in the constructor.
+ * @param {Object} data The data block from which to read the Records. The format of the data expected
+ * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
+ * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
+ * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
+ * the existing cache.
+ * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
+ * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
+ * new, unique ids will be added.
+ */
+ loadData : function(o, append){
+ var r = this.reader.readRecords(o);
+ this.loadRecords(r, {add: append}, true);
+ },
+
+ /**
+ * Gets the number of cached records.
+ * <p>If using paging, this may not be the total size of the dataset. If the data object
+ * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
+ * the dataset size. <b>Note</b>: see the Important note in {@link #load}.</p>
+ * @return {Number} The number of Records in the Store's cache.
+ */
+ getCount : function(){
+ return this.data.length || 0;
+ },
+
+ /**
+ * Gets the total number of records in the dataset as returned by the server.
+ * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
+ * must contain the dataset size. For remote data sources, the value for this property
+ * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
+ * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
+ * <b>Note</b>: see the Important note in {@link #load}.</p>
+ * @return {Number} The number of Records as specified in the data object passed to the Reader
+ * by the Proxy.
+ * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
+ */
+ getTotalCount : function(){
+ return this.totalLength || 0;
+ },
+
+ /**
+ * Returns an object describing the current sort state of this Store.
+ * @return {Object} The sort state of the Store. An object with two properties:<ul>
+ * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
+ * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
+ * </ul>
+ * See <tt>{@link #sortInfo}</tt> for additional details.
+ */
+ getSortState : function(){
+ return this.sortInfo;
+ },
+
+ /**
+ * @private
+ * Invokes sortData if we have sortInfo to sort on and are not sorting remotely
+ */
+ applySort : function(){
+ if ((this.sortInfo || this.multiSortInfo) && !this.remoteSort) {
+ this.sortData();
+ }
+ },
+
+ /**
+ * @private
+ * Performs the actual sorting of data. This checks to see if we currently have a multi sort or not. It applies
+ * each sorter field/direction pair in turn by building an OR'ed master sorting function and running it against
+ * the full dataset
+ */
+ sortData : function() {
+ var sortInfo = this.hasMultiSort ? this.multiSortInfo : this.sortInfo,
+ direction = sortInfo.direction || "ASC",
+ sorters = sortInfo.sorters,
+ sortFns = [];
+
+ //if we just have a single sorter, pretend it's the first in an array
+ if (!this.hasMultiSort) {
+ sorters = [{direction: direction, field: sortInfo.field}];
+ }
+
+ //create a sorter function for each sorter field/direction combo
+ for (var i=0, j = sorters.length; i < j; i++) {
+ sortFns.push(this.createSortFunction(sorters[i].field, sorters[i].direction));
+ }
+
+ if (sortFns.length == 0) {
+ return;
+ }
+
+ //the direction modifier is multiplied with the result of the sorting functions to provide overall sort direction
+ //(as opposed to direction per field)
+ var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
+
+ //create a function which ORs each sorter together to enable multi-sort
+ var fn = function(r1, r2) {
+ var result = sortFns[0].call(this, r1, r2);
+
+ //if we have more than one sorter, OR any additional sorter functions together
+ if (sortFns.length > 1) {
+ for (var i=1, j = sortFns.length; i < j; i++) {
+ result = result || sortFns[i].call(this, r1, r2);
+ }
+ }
+
+ return directionModifier * result;
+ };
+
+ //sort the data
+ this.data.sort(direction, fn);
+ if (this.snapshot && this.snapshot != this.data) {
+ this.snapshot.sort(direction, fn);
+ }
+ },
+
+ /**
+ * Creates and returns a function which sorts an array by the given field and direction
+ * @param {String} field The field to create the sorter for
+ * @param {String} direction The direction to sort by (defaults to "ASC")
+ * @return {Function} A function which sorts by the field/direction combination provided
+ */
+ createSortFunction: function(field, direction) {
+ direction = direction || "ASC";
+ var directionModifier = direction.toUpperCase() == "DESC" ? -1 : 1;
+
+ var sortType = this.fields.get(field).sortType;
+
+ //create a comparison function. Takes 2 records, returns 1 if record 1 is greater,
+ //-1 if record 2 is greater or 0 if they are equal
+ return function(r1, r2) {
+ var v1 = sortType(r1.data[field]),
+ v2 = sortType(r2.data[field]);
+
+ return directionModifier * (v1 > v2 ? 1 : (v1 < v2 ? -1 : 0));
+ };
+ },
+
+ /**
+ * Sets the default sort column and order to be used by the next {@link #load} operation.
+ * @param {String} fieldName The name of the field to sort by.
+ * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
+ */
+ setDefaultSort : function(field, dir) {
+ dir = dir ? dir.toUpperCase() : 'ASC';
+ this.sortInfo = {field: field, direction: dir};
+ this.sortToggle[field] = dir;
+ },
+
+ /**
+ * Sort the Records.
+ * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
+ * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
+ * This function accepts two call signatures - pass in a field name as the first argument to sort on a single
+ * field, or pass in an array of sort configuration objects to sort by multiple fields.
+ * Single sort example:
+ * store.sort('name', 'ASC');
+ * Multi sort example:
+ * store.sort([
+ * {
+ * field : 'name',
+ * direction: 'ASC'
+ * },
+ * {
+ * field : 'salary',
+ * direction: 'DESC'
+ * }
+ * ], 'ASC');
+ * In this second form, the sort configs are applied in order, with later sorters sorting within earlier sorters' results.
+ * For example, if two records with the same name are present they will also be sorted by salary if given the sort configs
+ * above. Any number of sort configs can be added.
+ * @param {String/Array} fieldName The name of the field to sort by, or an array of ordered sort configs
+ * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
+ */
+ sort : function(fieldName, dir) {
+ if (Ext.isArray(arguments[0])) {
+ return this.multiSort.call(this, fieldName, dir);
+ } else {
+ return this.singleSort(fieldName, dir);
+ }
+ },
+
+ /**
+ * Sorts the store contents by a single field and direction. This is called internally by {@link sort} and would
+ * not usually be called manually
+ * @param {String} fieldName The name of the field to sort by.
+ * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
+ */
+ singleSort: function(fieldName, dir) {
+ var field = this.fields.get(fieldName);
+ if (!field) return false;
+
+ var name = field.name,
+ sortInfo = this.sortInfo || null,
+ sortToggle = this.sortToggle ? this.sortToggle[name] : null;
+
+ if (!dir) {
+ if (sortInfo && sortInfo.field == name) { // toggle sort dir
+ dir = (this.sortToggle[name] || 'ASC').toggle('ASC', 'DESC');
+ } else {
+ dir = field.sortDir;
+ }
+ }
+
+ this.sortToggle[name] = dir;
+ this.sortInfo = {field: name, direction: dir};
+ this.hasMultiSort = false;
+
+ if (this.remoteSort) {
+ if (!this.load(this.lastOptions)) {
+ if (sortToggle) {
+ this.sortToggle[name] = sortToggle;
+ }
+ if (sortInfo) {
+ this.sortInfo = sortInfo;
+ }
+ }
+ } else {
+ this.applySort();
+ this.fireEvent('datachanged', this);
+ }
+ },
+
+ /**
+ * Sorts the contents of this store by multiple field/direction sorters. This is called internally by {@link sort}
+ * and would not usually be called manually.
+ * Multi sorting only currently applies to local datasets - multiple sort data is not currently sent to a proxy
+ * if remoteSort is used.
+ * @param {Array} sorters Array of sorter objects (field and direction)
+ * @param {String} direction Overall direction to sort the ordered results by (defaults to "ASC")
+ */
+ multiSort: function(sorters, direction) {
+ this.hasMultiSort = true;
+ direction = direction || "ASC";
+
+ //toggle sort direction
+ if (this.multiSortInfo && direction == this.multiSortInfo.direction) {
+ direction = direction.toggle("ASC", "DESC");
+ }
+
+ /**
+ * @property multiSortInfo
+ * @type Object
+ * Object containing overall sort direction and an ordered array of sorter configs used when sorting on multiple fields
+ */
+ this.multiSortInfo = {
+ sorters : sorters,
+ direction: direction
+ };
+
+ if (this.remoteSort) {
+ this.singleSort(sorters[0].field, sorters[0].direction);
+
+ } else {
+ this.applySort();
+ this.fireEvent('datachanged', this);
+ }
+ },
+
+ /**
+ * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
+ * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
+ * Returning <tt>false</tt> aborts and exits the iteration.
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
+ * Defaults to the current {@link Ext.data.Record Record} in the iteration.
+ */
+ each : function(fn, scope){
+ this.data.each(fn, scope);
+ },
+
+ /**
+ * Gets all {@link Ext.data.Record records} modified since the last commit. Modified records are
+ * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
+ * included. See also <tt>{@link #pruneModifiedRecords}</tt> and
+ * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
+ * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
+ * modifications. To obtain modified fields within a modified record see
+ *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
+ */
+ getModifiedRecords : function(){
+ return this.modified;
+ },
+
+ /**
+ * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
+ * and <tt>end</tt> and returns the result.
+ * @param {String} property A field in each record
+ * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
+ * @param {Number} end (optional) The last record index to include (defaults to length - 1)
+ * @return {Number} The sum
+ */
+ sum : function(property, start, end){
+ var rs = this.data.items, v = 0;
+ start = start || 0;
+ end = (end || end === 0) ? end : rs.length-1;
+
+ for(var i = start; i <= end; i++){
+ v += (rs[i].data[property] || 0);
+ }
+ return v;
+ },
+
+ /**
+ * @private
+ * Returns a filter function used to test a the given property's value. Defers most of the work to
+ * Ext.util.MixedCollection's createValueMatcher function
+ * @param {String} property The property to create the filter function for
+ * @param {String/RegExp} value The string/regex to compare the property value to
+ * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
+ * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
+ * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
+ */
+ createFilterFn : function(property, value, anyMatch, caseSensitive, exactMatch){
+ if(Ext.isEmpty(value, false)){
+ return false;
+ }
+ value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
+ return function(r) {
+ return value.test(r.data[property]);
+ };
+ },
+
+ /**
+ * Given an array of filter functions (each with optional scope), constructs and returns a single function that returns
+ * the result of all of the filters ANDed together
+ * @param {Array} filters The array of filter objects (each object should contain an 'fn' and optional scope)
+ * @return {Function} The multiple filter function
+ */
+ createMultipleFilterFn: function(filters) {
+ return function(record) {
+ var isMatch = true;
+
+ for (var i=0, j = filters.length; i < j; i++) {
+ var filter = filters[i],
+ fn = filter.fn,
+ scope = filter.scope;
+
+ isMatch = isMatch && fn.call(scope, record);
+ }
+
+ return isMatch;
+ };
+ },
+
+ /**
+ * Filter the {@link Ext.data.Record records} by a specified property. Alternatively, pass an array of filter
+ * options to filter by more than one property.
+ * Single filter example:
+ * store.filter('name', 'Ed', true, true); //finds all records containing the substring 'Ed'
+ * Multiple filter example:
+ * store.filter([
+ * {
+ * property : 'name',
+ * value : 'Ed',
+ * anyMatch : true, //optional, defaults to true
+ * caseSensitive: true //optional, defaults to true
+ * },
+ *
+ * //filter functions can also be passed
+ * {
+ * fn : function(record) {
+ * return record.get('age') == 24
+ * },
+ * scope: this
+ * }
+ * ]);
+ * @param {String|Array} field A field on your records, or an array containing multiple filter options
+ * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
+ * against the field.
+ * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
+ * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
+ * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false. Ignored if anyMatch is true.
+ */
+ filter : function(property, value, anyMatch, caseSensitive, exactMatch){
+ //we can accept an array of filter objects, or a single filter object - normalize them here
+ if (Ext.isObject(property)) {
+ property = [property];
+ }
+
+ if (Ext.isArray(property)) {
+ var filters = [];
+
+ //normalize the filters passed into an array of filter functions
+ for (var i=0, j = property.length; i < j; i++) {
+ var filter = property[i],
+ func = filter.fn,
+ scope = filter.scope || this;
+
+ //if we weren't given a filter function, construct one now
+ if (!Ext.isFunction(func)) {
+ func = this.createFilterFn(filter.property, filter.value, filter.anyMatch, filter.caseSensitive, filter.exactMatch);
+ }
+
+ filters.push({fn: func, scope: scope});
+ }
+
+ var fn = this.createMultipleFilterFn(filters);
+ } else {
+ //classic single property filter
+ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
+ }
+
+ return fn ? this.filterBy(fn) : this.clearFilter();
+ },
+
+ /**
+ * Filter by a function. The specified function will be called for each
+ * Record in this Store. If the function returns <tt>true</tt> the Record is included,
+ * otherwise it is filtered out.
+ * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
+ * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
+ * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
+ * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
+ * </ul>
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
+ */
+ filterBy : function(fn, scope){
+ this.snapshot = this.snapshot || this.data;
+ this.data = this.queryBy(fn, scope||this);
+ this.fireEvent('datachanged', this);
+ },
+
+ /**
+ * Revert to a view of the Record cache with no filtering applied.
+ * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
+ * {@link #datachanged} event.
+ */
+ clearFilter : function(suppressEvent){
+ if(this.isFiltered()){
+ this.data = this.snapshot;
+ delete this.snapshot;
+ if(suppressEvent !== true){
+ this.fireEvent('datachanged', this);
+ }
+ }
+ },
+
+ /**
+ * Returns true if this store is currently filtered
+ * @return {Boolean}
+ */
+ isFiltered : function(){
+ return !!this.snapshot && this.snapshot != this.data;
+ },
+
+ /**
+ * Query the records by a specified property.
+ * @param {String} field A field on your records
+ * @param {String/RegExp} value Either a string that the field
+ * should begin with, or a RegExp to test against the field.
+ * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
+ * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
+ * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
+ */
+ query : function(property, value, anyMatch, caseSensitive){
+ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
+ return fn ? this.queryBy(fn) : this.data.clone();
+ },
+
+ /**
+ * Query the cached records in this Store using a filtering function. The specified function
+ * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
+ * included in the results.
+ * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
+ * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
+ * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
+ * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
+ * </ul>
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
+ * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
+ **/
+ queryBy : function(fn, scope){
+ var data = this.snapshot || this.data;
+ return data.filterBy(fn, scope||this);
+ },
+
+ /**
+ * Finds the index of the first matching Record in this store by a specific field value.
+ * @param {String} fieldName The name of the Record field to test.
+ * @param {String/RegExp} value Either a string that the field value
+ * should begin with, or a RegExp to test against the field.
+ * @param {Number} startIndex (optional) The index to start searching at
+ * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
+ * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
+ * @return {Number} The matched index or -1
+ */
+ find : function(property, value, start, anyMatch, caseSensitive){
+ var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
+ return fn ? this.data.findIndexBy(fn, null, start) : -1;
+ },
+
+ /**
+ * Finds the index of the first matching Record in this store by a specific field value.
+ * @param {String} fieldName The name of the Record field to test.
+ * @param {Mixed} value The value to match the field against.
+ * @param {Number} startIndex (optional) The index to start searching at
+ * @return {Number} The matched index or -1
+ */
+ findExact: function(property, value, start){
+ return this.data.findIndexBy(function(rec){
+ return rec.get(property) === value;
+ }, this, start);
+ },
+
+ /**
+ * Find the index of the first matching Record in this Store by a function.
+ * If the function returns <tt>true</tt> it is considered a match.
+ * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
+ * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
+ * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
+ * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
+ * </ul>
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
+ * @param {Number} startIndex (optional) The index to start searching at
+ * @return {Number} The matched index or -1
+ */
+ findBy : function(fn, scope, start){
+ return this.data.findIndexBy(fn, scope, start);
+ },
+
+ /**
+ * Collects unique values for a particular dataIndex from this store.
+ * @param {String} dataIndex The property to collect
+ * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
+ * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
+ * @return {Array} An array of the unique values
+ **/
+ collect : function(dataIndex, allowNull, bypassFilter){
+ var d = (bypassFilter === true && this.snapshot) ?
+ this.snapshot.items : this.data.items;
+ var v, sv, r = [], l = {};
+ for(var i = 0, len = d.length; i < len; i++){
+ v = d[i].data[dataIndex];
+ sv = String(v);
+ if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
+ l[sv] = true;
+ r[r.length] = v;
+ }
+ }
+ return r;
+ },
+
+ // private
+ afterEdit : function(record){
+ if(this.modified.indexOf(record) == -1){
+ this.modified.push(record);
+ }
+ this.fireEvent('update', this, record, Ext.data.Record.EDIT);
+ },
+
+ // private
+ afterReject : function(record){
+ this.modified.remove(record);
+ this.fireEvent('update', this, record, Ext.data.Record.REJECT);
+ },
+
+ // private
+ afterCommit : function(record){
+ this.modified.remove(record);
+ this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
+ },
+
+ /**
+ * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
+ * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
+ * Ext.data.Record.COMMIT.
+ */
+ commitChanges : function(){
+ var m = this.modified.slice(0);
+ this.modified = [];
+ for(var i = 0, len = m.length; i < len; i++){
+ m[i].commit();
+ }
+ },
+
+ /**
+ * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
+ */
+ rejectChanges : function(){
+ var m = this.modified.slice(0);
+ this.modified = [];
+ for(var i = 0, len = m.length; i < len; i++){
+ m[i].reject();
+ }
+ var m = this.removed.slice(0).reverse();
+ this.removed = [];
+ for(var i = 0, len = m.length; i < len; i++){
+ this.insert(m[i].lastIndex||0, m[i]);
+ m[i].reject();
+ }
+ },
+
+ // private
+ onMetaChange : function(meta){
+ this.recordType = this.reader.recordType;
+ this.fields = this.recordType.prototype.fields;
+ delete this.snapshot;
+ if(this.reader.meta.sortInfo){
+ this.sortInfo = this.reader.meta.sortInfo;
+ }else if(this.sortInfo && !this.fields.get(this.sortInfo.field)){
+ delete this.sortInfo;
+ }
+ if(this.writer){
+ this.writer.meta = this.reader.meta;
+ }
+ this.modified = [];
+ this.fireEvent('metachange', this, this.reader.meta);
+ },
+
+ // private
+ findInsertIndex : function(record){
+ this.suspendEvents();
+ var data = this.data.clone();
+ this.data.add(record);
+ this.applySort();
+ var index = this.data.indexOf(record);
+ this.data = data;
+ this.resumeEvents();
+ return index;
+ },
+
+ /**
+ * Set the value for a property name in this store's {@link #baseParams}. Usage:</p><pre><code>
+myStore.setBaseParam('foo', {bar:3});
+</code></pre>
+ * @param {String} name Name of the property to assign
+ * @param {Mixed} value Value to assign the <tt>name</tt>d property
+ **/
+ setBaseParam : function (name, value){
+ this.baseParams = this.baseParams || {};
+ this.baseParams[name] = value;
+ }
+});
+
+Ext.reg('store', Ext.data.Store);
+
+/**
+ * @class Ext.data.Store.Error
+ * @extends Ext.Error
+ * Store Error extension.
+ * @param {String} name
+ */
+Ext.data.Store.Error = Ext.extend(Ext.Error, {
+ name: 'Ext.data.Store'
+});
+Ext.apply(Ext.data.Store.Error.prototype, {
+ lang: {
+ 'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'
+ }
+});
+/**
+ * @class Ext.data.Field
+ * <p>This class encapsulates the field definition information specified in the field definition objects
+ * passed to {@link Ext.data.Record#create}.</p>
+ * <p>Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
+ * and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
+ */
+Ext.data.Field = Ext.extend(Object, {
+
+ constructor : function(config){
+ if(Ext.isString(config)){
+ config = {name: config};
+ }
+ Ext.apply(this, config);
+
+ var types = Ext.data.Types,
+ st = this.sortType,
+ t;
+
+ if(this.type){
+ if(Ext.isString(this.type)){
+ this.type = Ext.data.Types[this.type.toUpperCase()] || types.AUTO;
+ }
+ }else{
+ this.type = types.AUTO;
+ }
+
+ // named sortTypes are supported, here we look them up
+ if(Ext.isString(st)){
+ this.sortType = Ext.data.SortTypes[st];
+ }else if(Ext.isEmpty(st)){
+ this.sortType = this.type.sortType;
+ }
+
+ if(!this.convert){
+ this.convert = this.type.convert;
+ }
+ },
+
+ /**
+ * @cfg {String} name
+ * The name by which the field is referenced within the Record. This is referenced by, for example,
+ * the <code>dataIndex</code> property in column definition objects passed to {@link Ext.grid.ColumnModel}.
+ * <p>Note: In the simplest case, if no properties other than <code>name</code> are required, a field
+ * definition may consist of just a String for the field name.</p>
+ */
+ /**
+ * @cfg {Mixed} type
+ * (Optional) The data type for automatic conversion from received data to the <i>stored</i> value if <code>{@link Ext.data.Field#convert convert}</code>
+ * has not been specified. This may be specified as a string value. Possible values are
+ * <div class="mdetail-params"><ul>
+ * <li>auto (Default, implies no conversion)</li>
+ * <li>string</li>
+ * <li>int</li>
+ * <li>float</li>
+ * <li>boolean</li>
+ * <li>date</li></ul></div>
+ * <p>This may also be specified by referencing a member of the {@link Ext.data.Types} class.</p>
+ * <p>Developers may create their own application-specific data types by defining new members of the
+ * {@link Ext.data.Types} class.</p>
+ */
+ /**
+ * @cfg {Function} convert
+ * (Optional) A function which converts the value provided by the Reader into an object that will be stored
+ * in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
+ * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
+ * the configured <code>{@link Ext.data.Field#defaultValue defaultValue}</code>.</div></li>
+ * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
+ * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
+ * ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
+ * </ul></div>
+ * <pre><code>
+// example of convert function
+function fullName(v, record){
+ return record.name.last + ', ' + record.name.first;
+}
+
+function location(v, record){
+ return !record.city ? '' : (record.city + ', ' + record.state);
+}
+
+var Dude = Ext.data.Record.create([
+ {name: 'fullname', convert: fullName},
+ {name: 'firstname', mapping: 'name.first'},
+ {name: 'lastname', mapping: 'name.last'},
+ {name: 'city', defaultValue: 'homeless'},
+ 'state',
+ {name: 'location', convert: location}
+]);
+
+// create the data store
+var store = new Ext.data.Store({
+ reader: new Ext.data.JsonReader(
+ {
+ idProperty: 'key',
+ root: 'daRoot',
+ totalProperty: 'total'
+ },
+ Dude // recordType
+ )
+});
+
+var myData = [
+ { key: 1,
+ name: { first: 'Fat', last: 'Albert' }
+ // notice no city, state provided in data object
+ },
+ { key: 2,
+ name: { first: 'Barney', last: 'Rubble' },
+ city: 'Bedrock', state: 'Stoneridge'
+ },
+ { key: 3,
+ name: { first: 'Cliff', last: 'Claven' },
+ city: 'Boston', state: 'MA'
+ }
+];
+ * </code></pre>
+ */
+ /**
+ * @cfg {String} dateFormat
+ * <p>(Optional) Used when converting received data into a Date when the {@link #type} is specified as <code>"date"</code>.</p>
+ * <p>A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
+ * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
+ * javascript millisecond timestamp. See {@link Date}</p>
+ */
+ dateFormat: null,
+ /**
+ * @cfg {Mixed} defaultValue
+ * (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b>
+ * when the item referenced by the <code>{@link Ext.data.Field#mapping mapping}</code> does not exist in the data
+ * object (i.e. undefined). (defaults to "")
+ */
+ defaultValue: "",
+ /**
+ * @cfg {String/Number} mapping
+ * <p>(Optional) A path expression for use by the {@link Ext.data.DataReader} implementation
+ * that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object.
+ * If the path expression is the same as the field name, the mapping may be omitted.</p>
+ * <p>The form of the mapping expression depends on the Reader being used.</p>
+ * <div class="mdetail-params"><ul>
+ * <li>{@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript
+ * expression to reference the data from an element of the data item's {@link Ext.data.JsonReader#root root} Array. Defaults to the field name.</div></li>
+ * <li>{@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
+ * item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li>
+ * <li>{@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index
+ * of the field's value. Defaults to the field specification's Array position.</div></li>
+ * </ul></div>
+ * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
+ * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
+ * return the desired data.</p>
+ */
+ mapping: null,
+ /**
+ * @cfg {Function} sortType
+ * (Optional) A function which converts a Field's value to a comparable value in order to ensure
+ * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
+ * sort example:<pre><code>
+// current sort after sort we want
+// +-+------+ +-+------+
+// |1|First | |1|First |
+// |2|Last | |3|Second|
+// |3|Second| |2|Last |
+// +-+------+ +-+------+
+
+sortType: function(value) {
+ switch (value.toLowerCase()) // native toLowerCase():
+ {
+ case 'first': return 1;
+ case 'second': return 2;
+ default: return 3;
+ }
+}
+ * </code></pre>
+ */
+ sortType : null,
+ /**
+ * @cfg {String} sortDir
+ * (Optional) Initial direction to sort (<code>"ASC"</code> or <code>"DESC"</code>). Defaults to
+ * <code>"ASC"</code>.
+ */
+ sortDir : "ASC",
+ /**
+ * @cfg {Boolean} allowBlank
+ * (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <code>true</code>.
+ * An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}
+ * to evaluate to <code>false</code>.
+ */
+ allowBlank : true
+});
+/**
+ * @class Ext.data.DataReader
+ * Abstract base class for reading structured data from a data source and converting
+ * it into an object containing {@link Ext.data.Record} objects and metadata for use
+ * by an {@link Ext.data.Store}. This class is intended to be extended and should not
+ * be created directly. For existing implementations, see {@link Ext.data.ArrayReader},
+ * {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.
+ * @constructor Create a new DataReader
+ * @param {Object} meta Metadata configuration options (implementation-specific).
+ * @param {Array/Object} recordType
+ * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
+ * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
+ * constructor created using {@link Ext.data.Record#create}.</p>
+ */
+Ext.data.DataReader = function(meta, recordType){
+ /**
+ * This DataReader's configured metadata as passed to the constructor.
+ * @type Mixed
+ * @property meta
+ */
+ this.meta = meta;
+ /**
+ * @cfg {Array/Object} fields
+ * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
+ * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
+ * constructor created from {@link Ext.data.Record#create}.</p>
+ */
+ this.recordType = Ext.isArray(recordType) ?
+ Ext.data.Record.create(recordType) : recordType;
+
+ // if recordType defined make sure extraction functions are defined
+ if (this.recordType){
+ this.buildExtractors();
+ }
+};
+
+Ext.data.DataReader.prototype = {
+ /**
+ * @cfg {String} messageProperty [undefined] Optional name of a property within a server-response that represents a user-feedback message.
+ */
+ /**
+ * Abstract method created in extension's buildExtractors impl.
+ */
+ getTotal: Ext.emptyFn,
+ /**
+ * Abstract method created in extension's buildExtractors impl.
+ */
+ getRoot: Ext.emptyFn,
+ /**
+ * Abstract method created in extension's buildExtractors impl.
+ */
+ getMessage: Ext.emptyFn,
+ /**
+ * Abstract method created in extension's buildExtractors impl.
+ */
+ getSuccess: Ext.emptyFn,
+ /**
+ * Abstract method created in extension's buildExtractors impl.
+ */
+ getId: Ext.emptyFn,
+ /**
+ * Abstract method, overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}
+ */
+ buildExtractors : Ext.emptyFn,
+ /**
+ * Abstract method overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}
+ */
+ extractValues : Ext.emptyFn,
+
+ /**
+ * Used for un-phantoming a record after a successful database insert. Sets the records pk along with new data from server.
+ * You <b>must</b> return at least the database pk using the idProperty defined in your DataReader configuration. The incoming
+ * data from server will be merged with the data in the local record.
+ * In addition, you <b>must</b> return record-data from the server in the same order received.
+ * Will perform a commit as well, un-marking dirty-fields. Store's "update" event will be suppressed.
+ * @param {Record/Record[]} record The phantom record to be realized.
+ * @param {Object/Object[]} data The new record data to apply. Must include the primary-key from database defined in idProperty field.
+ */
+ realize: function(rs, data){
+ if (Ext.isArray(rs)) {
+ for (var i = rs.length - 1; i >= 0; i--) {
+ // recurse
+ if (Ext.isArray(data)) {
+ this.realize(rs.splice(i,1).shift(), data.splice(i,1).shift());
+ }
+ else {
+ // weird...rs is an array but data isn't?? recurse but just send in the whole invalid data object.
+ // the else clause below will detect !this.isData and throw exception.
+ this.realize(rs.splice(i,1).shift(), data);
+ }
+ }
+ }
+ else {
+ // If rs is NOT an array but data IS, see if data contains just 1 record. If so extract it and carry on.
+ if (Ext.isArray(data) && data.length == 1) {
+ data = data.shift();
+ }
+ if (!this.isData(data)) {
+ // TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.
+ //rs.commit();
+ throw new Ext.data.DataReader.Error('realize', rs);
+ }
+ rs.phantom = false; // <-- That's what it's all about
+ rs._phid = rs.id; // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords
+ rs.id = this.getId(data);
+ rs.data = data;
+
+ rs.commit();
+ }
+ },
+
+ /**
+ * Used for updating a non-phantom or "real" record's data with fresh data from server after remote-save.
+ * If returning data from multiple-records after a batch-update, you <b>must</b> return record-data from the server in
+ * the same order received. Will perform a commit as well, un-marking dirty-fields. Store's "update" event will be
+ * suppressed as the record receives fresh new data-hash
+ * @param {Record/Record[]} rs
+ * @param {Object/Object[]} data
+ */
+ update : function(rs, data) {
+ if (Ext.isArray(rs)) {
+ for (var i=rs.length-1; i >= 0; i--) {
+ if (Ext.isArray(data)) {
+ this.update(rs.splice(i,1).shift(), data.splice(i,1).shift());
+ }
+ else {
+ // weird...rs is an array but data isn't?? recurse but just send in the whole data object.
+ // the else clause below will detect !this.isData and throw exception.
+ this.update(rs.splice(i,1).shift(), data);
+ }
+ }
+ }
+ else {
+ // If rs is NOT an array but data IS, see if data contains just 1 record. If so extract it and carry on.
+ if (Ext.isArray(data) && data.length == 1) {
+ data = data.shift();
+ }
+ if (this.isData(data)) {
+ rs.data = Ext.apply(rs.data, data);
+ }
+ rs.commit();
+ }
+ },
+
+ /**
+ * returns extracted, type-cast rows of data. Iterates to call #extractValues for each row
+ * @param {Object[]/Object} data-root from server response
+ * @param {Boolean} returnRecords [false] Set true to return instances of Ext.data.Record
+ * @private
+ */
+ extractData : function(root, returnRecords) {
+ // A bit ugly this, too bad the Record's raw data couldn't be saved in a common property named "raw" or something.
+ var rawName = (this instanceof Ext.data.JsonReader) ? 'json' : 'node';
+
+ var rs = [];
+
+ // Had to add Check for XmlReader, #isData returns true if root is an Xml-object. Want to check in order to re-factor
+ // #extractData into DataReader base, since the implementations are almost identical for JsonReader, XmlReader
+ if (this.isData(root) && !(this instanceof Ext.data.XmlReader)) {
+ root = [root];
+ }
+ var f = this.recordType.prototype.fields,
+ fi = f.items,
+ fl = f.length,
+ rs = [];
+ if (returnRecords === true) {
+ var Record = this.recordType;
+ for (var i = 0; i < root.length; i++) {
+ var n = root[i];
+ var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
+ record[rawName] = n; // <-- There's implementation of ugly bit, setting the raw record-data.
+ rs.push(record);
+ }
+ }
+ else {
+ for (var i = 0; i < root.length; i++) {
+ var data = this.extractValues(root[i], fi, fl);
+ data[this.meta.idProperty] = this.getId(root[i]);
+ rs.push(data);
+ }
+ }
+ return rs;
+ },
+
+ /**
+ * Returns true if the supplied data-hash <b>looks</b> and quacks like data. Checks to see if it has a key
+ * corresponding to idProperty defined in your DataReader config containing non-empty pk.
+ * @param {Object} data
+ * @return {Boolean}
+ */
+ isData : function(data) {
+ return (data && Ext.isObject(data) && !Ext.isEmpty(this.getId(data))) ? true : false;
+ },
+
+ // private function a store will createSequence upon
+ onMetaChange : function(meta){
+ delete this.ef;
+ this.meta = meta;
+ this.recordType = Ext.data.Record.create(meta.fields);
+ this.buildExtractors();
+ }
+};
+
+/**
+ * @class Ext.data.DataReader.Error
+ * @extends Ext.Error
+ * General error class for Ext.data.DataReader
+ */
+Ext.data.DataReader.Error = Ext.extend(Ext.Error, {
+ constructor : function(message, arg) {
+ this.arg = arg;
+ Ext.Error.call(this, message);
+ },
+ name: 'Ext.data.DataReader'
+});
+Ext.apply(Ext.data.DataReader.Error.prototype, {
+ lang : {
+ 'update': "#update received invalid data from server. Please see docs for DataReader#update and review your DataReader configuration.",
+ 'realize': "#realize was called with invalid remote-data. Please see the docs for DataReader#realize and review your DataReader configuration.",
+ 'invalid-response': "#readResponse received an invalid response from the server."
+ }
+});
+/**
+ * @class Ext.data.DataWriter
+ * <p>Ext.data.DataWriter facilitates create, update, and destroy actions between
+ * an Ext.data.Store and a server-side framework. A Writer enabled Store will
+ * automatically manage the Ajax requests to perform CRUD actions on a Store.</p>
+ * <p>Ext.data.DataWriter is an abstract base class which is intended to be extended
+ * and should not be created directly. For existing implementations, see
+ * {@link Ext.data.JsonWriter}.</p>
+ * <p>Creating a writer is simple:</p>
+ * <pre><code>
+var writer = new Ext.data.JsonWriter({
+ encode: false // <--- false causes data to be printed to jsonData config-property of Ext.Ajax#reqeust
+});
+ * </code></pre>
+ * * <p>Same old JsonReader as Ext-2.x:</p>
+ * <pre><code>
+var reader = new Ext.data.JsonReader({idProperty: 'id'}, [{name: 'first'}, {name: 'last'}, {name: 'email'}]);
+ * </code></pre>
+ *
+ * <p>The proxy for a writer enabled store can be configured with a simple <code>url</code>:</p>
+ * <pre><code>
+// Create a standard HttpProxy instance.
+var proxy = new Ext.data.HttpProxy({
+ url: 'app.php/users' // <--- Supports "provides"-type urls, such as '/users.json', '/products.xml' (Hello Rails/Merb)
+});
+ * </code></pre>
+ * <p>For finer grained control, the proxy may also be configured with an <code>API</code>:</p>
+ * <pre><code>
+// Maximum flexibility with the API-configuration
+var proxy = new Ext.data.HttpProxy({
+ api: {
+ read : 'app.php/users/read',
+ create : 'app.php/users/create',
+ update : 'app.php/users/update',
+ destroy : { // <--- Supports object-syntax as well
+ url: 'app.php/users/destroy',
+ method: "DELETE"
+ }
+ }
+});
+ * </code></pre>
+ * <p>Pulling it all together into a Writer-enabled Store:</p>
+ * <pre><code>
+var store = new Ext.data.Store({
+ proxy: proxy,
+ reader: reader,
+ writer: writer,
+ autoLoad: true,
+ autoSave: true // -- Cell-level updates.
+});
+ * </code></pre>
+ * <p>Initiating write-actions <b>automatically</b>, using the existing Ext2.0 Store/Record API:</p>
+ * <pre><code>
+var rec = store.getAt(0);
+rec.set('email', 'foo@bar.com'); // <--- Immediately initiates an UPDATE action through configured proxy.
+
+store.remove(rec); // <---- Immediately initiates a DESTROY action through configured proxy.
+ * </code></pre>
+ * <p>For <b>record/batch</b> updates, use the Store-configuration {@link Ext.data.Store#autoSave autoSave:false}</p>
+ * <pre><code>
+var store = new Ext.data.Store({
+ proxy: proxy,
+ reader: reader,
+ writer: writer,
+ autoLoad: true,
+ autoSave: false // -- disable cell-updates
+});
+
+var urec = store.getAt(0);
+urec.set('email', 'foo@bar.com');
+
+var drec = store.getAt(1);
+store.remove(drec);
+
+// Push the button!
+store.save();
+ * </code></pre>
+ * @constructor Create a new DataWriter
+ * @param {Object} meta Metadata configuration options (implementation-specific)
+ * @param {Object} recordType Either an Array of field definition objects as specified
+ * in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
+ * using {@link Ext.data.Record#create}.
+ */
+Ext.data.DataWriter = function(config){
+ Ext.apply(this, config);
+};
+Ext.data.DataWriter.prototype = {
+
+ /**
+ * @cfg {Boolean} writeAllFields
+ * <tt>false</tt> by default. Set <tt>true</tt> to have DataWriter return ALL fields of a modified
+ * record -- not just those that changed.
+ * <tt>false</tt> to have DataWriter only request modified fields from a record.
+ */
+ writeAllFields : false,
+ /**
+ * @cfg {Boolean} listful
+ * <tt>false</tt> by default. Set <tt>true</tt> to have the DataWriter <b>always</b> write HTTP params as a list,
+ * even when acting upon a single record.
+ */
+ listful : false, // <-- listful is actually not used internally here in DataWriter. @see Ext.data.Store#execute.
+
+ /**
+ * Compiles a Store recordset into a data-format defined by an extension such as {@link Ext.data.JsonWriter} or {@link Ext.data.XmlWriter} in preparation for a {@link Ext.data.Api#actions server-write action}. The first two params are similar similar in nature to {@link Ext#apply},
+ * Where the first parameter is the <i>receiver</i> of paramaters and the second, baseParams, <i>the source</i>.
+ * @param {Object} params The request-params receiver.
+ * @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
+ * @param {String} action [{@link Ext.data.Api#actions create|update|destroy}]
+ * @param {Record/Record[]} rs The recordset to write, the subject(s) of the write action.
+ */
+ apply : function(params, baseParams, action, rs) {
+ var data = [],
+ renderer = action + 'Record';
+ // TODO implement @cfg listful here
+ if (Ext.isArray(rs)) {
+ Ext.each(rs, function(rec){
+ data.push(this[renderer](rec));
+ }, this);
+ }
+ else if (rs instanceof Ext.data.Record) {
+ data = this[renderer](rs);
+ }
+ this.render(params, baseParams, data);
+ },
+
+ /**
+ * abstract method meant to be overridden by all DataWriter extensions. It's the extension's job to apply the "data" to the "params".
+ * The data-object provided to render is populated with data according to the meta-info defined in the user's DataReader config,
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Record[]} rs Store recordset
+ * @param {Object} params Http params to be sent to server.
+ * @param {Object} data object populated according to DataReader meta-data.
+ */
+ render : Ext.emptyFn,
+
+ /**
+ * @cfg {Function} updateRecord Abstract method that should be implemented in all subclasses
+ * (e.g.: {@link Ext.data.JsonWriter#updateRecord JsonWriter.updateRecord}
+ */
+ updateRecord : Ext.emptyFn,
+
+ /**
+ * @cfg {Function} createRecord Abstract method that should be implemented in all subclasses
+ * (e.g.: {@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord})
+ */
+ createRecord : Ext.emptyFn,
+
+ /**
+ * @cfg {Function} destroyRecord Abstract method that should be implemented in all subclasses
+ * (e.g.: {@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord})
+ */
+ destroyRecord : Ext.emptyFn,
+
+ /**
+ * Converts a Record to a hash, taking into account the state of the Ext.data.Record along with configuration properties
+ * related to its rendering, such as {@link #writeAllFields}, {@link Ext.data.Record#phantom phantom}, {@link Ext.data.Record#getChanges getChanges} and
+ * {@link Ext.data.DataReader#idProperty idProperty}
+ * @param {Ext.data.Record} rec The Record from which to create a hash.
+ * @param {Object} config <b>NOT YET IMPLEMENTED</b>. Will implement an exlude/only configuration for fine-control over which fields do/don't get rendered.
+ * @return {Object}
+ * @protected
+ * TODO Implement excludes/only configuration with 2nd param?
+ */
+ toHash : function(rec, config) {
+ var map = rec.fields.map,
+ data = {},
+ raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
+ m;
+ Ext.iterate(raw, function(prop, value){
+ if((m = map[prop])){
+ data[m.mapping ? m.mapping : m.name] = value;
+ }
+ });
+ // we don't want to write Ext auto-generated id to hash. Careful not to remove it on Models not having auto-increment pk though.
+ // We can tell its not auto-increment if the user defined a DataReader field for it *and* that field's value is non-empty.
+ // we could also do a RegExp here for the Ext.data.Record AUTO_ID prefix.
+ if (rec.phantom) {
+ if (rec.fields.containsKey(this.meta.idProperty) && Ext.isEmpty(rec.data[this.meta.idProperty])) {
+ delete data[this.meta.idProperty];
+ }
+ } else {
+ data[this.meta.idProperty] = rec.id
+ }
+ return data;
+ },
+
+ /**
+ * Converts a {@link Ext.data.DataWriter#toHash Hashed} {@link Ext.data.Record} to fields-array array suitable
+ * for encoding to xml via XTemplate, eg:
+<code><pre><tpl for="."><{name}>{value}</{name}</tpl></pre></code>
+ * eg, <b>non-phantom</b>:
+<code><pre>{id: 1, first: 'foo', last: 'bar'} --> [{name: 'id', value: 1}, {name: 'first', value: 'foo'}, {name: 'last', value: 'bar'}]</pre></code>
+ * {@link Ext.data.Record#phantom Phantom} records will have had their idProperty omitted in {@link #toHash} if determined to be auto-generated.
+ * Non AUTOINCREMENT pks should have been protected.
+ * @param {Hash} data Hashed by Ext.data.DataWriter#toHash
+ * @return {[Object]} Array of attribute-objects.
+ * @protected
+ */
+ toArray : function(data) {
+ var fields = [];
+ Ext.iterate(data, function(k, v) {fields.push({name: k, value: v});},this);
+ return fields;
+ }
+};/**
+ * @class Ext.data.DataProxy
+ * @extends Ext.util.Observable
+ * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.
+ * This class is intended to be extended and should not be created directly. For existing implementations,
+ * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and
+ * {@link Ext.data.MemoryProxy}.</p>
+ * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}
+ * (of the appropriate type which knows how to parse the data object) to provide a block of
+ * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>
+ * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the
+ * config object to an {@link Ext.data.Connection}.</p>
+ * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the
+ * <code>load</code> method (deprecated). See
+ * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or
+ * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>
+ * <p><b><u>Example 1</u></b></p>
+ * <pre><code>
+proxy: new Ext.data.ScriptTagProxy({
+ {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'
+}),
+ * </code></pre>
+ * <p><b><u>Example 2</u></b></p>
+ * <pre><code>
+proxy : new Ext.data.HttpProxy({
+ {@link Ext.data.Connection#method method}: 'GET',
+ {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,
+ {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}
+ {@link #api}: {
+ // all actions except the following will use above url
+ create : 'local/new.php',
+ update : 'local/update.php'
+ }
+}),
+ * </code></pre>
+ * <p>And <b>new in Ext version 3</b>, attach centralized event-listeners upon the DataProxy class itself! This is a great place
+ * to implement a <i>messaging system</i> to centralize your application's user-feedback and error-handling.</p>
+ * <pre><code>
+// Listen to all "beforewrite" event fired by all proxies.
+Ext.data.DataProxy.on('beforewrite', function(proxy, action) {
+ console.log('beforewrite: ', action);
+});
+
+// Listen to "write" event fired by all proxies
+Ext.data.DataProxy.on('write', function(proxy, action, data, res, rs) {
+ console.info('write: ', action);
+});
+
+// Listen to "exception" event fired by all proxies
+Ext.data.DataProxy.on('exception', function(proxy, type, action) {
+ console.error(type + action + ' exception);
+});
+ * </code></pre>
+ * <b>Note:</b> These three events are all fired with the signature of the corresponding <i>DataProxy instance</i> event {@link #beforewrite beforewrite}, {@link #write write} and {@link #exception exception}.
+ */
+Ext.data.DataProxy = function(conn){
+ // make sure we have a config object here to support ux proxies.
+ // All proxies should now send config into superclass constructor.
+ conn = conn || {};
+
+ // This line caused a bug when people use custom Connection object having its own request method.
+ // http://extjs.com/forum/showthread.php?t=67194. Have to set DataProxy config
+ //Ext.applyIf(this, conn);
+
+ this.api = conn.api;
+ this.url = conn.url;
+ this.restful = conn.restful;
+ this.listeners = conn.listeners;
+
+ // deprecated
+ this.prettyUrls = conn.prettyUrls;
+
+ /**
+ * @cfg {Object} api
+ * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".
+ * Defaults to:<pre><code>
+api: {
+ read : undefined,
+ create : undefined,
+ update : undefined,
+ destroy : undefined
+}
+ * </code></pre>
+ * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>
+ * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the
+ * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>
+ * <p>For example:</p>
+ * <pre><code>
+api: {
+ load : '/controller/load',
+ create : '/controller/new', // Server MUST return idProperty of new record
+ save : '/controller/update',
+ destroy : '/controller/destroy_action'
+}
+
+// Alternatively, one can use the object-form to specify each API-action
+api: {
+ load: {url: 'read.php', method: 'GET'},
+ create: 'create.php',
+ destroy: 'destroy.php',
+ save: 'update.php'
+}
+ * </code></pre>
+ * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request
+ * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>
+ * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API
+ * property should be modified before the action is requested using the corresponding before
+ * action event. For example to modify the URL associated with the load action:
+ * <pre><code>
+// modify the url for the action
+myStore.on({
+ beforeload: {
+ fn: function (store, options) {
+ // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.
+ store.proxy.setUrl('changed1.php');
+
+ // set optional second parameter to true to make this URL change
+ // permanent, applying this URL for all subsequent requests.
+ store.proxy.setUrl('changed1.php', true);
+
+ // Altering the proxy API should be done using the public
+ // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt>.
+ store.proxy.setApi('read', 'changed2.php');
+
+ // Or set the entire API with a config-object.
+ // When using the config-object option, you must redefine the <b>entire</b>
+ // API -- not just a specific action of it.
+ store.proxy.setApi({
+ read : 'changed_read.php',
+ create : 'changed_create.php',
+ update : 'changed_update.php',
+ destroy : 'changed_destroy.php'
+ });
+ }
+ }
+});
+ * </code></pre>
+ * </p>
+ */
+
+ this.addEvents(
+ /**
+ * @event exception
+ * <p>Fires if an exception occurs in the Proxy during a remote request. This event is relayed
+ * through a corresponding {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},
+ * so any Store instance may observe this event.</p>
+ * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
+ * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of exception events from <b>all</b>
+ * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
+ * <p>This event can be fired for one of two reasons:</p>
+ * <div class="mdetail-params"><ul>
+ * <li>remote-request <b>failed</b> : <div class="sub-desc">
+ * The server did not return status === 200.
+ * </div></li>
+ * <li>remote-request <b>succeeded</b> : <div class="sub-desc">
+ * The remote-request succeeded but the reader could not read the response.
+ * This means the server returned data, but the configured Reader threw an
+ * error while reading the response. In this case, this event will be
+ * raised and the caught error will be passed along into this event.
+ * </div></li>
+ * </ul></div>
+ * <br><p>This event fires with two different contexts based upon the 2nd
+ * parameter <tt>type [remote|response]</tt>. The first four parameters
+ * are identical between the two contexts -- only the final two parameters
+ * differ.</p>
+ * @param {DataProxy} this The proxy that sent the request
+ * @param {String} type
+ * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>
+ * <div class="mdetail-params"><ul>
+ * <li><b><tt>'response'</tt></b> : <div class="sub-desc">
+ * <p>An <b>invalid</b> response from the server was returned: either 404,
+ * 500 or the response meta-data does not match that defined in the DataReader
+ * (e.g.: root, idProperty, successProperty).</p>
+ * </div></li>
+ * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
+ * <p>A <b>valid</b> response was returned from the server having
+ * successProperty === false. This response might contain an error-message
+ * sent from the server. For example, the user may have failed
+ * authentication/authorization or a database validation error occurred.</p>
+ * </div></li>
+ * </ul></div>
+ * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.
+ * @param {Object} options The options for the action that were specified in the {@link #request}.
+ * @param {Object} response
+ * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>
+ * <div class="mdetail-params"><ul>
+ * <li><b><tt>'response'</tt></b> : <div class="sub-desc">
+ * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>
+ * </div></li>
+ * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">
+ * <p>The decoded response object sent from the server.</p>
+ * </div></li>
+ * </ul></div>
+ * @param {Mixed} arg
+ * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>
+ * <div class="mdetail-params"><ul>
+ * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">
+ * <p>The JavaScript Error object caught if the configured Reader could not read the data.
+ * If the remote request returns success===false, this parameter will be null.</p>
+ * </div></li>
+ * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">
+ * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action
+ * (Ext.data.Api.actions.create|update|destroy).</p>
+ * </div></li>
+ * </ul></div>
+ */
+ 'exception',
+ /**
+ * @event beforeload
+ * Fires before a request to retrieve a data object.
+ * @param {DataProxy} this The proxy for the request
+ * @param {Object} params The params object passed to the {@link #request} function
+ */
+ 'beforeload',
+ /**
+ * @event load
+ * Fires before the load method's callback is called.
+ * @param {DataProxy} this The proxy for the request
+ * @param {Object} o The request transaction object
+ * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
+ */
+ 'load',
+ /**
+ * @event loadexception
+ * <p>This event is <b>deprecated</b>. The signature of the loadexception event
+ * varies depending on the proxy, use the catch-all {@link #exception} event instead.
+ * This event will fire in addition to the {@link #exception} event.</p>
+ * @param {misc} misc See {@link #exception}.
+ * @deprecated
+ */
+ 'loadexception',
+ /**
+ * @event beforewrite
+ * <p>Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy</p>
+ * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
+ * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of beforewrite events from <b>all</b>
+ * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
+ * @param {DataProxy} this The proxy for the request
+ * @param {String} action [Ext.data.Api.actions.create|update|destroy]
+ * @param {Record/Record[]} rs The Record(s) to create|update|destroy.
+ * @param {Object} params The request <code>params</code> object. Edit <code>params</code> to add parameters to the request.
+ */
+ 'beforewrite',
+ /**
+ * @event write
+ * <p>Fires before the request-callback is called</p>
+ * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired
+ * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of write events from <b>all</b>
+ * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>
+ * @param {DataProxy} this The proxy that sent the request
+ * @param {String} action [Ext.data.Api.actions.create|upate|destroy]
+ * @param {Object} data The data object extracted from the server-response
+ * @param {Object} response The decoded response from server
+ * @param {Record/Record[]} rs The Record(s) from Store
+ * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function
+ */
+ 'write'
+ );
+ Ext.data.DataProxy.superclass.constructor.call(this);
+
+ // Prepare the proxy api. Ensures all API-actions are defined with the Object-form.
+ try {
+ Ext.data.Api.prepare(this);
+ } catch (e) {
+ if (e instanceof Ext.data.Api.Error) {
+ e.toConsole();
+ }
+ }
+ // relay each proxy's events onto Ext.data.DataProxy class for centralized Proxy-listening
+ Ext.data.DataProxy.relayEvents(this, ['beforewrite', 'write', 'exception']);
+};
+
+Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {
+ /**
+ * @cfg {Boolean} restful
+ * <p>Defaults to <tt>false</tt>. Set to <tt>true</tt> to operate in a RESTful manner.</p>
+ * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the
+ * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the
+ * Store is RESTful, there is no need to set this option on the proxy.</p>
+ * <br><p>RESTful implementations enable the serverside framework to automatically route
+ * actions sent to one url based upon the HTTP method, for example:
+ * <pre><code>
+store: new Ext.data.Store({
+ restful: true,
+ proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users
+ ...
+)}
+ * </code></pre>
+ * If there is no <code>{@link #api}</code> specified in the configuration of the proxy,
+ * all requests will be marshalled to a single RESTful url (/users) so the serverside
+ * framework can inspect the HTTP Method and act accordingly:
+ * <pre>
+<u>Method</u> <u>url</u> <u>action</u>
+POST /users create
+GET /users read
+PUT /users/23 update
+DESTROY /users/23 delete
+ * </pre></p>
+ * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's
+ * {@link Ext.data.Record#id id} will be appended to the url. Some MVC (e.g., Ruby on Rails,
+ * Merb and Django) support segment based urls where the segments in the URL follow the
+ * Model-View-Controller approach:<pre><code>
+ * someSite.com/controller/action/id
+ * </code></pre>
+ * Where the segments in the url are typically:<div class="mdetail-params"><ul>
+ * <li>The first segment : represents the controller class that should be invoked.</li>
+ * <li>The second segment : represents the class function, or method, that should be called.</li>
+ * <li>The third segment : represents the ID (a variable typically passed to the method).</li>
+ * </ul></div></p>
+ * <br><p>Refer to <code>{@link Ext.data.DataProxy#api}</code> for additional information.</p>
+ */
+ restful: false,
+
+ /**
+ * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>
+ * <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>
+proxy.setApi({
+ read : '/users/read',
+ create : '/users/create',
+ update : '/users/update',
+ destroy : '/users/destroy'
+});
+</code></pre>
+ * <p>If called with two parameters, the first parameter should be a string specifying the API action to
+ * redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>
+proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');
+</code></pre>
+ * @param {String/Object} api An API specification object, or the name of an action.
+ * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.
+ */
+ setApi : function() {
+ if (arguments.length == 1) {
+ var valid = Ext.data.Api.isValid(arguments[0]);
+ if (valid === true) {
+ this.api = arguments[0];
+ }
+ else {
+ throw new Ext.data.Api.Error('invalid', valid);
+ }
+ }
+ else if (arguments.length == 2) {
+ if (!Ext.data.Api.isAction(arguments[0])) {
+ throw new Ext.data.Api.Error('invalid', arguments[0]);
+ }
+ this.api[arguments[0]] = arguments[1];
+ }
+ Ext.data.Api.prepare(this);
+ },
+
+ /**
+ * Returns true if the specified action is defined as a unique action in the api-config.
+ * request. If all API-actions are routed to unique urls, the xaction parameter is unecessary. However, if no api is defined
+ * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to
+ * the corresponding code for CRUD action.
+ * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action
+ * @return {Boolean}
+ */
+ isApiAction : function(action) {
+ return (this.api[action]) ? true : false;
+ },
+
+ /**
+ * All proxy actions are executed through this method. Automatically fires the "before" + action event
+ * @param {String} action Name of the action
+ * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'
+ * @param {Object} params
+ * @param {Ext.data.DataReader} reader
+ * @param {Function} callback
+ * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the Proxy object.
+ * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.
+ */
+ request : function(action, rs, params, reader, callback, scope, options) {
+ if (!this.api[action] && !this.load) {
+ throw new Ext.data.DataProxy.Error('action-undefined', action);
+ }
+ params = params || {};
+ if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {
+ this.doRequest.apply(this, arguments);
+ }
+ else {
+ callback.call(scope || this, null, options, false);
+ }
+ },
+
+
+ /**
+ * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.
+ * @deprecated
+ * @param {Object} params
+ * @param {Object} reader
+ * @param {Object} callback
+ * @param {Object} scope
+ * @param {Object} arg
+ */
+ load : null,
+
+ /**
+ * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses. <b>Note:</b> Should only be used by custom-proxy developers.
+ * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},
+ * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).
+ */
+ doRequest : function(action, rs, params, reader, callback, scope, options) {
+ // default implementation of doRequest for backwards compatibility with 2.0 proxies.
+ // If we're executing here, the action is probably "load".
+ // Call with the pre-3.0 method signature.
+ this.load(params, reader, callback, scope, options);
+ },
+
+ /**
+ * @cfg {Function} onRead Abstract method that should be implemented in all subclasses. <b>Note:</b> Should only be used by custom-proxy developers. Callback for read {@link Ext.data.Api#actions action}.
+ * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.
+ * @param {Object} o The request transaction object
+ * @param {Object} res The server response
+ * @fires loadexception (deprecated)
+ * @fires exception
+ * @fires load
+ * @protected
+ */
+ onRead : Ext.emptyFn,
+ /**
+ * @cfg {Function} onWrite Abstract method that should be implemented in all subclasses. <b>Note:</b> Should only be used by custom-proxy developers. Callback for <i>create, update and destroy</i> {@link Ext.data.Api#actions actions}.
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Object} trans The request transaction object
+ * @param {Object} res The server response
+ * @fires exception
+ * @fires write
+ * @protected
+ */
+ onWrite : Ext.emptyFn,
+ /**
+ * buildUrl
+ * Sets the appropriate url based upon the action being executed. If restful is true, and only a single record is being acted upon,
+ * url will be built Rails-style, as in "/controller/action/32". restful will aply iff the supplied record is an
+ * instance of Ext.data.Record rather than an Array of them.
+ * @param {String} action The api action being executed [read|create|update|destroy]
+ * @param {Ext.data.Record/Ext.data.Record[]} record The record or Array of Records being acted upon.
+ * @return {String} url
+ * @private
+ */
+ buildUrl : function(action, record) {
+ record = record || null;
+
+ // conn.url gets nullified after each request. If it's NOT null here, that means the user must have intervened with a call
+ // to DataProxy#setUrl or DataProxy#setApi and changed it before the request was executed. If that's the case, use conn.url,
+ // otherwise, build the url from the api or this.url.
+ var url = (this.conn && this.conn.url) ? this.conn.url : (this.api[action]) ? this.api[action].url : this.url;
+ if (!url) {
+ throw new Ext.data.Api.Error('invalid-url', action);
+ }
+
+ // look for urls having "provides" suffix used in some MVC frameworks like Rails/Merb and others. The provides suffice informs
+ // the server what data-format the client is dealing with and returns data in the same format (eg: application/json, application/xml, etc)
+ // e.g.: /users.json, /users.xml, etc.
+ // with restful routes, we need urls like:
+ // PUT /users/1.json
+ // DELETE /users/1.json
+ var provides = null;
+ var m = url.match(/(.*)(\.json|\.xml|\.html)$/);
+ if (m) {
+ provides = m[2]; // eg ".json"
+ url = m[1]; // eg: "/users"
+ }
+ // prettyUrls is deprectated in favor of restful-config
+ if ((this.restful === true || this.prettyUrls === true) && record instanceof Ext.data.Record && !record.phantom) {
+ url += '/' + record.id;
+ }
+ return (provides === null) ? url : url + provides;
+ },
+
+ /**
+ * Destroys the proxy by purging any event listeners and cancelling any active requests.
+ */
+ destroy: function(){
+ this.purgeListeners();
+ }
+});
+
+// Apply the Observable prototype to the DataProxy class so that proxy instances can relay their
+// events to the class. Allows for centralized listening of all proxy instances upon the DataProxy class.
+Ext.apply(Ext.data.DataProxy, Ext.util.Observable.prototype);
+Ext.util.Observable.call(Ext.data.DataProxy);
+
+/**
+ * @class Ext.data.DataProxy.Error
+ * @extends Ext.Error
+ * DataProxy Error extension.
+ * constructor
+ * @param {String} message Message describing the error.
+ * @param {Record/Record[]} arg
+ */
+Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {
+ constructor : function(message, arg) {
+ this.arg = arg;
+ Ext.Error.call(this, message);
+ },
+ name: 'Ext.data.DataProxy'
+});
+Ext.apply(Ext.data.DataProxy.Error.prototype, {
+ lang: {
+ 'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function. Please review your Proxy url/api-configuration.",
+ 'api-invalid': 'Recieved an invalid API-configuration. Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'
+ }
+});
+
+
+/**
+ * @class Ext.data.Request
+ * A simple Request class used internally to the data package to provide more generalized remote-requests
+ * to a DataProxy.
+ * TODO Not yet implemented. Implement in Ext.data.Store#execute
+ */
+Ext.data.Request = function(params) {
+ Ext.apply(this, params);
+};
+Ext.data.Request.prototype = {
+ /**
+ * @cfg {String} action
+ */
+ action : undefined,
+ /**
+ * @cfg {Ext.data.Record[]/Ext.data.Record} rs The Store recordset associated with the request.
+ */
+ rs : undefined,
+ /**
+ * @cfg {Object} params HTTP request params
+ */
+ params: undefined,
+ /**
+ * @cfg {Function} callback The function to call when request is complete
+ */
+ callback : Ext.emptyFn,
+ /**
+ * @cfg {Object} scope The scope of the callback funtion
+ */
+ scope : undefined,
+ /**
+ * @cfg {Ext.data.DataReader} reader The DataReader instance which will parse the received response
+ */
+ reader : undefined
+};
+/**
+ * @class Ext.data.Response
+ * A generic response class to normalize response-handling internally to the framework.
+ */
+Ext.data.Response = function(params) {
+ Ext.apply(this, params);
+};
+Ext.data.Response.prototype = {
+ /**
+ * @cfg {String} action {@link Ext.data.Api#actions}
+ */
+ action: undefined,
+ /**
+ * @cfg {Boolean} success
+ */
+ success : undefined,
+ /**
+ * @cfg {String} message
+ */
+ message : undefined,
+ /**
+ * @cfg {Array/Object} data
+ */
+ data: undefined,
+ /**
+ * @cfg {Object} raw The raw response returned from server-code
+ */
+ raw: undefined,
+ /**
+ * @cfg {Ext.data.Record/Ext.data.Record[]} records related to the Request action
+ */
+ records: undefined
+};
+/**
+ * @class Ext.data.ScriptTagProxy
+ * @extends Ext.data.DataProxy
+ * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain
+ * other than the originating domain of the running page.<br>
+ * <p>
+ * <b>Note that if you are retrieving data from a page that is in a domain that is NOT the same as the originating domain
+ * of the running page, you must use this class, rather than HttpProxy.</b><br>
+ * <p>
+ * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript
+ * source code because it is used as the source inside a <script> tag.<br>
+ * <p>
+ * In order for the browser to process the returned data, the server must wrap the data object
+ * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.
+ * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy
+ * depending on whether the callback name was passed:
+ * <p>
+ * <pre><code>
+boolean scriptTag = false;
+String cb = request.getParameter("callback");
+if (cb != null) {
+ scriptTag = true;
+ response.setContentType("text/javascript");
+} else {
+ response.setContentType("application/x-json");
+}
+Writer out = response.getWriter();
+if (scriptTag) {
+ out.write(cb + "(");
+}
+out.print(dataBlock.toJsonString());
+if (scriptTag) {
+ out.write(");");
+}
+</code></pre>
+ * <p>Below is a PHP example to do the same thing:</p><pre><code>
+$callback = $_REQUEST['callback'];
+
+// Create the output object.
+$output = array('a' => 'Apple', 'b' => 'Banana');
+
+//start output
+if ($callback) {
+ header('Content-Type: text/javascript');
+ echo $callback . '(' . json_encode($output) . ');';
+} else {
+ header('Content-Type: application/x-json');
+ echo json_encode($output);
+}
+</code></pre>
+ * <p>Below is the ASP.Net code to do the same thing:</p><pre><code>
+String jsonString = "{success: true}";
+String cb = Request.Params.Get("callback");
+String responseString = "";
+if (!String.IsNullOrEmpty(cb)) {
+ responseString = cb + "(" + jsonString + ")";
+} else {
+ responseString = jsonString;
+}
+Response.Write(responseString);
+</code></pre>
+ *
+ * @constructor
+ * @param {Object} config A configuration object.
+ */
+Ext.data.ScriptTagProxy = function(config){
+ Ext.apply(this, config);
+
+ Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);
+
+ this.head = document.getElementsByTagName("head")[0];
+
+ /**
+ * @event loadexception
+ * <b>Deprecated</b> in favor of 'exception' event.
+ * Fires if an exception occurs in the Proxy during data loading. This event can be fired for one of two reasons:
+ * <ul><li><b>The load call timed out.</b> This means the load callback did not execute within the time limit
+ * specified by {@link #timeout}. In this case, this event will be raised and the
+ * fourth parameter (read error) will be null.</li>
+ * <li><b>The load succeeded but the reader could not read the response.</b> This means the server returned
+ * data, but the configured Reader threw an error while reading the data. In this case, this event will be
+ * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>
+ * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly
+ * on any Store instance.
+ * @param {Object} this
+ * @param {Object} options The loading options that were specified (see {@link #load} for details). If the load
+ * call timed out, this parameter will be null.
+ * @param {Object} arg The callback's arg object passed to the {@link #load} function
+ * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.
+ * If the remote request returns success: false, this parameter will be null.
+ */
+};
+
+Ext.data.ScriptTagProxy.TRANS_ID = 1000;
+
+Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {
+ /**
+ * @cfg {String} url The URL from which to request the data object.
+ */
+ /**
+ * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.
+ */
+ timeout : 30000,
+ /**
+ * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells
+ * the server the name of the callback function set up by the load call to process the returned data object.
+ * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate
+ * javascript output which calls this named function passing the data object as its only parameter.
+ */
+ callbackParam : "callback",
+ /**
+ * @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter
+ * name to the request.
+ */
+ nocache : true,
+
+ /**
+ * HttpProxy implementation of DataProxy#doRequest
+ * @param {String} action
+ * @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null
+ * @param {Object} params An object containing properties which are to be used as HTTP parameters
+ * for the request to the remote server.
+ * @param {Ext.data.DataReader} reader The Reader object which converts the data
+ * object into a block of Ext.data.Records.
+ * @param {Function} callback The function into which to pass the block of Ext.data.Records.
+ * The function must be passed <ul>
+ * <li>The Record block object</li>
+ * <li>The "arg" argument from the load function</li>
+ * <li>A boolean success indicator</li>
+ * </ul>
+ * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
+ * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
+ */
+ doRequest : function(action, rs, params, reader, callback, scope, arg) {
+ var p = Ext.urlEncode(Ext.apply(params, this.extraParams));
+
+ var url = this.buildUrl(action, rs);
+ if (!url) {
+ throw new Ext.data.Api.Error('invalid-url', url);
+ }
+ url = Ext.urlAppend(url, p);
+
+ if(this.nocache){
+ url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));
+ }
+ var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;
+ var trans = {
+ id : transId,
+ action: action,
+ cb : "stcCallback"+transId,
+ scriptId : "stcScript"+transId,
+ params : params,
+ arg : arg,
+ url : url,
+ callback : callback,
+ scope : scope,
+ reader : reader
+ };
+ window[trans.cb] = this.createCallback(action, rs, trans);
+ url += String.format("&{0}={1}", this.callbackParam, trans.cb);
+ if(this.autoAbort !== false){
+ this.abort();
+ }
+
+ trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);
+
+ var script = document.createElement("script");
+ script.setAttribute("src", url);
+ script.setAttribute("type", "text/javascript");
+ script.setAttribute("id", trans.scriptId);
+ this.head.appendChild(script);
+
+ this.trans = trans;
+ },
+
+ // @private createCallback
+ createCallback : function(action, rs, trans) {
+ var self = this;
+ return function(res) {
+ self.trans = false;
+ self.destroyTrans(trans, true);
+ if (action === Ext.data.Api.actions.read) {
+ self.onRead.call(self, action, trans, res);
+ } else {
+ self.onWrite.call(self, action, trans, res, rs);
+ }
+ };
+ },
+ /**
+ * Callback for read actions
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Object} trans The request transaction object
+ * @param {Object} res The server response
+ * @protected
+ */
+ onRead : function(action, trans, res) {
+ var result;
+ try {
+ result = trans.reader.readRecords(res);
+ }catch(e){
+ // @deprecated: fire loadexception
+ this.fireEvent("loadexception", this, trans, res, e);
+
+ this.fireEvent('exception', this, 'response', action, trans, res, e);
+ trans.callback.call(trans.scope||window, null, trans.arg, false);
+ return;
+ }
+ if (result.success === false) {
+ // @deprecated: fire old loadexception for backwards-compat.
+ this.fireEvent('loadexception', this, trans, res);
+
+ this.fireEvent('exception', this, 'remote', action, trans, res, null);
+ } else {
+ this.fireEvent("load", this, res, trans.arg);
+ }
+ trans.callback.call(trans.scope||window, result, trans.arg, result.success);
+ },
+ /**
+ * Callback for write actions
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Object} trans The request transaction object
+ * @param {Object} res The server response
+ * @protected
+ */
+ onWrite : function(action, trans, response, rs) {
+ var reader = trans.reader;
+ try {
+ // though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.
+ var res = reader.readResponse(action, response);
+ } catch (e) {
+ this.fireEvent('exception', this, 'response', action, trans, res, e);
+ trans.callback.call(trans.scope||window, null, res, false);
+ return;
+ }
+ if(!res.success === true){
+ this.fireEvent('exception', this, 'remote', action, trans, res, rs);
+ trans.callback.call(trans.scope||window, null, res, false);
+ return;
+ }
+ this.fireEvent("write", this, action, res.data, res, rs, trans.arg );
+ trans.callback.call(trans.scope||window, res.data, res, true);
+ },
+
+ // private
+ isLoading : function(){
+ return this.trans ? true : false;
+ },
+
+ /**
+ * Abort the current server request.
+ */
+ abort : function(){
+ if(this.isLoading()){
+ this.destroyTrans(this.trans);
+ }
+ },
+
+ // private
+ destroyTrans : function(trans, isLoaded){
+ this.head.removeChild(document.getElementById(trans.scriptId));
+ clearTimeout(trans.timeoutId);
+ if(isLoaded){
+ window[trans.cb] = undefined;
+ try{
+ delete window[trans.cb];
+ }catch(e){}
+ }else{
+ // if hasn't been loaded, wait for load to remove it to prevent script error
+ window[trans.cb] = function(){
+ window[trans.cb] = undefined;
+ try{
+ delete window[trans.cb];
+ }catch(e){}
+ };
+ }
+ },
+
+ // private
+ handleFailure : function(trans){
+ this.trans = false;
+ this.destroyTrans(trans, false);
+ if (trans.action === Ext.data.Api.actions.read) {
+ // @deprecated firing loadexception
+ this.fireEvent("loadexception", this, null, trans.arg);
+ }
+
+ this.fireEvent('exception', this, 'response', trans.action, {
+ response: null,
+ options: trans.arg
+ });
+ trans.callback.call(trans.scope||window, null, trans.arg, false);
+ },
+
+ // inherit docs
+ destroy: function(){
+ this.abort();
+ Ext.data.ScriptTagProxy.superclass.destroy.call(this);
+ }
+});/**
+ * @class Ext.data.HttpProxy
+ * @extends Ext.data.DataProxy
+ * <p>An implementation of {@link Ext.data.DataProxy} that processes data requests within the same
+ * domain of the originating page.</p>
+ * <p><b>Note</b>: this class cannot be used to retrieve data from a domain other
+ * than the domain from which the running page was served. For cross-domain requests, use a
+ * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p>
+ * <p>Be aware that to enable the browser to parse an XML document, the server must set
+ * the Content-Type header in the HTTP response to "<tt>text/xml</tt>".</p>
+ * @constructor
+ * @param {Object} conn
+ * An {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.
+ * <p>Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the
+ * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>
+ * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,
+ * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be
+ * used to pass parameters known at instantiation time.</p>
+ * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make
+ * the request.</p>
+ */
+Ext.data.HttpProxy = function(conn){
+ Ext.data.HttpProxy.superclass.constructor.call(this, conn);
+
+ /**
+ * The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy
+ * uses to make requests to the server. Properties of this object may be changed dynamically to
+ * change the way data is requested.
+ * @property
+ */
+ this.conn = conn;
+
+ // nullify the connection url. The url param has been copied to 'this' above. The connection
+ // url will be set during each execution of doRequest when buildUrl is called. This makes it easier for users to override the
+ // connection url during beforeaction events (ie: beforeload, beforewrite, etc).
+ // Url is always re-defined during doRequest.
+ this.conn.url = null;
+
+ this.useAjax = !conn || !conn.events;
+
+ // A hash containing active requests, keyed on action [Ext.data.Api.actions.create|read|update|destroy]
+ var actions = Ext.data.Api.actions;
+ this.activeRequest = {};
+ for (var verb in actions) {
+ this.activeRequest[actions[verb]] = undefined;
+ }
+};
+
+Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {
+ /**
+ * Return the {@link Ext.data.Connection} object being used by this Proxy.
+ * @return {Connection} The Connection object. This object may be used to subscribe to events on
+ * a finer-grained basis than the DataProxy events.
+ */
+ getConnection : function() {
+ return this.useAjax ? Ext.Ajax : this.conn;
+ },
+
+ /**
+ * Used for overriding the url used for a single request. Designed to be called during a beforeaction event. Calling setUrl
+ * will override any urls set via the api configuration parameter. Set the optional parameter makePermanent to set the url for
+ * all subsequent requests. If not set to makePermanent, the next request will use the same url or api configuration defined
+ * in the initial proxy configuration.
+ * @param {String} url
+ * @param {Boolean} makePermanent (Optional) [false]
+ *
+ * (e.g.: beforeload, beforesave, etc).
+ */
+ setUrl : function(url, makePermanent) {
+ this.conn.url = url;
+ if (makePermanent === true) {
+ this.url = url;
+ this.api = null;
+ Ext.data.Api.prepare(this);
+ }
+ },
+
+ /**
+ * HttpProxy implementation of DataProxy#doRequest
+ * @param {String} action The crud action type (create, read, update, destroy)
+ * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
+ * @param {Object} params An object containing properties which are to be used as HTTP parameters
+ * for the request to the remote server.
+ * @param {Ext.data.DataReader} reader The Reader object which converts the data
+ * object into a block of Ext.data.Records.
+ * @param {Function} callback
+ * <div class="sub-desc"><p>A function to be called after the request.
+ * The <tt>callback</tt> is passed the following arguments:<ul>
+ * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>
+ * <li><tt>options</tt>: Options object from the action request</li>
+ * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>
+ * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
+ * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
+ * @protected
+ */
+ doRequest : function(action, rs, params, reader, cb, scope, arg) {
+ var o = {
+ method: (this.api[action]) ? this.api[action]['method'] : undefined,
+ request: {
+ callback : cb,
+ scope : scope,
+ arg : arg
+ },
+ reader: reader,
+ callback : this.createCallback(action, rs),
+ scope: this
+ };
+
+ // If possible, transmit data using jsonData || xmlData on Ext.Ajax.request (An installed DataWriter would have written it there.).
+ // Use std HTTP params otherwise.
+ if (params.jsonData) {
+ o.jsonData = params.jsonData;
+ } else if (params.xmlData) {
+ o.xmlData = params.xmlData;
+ } else {
+ o.params = params || {};
+ }
+ // Set the connection url. If this.conn.url is not null here,
+ // the user must have overridden the url during a beforewrite/beforeload event-handler.
+ // this.conn.url is nullified after each request.
+ this.conn.url = this.buildUrl(action, rs);
+
+ if(this.useAjax){
+
+ Ext.applyIf(o, this.conn);
+
+ // If a currently running request is found for this action, abort it.
+ if (this.activeRequest[action]) {
+ ////
+ // Disabled aborting activeRequest while implementing REST. activeRequest[action] will have to become an array
+ // TODO ideas anyone?
+ //
+ //Ext.Ajax.abort(this.activeRequest[action]);
+ }
+ this.activeRequest[action] = Ext.Ajax.request(o);
+ }else{
+ this.conn.request(o);
+ }
+ // request is sent, nullify the connection url in preparation for the next request
+ this.conn.url = null;
+ },
+
+ /**
+ * Returns a callback function for a request. Note a special case is made for the
+ * read action vs all the others.
+ * @param {String} action [create|update|delete|load]
+ * @param {Ext.data.Record[]} rs The Store-recordset being acted upon
+ * @private
+ */
+ createCallback : function(action, rs) {
+ return function(o, success, response) {
+ this.activeRequest[action] = undefined;
+ if (!success) {
+ if (action === Ext.data.Api.actions.read) {
+ // @deprecated: fire loadexception for backwards compat.
+ // TODO remove
+ this.fireEvent('loadexception', this, o, response);
+ }
+ this.fireEvent('exception', this, 'response', action, o, response);
+ o.request.callback.call(o.request.scope, null, o.request.arg, false);
+ return;
+ }
+ if (action === Ext.data.Api.actions.read) {
+ this.onRead(action, o, response);
+ } else {
+ this.onWrite(action, o, response, rs);
+ }
+ };
+ },
+
+ /**
+ * Callback for read action
+ * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.
+ * @param {Object} o The request transaction object
+ * @param {Object} res The server response
+ * @fires loadexception (deprecated)
+ * @fires exception
+ * @fires load
+ * @protected
+ */
+ onRead : function(action, o, response) {
+ var result;
+ try {
+ result = o.reader.read(response);
+ }catch(e){
+ // @deprecated: fire old loadexception for backwards-compat.
+ // TODO remove
+ this.fireEvent('loadexception', this, o, response, e);
+
+ this.fireEvent('exception', this, 'response', action, o, response, e);
+ o.request.callback.call(o.request.scope, null, o.request.arg, false);
+ return;
+ }
+ if (result.success === false) {
+ // @deprecated: fire old loadexception for backwards-compat.
+ // TODO remove
+ this.fireEvent('loadexception', this, o, response);
+
+ // Get DataReader read-back a response-object to pass along to exception event
+ var res = o.reader.readResponse(action, response);
+ this.fireEvent('exception', this, 'remote', action, o, res, null);
+ }
+ else {
+ this.fireEvent('load', this, o, o.request.arg);
+ }
+ // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance
+ // the calls to request.callback(...) in each will have to be made identical.
+ // NOTE reader.readResponse does not currently return Ext.data.Response
+ o.request.callback.call(o.request.scope, result, o.request.arg, result.success);
+ },
+ /**
+ * Callback for write actions
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Object} trans The request transaction object
+ * @param {Object} res The server response
+ * @fires exception
+ * @fires write
+ * @protected
+ */
+ onWrite : function(action, o, response, rs) {
+ var reader = o.reader;
+ var res;
+ try {
+ res = reader.readResponse(action, response);
+ } catch (e) {
+ this.fireEvent('exception', this, 'response', action, o, response, e);
+ o.request.callback.call(o.request.scope, null, o.request.arg, false);
+ return;
+ }
+ if (res.success === true) {
+ this.fireEvent('write', this, action, res.data, res, rs, o.request.arg);
+ } else {
+ this.fireEvent('exception', this, 'remote', action, o, res, rs);
+ }
+ // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance
+ // the calls to request.callback(...) in each will have to be made similar.
+ // NOTE reader.readResponse does not currently return Ext.data.Response
+ o.request.callback.call(o.request.scope, res.data, res, res.success);
+ },
+
+ // inherit docs
+ destroy: function(){
+ if(!this.useAjax){
+ this.conn.abort();
+ }else if(this.activeRequest){
+ var actions = Ext.data.Api.actions;
+ for (var verb in actions) {
+ if(this.activeRequest[actions[verb]]){
+ Ext.Ajax.abort(this.activeRequest[actions[verb]]);
+ }
+ }
+ }
+ Ext.data.HttpProxy.superclass.destroy.call(this);
+ }
+});/**
+ * @class Ext.data.MemoryProxy
+ * @extends Ext.data.DataProxy
+ * An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor
+ * to the Reader when its load method is called.
+ * @constructor
+ * @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.
+ */
+Ext.data.MemoryProxy = function(data){
+ // Must define a dummy api with "read" action to satisfy DataProxy#doRequest and Ext.data.Api#prepare *before* calling super
+ var api = {};
+ api[Ext.data.Api.actions.read] = true;
+ Ext.data.MemoryProxy.superclass.constructor.call(this, {
+ api: api
+ });
+ this.data = data;
+};
+
+Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {
+ /**
+ * @event loadexception
+ * Fires if an exception occurs in the Proxy during data loading. Note that this event is also relayed
+ * through {@link Ext.data.Store}, so you can listen for it directly on any Store instance.
+ * @param {Object} this
+ * @param {Object} arg The callback's arg object passed to the {@link #load} function
+ * @param {Object} null This parameter does not apply and will always be null for MemoryProxy
+ * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data
+ */
+
+ /**
+ * MemoryProxy implementation of DataProxy#doRequest
+ * @param {String} action
+ * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
+ * @param {Object} params An object containing properties which are to be used as HTTP parameters
+ * for the request to the remote server.
+ * @param {Ext.data.DataReader} reader The Reader object which converts the data
+ * object into a block of Ext.data.Records.
+ * @param {Function} callback The function into which to pass the block of Ext.data.Records.
+ * The function must be passed <ul>
+ * <li>The Record block object</li>
+ * <li>The "arg" argument from the load function</li>
+ * <li>A boolean success indicator</li>
+ * </ul>
+ * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
+ * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
+ */
+ doRequest : function(action, rs, params, reader, callback, scope, arg) {
+ // No implementation for CRUD in MemoryProxy. Assumes all actions are 'load'
+ params = params || {};
+ var result;
+ try {
+ result = reader.readRecords(this.data);
+ }catch(e){
+ // @deprecated loadexception
+ this.fireEvent("loadexception", this, null, arg, e);
+
+ this.fireEvent('exception', this, 'response', action, arg, null, e);
+ callback.call(scope, null, arg, false);
+ return;
+ }
+ callback.call(scope, result, arg, true);
+ }
+});/**
+ * @class Ext.data.Types
+ * <p>This is s static class containing the system-supplied data types which may be given to a {@link Ext.data.Field Field}.<p/>
+ * <p>The properties in this class are used as type indicators in the {@link Ext.data.Field Field} class, so to
+ * test whether a Field is of a certain type, compare the {@link Ext.data.Field#type type} property against properties
+ * of this class.</p>
+ * <p>Developers may add their own application-specific data types to this class. Definition names must be UPPERCASE.
+ * each type definition must contain three properties:</p>
+ * <div class="mdetail-params"><ul>
+ * <li><code>convert</code> : <i>Function</i><div class="sub-desc">A function to convert raw data values from a data block into the data
+ * to be stored in the Field. The function is passed the collowing parameters:
+ * <div class="mdetail-params"><ul>
+ * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
+ * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
+ * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
+ * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
+ * ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
+ * </ul></div></div></li>
+ * <li><code>sortType</code> : <i>Function</i> <div class="sub-desc">A function to convert the stored data into comparable form, as defined by {@link Ext.data.SortTypes}.</div></li>
+ * <li><code>type</code> : <i>String</i> <div class="sub-desc">A textual data type name.</div></li>
+ * </ul></div>
+ * <p>For example, to create a VELatLong field (See the Microsoft Bing Mapping API) containing the latitude/longitude value of a datapoint on a map from a JsonReader data block
+ * which contained the properties <code>lat</code> and <code>long</code>, you would define a new data type like this:</p>
+ *<pre><code>
+// Add a new Field data type which stores a VELatLong object in the Record.
+Ext.data.Types.VELATLONG = {
+ convert: function(v, data) {
+ return new VELatLong(data.lat, data.long);
+ },
+ sortType: function(v) {
+ return v.Latitude; // When sorting, order by latitude
+ },
+ type: 'VELatLong'
+};
+</code></pre>
+ * <p>Then, when declaring a Record, use <pre><code>
+var types = Ext.data.Types; // allow shorthand type access
+UnitRecord = Ext.data.Record.create([
+ { name: 'unitName', mapping: 'UnitName' },
+ { name: 'curSpeed', mapping: 'CurSpeed', type: types.INT },
+ { name: 'latitude', mapping: 'lat', type: types.FLOAT },
+ { name: 'latitude', mapping: 'lat', type: types.FLOAT },
+ { name: 'position', type: types.VELATLONG }
+]);
+</code></pre>
+ * @singleton
+ */
+Ext.data.Types = new function(){
+ var st = Ext.data.SortTypes;
+ Ext.apply(this, {
+ /**
+ * @type Regexp
+ * @property stripRe
+ * A regular expression for stripping non-numeric characters from a numeric value. Defaults to <tt>/[\$,%]/g</tt>.
+ * This should be overridden for localization.
+ */
+ stripRe: /[\$,%]/g,
+
+ /**
+ * @type Object.
+ * @property AUTO
+ * This data type means that no conversion is applied to the raw data before it is placed into a Record.
+ */
+ AUTO: {
+ convert: function(v){ return v; },
+ sortType: st.none,
+ type: 'auto'
+ },
+
+ /**
+ * @type Object.
+ * @property STRING
+ * This data type means that the raw data is converted into a String before it is placed into a Record.
+ */
+ STRING: {
+ convert: function(v){ return (v === undefined || v === null) ? '' : String(v); },
+ sortType: st.asUCString,
+ type: 'string'
+ },
+
+ /**
+ * @type Object.
+ * @property INT
+ * This data type means that the raw data is converted into an integer before it is placed into a Record.
+ * <p>The synonym <code>INTEGER</code> is equivalent.</p>
+ */
+ INT: {
+ convert: function(v){
+ return v !== undefined && v !== null && v !== '' ?
+ parseInt(String(v).replace(Ext.data.Types.stripRe, ''), 10) : 0;
+ },
+ sortType: st.none,
+ type: 'int'
+ },
+
+ /**
+ * @type Object.
+ * @property FLOAT
+ * This data type means that the raw data is converted into a number before it is placed into a Record.
+ * <p>The synonym <code>NUMBER</code> is equivalent.</p>
+ */
+ FLOAT: {
+ convert: function(v){
+ return v !== undefined && v !== null && v !== '' ?
+ parseFloat(String(v).replace(Ext.data.Types.stripRe, ''), 10) : 0;
+ },
+ sortType: st.none,
+ type: 'float'
+ },
+
+ /**
+ * @type Object.
+ * @property BOOL
+ * <p>This data type means that the raw data is converted into a boolean before it is placed into
+ * a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p>
+ * <p>The synonym <code>BOOLEAN</code> is equivalent.</p>
+ */
+ BOOL: {
+ convert: function(v){ return v === true || v === 'true' || v == 1; },
+ sortType: st.none,
+ type: 'bool'
+ },
+
+ /**
+ * @type Object.
+ * @property DATE
+ * This data type means that the raw data is converted into a Date before it is placed into a Record.
+ * The date format is specified in the constructor of the {@link Ext.data.Field} to which this type is
+ * being applied.
+ */
+ DATE: {
+ convert: function(v){
+ var df = this.dateFormat;
+ if(!v){
+ return null;
+ }
+ if(Ext.isDate(v)){
+ return v;
+ }
+ if(df){
+ if(df == 'timestamp'){
+ return new Date(v*1000);
+ }
+ if(df == 'time'){
+ return new Date(parseInt(v, 10));
+ }
+ return Date.parseDate(v, df);
+ }
+ var parsed = Date.parse(v);
+ return parsed ? new Date(parsed) : null;
+ },
+ sortType: st.asDate,
+ type: 'date'
+ }
+ });
+
+ Ext.apply(this, {
+ /**
+ * @type Object.
+ * @property BOOLEAN
+ * <p>This data type means that the raw data is converted into a boolean before it is placed into
+ * a Record. The string "true" and the number 1 are converted to boolean <code>true</code>.</p>
+ * <p>The synonym <code>BOOL</code> is equivalent.</p>
+ */
+ BOOLEAN: this.BOOL,
+ /**
+ * @type Object.
+ * @property INTEGER
+ * This data type means that the raw data is converted into an integer before it is placed into a Record.
+ * <p>The synonym <code>INT</code> is equivalent.</p>
+ */
+ INTEGER: this.INT,
+ /**
+ * @type Object.
+ * @property NUMBER
+ * This data type means that the raw data is converted into a number before it is placed into a Record.
+ * <p>The synonym <code>FLOAT</code> is equivalent.</p>
+ */
+ NUMBER: this.FLOAT
+ });
+};/**
+ * @class Ext.data.JsonWriter
+ * @extends Ext.data.DataWriter
+ * DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action.
+ */
+Ext.data.JsonWriter = Ext.extend(Ext.data.DataWriter, {
+ /**
+ * @cfg {Boolean} encode <tt>true</tt> to {@link Ext.util.JSON#encode encode} the
+ * {@link Ext.data.DataWriter#toHash hashed data}. Defaults to <tt>true</tt>. When using
+ * {@link Ext.data.DirectProxy}, set this to <tt>false</tt> since Ext.Direct.JsonProvider will perform
+ * its own json-encoding. In addition, if you're using {@link Ext.data.HttpProxy}, setting to <tt>false</tt>
+ * will cause HttpProxy to transmit data using the <b>jsonData</b> configuration-params of {@link Ext.Ajax#request}
+ * instead of <b>params</b>. When using a {@link Ext.data.Store#restful} Store, some serverside frameworks are
+ * tuned to expect data through the jsonData mechanism. In those cases, one will want to set <b>encode: <tt>false</tt></b>, as in
+ * let the lower-level connection object (eg: Ext.Ajax) do the encoding.
+ */
+ encode : true,
+ /**
+ * @cfg {Boolean} encodeDelete False to send only the id to the server on delete, true to encode it in an object
+ * literal, eg: <pre><code>
+{id: 1}
+ * </code></pre> Defaults to <tt>false</tt>
+ */
+ encodeDelete: false,
+
+ constructor : function(config){
+ Ext.data.JsonWriter.superclass.constructor.call(this, config);
+ },
+
+ /**
+ * Final action of a write event. Apply the written data-object to params.
+ * @param {Object} http params-object to write-to.
+ * @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
+ * @param {Object/Object[]} data Data-object representing compiled Store-recordset.
+ */
+ render : function(params, baseParams, data) {
+ if (this.encode === true) {
+ // Encode here now.
+ Ext.apply(params, baseParams);
+ params[this.meta.root] = Ext.encode(data);
+ } else {
+ // defer encoding for some other layer, probably in {@link Ext.Ajax#request}. Place everything into "jsonData" key.
+ var jdata = Ext.apply({}, baseParams);
+ jdata[this.meta.root] = data;
+ params.jsonData = jdata;
+ }
+ },
+ /**
+ * Implements abstract Ext.data.DataWriter#createRecord
+ * @protected
+ * @param {Ext.data.Record} rec
+ * @return {Object}
+ */
+ createRecord : function(rec) {
+ return this.toHash(rec);
+ },
+ /**
+ * Implements abstract Ext.data.DataWriter#updateRecord
+ * @protected
+ * @param {Ext.data.Record} rec
+ * @return {Object}
+ */
+ updateRecord : function(rec) {
+ return this.toHash(rec);
+
+ },
+ /**
+ * Implements abstract Ext.data.DataWriter#destroyRecord
+ * @protected
+ * @param {Ext.data.Record} rec
+ * @return {Object}
+ */
+ destroyRecord : function(rec){
+ if(this.encodeDelete){
+ var data = {};
+ data[this.meta.idProperty] = rec.id;
+ return data;
+ }else{
+ return rec.id;
+ }
+ }
+});/**
+ * @class Ext.data.JsonReader
+ * @extends Ext.data.DataReader
+ * <p>Data reader class to create an Array of {@link Ext.data.Record} objects
+ * from a JSON packet based on mappings in a provided {@link Ext.data.Record}
+ * constructor.</p>
+ * <p>Example code:</p>
+ * <pre><code>
+var myReader = new Ext.data.JsonReader({
+ // metadata configuration options:
+ {@link #idProperty}: 'id'
+ {@link #root}: 'rows',
+ {@link #totalProperty}: 'results',
+ {@link Ext.data.DataReader#messageProperty}: "msg" // The element within the response that provides a user-feedback message (optional)
+
+ // the fields config option will internally create an {@link Ext.data.Record}
+ // constructor that provides mapping for reading the record data objects
+ {@link Ext.data.DataReader#fields fields}: [
+ // map Record's 'firstname' field to data object's key of same name
+ {name: 'name'},
+ // map Record's 'job' field to data object's 'occupation' key
+ {name: 'job', mapping: 'occupation'}
+ ]
+});
+</code></pre>
+ * <p>This would consume a JSON data object of the form:</p><pre><code>
+{
+ results: 2000, // Reader's configured {@link #totalProperty}
+ rows: [ // Reader's configured {@link #root}
+ // record data objects:
+ { {@link #idProperty id}: 1, firstname: 'Bill', occupation: 'Gardener' },
+ { {@link #idProperty id}: 2, firstname: 'Ben' , occupation: 'Horticulturalist' },
+ ...
+ ]
+}
+</code></pre>
+ * <p><b><u>Automatic configuration using metaData</u></b></p>
+ * <p>It is possible to change a JsonReader's metadata at any time by including
+ * a <b><tt>metaData</tt></b> property in the JSON data object. If the JSON data
+ * object has a <b><tt>metaData</tt></b> property, a {@link Ext.data.Store Store}
+ * object using this Reader will reconfigure itself to use the newly provided
+ * field definition and fire its {@link Ext.data.Store#metachange metachange}
+ * event. The metachange event handler may interrogate the <b><tt>metaData</tt></b>
+ * property to perform any configuration required.</p>
+ * <p>Note that reconfiguring a Store potentially invalidates objects which may
+ * refer to Fields or Records which no longer exist.</p>
+ * <p>To use this facility you would create the JsonReader like this:</p><pre><code>
+var myReader = new Ext.data.JsonReader();
+</code></pre>
+ * <p>The first data packet from the server would configure the reader by
+ * containing a <b><tt>metaData</tt></b> property <b>and</b> the data. For
+ * example, the JSON data object might take the form:</p><pre><code>
+{
+ metaData: {
+ "{@link #idProperty}": "id",
+ "{@link #root}": "rows",
+ "{@link #totalProperty}": "results"
+ "{@link #successProperty}": "success",
+ "{@link Ext.data.DataReader#fields fields}": [
+ {"name": "name"},
+ {"name": "job", "mapping": "occupation"}
+ ],
+ // used by store to set its sortInfo
+ "sortInfo":{
+ "field": "name",
+ "direction": "ASC"
+ },
+ // {@link Ext.PagingToolbar paging data} (if applicable)
+ "start": 0,
+ "limit": 2,
+ // custom property
+ "foo": "bar"
+ },
+ // Reader's configured {@link #successProperty}
+ "success": true,
+ // Reader's configured {@link #totalProperty}
+ "results": 2000,
+ // Reader's configured {@link #root}
+ // (this data simulates 2 results {@link Ext.PagingToolbar per page})
+ "rows": [ // <b>*Note:</b> this must be an Array
+ { "id": 1, "name": "Bill", "occupation": "Gardener" },
+ { "id": 2, "name": "Ben", "occupation": "Horticulturalist" }
+ ]
+}
+ * </code></pre>
+ * <p>The <b><tt>metaData</tt></b> property in the JSON data object should contain:</p>
+ * <div class="mdetail-params"><ul>
+ * <li>any of the configuration options for this class</li>
+ * <li>a <b><tt>{@link Ext.data.Record#fields fields}</tt></b> property which
+ * the JsonReader will use as an argument to the
+ * {@link Ext.data.Record#create data Record create method} in order to
+ * configure the layout of the Records it will produce.</li>
+ * <li>a <b><tt>{@link Ext.data.Store#sortInfo sortInfo}</tt></b> property
+ * which the JsonReader will use to set the {@link Ext.data.Store}'s
+ * {@link Ext.data.Store#sortInfo sortInfo} property</li>
+ * <li>any custom properties needed</li>
+ * </ul></div>
+ *
+ * @constructor
+ * Create a new JsonReader
+ * @param {Object} meta Metadata configuration options.
+ * @param {Array/Object} recordType
+ * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
+ * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
+ * constructor created from {@link Ext.data.Record#create}.</p>
+ */
+Ext.data.JsonReader = function(meta, recordType){
+ meta = meta || {};
+ /**
+ * @cfg {String} idProperty [id] Name of the property within a row object
+ * that contains a record identifier value. Defaults to <tt>id</tt>
+ */
+ /**
+ * @cfg {String} successProperty [success] Name of the property from which to
+ * retrieve the success attribute. Defaults to <tt>success</tt>. See
+ * {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
+ * for additional information.
+ */
+ /**
+ * @cfg {String} totalProperty [total] Name of the property from which to
+ * retrieve the total number of records in the dataset. This is only needed
+ * if the whole dataset is not passed in one go, but is being paged from
+ * the remote server. Defaults to <tt>total</tt>.
+ */
+ /**
+ * @cfg {String} root [undefined] <b>Required</b>. The name of the property
+ * which contains the Array of row objects. Defaults to <tt>undefined</tt>.
+ * An exception will be thrown if the root property is undefined. The data
+ * packet value for this property should be an empty array to clear the data
+ * or show no data.
+ */
+ Ext.applyIf(meta, {
+ idProperty: 'id',
+ successProperty: 'success',
+ totalProperty: 'total'
+ });
+
+ Ext.data.JsonReader.superclass.constructor.call(this, meta, recordType || meta.fields);
+};
+Ext.extend(Ext.data.JsonReader, Ext.data.DataReader, {
+ /**
+ * This JsonReader's metadata as passed to the constructor, or as passed in
+ * the last data packet's <b><tt>metaData</tt></b> property.
+ * @type Mixed
+ * @property meta
+ */
+ /**
+ * This method is only used by a DataProxy which has retrieved data from a remote server.
+ * @param {Object} response The XHR object which contains the JSON data in its responseText.
+ * @return {Object} data A data block which is used by an Ext.data.Store object as
+ * a cache of Ext.data.Records.
+ */
+ read : function(response){
+ var json = response.responseText;
+ var o = Ext.decode(json);
+ if(!o) {
+ throw {message: 'JsonReader.read: Json object not found'};
+ }
+ return this.readRecords(o);
+ },
+
+ /*
+ * TODO: refactor code between JsonReader#readRecords, #readResponse into 1 method.
+ * there's ugly duplication going on due to maintaining backwards compat. with 2.0. It's time to do this.
+ */
+ /**
+ * Decode a JSON response from server.
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Object} response The XHR object returned through an Ajax server request.
+ * @return {Response} A {@link Ext.data.Response Response} object containing the data response, and also status information.
+ */
+ readResponse : function(action, response) {
+ var o = (response.responseText !== undefined) ? Ext.decode(response.responseText) : response;
+ if(!o) {
+ throw new Ext.data.JsonReader.Error('response');
+ }
+
+ var root = this.getRoot(o);
+ if (action === Ext.data.Api.actions.create) {
+ var def = Ext.isDefined(root);
+ if (def && Ext.isEmpty(root)) {
+ throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
+ }
+ else if (!def) {
+ throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
+ }
+ }
+
+ // instantiate response object
+ var res = new Ext.data.Response({
+ action: action,
+ success: this.getSuccess(o),
+ data: (root) ? this.extractData(root, false) : [],
+ message: this.getMessage(o),
+ raw: o
+ });
+
+ // blow up if no successProperty
+ if (Ext.isEmpty(res.success)) {
+ throw new Ext.data.JsonReader.Error('successProperty-response', this.meta.successProperty);
+ }
+ return res;
+ },
+
+ /**
+ * Create a data block containing Ext.data.Records from a JSON object.
+ * @param {Object} o An object which contains an Array of row objects in the property specified
+ * in the config as 'root, and optionally a property, specified in the config as 'totalProperty'
+ * which contains the total size of the dataset.
+ * @return {Object} data A data block which is used by an Ext.data.Store object as
+ * a cache of Ext.data.Records.
+ */
+ readRecords : function(o){
+ /**
+ * After any data loads, the raw JSON data is available for further custom processing. If no data is
+ * loaded or there is a load exception this property will be undefined.
+ * @type Object
+ */
+ this.jsonData = o;
+ if(o.metaData){
+ this.onMetaChange(o.metaData);
+ }
+ var s = this.meta, Record = this.recordType,
+ f = Record.prototype.fields, fi = f.items, fl = f.length, v;
+
+ var root = this.getRoot(o), c = root.length, totalRecords = c, success = true;
+ if(s.totalProperty){
+ v = parseInt(this.getTotal(o), 10);
+ if(!isNaN(v)){
+ totalRecords = v;
+ }
+ }
+ if(s.successProperty){
+ v = this.getSuccess(o);
+ if(v === false || v === 'false'){
+ success = false;
+ }
+ }
+
+ // TODO return Ext.data.Response instance instead. @see #readResponse
+ return {
+ success : success,
+ records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
+ totalRecords : totalRecords
+ };
+ },
+
+ // private
+ buildExtractors : function() {
+ if(this.ef){
+ return;
+ }
+ var s = this.meta, Record = this.recordType,
+ f = Record.prototype.fields, fi = f.items, fl = f.length;
+
+ if(s.totalProperty) {
+ this.getTotal = this.createAccessor(s.totalProperty);
+ }
+ if(s.successProperty) {
+ this.getSuccess = this.createAccessor(s.successProperty);
+ }
+ if (s.messageProperty) {
+ this.getMessage = this.createAccessor(s.messageProperty);
+ }
+ this.getRoot = s.root ? this.createAccessor(s.root) : function(p){return p;};
+ if (s.id || s.idProperty) {
+ var g = this.createAccessor(s.id || s.idProperty);
+ this.getId = function(rec) {
+ var r = g(rec);
+ return (r === undefined || r === '') ? null : r;
+ };
+ } else {
+ this.getId = function(){return null;};
+ }
+ var ef = [];
+ for(var i = 0; i < fl; i++){
+ f = fi[i];
+ var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
+ ef.push(this.createAccessor(map));
+ }
+ this.ef = ef;
+ },
+
+ /**
+ * @ignore
+ * TODO This isn't used anywhere?? Don't we want to use this where possible instead of complex #createAccessor?
+ */
+ simpleAccess : function(obj, subsc) {
+ return obj[subsc];
+ },
+
+ /**
+ * @ignore
+ */
+ createAccessor : function(){
+ var re = /[\[\.]/;
+ return function(expr) {
+ if(Ext.isEmpty(expr)){
+ return Ext.emptyFn;
+ }
+ if(Ext.isFunction(expr)){
+ return expr;
+ }
+ var i = String(expr).search(re);
+ if(i >= 0){
+ return new Function('obj', 'return obj' + (i > 0 ? '.' : '') + expr);
+ }
+ return function(obj){
+ return obj[expr];
+ };
+
+ };
+ }(),
+
+ /**
+ * type-casts a single row of raw-data from server
+ * @param {Object} data
+ * @param {Array} items
+ * @param {Integer} len
+ * @private
+ */
+ extractValues : function(data, items, len) {
+ var f, values = {};
+ for(var j = 0; j < len; j++){
+ f = items[j];
+ var v = this.ef[j](data);
+ values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
+ }
+ return values;
+ }
+});
+
+/**
+ * @class Ext.data.JsonReader.Error
+ * Error class for JsonReader
+ */
+Ext.data.JsonReader.Error = Ext.extend(Ext.Error, {
+ constructor : function(message, arg) {
+ this.arg = arg;
+ Ext.Error.call(this, message);
+ },
+ name : 'Ext.data.JsonReader'
+});
+Ext.apply(Ext.data.JsonReader.Error.prototype, {
+ lang: {
+ 'response': 'An error occurred while json-decoding your server response',
+ 'successProperty-response': 'Could not locate your "successProperty" in your server response. Please review your JsonReader config to ensure the config-property "successProperty" matches the property in your server-response. See the JsonReader docs.',
+ 'root-undefined-config': 'Your JsonReader was configured without a "root" property. Please review your JsonReader config and make sure to define the root property. See the JsonReader docs.',
+ 'idProperty-undefined' : 'Your JsonReader was configured without an "idProperty" Please review your JsonReader configuration and ensure the "idProperty" is set (e.g.: "id"). See the JsonReader docs.',
+ 'root-empty': 'Data was expected to be returned by the server in the "root" property of the response. Please review your JsonReader configuration to ensure the "root" property matches that returned in the server-response. See JsonReader docs.'
+ }
+});
+/**
+ * @class Ext.data.ArrayReader
+ * @extends Ext.data.JsonReader
+ * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an Array.
+ * Each element of that Array represents a row of data fields. The
+ * fields are pulled into a Record object using as a subscript, the <code>mapping</code> property
+ * of the field definition if it exists, or the field's ordinal position in the definition.</p>
+ * <p>Example code:</p>
+ * <pre><code>
+var Employee = Ext.data.Record.create([
+ {name: 'name', mapping: 1}, // "mapping" only needed if an "id" field is present which
+ {name: 'occupation', mapping: 2} // precludes using the ordinal position as the index.
+]);
+var myReader = new Ext.data.ArrayReader({
+ {@link #idIndex}: 0
+}, Employee);
+</code></pre>
+ * <p>This would consume an Array like this:</p>
+ * <pre><code>
+[ [1, 'Bill', 'Gardener'], [2, 'Ben', 'Horticulturalist'] ]
+ * </code></pre>
+ * @constructor
+ * Create a new ArrayReader
+ * @param {Object} meta Metadata configuration options.
+ * @param {Array/Object} recordType
+ * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which
+ * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}
+ * constructor created from {@link Ext.data.Record#create}.</p>
+ */
+Ext.data.ArrayReader = Ext.extend(Ext.data.JsonReader, {
+ /**
+ * @cfg {String} successProperty
+ * @hide
+ */
+ /**
+ * @cfg {Number} id (optional) The subscript within row Array that provides an ID for the Record.
+ * Deprecated. Use {@link #idIndex} instead.
+ */
+ /**
+ * @cfg {Number} idIndex (optional) The subscript within row Array that provides an ID for the Record.
+ */
+ /**
+ * Create a data block containing Ext.data.Records from an Array.
+ * @param {Object} o An Array of row objects which represents the dataset.
+ * @return {Object} data A data block which is used by an Ext.data.Store object as
+ * a cache of Ext.data.Records.
+ */
+ readRecords : function(o){
+ this.arrayData = o;
+ var s = this.meta,
+ sid = s ? Ext.num(s.idIndex, s.id) : null,
+ recordType = this.recordType,
+ fields = recordType.prototype.fields,
+ records = [],
+ success = true,
+ v;
+
+ var root = this.getRoot(o);
+
+ for(var i = 0, len = root.length; i < len; i++) {
+ var n = root[i],
+ values = {},
+ id = ((sid || sid === 0) && n[sid] !== undefined && n[sid] !== "" ? n[sid] : null);
+ for(var j = 0, jlen = fields.length; j < jlen; j++) {
+ var f = fields.items[j],
+ k = f.mapping !== undefined && f.mapping !== null ? f.mapping : j;
+ v = n[k] !== undefined ? n[k] : f.defaultValue;
+ v = f.convert(v, n);
+ values[f.name] = v;
+ }
+ var record = new recordType(values, id);
+ record.json = n;
+ records[records.length] = record;
+ }
+
+ var totalRecords = records.length;
+
+ if(s.totalProperty) {
+ v = parseInt(this.getTotal(o), 10);
+ if(!isNaN(v)) {
+ totalRecords = v;
+ }
+ }
+ if(s.successProperty){
+ v = this.getSuccess(o);
+ if(v === false || v === 'false'){
+ success = false;
+ }
+ }
+
+ return {
+ success : success,
+ records : records,
+ totalRecords : totalRecords
+ };
+ }
+});/**
+ * @class Ext.data.ArrayStore
+ * @extends Ext.data.Store
+ * <p>Formerly known as "SimpleStore".</p>
+ * <p>Small helper class to make creating {@link Ext.data.Store}s from Array data easier.
+ * An ArrayStore will be automatically configured with a {@link Ext.data.ArrayReader}.</p>
+ * <p>A store configuration would be something like:<pre><code>
+var store = new Ext.data.ArrayStore({
+ // store configs
+ autoDestroy: true,
+ storeId: 'myStore',
+ // reader configs
+ idIndex: 0,
+ fields: [
+ 'company',
+ {name: 'price', type: 'float'},
+ {name: 'change', type: 'float'},
+ {name: 'pctChange', type: 'float'},
+ {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
+ ]
+});
+ * </code></pre></p>
+ * <p>This store is configured to consume a returned object of the form:<pre><code>
+var myData = [
+ ['3m Co',71.72,0.02,0.03,'9/1 12:00am'],
+ ['Alcoa Inc',29.01,0.42,1.47,'9/1 12:00am'],
+ ['Boeing Co.',75.43,0.53,0.71,'9/1 12:00am'],
+ ['Hewlett-Packard Co.',36.53,-0.03,-0.08,'9/1 12:00am'],
+ ['Wal-Mart Stores, Inc.',45.45,0.73,1.63,'9/1 12:00am']
+];
+ * </code></pre>
+ * An object literal of this form could also be used as the {@link #data} config option.</p>
+ * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
+ * <b>{@link Ext.data.ArrayReader ArrayReader}</b>.</p>
+ * @constructor
+ * @param {Object} config
+ * @xtype arraystore
+ */
+Ext.data.ArrayStore = Ext.extend(Ext.data.Store, {
+ /**
+ * @cfg {Ext.data.DataReader} reader @hide
+ */
+ constructor: function(config){
+ Ext.data.ArrayStore.superclass.constructor.call(this, Ext.apply(config, {
+ reader: new Ext.data.ArrayReader(config)
+ }));
+ },
+
+ loadData : function(data, append){
+ if(this.expandData === true){
+ var r = [];
+ for(var i = 0, len = data.length; i < len; i++){
+ r[r.length] = [data[i]];
+ }
+ data = r;
+ }
+ Ext.data.ArrayStore.superclass.loadData.call(this, data, append);
+ }
+});
+Ext.reg('arraystore', Ext.data.ArrayStore);
+
+// backwards compat
+Ext.data.SimpleStore = Ext.data.ArrayStore;
+Ext.reg('simplestore', Ext.data.SimpleStore);/**
+ * @class Ext.data.JsonStore
+ * @extends Ext.data.Store
+ * <p>Small helper class to make creating {@link Ext.data.Store}s from JSON data easier.
+ * A JsonStore will be automatically configured with a {@link Ext.data.JsonReader}.</p>
+ * <p>A store configuration would be something like:<pre><code>
+var store = new Ext.data.JsonStore({
+ // store configs
+ autoDestroy: true,
+ url: 'get-images.php',
+ storeId: 'myStore',
+ // reader configs
+ root: 'images',
+ idProperty: 'name',
+ fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date'}]
+});
+ * </code></pre></p>
+ * <p>This store is configured to consume a returned object of the form:<pre><code>
+{
+ images: [
+ {name: 'Image one', url:'/GetImage.php?id=1', size:46.5, lastmod: new Date(2007, 10, 29)},
+ {name: 'Image Two', url:'/GetImage.php?id=2', size:43.2, lastmod: new Date(2007, 10, 30)}
+ ]
+}
+ * </code></pre>
+ * An object literal of this form could also be used as the {@link #data} config option.</p>
+ * <p><b>*Note:</b> Although not listed here, this class accepts all of the configuration options of
+ * <b>{@link Ext.data.JsonReader JsonReader}</b>.</p>
+ * @constructor
+ * @param {Object} config
+ * @xtype jsonstore
+ */
+Ext.data.JsonStore = Ext.extend(Ext.data.Store, {
+ /**
+ * @cfg {Ext.data.DataReader} reader @hide
+ */
+ constructor: function(config){
+ Ext.data.JsonStore.superclass.constructor.call(this, Ext.apply(config, {
+ reader: new Ext.data.JsonReader(config)
+ }));
+ }
+});
+Ext.reg('jsonstore', Ext.data.JsonStore);/**
+ * @class Ext.data.XmlWriter
+ * @extends Ext.data.DataWriter
+ * DataWriter extension for writing an array or single {@link Ext.data.Record} object(s) in preparation for executing a remote CRUD action via XML.
+ * XmlWriter uses an instance of {@link Ext.XTemplate} for maximum flexibility in defining your own custom XML schema if the default schema is not appropriate for your needs.
+ * See the {@link #tpl} configuration-property.
+ */
+Ext.data.XmlWriter = function(params) {
+ Ext.data.XmlWriter.superclass.constructor.apply(this, arguments);
+ // compile the XTemplate for rendering XML documents.
+ this.tpl = (typeof(this.tpl) === 'string') ? new Ext.XTemplate(this.tpl).compile() : this.tpl.compile();
+};
+Ext.extend(Ext.data.XmlWriter, Ext.data.DataWriter, {
+ /**
+ * @cfg {String} documentRoot [xrequest] (Optional) The name of the XML document root-node. <b>Note:</b>
+ * this parameter is required </b>only when</b> sending extra {@link Ext.data.Store#baseParams baseParams} to the server
+ * during a write-request -- if no baseParams are set, the {@link Ext.data.XmlReader#record} meta-property can
+ * suffice as the XML document root-node for write-actions involving just a <b>single record</b>. For requests
+ * involving <b>multiple</b> records and <b>NO</b> baseParams, the {@link Ext.data.XmlWriter#root} property can
+ * act as the XML document root.
+ */
+ documentRoot: 'xrequest',
+ /**
+ * @cfg {Boolean} forceDocumentRoot [false] Set to <tt>true</tt> to force XML documents having a root-node as defined
+ * by {@link #documentRoot}, even with no baseParams defined.
+ */
+ forceDocumentRoot: false,
+ /**
+ * @cfg {String} root [records] The name of the containing element which will contain the nodes of an write-action involving <b>multiple</b> records. Each
+ * xml-record written to the server will be wrapped in an element named after {@link Ext.data.XmlReader#record} property.
+ * eg:
+<code><pre>
+<?xml version="1.0" encoding="UTF-8"?>
+<user><first>Barney</first></user>
+</code></pre>
+ * However, when <b>multiple</b> records are written in a batch-operation, these records must be wrapped in a containing
+ * Element.
+ * eg:
+<code><pre>
+<?xml version="1.0" encoding="UTF-8"?>
+ <records>
+ <first>Barney</first></user>
+ <records><first>Barney</first></user>
+ </records>
+</code></pre>
+ * Defaults to <tt>records</tt>. Do not confuse the nature of this property with that of {@link #documentRoot}
+ */
+ root: 'records',
+ /**
+ * @cfg {String} xmlVersion [1.0] The <tt>version</tt> written to header of xml documents.
+<code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
+ */
+ xmlVersion : '1.0',
+ /**
+ * @cfg {String} xmlEncoding [ISO-8859-15] The <tt>encoding</tt> written to header of xml documents.
+<code><pre><?xml version="1.0" encoding="ISO-8859-15"?></pre></code>
+ */
+ xmlEncoding: 'ISO-8859-15',
+ /**
+ * @cfg {String/Ext.XTemplate} tpl The XML template used to render {@link Ext.data.Api#actions write-actions} to your server.
+ * <p>One can easily provide his/her own custom {@link Ext.XTemplate#constructor template-definition} if the default does not suffice.</p>
+ * <p>Defaults to:</p>
+<code><pre>
+<?xml version="{version}" encoding="{encoding}"?>
+ <tpl if="documentRoot"><{documentRoot}>
+ <tpl for="baseParams">
+ <tpl for=".">
+ <{name}>{value}</{name}>
+ </tpl>
+ </tpl>
+ <tpl if="records.length > 1"><{root}>',
+ <tpl for="records">
+ <{parent.record}>
+ <tpl for=".">
+ <{name}>{value}</{name}>
+ </tpl>
+ </{parent.record}>
+ </tpl>
+ <tpl if="records.length > 1"></{root}></tpl>
+ <tpl if="documentRoot"></{documentRoot}></tpl>
+</pre></code>
+ * <p>Templates will be called with the following API</p>
+ * <ul>
+ * <li>{String} version [1.0] The xml version.</li>
+ * <li>{String} encoding [ISO-8859-15] The xml encoding.</li>
+ * <li>{String/false} documentRoot The XML document root-node name or <tt>false</tt> if not required. See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
+ * <li>{String} record The meta-data parameter defined on your {@link Ext.data.XmlReader#record} configuration represents the name of the xml-tag containing each record.</li>
+ * <li>{String} root The meta-data parameter defined by {@link Ext.data.XmlWriter#root} configuration-parameter. Represents the name of the xml root-tag when sending <b>multiple</b> records to the server.</li>
+ * <li>{Array} records The records being sent to the server, ie: the subject of the write-action being performed. The records parameter will be always be an array, even when only a single record is being acted upon.
+ * Each item within the records array will contain an array of field objects having the following properties:
+ * <ul>
+ * <li>{String} name The field-name of the record as defined by your {@link Ext.data.Record#create Ext.data.Record definition}. The "mapping" property will be used, otherwise it will match the "name" property. Use this parameter to define the XML tag-name of the property.</li>
+ * <li>{Mixed} value The record value of the field enclosed within XML tags specified by name property above.</li>
+ * </ul></li>
+ * <li>{Array} baseParams. The baseParams as defined upon {@link Ext.data.Store#baseParams}. Note that the baseParams have been converted into an array of [{name : "foo", value: "bar"}, ...] pairs in the same manner as the <b>records</b> parameter above. See {@link #documentRoot} and {@link #forceDocumentRoot}.</li>
+ * </ul>
+ */
+ // Encoding the ? here in case it's being included by some kind of page that will parse it (eg. PHP)
+ tpl: '<tpl for="."><\u003fxml version="{version}" encoding="{encoding}"\u003f><tpl if="documentRoot"><{documentRoot}><tpl for="baseParams"><tpl for="."><{name}>{value}</{name}</tpl></tpl></tpl><tpl if="records.length>1"><{root}></tpl><tpl for="records"><{parent.record}><tpl for="."><{name}>{value}</{name}></tpl></{parent.record}></tpl><tpl if="records.length>1"></{root}></tpl><tpl if="documentRoot"></{documentRoot}></tpl></tpl>',
+
+
+ /**
+ * XmlWriter implementation of the final stage of a write action.
+ * @param {Object} params Transport-proxy's (eg: {@link Ext.Ajax#request}) params-object to write-to.
+ * @param {Object} baseParams as defined by {@link Ext.data.Store#baseParams}. The baseParms must be encoded by the extending class, eg: {@link Ext.data.JsonWriter}, {@link Ext.data.XmlWriter}.
+ * @param {Object/Object[]} data Data-object representing the compiled Store-recordset.
+ */
+ render : function(params, baseParams, data) {
+ baseParams = this.toArray(baseParams);
+ params.xmlData = this.tpl.applyTemplate({
+ version: this.xmlVersion,
+ encoding: this.xmlEncoding,
+ documentRoot: (baseParams.length > 0 || this.forceDocumentRoot === true) ? this.documentRoot : false,
+ record: this.meta.record,
+ root: this.root,
+ baseParams: baseParams,
+ records: (Ext.isArray(data[0])) ? data : [data]
+ });
+ },
+
+ /**
+ * createRecord
+ * @protected
+ * @param {Ext.data.Record} rec
+ * @return {Array} Array of <tt>name:value</tt> pairs for attributes of the {@link Ext.data.Record}. See {@link Ext.data.DataWriter#toHash}.
+ */
+ createRecord : function(rec) {
+ return this.toArray(this.toHash(rec));
+ },
+
+ /**
+ * updateRecord
+ * @protected
+ * @param {Ext.data.Record} rec
+ * @return {Array} Array of {name:value} pairs for attributes of the {@link Ext.data.Record}. See {@link Ext.data.DataWriter#toHash}.
+ */
+ updateRecord : function(rec) {
+ return this.toArray(this.toHash(rec));
+
+ },
+ /**
+ * destroyRecord
+ * @protected
+ * @param {Ext.data.Record} rec
+ * @return {Array} Array containing a attribute-object (name/value pair) representing the {@link Ext.data.DataReader#idProperty idProperty}.
+ */
+ destroyRecord : function(rec) {
+ var data = {};
+ data[this.meta.idProperty] = rec.id;
+ return this.toArray(data);
+ }
+});
+/**
+ * @class Ext.data.XmlReader
+ * @extends Ext.data.DataReader
+ * <p>Data reader class to create an Array of {@link Ext.data.Record} objects from an XML document
+ * based on mappings in a provided {@link Ext.data.Record} constructor.</p>
+ * <p><b>Note</b>: that in order for the browser to parse a returned XML document, the Content-Type
+ * header in the HTTP response must be set to "text/xml" or "application/xml".</p>
+ * <p>Example code:</p>
+ * <pre><code>
+var Employee = Ext.data.Record.create([
+ {name: 'name', mapping: 'name'}, // "mapping" property not needed if it is the same as "name"
+ {name: 'occupation'} // This field will use "occupation" as the mapping.
+]);
+var myReader = new Ext.data.XmlReader({
+ totalProperty: "results", // The element which contains the total dataset size (optional)
+ record: "row", // The repeated element which contains row information
+ idProperty: "id" // The element within the row that provides an ID for the record (optional)
+ messageProperty: "msg" // The element within the response that provides a user-feedback message (optional)
+}, Employee);
+</code></pre>
+ * <p>
+ * This would consume an XML file like this:
+ * <pre><code>
+<?xml version="1.0" encoding="UTF-8"?>
+<dataset>
+ <results>2</results>
+ <row>
+ <id>1</id>
+ <name>Bill</name>
+ <occupation>Gardener</occupation>
+ </row>
+ <row>
+ <id>2</id>
+ <name>Ben</name>
+ <occupation>Horticulturalist</occupation>
+ </row>
+</dataset>
+</code></pre>
+ * @cfg {String} totalProperty The DomQuery path from which to retrieve the total number of records
+ * in the dataset. This is only needed if the whole dataset is not passed in one go, but is being
+ * paged from the remote server.
+ * @cfg {String} record The DomQuery path to the repeated element which contains record information.
+ * @cfg {String} record The DomQuery path to the repeated element which contains record information.
+ * @cfg {String} successProperty The DomQuery path to the success attribute used by forms.
+ * @cfg {String} idPath The DomQuery path relative from the record element to the element that contains
+ * a record identifier value.
+ * @constructor
+ * Create a new XmlReader.
+ * @param {Object} meta Metadata configuration options
+ * @param {Object} recordType Either an Array of field definition objects as passed to
+ * {@link Ext.data.Record#create}, or a Record constructor object created using {@link Ext.data.Record#create}.
+ */
+Ext.data.XmlReader = function(meta, recordType){
+ meta = meta || {};
+
+ // backwards compat, convert idPath or id / success
+ Ext.applyIf(meta, {
+ idProperty: meta.idProperty || meta.idPath || meta.id,
+ successProperty: meta.successProperty || meta.success
+ });
+
+ Ext.data.XmlReader.superclass.constructor.call(this, meta, recordType || meta.fields);
+};
+Ext.extend(Ext.data.XmlReader, Ext.data.DataReader, {
+ /**
+ * This method is only used by a DataProxy which has retrieved data from a remote server.
+ * @param {Object} response The XHR object which contains the parsed XML document. The response is expected
+ * to contain a property called <tt>responseXML</tt> which refers to an XML document object.
+ * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
+ * a cache of Ext.data.Records.
+ */
+ read : function(response){
+ var doc = response.responseXML;
+ if(!doc) {
+ throw {message: "XmlReader.read: XML Document not available"};
+ }
+ return this.readRecords(doc);
+ },
+
+ /**
+ * Create a data block containing Ext.data.Records from an XML document.
+ * @param {Object} doc A parsed XML document.
+ * @return {Object} records A data block which is used by an {@link Ext.data.Store} as
+ * a cache of Ext.data.Records.
+ */
+ readRecords : function(doc){
+ /**
+ * After any data loads/reads, the raw XML Document is available for further custom processing.
+ * @type XMLDocument
+ */
+ this.xmlData = doc;
+
+ var root = doc.documentElement || doc,
+ q = Ext.DomQuery,
+ totalRecords = 0,
+ success = true;
+
+ if(this.meta.totalProperty){
+ totalRecords = this.getTotal(root, 0);
+ }
+ if(this.meta.successProperty){
+ success = this.getSuccess(root);
+ }
+
+ var records = this.extractData(q.select(this.meta.record, root), true); // <-- true to return Ext.data.Record[]
+
+ // TODO return Ext.data.Response instance. @see #readResponse
+ return {
+ success : success,
+ records : records,
+ totalRecords : totalRecords || records.length
+ };
+ },
+
+ /**
+ * Decode an XML response from server.
+ * @param {String} action [{@link Ext.data.Api#actions} create|read|update|destroy]
+ * @param {Object} response HTTP Response object from browser.
+ * @return {Ext.data.Response} An instance of {@link Ext.data.Response}
+ */
+ readResponse : function(action, response) {
+ var q = Ext.DomQuery,
+ doc = response.responseXML;
+
+ // create general Response instance.
+ var res = new Ext.data.Response({
+ action: action,
+ success : this.getSuccess(doc),
+ message: this.getMessage(doc),
+ data: this.extractData(q.select(this.meta.record, doc) || q.select(this.meta.root, doc), false),
+ raw: doc
+ });
+
+ if (Ext.isEmpty(res.success)) {
+ throw new Ext.data.DataReader.Error('successProperty-response', this.meta.successProperty);
+ }
+
+ // Create actions from a response having status 200 must return pk
+ if (action === Ext.data.Api.actions.create) {
+ var def = Ext.isDefined(res.data);
+ if (def && Ext.isEmpty(res.data)) {
+ throw new Ext.data.JsonReader.Error('root-empty', this.meta.root);
+ }
+ else if (!def) {
+ throw new Ext.data.JsonReader.Error('root-undefined-response', this.meta.root);
+ }
+ }
+ return res;
+ },
+
+ getSuccess : function() {
+ return true;
+ },
+
+ /**
+ * build response-data extractor functions.
+ * @private
+ * @ignore
+ */
+ buildExtractors : function() {
+ if(this.ef){
+ return;
+ }
+ var s = this.meta,
+ Record = this.recordType,
+ f = Record.prototype.fields,
+ fi = f.items,
+ fl = f.length;
+
+ if(s.totalProperty) {
+ this.getTotal = this.createAccessor(s.totalProperty);
+ }
+ if(s.successProperty) {
+ this.getSuccess = this.createAccessor(s.successProperty);
+ }
+ if (s.messageProperty) {
+ this.getMessage = this.createAccessor(s.messageProperty);
+ }
+ this.getRoot = function(res) {
+ return (!Ext.isEmpty(res[this.meta.record])) ? res[this.meta.record] : res[this.meta.root];
+ };
+ if (s.idPath || s.idProperty) {
+ var g = this.createAccessor(s.idPath || s.idProperty);
+ this.getId = function(rec) {
+ var id = g(rec) || rec.id;
+ return (id === undefined || id === '') ? null : id;
+ };
+ } else {
+ this.getId = function(){return null;};
+ }
+ var ef = [];
+ for(var i = 0; i < fl; i++){
+ f = fi[i];
+ var map = (f.mapping !== undefined && f.mapping !== null) ? f.mapping : f.name;
+ ef.push(this.createAccessor(map));
+ }
+ this.ef = ef;
+ },
+
+ /**
+ * Creates a function to return some particular key of data from a response.
+ * @param {String} key
+ * @return {Function}
+ * @private
+ * @ignore
+ */
+ createAccessor : function(){
+ var q = Ext.DomQuery;
+ return function(key) {
+ switch(key) {
+ case this.meta.totalProperty:
+ return function(root, def){
+ return q.selectNumber(key, root, def);
+ };
+ break;
+ case this.meta.successProperty:
+ return function(root, def) {
+ var sv = q.selectValue(key, root, true);
+ var success = sv !== false && sv !== 'false';
+ return success;
+ };
+ break;
+ default:
+ return function(root, def) {
+ return q.selectValue(key, root, def);
+ };
+ break;
+ }
+ };
+ }(),
+
+ /**
+ * extracts values and type-casts a row of data from server, extracted by #extractData
+ * @param {Hash} data
+ * @param {Ext.data.Field[]} items
+ * @param {Number} len
+ * @private
+ * @ignore
+ */
+ extractValues : function(data, items, len) {
+ var f, values = {};
+ for(var j = 0; j < len; j++){
+ f = items[j];
+ var v = this.ef[j](data);
+ values[f.name] = f.convert((v !== undefined) ? v : f.defaultValue, data);
+ }
+ return values;
+ }
+});/**
+ * @class Ext.data.XmlStore
+ * @extends Ext.data.Store
+ * <p>Small helper class to make creating {@link Ext.data.Store}s from XML data easier.
+ * A XmlStore will be automatically configured with a {@link Ext.data.XmlReader}.</p>
+ * <p>A store configuration would be something like:<pre><code>
+var store = new Ext.data.XmlStore({
+ // store configs
+ autoDestroy: true,
+ storeId: 'myStore',
+ url: 'sheldon.xml', // automatically configures a HttpProxy
+ // reader configs
+ record: 'Item', // records will have an "Item" tag
+ idPath: 'ASIN',
+ totalRecords: '@TotalResults'
+ fields: [
+ // set up the fields mapping into the xml doc
+ // The first needs mapping, the others are very basic
+ {name: 'Author', mapping: 'ItemAttributes > Author'},
+ 'Title', 'Manufacturer', 'ProductGroup'
+ ]
+});
+ * </code></pre></p>
+ * <p>This store is configured to consume a returned object of the form:<pre><code>
+<?xml version="1.0" encoding="UTF-8"?>
+<ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2009-05-15">
+ <Items>
+ <Request>
+ <IsValid>True</IsValid>
+ <ItemSearchRequest>
+ <Author>Sidney Sheldon</Author>
+ <SearchIndex>Books</SearchIndex>
+ </ItemSearchRequest>
+ </Request>
+ <TotalResults>203</TotalResults>
+ <TotalPages>21</TotalPages>
+ <Item>
+ <ASIN>0446355453</ASIN>
+ <DetailPageURL>
+ http://www.amazon.com/
+ </DetailPageURL>
+ <ItemAttributes>
+ <Author>Sidney Sheldon</Author>
+ <Manufacturer>Warner Books</Manufacturer>
+ <ProductGroup>Book</ProductGroup>
+ <Title>Master of the Game</Title>
+ </ItemAttributes>
+ </Item>
+ </Items>
+</ItemSearchResponse>
+ * </code></pre>
+ * An object literal of this form could also be used as the {@link #data} config option.</p>
+ * <p><b>Note:</b> Although not listed here, this class accepts all of the configuration options of
+ * <b>{@link Ext.data.XmlReader XmlReader}</b>.</p>
+ * @constructor
+ * @param {Object} config
+ * @xtype xmlstore
+ */
+Ext.data.XmlStore = Ext.extend(Ext.data.Store, {
+ /**
+ * @cfg {Ext.data.DataReader} reader @hide
+ */
+ constructor: function(config){
+ Ext.data.XmlStore.superclass.constructor.call(this, Ext.apply(config, {
+ reader: new Ext.data.XmlReader(config)
+ }));
+ }
+});
+Ext.reg('xmlstore', Ext.data.XmlStore);/**
+ * @class Ext.data.GroupingStore
+ * @extends Ext.data.Store
+ * A specialized store implementation that provides for grouping records by one of the available fields. This
+ * is usually used in conjunction with an {@link Ext.grid.GroupingView} to provide the data model for
+ * a grouped GridPanel.
+ *
+ * Internally, GroupingStore is simply a normal Store with multi sorting enabled from the start. The grouping field
+ * and direction are always injected as the first sorter pair. GroupingView picks up on the configured groupField and
+ * builds grid rows appropriately.
+ *
+ * @constructor
+ * Creates a new GroupingStore.
+ * @param {Object} config A config object containing the objects needed for the Store to access data,
+ * and read the data into Records.
+ * @xtype groupingstore
+ */
+Ext.data.GroupingStore = Ext.extend(Ext.data.Store, {
+
+ //inherit docs
+ constructor: function(config) {
+ config = config || {};
+
+ //We do some preprocessing here to massage the grouping + sorting options into a single
+ //multi sort array. If grouping and sorting options are both presented to the constructor,
+ //the sorters array consists of the grouping sorter object followed by the sorting sorter object
+ //see Ext.data.Store's sorting functions for details about how multi sorting works
+ this.hasMultiSort = true;
+ this.multiSortInfo = this.multiSortInfo || {sorters: []};
+
+ var sorters = this.multiSortInfo.sorters,
+ groupField = config.groupField || this.groupField,
+ sortInfo = config.sortInfo || this.sortInfo,
+ groupDir = config.groupDir || this.groupDir;
+
+ //add the grouping sorter object first
+ if(groupField){
+ sorters.push({
+ field : groupField,
+ direction: groupDir
+ });
+ }
+
+ //add the sorting sorter object if it is present
+ if (sortInfo) {
+ sorters.push(sortInfo);
+ }
+
+ Ext.data.GroupingStore.superclass.constructor.call(this, config);
+
+ this.addEvents(
+ /**
+ * @event groupchange
+ * Fired whenever a call to store.groupBy successfully changes the grouping on the store
+ * @param {Ext.data.GroupingStore} store The grouping store
+ * @param {String} groupField The field that the store is now grouped by
+ */
+ 'groupchange'
+ );
+
+ this.applyGroupField();
+ },
+
+ /**
+ * @cfg {String} groupField
+ * The field name by which to sort the store's data (defaults to '').
+ */
+ /**
+ * @cfg {Boolean} remoteGroup
+ * True if the grouping should apply on the server side, false if it is local only (defaults to false). If the
+ * grouping is local, it can be applied immediately to the data. If it is remote, then it will simply act as a
+ * helper, automatically sending the grouping field name as the 'groupBy' param with each XHR call.
+ */
+ remoteGroup : false,
+ /**
+ * @cfg {Boolean} groupOnSort
+ * True to sort the data on the grouping field when a grouping operation occurs, false to sort based on the
+ * existing sort info (defaults to false).
+ */
+ groupOnSort:false,
+
+ groupDir : 'ASC',
+
+ /**
+ * Clears any existing grouping and refreshes the data using the default sort.
+ */
+ clearGrouping : function(){
+ this.groupField = false;
+
+ if(this.remoteGroup){
+ if(this.baseParams){
+ delete this.baseParams.groupBy;
+ delete this.baseParams.groupDir;
+ }
+ var lo = this.lastOptions;
+ if(lo && lo.params){
+ delete lo.params.groupBy;
+ delete lo.params.groupDir;
+ }
+
+ this.reload();
+ }else{
+ this.sort();
+ this.fireEvent('datachanged', this);
+ }
+ },
+
+ /**
+ * Groups the data by the specified field.
+ * @param {String} field The field name by which to sort the store's data
+ * @param {Boolean} forceRegroup (optional) True to force the group to be refreshed even if the field passed
+ * in is the same as the current grouping field, false to skip grouping on the same field (defaults to false)
+ */
+ groupBy : function(field, forceRegroup, direction) {
+ direction = direction ? (String(direction).toUpperCase() == 'DESC' ? 'DESC' : 'ASC') : this.groupDir;
+
+ if (this.groupField == field && this.groupDir == direction && !forceRegroup) {
+ return; // already grouped by this field
+ }
+
+ //check the contents of the first sorter. If the field matches the CURRENT groupField (before it is set to the new one),
+ //remove the sorter as it is actually the grouper. The new grouper is added back in by this.sort
+ sorters = this.multiSortInfo.sorters;
+ if (sorters.length > 0 && sorters[0].field == this.groupField) {
+ sorters.shift();
+ }
+
+ this.groupField = field;
+ this.groupDir = direction;
+ this.applyGroupField();
+
+ var fireGroupEvent = function() {
+ this.fireEvent('groupchange', this, this.getGroupState());
+ };
+
+ if (this.groupOnSort) {
+ this.sort(field, direction);
+ fireGroupEvent.call(this);
+ return;
+ }
+
+ if (this.remoteGroup) {
+ this.on('load', fireGroupEvent, this, {single: true});
+ this.reload();
+ } else {
+ this.sort(sorters);
+ fireGroupEvent.call(this);
+ }
+ },
+
+ //GroupingStore always uses multisorting so we intercept calls to sort here to make sure that our grouping sorter object
+ //is always injected first.
+ sort : function(fieldName, dir) {
+ if (this.remoteSort) {
+ return Ext.data.GroupingStore.superclass.sort.call(this, fieldName, dir);
+ }
+
+ var sorters = [];
+
+ //cater for any existing valid arguments to this.sort, massage them into an array of sorter objects
+ if (Ext.isArray(arguments[0])) {
+ sorters = arguments[0];
+ } else if (fieldName == undefined) {
+ //we preserve the existing sortInfo here because this.sort is called after
+ //clearGrouping and there may be existing sorting
+ sorters = [this.sortInfo];
+ } else {
+ //TODO: this is lifted straight from Ext.data.Store's singleSort function. It should instead be
+ //refactored into a common method if possible
+ var field = this.fields.get(fieldName);
+ if (!field) return false;
+
+ var name = field.name,
+ sortInfo = this.sortInfo || null,
+ sortToggle = this.sortToggle ? this.sortToggle[name] : null;
+
+ if (!dir) {
+ if (sortInfo && sortInfo.field == name) { // toggle sort dir
+ dir = (this.sortToggle[name] || 'ASC').toggle('ASC', 'DESC');
+ } else {
+ dir = field.sortDir;
+ }
+ }
+
+ this.sortToggle[name] = dir;
+ this.sortInfo = {field: name, direction: dir};
+
+ sorters = [this.sortInfo];
+ }
+
+ //add the grouping sorter object as the first multisort sorter
+ if (this.groupField) {
+ sorters.unshift({direction: this.groupDir, field: this.groupField});
+ }
+
+ return this.multiSort.call(this, sorters, dir);
+ },
+
+ /**
+ * @private
+ * Saves the current grouping field and direction to this.baseParams and this.lastOptions.params
+ * if we're using remote grouping. Does not actually perform any grouping - just stores values
+ */
+ applyGroupField: function(){
+ if (this.remoteGroup) {
+ if(!this.baseParams){
+ this.baseParams = {};
+ }
+
+ Ext.apply(this.baseParams, {
+ groupBy : this.groupField,
+ groupDir: this.groupDir
+ });
+
+ var lo = this.lastOptions;
+ if (lo && lo.params) {
+ lo.params.groupDir = this.groupDir;
+
+ //this is deleted because of a bug reported at http://www.extjs.com/forum/showthread.php?t=82907
+ delete lo.params.groupBy;
+ }
+ }
+ },
+
+ /**
+ * @private
+ * TODO: This function is apparently never invoked anywhere in the framework. It has no documentation
+ * and should be considered for deletion
+ */
+ applyGrouping : function(alwaysFireChange){
+ if(this.groupField !== false){
+ this.groupBy(this.groupField, true, this.groupDir);
+ return true;
+ }else{
+ if(alwaysFireChange === true){
+ this.fireEvent('datachanged', this);
+ }
+ return false;
+ }
+ },
+
+ /**
+ * @private
+ * Returns the grouping field that should be used. If groupOnSort is used this will be sortInfo's field,
+ * otherwise it will be this.groupField
+ * @return {String} The group field
+ */
+ getGroupState : function(){
+ return this.groupOnSort && this.groupField !== false ?
+ (this.sortInfo ? this.sortInfo.field : undefined) : this.groupField;
+ }
+});
+Ext.reg('groupingstore', Ext.data.GroupingStore);
+/**
+ * @class Ext.data.DirectProxy
+ * @extends Ext.data.DataProxy
+ */
+Ext.data.DirectProxy = function(config){
+ Ext.apply(this, config);
+ if(typeof this.paramOrder == 'string'){
+ this.paramOrder = this.paramOrder.split(/[\s,|]/);
+ }
+ Ext.data.DirectProxy.superclass.constructor.call(this, config);
+};
+
+Ext.extend(Ext.data.DirectProxy, Ext.data.DataProxy, {
+ /**
+ * @cfg {Array/String} paramOrder Defaults to <tt>undefined</tt>. A list of params to be executed
+ * server side. Specify the params in the order in which they must be executed on the server-side
+ * as either (1) an Array of String values, or (2) a String of params delimited by either whitespace,
+ * comma, or pipe. For example,
+ * any of the following would be acceptable:<pre><code>
+paramOrder: ['param1','param2','param3']
+paramOrder: 'param1 param2 param3'
+paramOrder: 'param1,param2,param3'
+paramOrder: 'param1|param2|param'
+ </code></pre>
+ */
+ paramOrder: undefined,
+
+ /**
+ * @cfg {Boolean} paramsAsHash
+ * Send parameters as a collection of named arguments (defaults to <tt>true</tt>). Providing a
+ * <tt>{@link #paramOrder}</tt> nullifies this configuration.
+ */
+ paramsAsHash: true,
+
+ /**
+ * @cfg {Function} directFn
+ * Function to call when executing a request. directFn is a simple alternative to defining the api configuration-parameter
+ * for Store's which will not implement a full CRUD api.
+ */
+ directFn : undefined,
+
+ /**
+ * DirectProxy implementation of {@link Ext.data.DataProxy#doRequest}
+ * @param {String} action The crud action type (create, read, update, destroy)
+ * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null
+ * @param {Object} params An object containing properties which are to be used as HTTP parameters
+ * for the request to the remote server.
+ * @param {Ext.data.DataReader} reader The Reader object which converts the data
+ * object into a block of Ext.data.Records.
+ * @param {Function} callback
+ * <div class="sub-desc"><p>A function to be called after the request.
+ * The <tt>callback</tt> is passed the following arguments:<ul>
+ * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>
+ * <li><tt>options</tt>: Options object from the action request</li>
+ * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>
+ * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.
+ * @param {Object} arg An optional argument which is passed to the callback as its second parameter.
+ * @protected
+ */
+ doRequest : function(action, rs, params, reader, callback, scope, options) {
+ var args = [],
+ directFn = this.api[action] || this.directFn;
+
+ switch (action) {
+ case Ext.data.Api.actions.create:
+ args.push(params.jsonData); // <-- create(Hash)
+ break;
+ case Ext.data.Api.actions.read:
+ // If the method has no parameters, ignore the paramOrder/paramsAsHash.
+ if(directFn.directCfg.method.len > 0){
+ if(this.paramOrder){
+ for(var i = 0, len = this.paramOrder.length; i < len; i++){
+ args.push(params[this.paramOrder[i]]);
+ }
+ }else if(this.paramsAsHash){
+ args.push(params);
+ }
+ }
+ break;
+ case Ext.data.Api.actions.update:
+ args.push(params.jsonData); // <-- update(Hash/Hash[])
+ break;
+ case Ext.data.Api.actions.destroy:
+ args.push(params.jsonData); // <-- destroy(Int/Int[])
+ break;
+ }
+
+ var trans = {
+ params : params || {},
+ request: {
+ callback : callback,
+ scope : scope,
+ arg : options
+ },
+ reader: reader
+ };
+
+ args.push(this.createCallback(action, rs, trans), this);
+ directFn.apply(window, args);
+ },
+
+ // private
+ createCallback : function(action, rs, trans) {
+ var me = this;
+ return function(result, res) {
+ if (!res.status) {
+ // @deprecated fire loadexception
+ if (action === Ext.data.Api.actions.read) {
+ me.fireEvent("loadexception", me, trans, res, null);
+ }
+ me.fireEvent('exception', me, 'remote', action, trans, res, null);
+ trans.request.callback.call(trans.request.scope, null, trans.request.arg, false);
+ return;
+ }
+ if (action === Ext.data.Api.actions.read) {
+ me.onRead(action, trans, result, res);
+ } else {
+ me.onWrite(action, trans, result, res, rs);
+ }
+ };
+ },
+
+ /**
+ * Callback for read actions
+ * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
+ * @param {Object} trans The request transaction object
+ * @param {Object} result Data object picked out of the server-response.
+ * @param {Object} res The server response
+ * @protected
+ */
+ onRead : function(action, trans, result, res) {
+ var records;
+ try {
+ records = trans.reader.readRecords(result);
+ }
+ catch (ex) {
+ // @deprecated: Fire old loadexception for backwards-compat.
+ this.fireEvent("loadexception", this, trans, res, ex);
+
+ this.fireEvent('exception', this, 'response', action, trans, res, ex);
+ trans.request.callback.call(trans.request.scope, null, trans.request.arg, false);
+ return;
+ }
+ this.fireEvent("load", this, res, trans.request.arg);
+ trans.request.callback.call(trans.request.scope, records, trans.request.arg, true);
+ },
+ /**
+ * Callback for write actions
+ * @param {String} action [{@link Ext.data.Api#actions create|read|update|destroy}]
+ * @param {Object} trans The request transaction object
+ * @param {Object} result Data object picked out of the server-response.
+ * @param {Object} res The server response
+ * @param {Ext.data.Record/[Ext.data.Record]} rs The Store resultset associated with the action.
+ * @protected
+ */
+ onWrite : function(action, trans, result, res, rs) {
+ var data = trans.reader.extractData(trans.reader.getRoot(result), false);
+ var success = trans.reader.getSuccess(result);
+ success = (success !== false);
+ if (success){
+ this.fireEvent("write", this, action, data, res, rs, trans.request.arg);
+ }else{
+ this.fireEvent('exception', this, 'remote', action, trans, result, rs);
+ }
+ trans.request.callback.call(trans.request.scope, data, res, success);
+ }
+});
+/**
+ * @class Ext.data.DirectStore
+ * @extends Ext.data.Store
+ * <p>Small helper class to create an {@link Ext.data.Store} configured with an
+ * {@link Ext.data.DirectProxy} and {@link Ext.data.JsonReader} to make interacting
+ * with an {@link Ext.Direct} Server-side {@link Ext.direct.Provider Provider} easier.
+ * To create a different proxy/reader combination create a basic {@link Ext.data.Store}
+ * configured as needed.</p>
+ *
+ * <p><b>*Note:</b> Although they are not listed, this class inherits all of the config options of:</p>
+ * <div><ul class="mdetail-params">
+ * <li><b>{@link Ext.data.Store Store}</b></li>
+ * <div class="sub-desc"><ul class="mdetail-params">
+ *
+ * </ul></div>
+ * <li><b>{@link Ext.data.JsonReader JsonReader}</b></li>
+ * <div class="sub-desc"><ul class="mdetail-params">
+ * <li><tt><b>{@link Ext.data.JsonReader#root root}</b></tt></li>
+ * <li><tt><b>{@link Ext.data.JsonReader#idProperty idProperty}</b></tt></li>
+ * <li><tt><b>{@link Ext.data.JsonReader#totalProperty totalProperty}</b></tt></li>
+ * </ul></div>
+ *
+ * <li><b>{@link Ext.data.DirectProxy DirectProxy}</b></li>
+ * <div class="sub-desc"><ul class="mdetail-params">
+ * <li><tt><b>{@link Ext.data.DirectProxy#directFn directFn}</b></tt></li>
+ * <li><tt><b>{@link Ext.data.DirectProxy#paramOrder paramOrder}</b></tt></li>
+ * <li><tt><b>{@link Ext.data.DirectProxy#paramsAsHash paramsAsHash}</b></tt></li>
+ * </ul></div>
+ * </ul></div>
+ *
+ * @xtype directstore
+ *
+ * @constructor
+ * @param {Object} config
+ */
+Ext.data.DirectStore = Ext.extend(Ext.data.Store, {
+ constructor : function(config){
+ // each transaction upon a singe record will generate a distinct Direct transaction since Direct queues them into one Ajax request.
+ var c = Ext.apply({}, {
+ batchTransactions: false
+ }, config);
+ Ext.data.DirectStore.superclass.constructor.call(this, Ext.apply(c, {
+ proxy: Ext.isDefined(c.proxy) ? c.proxy : new Ext.data.DirectProxy(Ext.copyTo({}, c, 'paramOrder,paramsAsHash,directFn,api')),
+ reader: (!Ext.isDefined(c.reader) && c.fields) ? new Ext.data.JsonReader(Ext.copyTo({}, c, 'totalProperty,root,idProperty'), c.fields) : c.reader
+ }));
+ }
+});
+Ext.reg('directstore', Ext.data.DirectStore);
+/**
+ * @class Ext.Direct
+ * @extends Ext.util.Observable
+ * <p><b><u>Overview</u></b></p>
+ *
+ * <p>Ext.Direct aims to streamline communication between the client and server
+ * by providing a single interface that reduces the amount of common code
+ * typically required to validate data and handle returned data packets
+ * (reading data, error conditions, etc).</p>
+ *
+ * <p>The Ext.direct namespace includes several classes for a closer integration
+ * with the server-side. The Ext.data namespace also includes classes for working
+ * with Ext.data.Stores which are backed by data from an Ext.Direct method.</p>
+ *
+ * <p><b><u>Specification</u></b></p>
+ *
+ * <p>For additional information consult the
+ * <a href="http://extjs.com/products/extjs/direct.php">Ext.Direct Specification</a>.</p>
+ *
+ * <p><b><u>Providers</u></b></p>
+ *
+ * <p>Ext.Direct uses a provider architecture, where one or more providers are
+ * used to transport data to and from the server. There are several providers
+ * that exist in the core at the moment:</p><div class="mdetail-params"><ul>
+ *
+ * <li>{@link Ext.direct.JsonProvider JsonProvider} for simple JSON operations</li>
+ * <li>{@link Ext.direct.PollingProvider PollingProvider} for repeated requests</li>
+ * <li>{@link Ext.direct.RemotingProvider RemotingProvider} exposes server side
+ * on the client.</li>
+ * </ul></div>
+ *
+ * <p>A provider does not need to be invoked directly, providers are added via
+ * {@link Ext.Direct}.{@link Ext.Direct#add add}.</p>
+ *
+ * <p><b><u>Router</u></b></p>
+ *
+ * <p>Ext.Direct utilizes a "router" on the server to direct requests from the client
+ * to the appropriate server-side method. Because the Ext.Direct API is completely
+ * platform-agnostic, you could completely swap out a Java based server solution
+ * and replace it with one that uses C# without changing the client side JavaScript
+ * at all.</p>
+ *
+ * <p><b><u>Server side events</u></b></p>
+ *
+ * <p>Custom events from the server may be handled by the client by adding
+ * listeners, for example:</p>
+ * <pre><code>
+{"type":"event","name":"message","data":"Successfully polled at: 11:19:30 am"}
+
+// add a handler for a 'message' event sent by the server
+Ext.Direct.on('message', function(e){
+ out.append(String.format('<p><i>{0}</i></p>', e.data));
+ out.el.scrollTo('t', 100000, true);
+});
+ * </code></pre>
+ * @singleton
+ */
+Ext.Direct = Ext.extend(Ext.util.Observable, {
+ /**
+ * Each event type implements a getData() method. The default event types are:
+ * <div class="mdetail-params"><ul>
+ * <li><b><tt>event</tt></b> : Ext.Direct.Event</li>
+ * <li><b><tt>exception</tt></b> : Ext.Direct.ExceptionEvent</li>
+ * <li><b><tt>rpc</tt></b> : Ext.Direct.RemotingEvent</li>
+ * </ul></div>
+ * @property eventTypes
+ * @type Object
+ */
+
+ /**
+ * Four types of possible exceptions which can occur:
+ * <div class="mdetail-params"><ul>
+ * <li><b><tt>Ext.Direct.exceptions.TRANSPORT</tt></b> : 'xhr'</li>
+ * <li><b><tt>Ext.Direct.exceptions.PARSE</tt></b> : 'parse'</li>
+ * <li><b><tt>Ext.Direct.exceptions.LOGIN</tt></b> : 'login'</li>
+ * <li><b><tt>Ext.Direct.exceptions.SERVER</tt></b> : 'exception'</li>
+ * </ul></div>
+ * @property exceptions
+ * @type Object
+ */
+ exceptions: {
+ TRANSPORT: 'xhr',
+ PARSE: 'parse',
+ LOGIN: 'login',
+ SERVER: 'exception'
+ },
+
+ // private
+ constructor: function(){
+ this.addEvents(
+ /**
+ * @event event
+ * Fires after an event.
+ * @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
+ * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
+ */
+ 'event',
+ /**
+ * @event exception
+ * Fires after an event exception.
+ * @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
+ */
+ 'exception'
+ );
+ this.transactions = {};
+ this.providers = {};
+ },
+
+ /**
+ * Adds an Ext.Direct Provider and creates the proxy or stub methods to execute server-side methods.
+ * If the provider is not already connected, it will auto-connect.
+ * <pre><code>
+var pollProv = new Ext.direct.PollingProvider({
+ url: 'php/poll2.php'
+});
+
+Ext.Direct.addProvider(
+ {
+ "type":"remoting", // create a {@link Ext.direct.RemotingProvider}
+ "url":"php\/router.php", // url to connect to the Ext.Direct server-side router.
+ "actions":{ // each property within the actions object represents a Class
+ "TestAction":[ // array of methods within each server side Class
+ {
+ "name":"doEcho", // name of method
+ "len":1
+ },{
+ "name":"multiply",
+ "len":1
+ },{
+ "name":"doForm",
+ "formHandler":true, // handle form on server with Ext.Direct.Transaction
+ "len":1
+ }]
+ },
+ "namespace":"myApplication",// namespace to create the Remoting Provider in
+ },{
+ type: 'polling', // create a {@link Ext.direct.PollingProvider}
+ url: 'php/poll.php'
+ },
+ pollProv // reference to previously created instance
+);
+ * </code></pre>
+ * @param {Object/Array} provider Accepts either an Array of Provider descriptions (an instance
+ * or config object for a Provider) or any number of Provider descriptions as arguments. Each
+ * Provider description instructs Ext.Direct how to create client-side stub methods.
+ */
+ addProvider : function(provider){
+ var a = arguments;
+ if(a.length > 1){
+ for(var i = 0, len = a.length; i < len; i++){
+ this.addProvider(a[i]);
+ }
+ return;
+ }
+
+ // if provider has not already been instantiated
+ if(!provider.events){
+ provider = new Ext.Direct.PROVIDERS[provider.type](provider);
+ }
+ provider.id = provider.id || Ext.id();
+ this.providers[provider.id] = provider;
+
+ provider.on('data', this.onProviderData, this);
+ provider.on('exception', this.onProviderException, this);
+
+
+ if(!provider.isConnected()){
+ provider.connect();
+ }
+
+ return provider;
+ },
+
+ /**
+ * Retrieve a {@link Ext.direct.Provider provider} by the
+ * <b><tt>{@link Ext.direct.Provider#id id}</tt></b> specified when the provider is
+ * {@link #addProvider added}.
+ * @param {String} id Unique identifier assigned to the provider when calling {@link #addProvider}
+ */
+ getProvider : function(id){
+ return this.providers[id];
+ },
+
+ removeProvider : function(id){
+ var provider = id.id ? id : this.providers[id];
+ provider.un('data', this.onProviderData, this);
+ provider.un('exception', this.onProviderException, this);
+ delete this.providers[provider.id];
+ return provider;
+ },
+
+ addTransaction: function(t){
+ this.transactions[t.tid] = t;
+ return t;
+ },
+
+ removeTransaction: function(t){
+ delete this.transactions[t.tid || t];
+ return t;
+ },
+
+ getTransaction: function(tid){
+ return this.transactions[tid.tid || tid];
+ },
+
+ onProviderData : function(provider, e){
+ if(Ext.isArray(e)){
+ for(var i = 0, len = e.length; i < len; i++){
+ this.onProviderData(provider, e[i]);
+ }
+ return;
+ }
+ if(e.name && e.name != 'event' && e.name != 'exception'){
+ this.fireEvent(e.name, e);
+ }else if(e.type == 'exception'){
+ this.fireEvent('exception', e);
+ }
+ this.fireEvent('event', e, provider);
+ },
+
+ createEvent : function(response, extraProps){
+ return new Ext.Direct.eventTypes[response.type](Ext.apply(response, extraProps));
+ }
+});
+// overwrite impl. with static instance
+Ext.Direct = new Ext.Direct();
+
+Ext.Direct.TID = 1;
+Ext.Direct.PROVIDERS = {};/**
+ * @class Ext.Direct.Transaction
+ * @extends Object
+ * <p>Supporting Class for Ext.Direct (not intended to be used directly).</p>
+ * @constructor
+ * @param {Object} config
+ */
+Ext.Direct.Transaction = function(config){
+ Ext.apply(this, config);
+ this.tid = ++Ext.Direct.TID;
+ this.retryCount = 0;
+};
+Ext.Direct.Transaction.prototype = {
+ send: function(){
+ this.provider.queueTransaction(this);
+ },
+
+ retry: function(){
+ this.retryCount++;
+ this.send();
+ },
+
+ getProvider: function(){
+ return this.provider;
+ }
+};Ext.Direct.Event = function(config){
+ Ext.apply(this, config);
+};
+
+Ext.Direct.Event.prototype = {
+ status: true,
+ getData: function(){
+ return this.data;
+ }
+};
+
+Ext.Direct.RemotingEvent = Ext.extend(Ext.Direct.Event, {
+ type: 'rpc',
+ getTransaction: function(){
+ return this.transaction || Ext.Direct.getTransaction(this.tid);
+ }
+});
+
+Ext.Direct.ExceptionEvent = Ext.extend(Ext.Direct.RemotingEvent, {
+ status: false,
+ type: 'exception'
+});
+
+Ext.Direct.eventTypes = {
+ 'rpc': Ext.Direct.RemotingEvent,
+ 'event': Ext.Direct.Event,
+ 'exception': Ext.Direct.ExceptionEvent
+};
+/**
+ * @class Ext.direct.Provider
+ * @extends Ext.util.Observable
+ * <p>Ext.direct.Provider is an abstract class meant to be extended.</p>
+ *
+ * <p>For example ExtJs implements the following subclasses:</p>
+ * <pre><code>
+Provider
+|
++---{@link Ext.direct.JsonProvider JsonProvider}
+ |
+ +---{@link Ext.direct.PollingProvider PollingProvider}
+ |
+ +---{@link Ext.direct.RemotingProvider RemotingProvider}
+ * </code></pre>
+ * @abstract
+ */
+Ext.direct.Provider = Ext.extend(Ext.util.Observable, {
+ /**
+ * @cfg {String} id
+ * The unique id of the provider (defaults to an {@link Ext#id auto-assigned id}).
+ * You should assign an id if you need to be able to access the provider later and you do
+ * not have an object reference available, for example:
+ * <pre><code>
+Ext.Direct.addProvider(
+ {
+ type: 'polling',
+ url: 'php/poll.php',
+ id: 'poll-provider'
+ }
+);
+
+var p = {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#getProvider getProvider}('poll-provider');
+p.disconnect();
+ * </code></pre>
+ */
+
+ /**
+ * @cfg {Number} priority
+ * Priority of the request. Lower is higher priority, <tt>0</tt> means "duplex" (always on).
+ * All Providers default to <tt>1</tt> except for PollingProvider which defaults to <tt>3</tt>.
+ */
+ priority: 1,
+
+ /**
+ * @cfg {String} type
+ * <b>Required</b>, <tt>undefined</tt> by default. The <tt>type</tt> of provider specified
+ * to {@link Ext.Direct Ext.Direct}.{@link Ext.Direct#addProvider addProvider} to create a
+ * new Provider. Acceptable values by default are:<div class="mdetail-params"><ul>
+ * <li><b><tt>polling</tt></b> : {@link Ext.direct.PollingProvider PollingProvider}</li>
+ * <li><b><tt>remoting</tt></b> : {@link Ext.direct.RemotingProvider RemotingProvider}</li>
+ * </ul></div>
+ */
+
+ // private
+ constructor : function(config){
+ Ext.apply(this, config);
+ this.addEvents(
+ /**
+ * @event connect
+ * Fires when the Provider connects to the server-side
+ * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
+ */
+ 'connect',
+ /**
+ * @event disconnect
+ * Fires when the Provider disconnects from the server-side
+ * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
+ */
+ 'disconnect',
+ /**
+ * @event data
+ * Fires when the Provider receives data from the server-side
+ * @param {Ext.direct.Provider} provider The {@link Ext.direct.Provider Provider}.
+ * @param {event} e The {@link Ext.Direct#eventTypes Ext.Direct.Event type} that occurred.
+ */
+ 'data',
+ /**
+ * @event exception
+ * Fires when the Provider receives an exception from the server-side
+ */
+ 'exception'
+ );
+ Ext.direct.Provider.superclass.constructor.call(this, config);
+ },
+
+ /**
+ * Returns whether or not the server-side is currently connected.
+ * Abstract method for subclasses to implement.
+ */
+ isConnected: function(){
+ return false;
+ },
+
+ /**
+ * Abstract methods for subclasses to implement.
+ */
+ connect: Ext.emptyFn,
+
+ /**
+ * Abstract methods for subclasses to implement.
+ */
+ disconnect: Ext.emptyFn
+});
+/**
+ * @class Ext.direct.JsonProvider
+ * @extends Ext.direct.Provider
+ */
+Ext.direct.JsonProvider = Ext.extend(Ext.direct.Provider, {
+ parseResponse: function(xhr){
+ if(!Ext.isEmpty(xhr.responseText)){
+ if(typeof xhr.responseText == 'object'){
+ return xhr.responseText;
+ }
+ return Ext.decode(xhr.responseText);
+ }
+ return null;
+ },
+
+ getEvents: function(xhr){
+ var data = null;
+ try{
+ data = this.parseResponse(xhr);
+ }catch(e){
+ var event = new Ext.Direct.ExceptionEvent({
+ data: e,
+ xhr: xhr,
+ code: Ext.Direct.exceptions.PARSE,
+ message: 'Error parsing json response: \n\n ' + data
+ });
+ return [event];
+ }
+ var events = [];
+ if(Ext.isArray(data)){
+ for(var i = 0, len = data.length; i < len; i++){
+ events.push(Ext.Direct.createEvent(data[i]));
+ }
+ }else{
+ events.push(Ext.Direct.createEvent(data));
+ }
+ return events;
+ }
+});/**
+ * @class Ext.direct.PollingProvider
+ * @extends Ext.direct.JsonProvider
+ *
+ * <p>Provides for repetitive polling of the server at distinct {@link #interval intervals}.
+ * The initial request for data originates from the client, and then is responded to by the
+ * server.</p>
+ *
+ * <p>All configurations for the PollingProvider should be generated by the server-side
+ * API portion of the Ext.Direct stack.</p>
+ *
+ * <p>An instance of PollingProvider may be created directly via the new keyword or by simply
+ * specifying <tt>type = 'polling'</tt>. For example:</p>
+ * <pre><code>
+var pollA = new Ext.direct.PollingProvider({
+ type:'polling',
+ url: 'php/pollA.php',
+});
+Ext.Direct.addProvider(pollA);
+pollA.disconnect();
+
+Ext.Direct.addProvider(
+ {
+ type:'polling',
+ url: 'php/pollB.php',
+ id: 'pollB-provider'
+ }
+);
+var pollB = Ext.Direct.getProvider('pollB-provider');
+ * </code></pre>
+ */
+Ext.direct.PollingProvider = Ext.extend(Ext.direct.JsonProvider, {
+ /**
+ * @cfg {Number} priority
+ * Priority of the request (defaults to <tt>3</tt>). See {@link Ext.direct.Provider#priority}.
+ */
+ // override default priority
+ priority: 3,
+
+ /**
+ * @cfg {Number} interval
+ * How often to poll the server-side in milliseconds (defaults to <tt>3000</tt> - every
+ * 3 seconds).
+ */
+ interval: 3000,
+
+ /**
+ * @cfg {Object} baseParams An object containing properties which are to be sent as parameters
+ * on every polling request
+ */
+
+ /**
+ * @cfg {String/Function} url
+ * The url which the PollingProvider should contact with each request. This can also be
+ * an imported Ext.Direct method which will accept the baseParams as its only argument.
+ */
+
+ // private
+ constructor : function(config){
+ Ext.direct.PollingProvider.superclass.constructor.call(this, config);
+ this.addEvents(
+ /**
+ * @event beforepoll
+ * Fired immediately before a poll takes place, an event handler can return false
+ * in order to cancel the poll.
+ * @param {Ext.direct.PollingProvider}
+ */
+ 'beforepoll',
+ /**
+ * @event poll
+ * This event has not yet been implemented.
+ * @param {Ext.direct.PollingProvider}
+ */
+ 'poll'
+ );
+ },
+
+ // inherited
+ isConnected: function(){
+ return !!this.pollTask;
+ },
+
+ /**
+ * Connect to the server-side and begin the polling process. To handle each
+ * response subscribe to the data event.
+ */
+ connect: function(){
+ if(this.url && !this.pollTask){
+ this.pollTask = Ext.TaskMgr.start({
+ run: function(){
+ if(this.fireEvent('beforepoll', this) !== false){
+ if(typeof this.url == 'function'){
+ this.url(this.baseParams);
+ }else{
+ Ext.Ajax.request({
+ url: this.url,
+ callback: this.onData,
+ scope: this,
+ params: this.baseParams
+ });
+ }
+ }
+ },
+ interval: this.interval,
+ scope: this
+ });
+ this.fireEvent('connect', this);
+ }else if(!this.url){
+ throw 'Error initializing PollingProvider, no url configured.';
+ }
+ },
+
+ /**
+ * Disconnect from the server-side and stop the polling process. The disconnect
+ * event will be fired on a successful disconnect.
+ */
+ disconnect: function(){
+ if(this.pollTask){
+ Ext.TaskMgr.stop(this.pollTask);
+ delete this.pollTask;
+ this.fireEvent('disconnect', this);
+ }
+ },
+
+ // private
+ onData: function(opt, success, xhr){
+ if(success){
+ var events = this.getEvents(xhr);
+ for(var i = 0, len = events.length; i < len; i++){
+ var e = events[i];
+ this.fireEvent('data', this, e);
+ }
+ }else{
+ var e = new Ext.Direct.ExceptionEvent({
+ data: e,
+ code: Ext.Direct.exceptions.TRANSPORT,
+ message: 'Unable to connect to the server.',
+ xhr: xhr
+ });
+ this.fireEvent('data', this, e);
+ }
+ }
+});
+
+Ext.Direct.PROVIDERS['polling'] = Ext.direct.PollingProvider;/**
+ * @class Ext.direct.RemotingProvider
+ * @extends Ext.direct.JsonProvider
+ *
+ * <p>The {@link Ext.direct.RemotingProvider RemotingProvider} exposes access to
+ * server side methods on the client (a remote procedure call (RPC) type of
+ * connection where the client can initiate a procedure on the server).</p>
+ *
+ * <p>This allows for code to be organized in a fashion that is maintainable,
+ * while providing a clear path between client and server, something that is
+ * not always apparent when using URLs.</p>
+ *
+ * <p>To accomplish this the server-side needs to describe what classes and methods
+ * are available on the client-side. This configuration will typically be
+ * outputted by the server-side Ext.Direct stack when the API description is built.</p>
+ */
+Ext.direct.RemotingProvider = Ext.extend(Ext.direct.JsonProvider, {
+ /**
+ * @cfg {Object} actions
+ * Object literal defining the server side actions and methods. For example, if
+ * the Provider is configured with:
+ * <pre><code>
+"actions":{ // each property within the 'actions' object represents a server side Class
+ "TestAction":[ // array of methods within each server side Class to be
+ { // stubbed out on client
+ "name":"doEcho",
+ "len":1
+ },{
+ "name":"multiply",// name of method
+ "len":2 // The number of parameters that will be used to create an
+ // array of data to send to the server side function.
+ // Ensure the server sends back a Number, not a String.
+ },{
+ "name":"doForm",
+ "formHandler":true, // direct the client to use specialized form handling method
+ "len":1
+ }]
+}
+ * </code></pre>
+ * <p>Note that a Store is not required, a server method can be called at any time.
+ * In the following example a <b>client side</b> handler is used to call the
+ * server side method "multiply" in the server-side "TestAction" Class:</p>
+ * <pre><code>
+TestAction.multiply(
+ 2, 4, // pass two arguments to server, so specify len=2
+ // callback function after the server is called
+ // result: the result returned by the server
+ // e: Ext.Direct.RemotingEvent object
+ function(result, e){
+ var t = e.getTransaction();
+ var action = t.action; // server side Class called
+ var method = t.method; // server side method called
+ if(e.status){
+ var answer = Ext.encode(result); // 8
+
+ }else{
+ var msg = e.message; // failure message
+ }
+ }
+);
+ * </code></pre>
+ * In the example above, the server side "multiply" function will be passed two
+ * arguments (2 and 4). The "multiply" method should return the value 8 which will be
+ * available as the <tt>result</tt> in the example above.
+ */
+
+ /**
+ * @cfg {String/Object} namespace
+ * Namespace for the Remoting Provider (defaults to the browser global scope of <i>window</i>).
+ * Explicitly specify the namespace Object, or specify a String to have a
+ * {@link Ext#namespace namespace created} implicitly.
+ */
+
+ /**
+ * @cfg {String} url
+ * <b>Required<b>. The url to connect to the {@link Ext.Direct} server-side router.
+ */
+
+ /**
+ * @cfg {String} enableUrlEncode
+ * Specify which param will hold the arguments for the method.
+ * Defaults to <tt>'data'</tt>.
+ */
+
+ /**
+ * @cfg {Number/Boolean} enableBuffer
+ * <p><tt>true</tt> or <tt>false</tt> to enable or disable combining of method
+ * calls. If a number is specified this is the amount of time in milliseconds
+ * to wait before sending a batched request (defaults to <tt>10</tt>).</p>
+ * <br><p>Calls which are received within the specified timeframe will be
+ * concatenated together and sent in a single request, optimizing the
+ * application by reducing the amount of round trips that have to be made
+ * to the server.</p>
+ */
+ enableBuffer: 10,
+
+ /**
+ * @cfg {Number} maxRetries
+ * Number of times to re-attempt delivery on failure of a call. Defaults to <tt>1</tt>.
+ */
+ maxRetries: 1,
+
+ /**
+ * @cfg {Number} timeout
+ * The timeout to use for each request. Defaults to <tt>undefined</tt>.
+ */
+ timeout: undefined,
+
+ constructor : function(config){
+ Ext.direct.RemotingProvider.superclass.constructor.call(this, config);
+ this.addEvents(
+ /**
+ * @event beforecall
+ * Fires immediately before the client-side sends off the RPC call.
+ * By returning false from an event handler you can prevent the call from
+ * executing.
+ * @param {Ext.direct.RemotingProvider} provider
+ * @param {Ext.Direct.Transaction} transaction
+ */
+ 'beforecall',
+ /**
+ * @event call
+ * Fires immediately after the request to the server-side is sent. This does
+ * NOT fire after the response has come back from the call.
+ * @param {Ext.direct.RemotingProvider} provider
+ * @param {Ext.Direct.Transaction} transaction
+ */
+ 'call'
+ );
+ this.namespace = (Ext.isString(this.namespace)) ? Ext.ns(this.namespace) : this.namespace || window;
+ this.transactions = {};
+ this.callBuffer = [];
+ },
+
+ // private
+ initAPI : function(){
+ var o = this.actions;
+ for(var c in o){
+ var cls = this.namespace[c] || (this.namespace[c] = {}),
+ ms = o[c];
+ for(var i = 0, len = ms.length; i < len; i++){
+ var m = ms[i];
+ cls[m.name] = this.createMethod(c, m);
+ }
+ }
+ },
+
+ // inherited
+ isConnected: function(){
+ return !!this.connected;
+ },
+
+ connect: function(){
+ if(this.url){
+ this.initAPI();
+ this.connected = true;
+ this.fireEvent('connect', this);
+ }else if(!this.url){
+ throw 'Error initializing RemotingProvider, no url configured.';
+ }
+ },
+
+ disconnect: function(){
+ if(this.connected){
+ this.connected = false;
+ this.fireEvent('disconnect', this);
+ }
+ },
+
+ onData: function(opt, success, xhr){
+ if(success){
+ var events = this.getEvents(xhr);
+ for(var i = 0, len = events.length; i < len; i++){
+ var e = events[i],
+ t = this.getTransaction(e);
+ this.fireEvent('data', this, e);
+ if(t){
+ this.doCallback(t, e, true);
+ Ext.Direct.removeTransaction(t);
+ }
+ }
+ }else{
+ var ts = [].concat(opt.ts);
+ for(var i = 0, len = ts.length; i < len; i++){
+ var t = this.getTransaction(ts[i]);
+ if(t && t.retryCount < this.maxRetries){
+ t.retry();
+ }else{
+ var e = new Ext.Direct.ExceptionEvent({
+ data: e,
+ transaction: t,
+ code: Ext.Direct.exceptions.TRANSPORT,
+ message: 'Unable to connect to the server.',
+ xhr: xhr
+ });
+ this.fireEvent('data', this, e);
+ if(t){
+ this.doCallback(t, e, false);
+ Ext.Direct.removeTransaction(t);
+ }
+ }
+ }
+ }
+ },
+
+ getCallData: function(t){
+ return {
+ action: t.action,
+ method: t.method,
+ data: t.data,
+ type: 'rpc',
+ tid: t.tid
+ };
+ },
+
+ doSend : function(data){
+ var o = {
+ url: this.url,
+ callback: this.onData,
+ scope: this,
+ ts: data,
+ timeout: this.timeout
+ }, callData;
+
+ if(Ext.isArray(data)){
+ callData = [];
+ for(var i = 0, len = data.length; i < len; i++){
+ callData.push(this.getCallData(data[i]));
+ }
+ }else{
+ callData = this.getCallData(data);
+ }
+
+ if(this.enableUrlEncode){
+ var params = {};
+ params[Ext.isString(this.enableUrlEncode) ? this.enableUrlEncode : 'data'] = Ext.encode(callData);
+ o.params = params;
+ }else{
+ o.jsonData = callData;
+ }
+ Ext.Ajax.request(o);
+ },
+
+ combineAndSend : function(){
+ var len = this.callBuffer.length;
+ if(len > 0){
+ this.doSend(len == 1 ? this.callBuffer[0] : this.callBuffer);
+ this.callBuffer = [];
+ }
+ },
+
+ queueTransaction: function(t){
+ if(t.form){
+ this.processForm(t);
+ return;
+ }
+ this.callBuffer.push(t);
+ if(this.enableBuffer){
+ if(!this.callTask){
+ this.callTask = new Ext.util.DelayedTask(this.combineAndSend, this);
+ }
+ this.callTask.delay(Ext.isNumber(this.enableBuffer) ? this.enableBuffer : 10);
+ }else{
+ this.combineAndSend();
+ }
+ },
+
+ doCall : function(c, m, args){
+ var data = null, hs = args[m.len], scope = args[m.len+1];
+
+ if(m.len !== 0){
+ data = args.slice(0, m.len);
+ }
+
+ var t = new Ext.Direct.Transaction({
+ provider: this,
+ args: args,
+ action: c,
+ method: m.name,
+ data: data,
+ cb: scope && Ext.isFunction(hs) ? hs.createDelegate(scope) : hs
+ });
+
+ if(this.fireEvent('beforecall', this, t) !== false){
+ Ext.Direct.addTransaction(t);
+ this.queueTransaction(t);
+ this.fireEvent('call', this, t);
+ }
+ },
+
+ doForm : function(c, m, form, callback, scope){
+ var t = new Ext.Direct.Transaction({
+ provider: this,
+ action: c,
+ method: m.name,
+ args:[form, callback, scope],
+ cb: scope && Ext.isFunction(callback) ? callback.createDelegate(scope) : callback,
+ isForm: true
+ });
+
+ if(this.fireEvent('beforecall', this, t) !== false){
+ Ext.Direct.addTransaction(t);
+ var isUpload = String(form.getAttribute("enctype")).toLowerCase() == 'multipart/form-data',
+ params = {
+ extTID: t.tid,
+ extAction: c,
+ extMethod: m.name,
+ extType: 'rpc',
+ extUpload: String(isUpload)
+ };
+
+ // change made from typeof callback check to callback.params
+ // to support addl param passing in DirectSubmit EAC 6/2
+ Ext.apply(t, {
+ form: Ext.getDom(form),
+ isUpload: isUpload,
+ params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params
+ });
+ this.fireEvent('call', this, t);
+ this.processForm(t);
+ }
+ },
+
+ processForm: function(t){
+ Ext.Ajax.request({
+ url: this.url,
+ params: t.params,
+ callback: this.onData,
+ scope: this,
+ form: t.form,
+ isUpload: t.isUpload,
+ ts: t
+ });
+ },
+
+ createMethod : function(c, m){
+ var f;
+ if(!m.formHandler){
+ f = function(){
+ this.doCall(c, m, Array.prototype.slice.call(arguments, 0));
+ }.createDelegate(this);
+ }else{
+ f = function(form, callback, scope){
+ this.doForm(c, m, form, callback, scope);
+ }.createDelegate(this);
+ }
+ f.directCfg = {
+ action: c,
+ method: m
+ };
+ return f;
+ },
+
+ getTransaction: function(opt){
+ return opt && opt.tid ? Ext.Direct.getTransaction(opt.tid) : null;
+ },
+
+ doCallback: function(t, e){
+ var fn = e.status ? 'success' : 'failure';
+ if(t && t.cb){
+ var hs = t.cb,
+ result = Ext.isDefined(e.result) ? e.result : e.data;
+ if(Ext.isFunction(hs)){
+ hs(result, e);
+ } else{
+ Ext.callback(hs[fn], hs.scope, [result, e]);
+ Ext.callback(hs.callback, hs.scope, [result, e]);
+ }
+ }
+ }
+});
+Ext.Direct.PROVIDERS['remoting'] = Ext.direct.RemotingProvider;/**
+ * @class Ext.Resizable
+ * @extends Ext.util.Observable
+ * <p>Applies drag handles to an element to make it resizable. The drag handles are inserted into the element
+ * and positioned absolute. Some elements, such as a textarea or image, don't support this. To overcome that, you can wrap
+ * the textarea in a div and set 'resizeChild' to true (or to the id of the element), <b>or</b> set wrap:true in your config and
+ * the element will be wrapped for you automatically.</p>
+ * <p>Here is the list of valid resize handles:</p>
+ * <pre>
+Value Description
+------ -------------------
+ 'n' north
+ 's' south
+ 'e' east
+ 'w' west
+ 'nw' northwest
+ 'sw' southwest
+ 'se' southeast
+ 'ne' northeast
+ 'all' all
+</pre>
+ * <p>Here's an example showing the creation of a typical Resizable:</p>
+ * <pre><code>
+var resizer = new Ext.Resizable('element-id', {
+ handles: 'all',
+ minWidth: 200,
+ minHeight: 100,
+ maxWidth: 500,
+ maxHeight: 400,
+ pinned: true
+});
+resizer.on('resize', myHandler);
+</code></pre>
+ * <p>To hide a particular handle, set its display to none in CSS, or through script:<br>
+ * resizer.east.setDisplayed(false);</p>
+ * @constructor
+ * Create a new resizable component
+ * @param {Mixed} el The id or element to resize
+ * @param {Object} config configuration options
+ */
+Ext.Resizable = Ext.extend(Ext.util.Observable, {
+
+ constructor: function(el, config){
+ this.el = Ext.get(el);
+ if(config && config.wrap){
+ config.resizeChild = this.el;
+ this.el = this.el.wrap(typeof config.wrap == 'object' ? config.wrap : {cls:'xresizable-wrap'});
+ this.el.id = this.el.dom.id = config.resizeChild.id + '-rzwrap';
+ this.el.setStyle('overflow', 'hidden');
+ this.el.setPositioning(config.resizeChild.getPositioning());
+ config.resizeChild.clearPositioning();
+ if(!config.width || !config.height){
+ var csize = config.resizeChild.getSize();
+ this.el.setSize(csize.width, csize.height);
+ }
+ if(config.pinned && !config.adjustments){
+ config.adjustments = 'auto';
+ }
+ }
+
+ /**
+ * The proxy Element that is resized in place of the real Element during the resize operation.
+ * This may be queried using {@link Ext.Element#getBox} to provide the new area to resize to.
+ * Read only.
+ * @type Ext.Element.
+ * @property proxy
+ */
+ this.proxy = this.el.createProxy({tag: 'div', cls: 'x-resizable-proxy', id: this.el.id + '-rzproxy'}, Ext.getBody());
+ this.proxy.unselectable();
+ this.proxy.enableDisplayMode('block');
+
+ Ext.apply(this, config);
+
+ if(this.pinned){
+ this.disableTrackOver = true;
+ this.el.addClass('x-resizable-pinned');
+ }
+ // if the element isn't positioned, make it relative
+ var position = this.el.getStyle('position');
+ if(position != 'absolute' && position != 'fixed'){
+ this.el.setStyle('position', 'relative');
+ }
+ if(!this.handles){ // no handles passed, must be legacy style
+ this.handles = 's,e,se';
+ if(this.multiDirectional){
+ this.handles += ',n,w';
+ }
+ }
+ if(this.handles == 'all'){
+ this.handles = 'n s e w ne nw se sw';
+ }
+ var hs = this.handles.split(/\s*?[,;]\s*?| /);
+ var ps = Ext.Resizable.positions;
+ for(var i = 0, len = hs.length; i < len; i++){
+ if(hs[i] && ps[hs[i]]){
+ var pos = ps[hs[i]];
+ this[pos] = new Ext.Resizable.Handle(this, pos, this.disableTrackOver, this.transparent, this.handleCls);
+ }
+ }
+ // legacy
+ this.corner = this.southeast;
+
+ if(this.handles.indexOf('n') != -1 || this.handles.indexOf('w') != -1){
+ this.updateBox = true;
+ }
+
+ this.activeHandle = null;
+
+ if(this.resizeChild){
+ if(typeof this.resizeChild == 'boolean'){
+ this.resizeChild = Ext.get(this.el.dom.firstChild, true);
+ }else{
+ this.resizeChild = Ext.get(this.resizeChild, true);
+ }
+ }
+
+ if(this.adjustments == 'auto'){
+ var rc = this.resizeChild;
+ var hw = this.west, he = this.east, hn = this.north, hs = this.south;
+ if(rc && (hw || hn)){
+ rc.position('relative');
+ rc.setLeft(hw ? hw.el.getWidth() : 0);
+ rc.setTop(hn ? hn.el.getHeight() : 0);
+ }
+ this.adjustments = [
+ (he ? -he.el.getWidth() : 0) + (hw ? -hw.el.getWidth() : 0),
+ (hn ? -hn.el.getHeight() : 0) + (hs ? -hs.el.getHeight() : 0) -1
+ ];
+ }
+
+ if(this.draggable){
+ this.dd = this.dynamic ?
+ this.el.initDD(null) : this.el.initDDProxy(null, {dragElId: this.proxy.id});
+ this.dd.setHandleElId(this.resizeChild ? this.resizeChild.id : this.el.id);
+ if(this.constrainTo){
+ this.dd.constrainTo(this.constrainTo);
+ }
+ }
+
+ this.addEvents(
+ /**
+ * @event beforeresize
+ * Fired before resize is allowed. Set {@link #enabled} to false to cancel resize.
+ * @param {Ext.Resizable} this
+ * @param {Ext.EventObject} e The mousedown event
+ */
+ 'beforeresize',
+ /**
+ * @event resize
+ * Fired after a resize.
+ * @param {Ext.Resizable} this
+ * @param {Number} width The new width
+ * @param {Number} height The new height
+ * @param {Ext.EventObject} e The mouseup event
+ */
+ 'resize'
+ );
+
+ if(this.width !== null && this.height !== null){
+ this.resizeTo(this.width, this.height);
+ }else{
+ this.updateChildSize();
+ }
+ if(Ext.isIE){
+ this.el.dom.style.zoom = 1;
+ }
+ Ext.Resizable.superclass.constructor.call(this);
+ },
+
+ /**
+ * @cfg {Array/String} adjustments String 'auto' or an array [width, height] with values to be <b>added</b> to the
+ * resize operation's new size (defaults to <tt>[0, 0]</tt>)
+ */
+ adjustments : [0, 0],
+ /**
+ * @cfg {Boolean} animate True to animate the resize (not compatible with dynamic sizing, defaults to false)
+ */
+ animate : false,
+ /**
+ * @cfg {Mixed} constrainTo Constrain the resize to a particular element
+ */
+ /**
+ * @cfg {Boolean} disableTrackOver True to disable mouse tracking. This is only applied at config time. (defaults to false)
+ */
+ disableTrackOver : false,
+ /**
+ * @cfg {Boolean} draggable Convenience to initialize drag drop (defaults to false)
+ */
+ draggable: false,
+ /**
+ * @cfg {Number} duration Animation duration if animate = true (defaults to 0.35)
+ */
+ duration : 0.35,
+ /**
+ * @cfg {Boolean} dynamic True to resize the element while dragging instead of using a proxy (defaults to false)
+ */
+ dynamic : false,
+ /**
+ * @cfg {String} easing Animation easing if animate = true (defaults to <tt>'easingOutStrong'</tt>)
+ */
+ easing : 'easeOutStrong',
+ /**
+ * @cfg {Boolean} enabled False to disable resizing (defaults to true)
+ */
+ enabled : true,
+ /**
+ * @property enabled Writable. False if resizing is disabled.
+ * @type Boolean
+ */
+ /**
+ * @cfg {String} handles String consisting of the resize handles to display (defaults to undefined).
+ * Specify either <tt>'all'</tt> or any of <tt>'n s e w ne nw se sw'</tt>.
+ */
+ handles : false,
+ /**
+ * @cfg {Boolean} multiDirectional <b>Deprecated</b>. Deprecated style of adding multi-direction resize handles.
+ */
+ multiDirectional : false,
+ /**
+ * @cfg {Number} height The height of the element in pixels (defaults to null)
+ */
+ height : null,
+ /**
+ * @cfg {Number} width The width of the element in pixels (defaults to null)
+ */
+ width : null,
+ /**
+ * @cfg {Number} heightIncrement The increment to snap the height resize in pixels
+ * (only applies if <code>{@link #dynamic}==true</code>). Defaults to <tt>0</tt>.
+ */
+ heightIncrement : 0,
+ /**
+ * @cfg {Number} widthIncrement The increment to snap the width resize in pixels
+ * (only applies if <code>{@link #dynamic}==true</code>). Defaults to <tt>0</tt>.
+ */
+ widthIncrement : 0,
+ /**
+ * @cfg {Number} minHeight The minimum height for the element (defaults to 5)
+ */
+ minHeight : 5,
+ /**
+ * @cfg {Number} minWidth The minimum width for the element (defaults to 5)
+ */
+ minWidth : 5,
+ /**
+ * @cfg {Number} maxHeight The maximum height for the element (defaults to 10000)
+ */
+ maxHeight : 10000,
+ /**
+ * @cfg {Number} maxWidth The maximum width for the element (defaults to 10000)
+ */
+ maxWidth : 10000,
+ /**
+ * @cfg {Number} minX The minimum x for the element (defaults to 0)
+ */
+ minX: 0,
+ /**
+ * @cfg {Number} minY The minimum x for the element (defaults to 0)
+ */
+ minY: 0,
+ /**
+ * @cfg {Boolean} pinned True to ensure that the resize handles are always visible, false to display them only when the
+ * user mouses over the resizable borders. This is only applied at config time. (defaults to false)
+ */
+ pinned : false,
+ /**
+ * @cfg {Boolean} preserveRatio True to preserve the original ratio between height
+ * and width during resize (defaults to false)
+ */
+ preserveRatio : false,
+ /**
+ * @cfg {Boolean/String/Element} resizeChild True to resize the first child, or id/element to resize (defaults to false)
+ */
+ resizeChild : false,
+ /**
+ * @cfg {Boolean} transparent True for transparent handles. This is only applied at config time. (defaults to false)
+ */
+ transparent: false,
+ /**
+ * @cfg {Ext.lib.Region} resizeRegion Constrain the resize to a particular region
+ */
+ /**
+ * @cfg {Boolean} wrap True to wrap an element with a div if needed (required for textareas and images, defaults to false)
+ * in favor of the handles config option (defaults to false)
+ */
+ /**
+ * @cfg {String} handleCls A css class to add to each handle. Defaults to <tt>''</tt>.
+ */
+
+
+ /**
+ * Perform a manual resize and fires the 'resize' event.
+ * @param {Number} width
+ * @param {Number} height
+ */
+ resizeTo : function(width, height){
+ this.el.setSize(width, height);
+ this.updateChildSize();
+ this.fireEvent('resize', this, width, height, null);
+ },
+
+ // private
+ startSizing : function(e, handle){
+ this.fireEvent('beforeresize', this, e);
+ if(this.enabled){ // 2nd enabled check in case disabled before beforeresize handler
+
+ if(!this.overlay){
+ this.overlay = this.el.createProxy({tag: 'div', cls: 'x-resizable-overlay', html: ' '}, Ext.getBody());
+ this.overlay.unselectable();
+ this.overlay.enableDisplayMode('block');
+ this.overlay.on({
+ scope: this,
+ mousemove: this.onMouseMove,
+ mouseup: this.onMouseUp
+ });
+ }
+ this.overlay.setStyle('cursor', handle.el.getStyle('cursor'));
+
+ this.resizing = true;
+ this.startBox = this.el.getBox();
+ this.startPoint = e.getXY();
+ this.offsets = [(this.startBox.x + this.startBox.width) - this.startPoint[0],
+ (this.startBox.y + this.startBox.height) - this.startPoint[1]];
+
+ this.overlay.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
+ this.overlay.show();
+
+ if(this.constrainTo) {
+ var ct = Ext.get(this.constrainTo);
+ this.resizeRegion = ct.getRegion().adjust(
+ ct.getFrameWidth('t'),
+ ct.getFrameWidth('l'),
+ -ct.getFrameWidth('b'),
+ -ct.getFrameWidth('r')
+ );
+ }
+
+ this.proxy.setStyle('visibility', 'hidden'); // workaround display none
+ this.proxy.show();
+ this.proxy.setBox(this.startBox);
+ if(!this.dynamic){
+ this.proxy.setStyle('visibility', 'visible');
+ }
+ }
+ },
+
+ // private
+ onMouseDown : function(handle, e){
+ if(this.enabled){
+ e.stopEvent();
+ this.activeHandle = handle;
+ this.startSizing(e, handle);
+ }
+ },
+
+ // private
+ onMouseUp : function(e){
+ this.activeHandle = null;
+ var size = this.resizeElement();
+ this.resizing = false;
+ this.handleOut();
+ this.overlay.hide();
+ this.proxy.hide();
+ this.fireEvent('resize', this, size.width, size.height, e);
+ },
+
+ // private
+ updateChildSize : function(){
+ if(this.resizeChild){
+ var el = this.el;
+ var child = this.resizeChild;
+ var adj = this.adjustments;
+ if(el.dom.offsetWidth){
+ var b = el.getSize(true);
+ child.setSize(b.width+adj[0], b.height+adj[1]);
+ }
+ // Second call here for IE
+ // The first call enables instant resizing and
+ // the second call corrects scroll bars if they
+ // exist
+ if(Ext.isIE){
+ setTimeout(function(){
+ if(el.dom.offsetWidth){
+ var b = el.getSize(true);
+ child.setSize(b.width+adj[0], b.height+adj[1]);
+ }
+ }, 10);
+ }
+ }
+ },
+
+ // private
+ snap : function(value, inc, min){
+ if(!inc || !value){
+ return value;
+ }
+ var newValue = value;
+ var m = value % inc;
+ if(m > 0){
+ if(m > (inc/2)){
+ newValue = value + (inc-m);
+ }else{
+ newValue = value - m;
+ }
+ }
+ return Math.max(min, newValue);
+ },
+
+ /**
+ * <p>Performs resizing of the associated Element. This method is called internally by this
+ * class, and should not be called by user code.</p>
+ * <p>If a Resizable is being used to resize an Element which encapsulates a more complex UI
+ * component such as a Panel, this method may be overridden by specifying an implementation
+ * as a config option to provide appropriate behaviour at the end of the resize operation on
+ * mouseup, for example resizing the Panel, and relaying the Panel's content.</p>
+ * <p>The new area to be resized to is available by examining the state of the {@link #proxy}
+ * Element. Example:
+<pre><code>
+new Ext.Panel({
+ title: 'Resize me',
+ x: 100,
+ y: 100,
+ renderTo: Ext.getBody(),
+ floating: true,
+ frame: true,
+ width: 400,
+ height: 200,
+ listeners: {
+ render: function(p) {
+ new Ext.Resizable(p.getEl(), {
+ handles: 'all',
+ pinned: true,
+ transparent: true,
+ resizeElement: function() {
+ var box = this.proxy.getBox();
+ p.updateBox(box);
+ if (p.layout) {
+ p.doLayout();
+ }
+ return box;
+ }
+ });
+ }
+ }
+}).show();
+</code></pre>
+ */
+ resizeElement : function(){
+ var box = this.proxy.getBox();
+ if(this.updateBox){
+ this.el.setBox(box, false, this.animate, this.duration, null, this.easing);
+ }else{
+ this.el.setSize(box.width, box.height, this.animate, this.duration, null, this.easing);
+ }
+ this.updateChildSize();
+ if(!this.dynamic){
+ this.proxy.hide();
+ }
+ if(this.draggable && this.constrainTo){
+ this.dd.resetConstraints();
+ this.dd.constrainTo(this.constrainTo);
+ }
+ return box;
+ },
+
+ // private
+ constrain : function(v, diff, m, mx){
+ if(v - diff < m){
+ diff = v - m;
+ }else if(v - diff > mx){
+ diff = v - mx;
+ }
+ return diff;
+ },
+
+ // private
+ onMouseMove : function(e){
+ if(this.enabled && this.activeHandle){
+ try{// try catch so if something goes wrong the user doesn't get hung
+
+ if(this.resizeRegion && !this.resizeRegion.contains(e.getPoint())) {
+ return;
+ }
+
+ //var curXY = this.startPoint;
+ var curSize = this.curSize || this.startBox,
+ x = this.startBox.x, y = this.startBox.y,
+ ox = x,
+ oy = y,
+ w = curSize.width,
+ h = curSize.height,
+ ow = w,
+ oh = h,
+ mw = this.minWidth,
+ mh = this.minHeight,
+ mxw = this.maxWidth,
+ mxh = this.maxHeight,
+ wi = this.widthIncrement,
+ hi = this.heightIncrement,
+ eventXY = e.getXY(),
+ diffX = -(this.startPoint[0] - Math.max(this.minX, eventXY[0])),
+ diffY = -(this.startPoint[1] - Math.max(this.minY, eventXY[1])),
+ pos = this.activeHandle.position,
+ tw,
+ th;
+
+ switch(pos){
+ case 'east':
+ w += diffX;
+ w = Math.min(Math.max(mw, w), mxw);
+ break;
+ case 'south':
+ h += diffY;
+ h = Math.min(Math.max(mh, h), mxh);
+ break;
+ case 'southeast':
+ w += diffX;
+ h += diffY;
+ w = Math.min(Math.max(mw, w), mxw);
+ h = Math.min(Math.max(mh, h), mxh);
+ break;
+ case 'north':
+ diffY = this.constrain(h, diffY, mh, mxh);
+ y += diffY;
+ h -= diffY;
+ break;
+ case 'west':
+ diffX = this.constrain(w, diffX, mw, mxw);
+ x += diffX;
+ w -= diffX;
+ break;
+ case 'northeast':
+ w += diffX;
+ w = Math.min(Math.max(mw, w), mxw);
+ diffY = this.constrain(h, diffY, mh, mxh);
+ y += diffY;
+ h -= diffY;
+ break;
+ case 'northwest':
+ diffX = this.constrain(w, diffX, mw, mxw);
+ diffY = this.constrain(h, diffY, mh, mxh);
+ y += diffY;
+ h -= diffY;
+ x += diffX;
+ w -= diffX;
+ break;
+ case 'southwest':
+ diffX = this.constrain(w, diffX, mw, mxw);
+ h += diffY;
+ h = Math.min(Math.max(mh, h), mxh);
+ x += diffX;
+ w -= diffX;
+ break;
+ }
+
+ var sw = this.snap(w, wi, mw);
+ var sh = this.snap(h, hi, mh);
+ if(sw != w || sh != h){
+ switch(pos){
+ case 'northeast':
+ y -= sh - h;
+ break;
+ case 'north':
+ y -= sh - h;
+ break;
+ case 'southwest':
+ x -= sw - w;
+ break;
+ case 'west':
+ x -= sw - w;
+ break;
+ case 'northwest':
+ x -= sw - w;
+ y -= sh - h;
+ break;
+ }
+ w = sw;
+ h = sh;
+ }
+
+ if(this.preserveRatio){
+ switch(pos){
+ case 'southeast':
+ case 'east':
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ w = ow * (h/oh);
+ break;
+ case 'south':
+ w = ow * (h/oh);
+ w = Math.min(Math.max(mw, w), mxw);
+ h = oh * (w/ow);
+ break;
+ case 'northeast':
+ w = ow * (h/oh);
+ w = Math.min(Math.max(mw, w), mxw);
+ h = oh * (w/ow);
+ break;
+ case 'north':
+ tw = w;
+ w = ow * (h/oh);
+ w = Math.min(Math.max(mw, w), mxw);
+ h = oh * (w/ow);
+ x += (tw - w) / 2;
+ break;
+ case 'southwest':
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ tw = w;
+ w = ow * (h/oh);
+ x += tw - w;
+ break;
+ case 'west':
+ th = h;
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ y += (th - h) / 2;
+ tw = w;
+ w = ow * (h/oh);
+ x += tw - w;
+ break;
+ case 'northwest':
+ tw = w;
+ th = h;
+ h = oh * (w/ow);
+ h = Math.min(Math.max(mh, h), mxh);
+ w = ow * (h/oh);
+ y += th - h;
+ x += tw - w;
+ break;
+
+ }
+ }
+ this.proxy.setBounds(x, y, w, h);
+ if(this.dynamic){
+ this.resizeElement();
+ }
+ }catch(ex){}
+ }
+ },
+
+ // private
+ handleOver : function(){
+ if(this.enabled){
+ this.el.addClass('x-resizable-over');
+ }
+ },
+
+ // private
+ handleOut : function(){
+ if(!this.resizing){
+ this.el.removeClass('x-resizable-over');
+ }
+ },
+
+ /**
+ * Returns the element this component is bound to.
+ * @return {Ext.Element}
+ */
+ getEl : function(){
+ return this.el;
+ },
+
+ /**
+ * Returns the resizeChild element (or null).
+ * @return {Ext.Element}
+ */
+ getResizeChild : function(){
+ return this.resizeChild;
+ },
+
+ /**
+ * Destroys this resizable. If the element was wrapped and
+ * removeEl is not true then the element remains.
+ * @param {Boolean} removeEl (optional) true to remove the element from the DOM
+ */
+ destroy : function(removeEl){
+ Ext.destroy(this.dd, this.overlay, this.proxy);
+ this.overlay = null;
+ this.proxy = null;
+
+ var ps = Ext.Resizable.positions;
+ for(var k in ps){
+ if(typeof ps[k] != 'function' && this[ps[k]]){
+ this[ps[k]].destroy();
+ }
+ }
+ if(removeEl){
+ this.el.update('');
+ Ext.destroy(this.el);
+ this.el = null;
+ }
+ this.purgeListeners();
+ },
+
+ syncHandleHeight : function(){
+ var h = this.el.getHeight(true);
+ if(this.west){
+ this.west.el.setHeight(h);
+ }
+ if(this.east){
+ this.east.el.setHeight(h);
+ }
+ }
+});
+
+// private
+// hash to map config positions to true positions
+Ext.Resizable.positions = {
+ n: 'north', s: 'south', e: 'east', w: 'west', se: 'southeast', sw: 'southwest', nw: 'northwest', ne: 'northeast'
+};
+
+Ext.Resizable.Handle = Ext.extend(Object, {
+ constructor : function(rz, pos, disableTrackOver, transparent, cls){
+ if(!this.tpl){
+ // only initialize the template if resizable is used
+ var tpl = Ext.DomHelper.createTemplate(
+ {tag: 'div', cls: 'x-resizable-handle x-resizable-handle-{0}'}
+ );
+ tpl.compile();
+ Ext.Resizable.Handle.prototype.tpl = tpl;
+ }
+ this.position = pos;
+ this.rz = rz;
+ this.el = this.tpl.append(rz.el.dom, [this.position], true);
+ this.el.unselectable();
+ if(transparent){
+ this.el.setOpacity(0);
+ }
+ if(!Ext.isEmpty(cls)){
+ this.el.addClass(cls);
+ }
+ this.el.on('mousedown', this.onMouseDown, this);
+ if(!disableTrackOver){
+ this.el.on({
+ scope: this,
+ mouseover: this.onMouseOver,
+ mouseout: this.onMouseOut
+ });
+ }
+ },
+
+ // private
+ afterResize : function(rz){
+ // do nothing
+ },
+ // private
+ onMouseDown : function(e){
+ this.rz.onMouseDown(this, e);
+ },
+ // private
+ onMouseOver : function(e){
+ this.rz.handleOver(this, e);
+ },
+ // private
+ onMouseOut : function(e){
+ this.rz.handleOut(this, e);
+ },
+ // private
+ destroy : function(){
+ Ext.destroy(this.el);
+ this.el = null;
+ }
+});
+/**
+ * @class Ext.Window
+ * @extends Ext.Panel
+ * <p>A specialized panel intended for use as an application window. Windows are floated, {@link #resizable}, and
+ * {@link #draggable} by default. Windows can be {@link #maximizable maximized} to fill the viewport,
+ * restored to their prior size, and can be {@link #minimize}d.</p>
+ * <p>Windows can also be linked to a {@link Ext.WindowGroup} or managed by the {@link Ext.WindowMgr} to provide
+ * grouping, activation, to front, to back and other application-specific behavior.</p>
+ * <p>By default, Windows will be rendered to document.body. To {@link #constrain} a Window to another element
+ * specify {@link Ext.Component#renderTo renderTo}.</p>
+ * <p><b>Note:</b> By default, the <code>{@link #closable close}</code> header tool <i>destroys</i> the Window resulting in
+ * destruction of any child Components. This makes the Window object, and all its descendants <b>unusable</b>. To enable
+ * re-use of a Window, use <b><code>{@link #closeAction closeAction: 'hide'}</code></b>.</p>
+ * @constructor
+ * @param {Object} config The config object
+ * @xtype window
+ */
+Ext.Window = Ext.extend(Ext.Panel, {
+ /**
+ * @cfg {Number} x
+ * The X position of the left edge of the window on initial showing. Defaults to centering the Window within
+ * the width of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
+ */
+ /**
+ * @cfg {Number} y
+ * The Y position of the top edge of the window on initial showing. Defaults to centering the Window within
+ * the height of the Window's container {@link Ext.Element Element) (The Element that the Window is rendered to).
+ */
+ /**
+ * @cfg {Boolean} modal
+ * True to make the window modal and mask everything behind it when displayed, false to display it without
+ * restricting access to other UI elements (defaults to false).
+ */
+ /**
+ * @cfg {String/Element} animateTarget
+ * Id or element from which the window should animate while opening (defaults to null with no animation).
+ */
+ /**
+ * @cfg {String} resizeHandles
+ * A valid {@link Ext.Resizable} handles config string (defaults to 'all'). Only applies when resizable = true.
+ */
+ /**
+ * @cfg {Ext.WindowGroup} manager
+ * A reference to the WindowGroup that should manage this window (defaults to {@link Ext.WindowMgr}).
+ */
+ /**
+ * @cfg {String/Number/Component} defaultButton
+ * <p>Specifies a Component to receive focus when this Window is focussed.</p>
+ * <p>This may be one of:</p><div class="mdetail-params"><ul>
+ * <li>The index of a footer Button.</li>
+ * <li>The id of a Component.</li>
+ * <li>A Component.</li>
+ * </ul></div>
+ */
+ /**
+ * @cfg {Function} onEsc
+ * Allows override of the built-in processing for the escape key. Default action
+ * is to close the Window (performing whatever action is specified in {@link #closeAction}.
+ * To prevent the Window closing when the escape key is pressed, specify this as
+ * Ext.emptyFn (See {@link Ext#emptyFn}).
+ */
+ /**
+ * @cfg {Boolean} collapsed
+ * True to render the window collapsed, false to render it expanded (defaults to false). Note that if
+ * {@link #expandOnShow} is true (the default) it will override the <tt>collapsed</tt> config and the window
+ * will always be expanded when shown.
+ */
+ /**
+ * @cfg {Boolean} maximized
+ * True to initially display the window in a maximized state. (Defaults to false).
+ */
+
+ /**
+ * @cfg {String} baseCls
+ * The base CSS class to apply to this panel's element (defaults to 'x-window').
+ */
+ baseCls : 'x-window',
+ /**
+ * @cfg {Boolean} resizable
+ * True to allow user resizing at each edge and corner of the window, false to disable resizing (defaults to true).
+ */
+ resizable : true,
+ /**
+ * @cfg {Boolean} draggable
+ * True to allow the window to be dragged by the header bar, false to disable dragging (defaults to true). Note
+ * that by default the window will be centered in the viewport, so if dragging is disabled the window may need
+ * to be positioned programmatically after render (e.g., myWindow.setPosition(100, 100);).
+ */
+ draggable : true,
+ /**
+ * @cfg {Boolean} closable
+ * <p>True to display the 'close' tool button and allow the user to close the window, false to
+ * hide the button and disallow closing the window (defaults to true).</p>
+ * <p>By default, when close is requested by either clicking the close button in the header
+ * or pressing ESC when the Window has focus, the {@link #close} method will be called. This
+ * will <i>{@link Ext.Component#destroy destroy}</i> the Window and its content meaning that
+ * it may not be reused.</p>
+ * <p>To make closing a Window <i>hide</i> the Window so that it may be reused, set
+ * {@link #closeAction} to 'hide'.
+ */
+ closable : true,
+ /**
+ * @cfg {String} closeAction
+ * <p>The action to take when the close header tool is clicked:
+ * <div class="mdetail-params"><ul>
+ * <li><b><code>'{@link #close}'</code></b> : <b>Default</b><div class="sub-desc">
+ * {@link #close remove} the window from the DOM and {@link Ext.Component#destroy destroy}
+ * it and all descendant Components. The window will <b>not</b> be available to be
+ * redisplayed via the {@link #show} method.
+ * </div></li>
+ * <li><b><code>'{@link #hide}'</code></b> : <div class="sub-desc">
+ * {@link #hide} the window by setting visibility to hidden and applying negative offsets.
+ * The window will be available to be redisplayed via the {@link #show} method.
+ * </div></li>
+ * </ul></div>
+ * <p><b>Note:</b> This setting does not affect the {@link #close} method
+ * which will always {@link Ext.Component#destroy destroy} the window. To
+ * programatically <i>hide</i> a window, call {@link #hide}.</p>
+ */
+ closeAction : 'close',
+ /**
+ * @cfg {Boolean} constrain
+ * True to constrain the window within its containing element, false to allow it to fall outside of its
+ * containing element. By default the window will be rendered to document.body. To render and constrain the
+ * window within another element specify {@link #renderTo}.
+ * (defaults to false). Optionally the header only can be constrained using {@link #constrainHeader}.
+ */
+ constrain : false,
+ /**
+ * @cfg {Boolean} constrainHeader
+ * True to constrain the window header within its containing element (allowing the window body to fall outside
+ * of its containing element) or false to allow the header to fall outside its containing element (defaults to
+ * false). Optionally the entire window can be constrained using {@link #constrain}.
+ */
+ constrainHeader : false,
+ /**
+ * @cfg {Boolean} plain
+ * True to render the window body with a transparent background so that it will blend into the framing
+ * elements, false to add a lighter background color to visually highlight the body element and separate it
+ * more distinctly from the surrounding frame (defaults to false).
+ */
+ plain : false,
+ /**
+ * @cfg {Boolean} minimizable
+ * True to display the 'minimize' tool button and allow the user to minimize the window, false to hide the button
+ * and disallow minimizing the window (defaults to false). Note that this button provides no implementation --
+ * the behavior of minimizing a window is implementation-specific, so the minimize event must be handled and a
+ * custom minimize behavior implemented for this option to be useful.
+ */
+ minimizable : false,
+ /**
+ * @cfg {Boolean} maximizable
+ * True to display the 'maximize' tool button and allow the user to maximize the window, false to hide the button
+ * and disallow maximizing the window (defaults to false). Note that when a window is maximized, the tool button
+ * will automatically change to a 'restore' button with the appropriate behavior already built-in that will
+ * restore the window to its previous size.
+ */
+ maximizable : false,
+ /**
+ * @cfg {Number} minHeight
+ * The minimum height in pixels allowed for this window (defaults to 100). Only applies when resizable = true.
+ */
+ minHeight : 100,
+ /**
+ * @cfg {Number} minWidth
+ * The minimum width in pixels allowed for this window (defaults to 200). Only applies when resizable = true.
+ */
+ minWidth : 200,
+ /**
+ * @cfg {Boolean} expandOnShow
+ * True to always expand the window when it is displayed, false to keep it in its current state (which may be
+ * {@link #collapsed}) when displayed (defaults to true).
+ */
+ expandOnShow : true,
+
+ // inherited docs, same default
+ collapsible : false,
+
+ /**
+ * @cfg {Boolean} initHidden
+ * True to hide the window until show() is explicitly called (defaults to true).
+ * @deprecated
+ */
+ initHidden : undefined,
+
+ /**
+ * @cfg {Boolean} hidden
+ * Render this component hidden (default is <tt>true</tt>). If <tt>true</tt>, the
+ * {@link #hide} method will be called internally.
+ */
+ hidden : true,
+
+ // The following configs are set to provide the basic functionality of a window.
+ // Changing them would require additional code to handle correctly and should
+ // usually only be done in subclasses that can provide custom behavior. Changing them
+ // may have unexpected or undesirable results.
+ /** @cfg {String} elements @hide */
+ elements : 'header,body',
+ /** @cfg {Boolean} frame @hide */
+ frame : true,
+ /** @cfg {Boolean} floating @hide */
+ floating : true,
+
+ // private
+ initComponent : function(){
+ this.initTools();
+ Ext.Window.superclass.initComponent.call(this);
+ this.addEvents(
+ /**
+ * @event activate
+ * Fires after the window has been visually activated via {@link #setActive}.
+ * @param {Ext.Window} this
+ */
+ /**
+ * @event deactivate
+ * Fires after the window has been visually deactivated via {@link #setActive}.
+ * @param {Ext.Window} this
+ */
+ /**
+ * @event resize
+ * Fires after the window has been resized.
+ * @param {Ext.Window} this
+ * @param {Number} width The window's new width
+ * @param {Number} height The window's new height
+ */
+ 'resize',
+ /**
+ * @event maximize
+ * Fires after the window has been maximized.
+ * @param {Ext.Window} this
+ */
+ 'maximize',
+ /**
+ * @event minimize
+ * Fires after the window has been minimized.
+ * @param {Ext.Window} this
+ */
+ 'minimize',
+ /**
+ * @event restore
+ * Fires after the window has been restored to its original size after being maximized.
+ * @param {Ext.Window} this
+ */
+ 'restore'
+ );
+ // for backwards compat, this should be removed at some point
+ if(Ext.isDefined(this.initHidden)){
+ this.hidden = this.initHidden;
+ }
+ if(this.hidden === false){
+ this.hidden = true;
+ this.show();
+ }
+ },
+
+ // private
+ getState : function(){
+ return Ext.apply(Ext.Window.superclass.getState.call(this) || {}, this.getBox(true));
+ },
+
+ // private
+ onRender : function(ct, position){
+ Ext.Window.superclass.onRender.call(this, ct, position);
+
+ if(this.plain){
+ this.el.addClass('x-window-plain');
+ }
+
+ // this element allows the Window to be focused for keyboard events
+ this.focusEl = this.el.createChild({
+ tag: 'a', href:'#', cls:'x-dlg-focus',
+ tabIndex:'-1', html: ' '});
+ this.focusEl.swallowEvent('click', true);
+
+ this.proxy = this.el.createProxy('x-window-proxy');
+ this.proxy.enableDisplayMode('block');
+
+ if(this.modal){
+ this.mask = this.container.createChild({cls:'ext-el-mask'}, this.el.dom);
+ this.mask.enableDisplayMode('block');
+ this.mask.hide();
+ this.mon(this.mask, 'click', this.focus, this);
+ }
+ if(this.maximizable){
+ this.mon(this.header, 'dblclick', this.toggleMaximize, this);
+ }
+ },
+
+ // private
+ initEvents : function(){
+ Ext.Window.superclass.initEvents.call(this);
+ if(this.animateTarget){
+ this.setAnimateTarget(this.animateTarget);
+ }
+
+ if(this.resizable){
+ this.resizer = new Ext.Resizable(this.el, {
+ minWidth: this.minWidth,
+ minHeight:this.minHeight,
+ handles: this.resizeHandles || 'all',
+ pinned: true,
+ resizeElement : this.resizerAction,
+ handleCls: 'x-window-handle'
+ });
+ this.resizer.window = this;
+ this.mon(this.resizer, 'beforeresize', this.beforeResize, this);
+ }
+
+ if(this.draggable){
+ this.header.addClass('x-window-draggable');
+ }
+ this.mon(this.el, 'mousedown', this.toFront, this);
+ this.manager = this.manager || Ext.WindowMgr;
+ this.manager.register(this);
+ if(this.maximized){
+ this.maximized = false;
+ this.maximize();
+ }
+ if(this.closable){
+ var km = this.getKeyMap();
+ km.on(27, this.onEsc, this);
+ km.disable();
+ }
+ },
+
+ initDraggable : function(){
+ /**
+ * <p>If this Window is configured {@link #draggable}, this property will contain
+ * an instance of {@link Ext.dd.DD} which handles dragging the Window's DOM Element.</p>
+ * <p>This has implementations of <code>startDrag</code>, <code>onDrag</code> and <code>endDrag</code>
+ * which perform the dragging action. If extra logic is needed at these points, use
+ * {@link Function#createInterceptor createInterceptor} or {@link Function#createSequence createSequence} to
+ * augment the existing implementations.</p>
+ * @type Ext.dd.DD
+ * @property dd
+ */
+ this.dd = new Ext.Window.DD(this);
+ },
+
+ // private
+ onEsc : function(k, e){
+ e.stopEvent();
+ this[this.closeAction]();
+ },
+
+ // private
+ beforeDestroy : function(){
+ if(this.rendered){
+ this.hide();
+ this.clearAnchor();
+ Ext.destroy(
+ this.focusEl,
+ this.resizer,
+ this.dd,
+ this.proxy,
+ this.mask
+ );
+ }
+ Ext.Window.superclass.beforeDestroy.call(this);
+ },
+
+ // private
+ onDestroy : function(){
+ if(this.manager){
+ this.manager.unregister(this);
+ }
+ Ext.Window.superclass.onDestroy.call(this);
+ },
+
+ // private
+ initTools : function(){
+ if(this.minimizable){
+ this.addTool({
+ id: 'minimize',
+ handler: this.minimize.createDelegate(this, [])
+ });
+ }
+ if(this.maximizable){
+ this.addTool({
+ id: 'maximize',
+ handler: this.maximize.createDelegate(this, [])
+ });
+ this.addTool({
+ id: 'restore',
+ handler: this.restore.createDelegate(this, []),
+ hidden:true
+ });
+ }
+ if(this.closable){
+ this.addTool({
+ id: 'close',
+ handler: this[this.closeAction].createDelegate(this, [])
+ });
+ }
+ },
+
+ // private
+ resizerAction : function(){
+ var box = this.proxy.getBox();
+ this.proxy.hide();
+ this.window.handleResize(box);
+ return box;
+ },
+
+ // private
+ beforeResize : function(){
+ this.resizer.minHeight = Math.max(this.minHeight, this.getFrameHeight() + 40); // 40 is a magic minimum content size?
+ this.resizer.minWidth = Math.max(this.minWidth, this.getFrameWidth() + 40);
+ this.resizeBox = this.el.getBox();
+ },
+
+ // private
+ updateHandles : function(){
+ if(Ext.isIE && this.resizer){
+ this.resizer.syncHandleHeight();
+ this.el.repaint();
+ }
+ },
+
+ // private
+ handleResize : function(box){
+ var rz = this.resizeBox;
+ if(rz.x != box.x || rz.y != box.y){
+ this.updateBox(box);
+ }else{
+ this.setSize(box);
+ if (Ext.isIE6 && Ext.isStrict) {
+ this.doLayout();
+ }
+ }
+ this.focus();
+ this.updateHandles();
+ this.saveState();
+ },
+
+ /**
+ * Focuses the window. If a defaultButton is set, it will receive focus, otherwise the
+ * window itself will receive focus.
+ */
+ focus : function(){
+ var f = this.focusEl,
+ db = this.defaultButton,
+ t = typeof db,
+ el,
+ ct;
+ if(Ext.isDefined(db)){
+ if(Ext.isNumber(db) && this.fbar){
+ f = this.fbar.items.get(db);
+ }else if(Ext.isString(db)){
+ f = Ext.getCmp(db);
+ }else{
+ f = db;
+ }
+ el = f.getEl();
+ ct = Ext.getDom(this.container);
+ if (el && ct) {
+ if (!Ext.lib.Region.getRegion(ct).contains(Ext.lib.Region.getRegion(el.dom))){
+ return;
+ }
+ }
+ }
+ f = f || this.focusEl;
+ f.focus.defer(10, f);
+ },
+
+ /**
+ * Sets the target element from which the window should animate while opening.
+ * @param {String/Element} el The target element or id
+ */
+ setAnimateTarget : function(el){
+ el = Ext.get(el);
+ this.animateTarget = el;
+ },
+
+ // private
+ beforeShow : function(){
+ delete this.el.lastXY;
+ delete this.el.lastLT;
+ if(this.x === undefined || this.y === undefined){
+ var xy = this.el.getAlignToXY(this.container, 'c-c');
+ var pos = this.el.translatePoints(xy[0], xy[1]);
+ this.x = this.x === undefined? pos.left : this.x;
+ this.y = this.y === undefined? pos.top : this.y;
+ }
+ this.el.setLeftTop(this.x, this.y);
+
+ if(this.expandOnShow){
+ this.expand(false);
+ }
+
+ if(this.modal){
+ Ext.getBody().addClass('x-body-masked');
+ this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
+ this.mask.show();
+ }
+ },
+
+ /**
+ * Shows the window, rendering it first if necessary, or activates it and brings it to front if hidden.
+ * @param {String/Element} animateTarget (optional) The target element or id from which the window should
+ * animate while opening (defaults to null with no animation)
+ * @param {Function} callback (optional) A callback function to call after the window is displayed
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Window.
+ * @return {Ext.Window} this
+ */
+ show : function(animateTarget, cb, scope){
+ if(!this.rendered){
+ this.render(Ext.getBody());
+ }
+ if(this.hidden === false){
+ this.toFront();
+ return this;
+ }
+ if(this.fireEvent('beforeshow', this) === false){
+ return this;
+ }
+ if(cb){
+ this.on('show', cb, scope, {single:true});
+ }
+ this.hidden = false;
+ if(Ext.isDefined(animateTarget)){
+ this.setAnimateTarget(animateTarget);
+ }
+ this.beforeShow();
+ if(this.animateTarget){
+ this.animShow();
+ }else{
+ this.afterShow();
+ }
+ return this;
+ },
+
+ // private
+ afterShow : function(isAnim){
+ if (this.isDestroyed){
+ return false;
+ }
+ this.proxy.hide();
+ this.el.setStyle('display', 'block');
+ this.el.show();
+ if(this.maximized){
+ this.fitContainer();
+ }
+ if(Ext.isMac && Ext.isGecko2){ // work around stupid FF 2.0/Mac scroll bar bug
+ this.cascade(this.setAutoScroll);
+ }
+
+ if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){
+ Ext.EventManager.onWindowResize(this.onWindowResize, this);
+ }
+ this.doConstrain();
+ this.doLayout();
+ if(this.keyMap){
+ this.keyMap.enable();
+ }
+ this.toFront();
+ this.updateHandles();
+ if(isAnim && (Ext.isIE || Ext.isWebKit)){
+ var sz = this.getSize();
+ this.onResize(sz.width, sz.height);
+ }
+ this.onShow();
+ this.fireEvent('show', this);
+ },
+
+ // private
+ animShow : function(){
+ this.proxy.show();
+ this.proxy.setBox(this.animateTarget.getBox());
+ this.proxy.setOpacity(0);
+ var b = this.getBox();
+ this.el.setStyle('display', 'none');
+ this.proxy.shift(Ext.apply(b, {
+ callback: this.afterShow.createDelegate(this, [true], false),
+ scope: this,
+ easing: 'easeNone',
+ duration: 0.25,
+ opacity: 0.5
+ }));
+ },
+
+ /**
+ * Hides the window, setting it to invisible and applying negative offsets.
+ * @param {String/Element} animateTarget (optional) The target element or id to which the window should
+ * animate while hiding (defaults to null with no animation)
+ * @param {Function} callback (optional) A callback function to call after the window is hidden
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the callback is executed. Defaults to this Window.
+ * @return {Ext.Window} this
+ */
+ hide : function(animateTarget, cb, scope){
+ if(this.hidden || this.fireEvent('beforehide', this) === false){
+ return this;
+ }
+ if(cb){
+ this.on('hide', cb, scope, {single:true});
+ }
+ this.hidden = true;
+ if(animateTarget !== undefined){
+ this.setAnimateTarget(animateTarget);
+ }
+ if(this.modal){
+ this.mask.hide();
+ Ext.getBody().removeClass('x-body-masked');
+ }
+ if(this.animateTarget){
+ this.animHide();
+ }else{
+ this.el.hide();
+ this.afterHide();
+ }
+ return this;
+ },
+
+ // private
+ afterHide : function(){
+ this.proxy.hide();
+ if(this.monitorResize || this.modal || this.constrain || this.constrainHeader){
+ Ext.EventManager.removeResizeListener(this.onWindowResize, this);
+ }
+ if(this.keyMap){
+ this.keyMap.disable();
+ }
+ this.onHide();
+ this.fireEvent('hide', this);
+ },
+
+ // private
+ animHide : function(){
+ this.proxy.setOpacity(0.5);
+ this.proxy.show();
+ var tb = this.getBox(false);
+ this.proxy.setBox(tb);
+ this.el.hide();
+ this.proxy.shift(Ext.apply(this.animateTarget.getBox(), {
+ callback: this.afterHide,
+ scope: this,
+ duration: 0.25,
+ easing: 'easeNone',
+ opacity: 0
+ }));
+ },
+
+ /**
+ * Method that is called immediately before the <code>show</code> event is fired.
+ * Defaults to <code>Ext.emptyFn</code>.
+ */
+ onShow : Ext.emptyFn,
+
+ /**
+ * Method that is called immediately before the <code>hide</code> event is fired.
+ * Defaults to <code>Ext.emptyFn</code>.
+ */
+ onHide : Ext.emptyFn,
+
+ // private
+ onWindowResize : function(){
+ if(this.maximized){
+ this.fitContainer();
+ }
+ if(this.modal){
+ this.mask.setSize('100%', '100%');
+ var force = this.mask.dom.offsetHeight;
+ this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
+ }
+ this.doConstrain();
+ },
+
+ // private
+ doConstrain : function(){
+ if(this.constrain || this.constrainHeader){
+ var offsets;
+ if(this.constrain){
+ offsets = {
+ right:this.el.shadowOffset,
+ left:this.el.shadowOffset,
+ bottom:this.el.shadowOffset
+ };
+ }else {
+ var s = this.getSize();
+ offsets = {
+ right:-(s.width - 100),
+ bottom:-(s.height - 25)
+ };
+ }
+
+ var xy = this.el.getConstrainToXY(this.container, true, offsets);
+ if(xy){
+ this.setPosition(xy[0], xy[1]);
+ }
+ }
+ },
+
+ // private - used for dragging
+ ghost : function(cls){
+ var ghost = this.createGhost(cls);
+ var box = this.getBox(true);
+ ghost.setLeftTop(box.x, box.y);
+ ghost.setWidth(box.width);
+ this.el.hide();
+ this.activeGhost = ghost;
+ return ghost;
+ },
+
+ // private
+ unghost : function(show, matchPosition){
+ if(!this.activeGhost) {
+ return;
+ }
+ if(show !== false){
+ this.el.show();
+ this.focus.defer(10, this);
+ if(Ext.isMac && Ext.isGecko2){ // work around stupid FF 2.0/Mac scroll bar bug
+ this.cascade(this.setAutoScroll);
+ }
+ }
+ if(matchPosition !== false){
+ this.setPosition(this.activeGhost.getLeft(true), this.activeGhost.getTop(true));
+ }
+ this.activeGhost.hide();
+ this.activeGhost.remove();
+ delete this.activeGhost;
+ },
+
+ /**
+ * Placeholder method for minimizing the window. By default, this method simply fires the {@link #minimize} event
+ * since the behavior of minimizing a window is application-specific. To implement custom minimize behavior,
+ * either the minimize event can be handled or this method can be overridden.
+ * @return {Ext.Window} this
+ */
+ minimize : function(){
+ this.fireEvent('minimize', this);
+ return this;
+ },
+
+ /**
+ * <p>Closes the Window, removes it from the DOM, {@link Ext.Component#destroy destroy}s
+ * the Window object and all its descendant Components. The {@link Ext.Panel#beforeclose beforeclose}
+ * event is fired before the close happens and will cancel the close action if it returns false.<p>
+ * <p><b>Note:</b> This method is not affected by the {@link #closeAction} setting which
+ * only affects the action triggered when clicking the {@link #closable 'close' tool in the header}.
+ * To hide the Window without destroying it, call {@link #hide}.</p>
+ */
+ close : function(){
+ if(this.fireEvent('beforeclose', this) !== false){
+ if(this.hidden){
+ this.doClose();
+ }else{
+ this.hide(null, this.doClose, this);
+ }
+ }
+ },
+
+ // private
+ doClose : function(){
+ this.fireEvent('close', this);
+ this.destroy();
+ },
+
+ /**
+ * Fits the window within its current container and automatically replaces
+ * the {@link #maximizable 'maximize' tool button} with the 'restore' tool button.
+ * Also see {@link #toggleMaximize}.
+ * @return {Ext.Window} this
+ */
+ maximize : function(){
+ if(!this.maximized){
+ this.expand(false);
+ this.restoreSize = this.getSize();
+ this.restorePos = this.getPosition(true);
+ if (this.maximizable){
+ this.tools.maximize.hide();
+ this.tools.restore.show();
+ }
+ this.maximized = true;
+ this.el.disableShadow();
+
+ if(this.dd){
+ this.dd.lock();
+ }
+ if(this.collapsible){
+ this.tools.toggle.hide();
+ }
+ this.el.addClass('x-window-maximized');
+ this.container.addClass('x-window-maximized-ct');
+
+ this.setPosition(0, 0);
+ this.fitContainer();
+ this.fireEvent('maximize', this);
+ }
+ return this;
+ },
+
+ /**
+ * Restores a {@link #maximizable maximized} window back to its original
+ * size and position prior to being maximized and also replaces
+ * the 'restore' tool button with the 'maximize' tool button.
+ * Also see {@link #toggleMaximize}.
+ * @return {Ext.Window} this
+ */
+ restore : function(){
+ if(this.maximized){
+ var t = this.tools;
+ this.el.removeClass('x-window-maximized');
+ if(t.restore){
+ t.restore.hide();
+ }
+ if(t.maximize){
+ t.maximize.show();
+ }
+ this.setPosition(this.restorePos[0], this.restorePos[1]);
+ this.setSize(this.restoreSize.width, this.restoreSize.height);
+ delete this.restorePos;
+ delete this.restoreSize;
+ this.maximized = false;
+ this.el.enableShadow(true);
+
+ if(this.dd){
+ this.dd.unlock();
+ }
+ if(this.collapsible && t.toggle){
+ t.toggle.show();
+ }
+ this.container.removeClass('x-window-maximized-ct');
+
+ this.doConstrain();
+ this.fireEvent('restore', this);
+ }
+ return this;
+ },
+
+ /**
+ * A shortcut method for toggling between {@link #maximize} and {@link #restore} based on the current maximized
+ * state of the window.
+ * @return {Ext.Window} this
+ */
+ toggleMaximize : function(){
+ return this[this.maximized ? 'restore' : 'maximize']();
+ },
+
+ // private
+ fitContainer : function(){
+ var vs = this.container.getViewSize(false);
+ this.setSize(vs.width, vs.height);
+ },
+
+ // private
+ // z-index is managed by the WindowManager and may be overwritten at any time
+ setZIndex : function(index){
+ if(this.modal){
+ this.mask.setStyle('z-index', index);
+ }
+ this.el.setZIndex(++index);
+ index += 5;
+
+ if(this.resizer){
+ this.resizer.proxy.setStyle('z-index', ++index);
+ }
+
+ this.lastZIndex = index;
+ },
+
+ /**
+ * Aligns the window to the specified element
+ * @param {Mixed} element The element to align to.
+ * @param {String} position (optional, defaults to "tl-bl?") The position to align to (see {@link Ext.Element#alignTo} for more details).
+ * @param {Array} offsets (optional) Offset the positioning by [x, y]
+ * @return {Ext.Window} this
+ */
+ alignTo : function(element, position, offsets){
+ var xy = this.el.getAlignToXY(element, position, offsets);
+ this.setPagePosition(xy[0], xy[1]);
+ return this;
+ },
+
+ /**
+ * Anchors this window to another element and realigns it when the window is resized or scrolled.
+ * @param {Mixed} element The element to align to.
+ * @param {String} position The position to align to (see {@link Ext.Element#alignTo} for more details)
+ * @param {Array} offsets (optional) Offset the positioning by [x, y]
+ * @param {Boolean/Number} monitorScroll (optional) true to monitor body scroll and reposition. If this parameter
+ * is a number, it is used as the buffer delay (defaults to 50ms).
+ * @return {Ext.Window} this
+ */
+ anchorTo : function(el, alignment, offsets, monitorScroll){
+ this.clearAnchor();
+ this.anchorTarget = {
+ el: el,
+ alignment: alignment,
+ offsets: offsets
+ };
+
+ Ext.EventManager.onWindowResize(this.doAnchor, this);
+ var tm = typeof monitorScroll;
+ if(tm != 'undefined'){
+ Ext.EventManager.on(window, 'scroll', this.doAnchor, this,
+ {buffer: tm == 'number' ? monitorScroll : 50});
+ }
+ return this.doAnchor();
+ },
+
+ /**
+ * Performs the anchor, using the saved anchorTarget property.
+ * @return {Ext.Window} this
+ * @private
+ */
+ doAnchor : function(){
+ var o = this.anchorTarget;
+ this.alignTo(o.el, o.alignment, o.offsets);
+ return this;
+ },
+
+ /**
+ * Removes any existing anchor from this window. See {@link #anchorTo}.
+ * @return {Ext.Window} this
+ */
+ clearAnchor : function(){
+ if(this.anchorTarget){
+ Ext.EventManager.removeResizeListener(this.doAnchor, this);
+ Ext.EventManager.un(window, 'scroll', this.doAnchor, this);
+ delete this.anchorTarget;
+ }
+ return this;
+ },
+
+ /**
+ * Brings this window to the front of any other visible windows
+ * @param {Boolean} e (optional) Specify <tt>false</tt> to prevent the window from being focused.
+ * @return {Ext.Window} this
+ */
+ toFront : function(e){
+ if(this.manager.bringToFront(this)){
+ if(!e || !e.getTarget().focus){
+ this.focus();
+ }
+ }
+ return this;
+ },
+
+ /**
+ * Makes this the active window by showing its shadow, or deactivates it by hiding its shadow. This method also
+ * fires the {@link #activate} or {@link #deactivate} event depending on which action occurred. This method is
+ * called internally by {@link Ext.WindowMgr}.
+ * @param {Boolean} active True to activate the window, false to deactivate it (defaults to false)
+ */
+ setActive : function(active){
+ if(active){
+ if(!this.maximized){
+ this.el.enableShadow(true);
+ }
+ this.fireEvent('activate', this);
+ }else{
+ this.el.disableShadow();
+ this.fireEvent('deactivate', this);
+ }
+ },
+
+ /**
+ * Sends this window to the back of (lower z-index than) any other visible windows
+ * @return {Ext.Window} this
+ */
+ toBack : function(){
+ this.manager.sendToBack(this);
+ return this;
+ },
+
+ /**
+ * Centers this window in the viewport
+ * @return {Ext.Window} this
+ */
+ center : function(){
+ var xy = this.el.getAlignToXY(this.container, 'c-c');
+ this.setPagePosition(xy[0], xy[1]);
+ return this;
+ }
+
+ /**
+ * @cfg {Boolean} autoWidth @hide
+ **/
+});
+Ext.reg('window', Ext.Window);
+
+// private - custom Window DD implementation
+Ext.Window.DD = function(win){
+ this.win = win;
+ Ext.Window.DD.superclass.constructor.call(this, win.el.id, 'WindowDD-'+win.id);
+ this.setHandleElId(win.header.id);
+ this.scroll = false;
+};
+
+Ext.extend(Ext.Window.DD, Ext.dd.DD, {
+ moveOnly:true,
+ headerOffsets:[100, 25],
+ startDrag : function(){
+ var w = this.win;
+ this.proxy = w.ghost();
+ if(w.constrain !== false){
+ var so = w.el.shadowOffset;
+ this.constrainTo(w.container, {right: so, left: so, bottom: so});
+ }else if(w.constrainHeader !== false){
+ var s = this.proxy.getSize();
+ this.constrainTo(w.container, {right: -(s.width-this.headerOffsets[0]), bottom: -(s.height-this.headerOffsets[1])});
+ }
+ },
+ b4Drag : Ext.emptyFn,
+
+ onDrag : function(e){
+ this.alignElWithMouse(this.proxy, e.getPageX(), e.getPageY());
+ },
+
+ endDrag : function(e){
+ this.win.unghost();
+ this.win.saveState();
+ }
+});
+/**
+ * @class Ext.WindowGroup
+ * An object that manages a group of {@link Ext.Window} instances and provides z-order management
+ * and window activation behavior.
+ * @constructor
+ */
+Ext.WindowGroup = function(){
+ var list = {};
+ var accessList = [];
+ var front = null;
+
+ // private
+ var sortWindows = function(d1, d2){
+ return (!d1._lastAccess || d1._lastAccess < d2._lastAccess) ? -1 : 1;
+ };
+
+ // private
+ var orderWindows = function(){
+ var a = accessList, len = a.length;
+ if(len > 0){
+ a.sort(sortWindows);
+ var seed = a[0].manager.zseed;
+ for(var i = 0; i < len; i++){
+ var win = a[i];
+ if(win && !win.hidden){
+ win.setZIndex(seed + (i*10));
+ }
+ }
+ }
+ activateLast();
+ };
+
+ // private
+ var setActiveWin = function(win){
+ if(win != front){
+ if(front){
+ front.setActive(false);
+ }
+ front = win;
+ if(win){
+ win.setActive(true);
+ }
+ }
+ };
+
+ // private
+ var activateLast = function(){
+ for(var i = accessList.length-1; i >=0; --i) {
+ if(!accessList[i].hidden){
+ setActiveWin(accessList[i]);
+ return;
+ }
+ }
+ // none to activate
+ setActiveWin(null);
+ };
+
+ return {
+ /**
+ * The starting z-index for windows in this WindowGroup (defaults to 9000)
+ * @type Number The z-index value
+ */
+ zseed : 9000,
+
+ /**
+ * <p>Registers a {@link Ext.Window Window} with this WindowManager. This should not
+ * need to be called under normal circumstances. Windows are automatically registered
+ * with a {@link Ext.Window#manager manager} at construction time.</p>
+ * <p>Where this may be useful is moving Windows between two WindowManagers. For example,
+ * to bring the Ext.MessageBox dialog under the same manager as the Desktop's
+ * WindowManager in the desktop sample app:</p><code><pre>
+var msgWin = Ext.MessageBox.getDialog();
+MyDesktop.getDesktop().getManager().register(msgWin);
+</pre></code>
+ * @param {Window} win The Window to register.
+ */
+ register : function(win){
+ if(win.manager){
+ win.manager.unregister(win);
+ }
+ win.manager = this;
+
+ list[win.id] = win;
+ accessList.push(win);
+ win.on('hide', activateLast);
+ },
+
+ /**
+ * <p>Unregisters a {@link Ext.Window Window} from this WindowManager. This should not
+ * need to be called. Windows are automatically unregistered upon destruction.
+ * See {@link #register}.</p>
+ * @param {Window} win The Window to unregister.
+ */
+ unregister : function(win){
+ delete win.manager;
+ delete list[win.id];
+ win.un('hide', activateLast);
+ accessList.remove(win);
+ },
+
+ /**
+ * Gets a registered window by id.
+ * @param {String/Object} id The id of the window or a {@link Ext.Window} instance
+ * @return {Ext.Window}
+ */
+ get : function(id){
+ return typeof id == "object" ? id : list[id];
+ },
+
+ /**
+ * Brings the specified window to the front of any other active windows in this WindowGroup.
+ * @param {String/Object} win The id of the window or a {@link Ext.Window} instance
+ * @return {Boolean} True if the dialog was brought to the front, else false
+ * if it was already in front
+ */
+ bringToFront : function(win){
+ win = this.get(win);
+ if(win != front){
+ win._lastAccess = new Date().getTime();
+ orderWindows();
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Sends the specified window to the back of other active windows in this WindowGroup.
+ * @param {String/Object} win The id of the window or a {@link Ext.Window} instance
+ * @return {Ext.Window} The window
+ */
+ sendToBack : function(win){
+ win = this.get(win);
+ win._lastAccess = -(new Date().getTime());
+ orderWindows();
+ return win;
+ },
+
+ /**
+ * Hides all windows in this WindowGroup.
+ */
+ hideAll : function(){
+ for(var id in list){
+ if(list[id] && typeof list[id] != "function" && list[id].isVisible()){
+ list[id].hide();
+ }
+ }
+ },
+
+ /**
+ * Gets the currently-active window in this WindowGroup.
+ * @return {Ext.Window} The active window
+ */
+ getActive : function(){
+ return front;
+ },
+
+ /**
+ * Returns zero or more windows in this WindowGroup using the custom search function passed to this method.
+ * The function should accept a single {@link Ext.Window} reference as its only argument and should
+ * return true if the window matches the search criteria, otherwise it should return false.
+ * @param {Function} fn The search function
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the Window being tested.
+ * that gets passed to the function if not specified)
+ * @return {Array} An array of zero or more matching windows
+ */
+ getBy : function(fn, scope){
+ var r = [];
+ for(var i = accessList.length-1; i >=0; --i) {
+ var win = accessList[i];
+ if(fn.call(scope||win, win) !== false){
+ r.push(win);
+ }
+ }
+ return r;
+ },
+
+ /**
+ * Executes the specified function once for every window in this WindowGroup, passing each
+ * window as the only parameter. Returning false from the function will stop the iteration.
+ * @param {Function} fn The function to execute for each item
+ * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the current Window in the iteration.
+ */
+ each : function(fn, scope){
+ for(var id in list){
+ if(list[id] && typeof list[id] != "function"){
+ if(fn.call(scope || list[id], list[id]) === false){
+ return;
+ }
+ }
+ }
+ }
+ };
+};
+
+
+/**
+ * @class Ext.WindowMgr
+ * @extends Ext.WindowGroup
+ * The default global window group that is available automatically. To have more than one group of windows
+ * with separate z-order stacks, create additional instances of {@link Ext.WindowGroup} as needed.
+ * @singleton
+ */
+Ext.WindowMgr = new Ext.WindowGroup();/**
+ * @class Ext.MessageBox
+ * <p>Utility class for generating different styles of message boxes. The alias Ext.Msg can also be used.<p/>
+ * <p>Note that the MessageBox is asynchronous. Unlike a regular JavaScript <code>alert</code> (which will halt
+ * browser execution), showing a MessageBox will not cause the code to stop. For this reason, if you have code
+ * that should only run <em>after</em> some user feedback from the MessageBox, you must use a callback function
+ * (see the <code>function</code> parameter for {@link #show} for more details).</p>
+ * <p>Example usage:</p>
+ *<pre><code>
+// Basic alert:
+Ext.Msg.alert('Status', 'Changes saved successfully.');
+
+// Prompt for user data and process the result using a callback:
+Ext.Msg.prompt('Name', 'Please enter your name:', function(btn, text){
+ if (btn == 'ok'){
+ // process text value and close...
+ }
+});
+
+// Show a dialog using config options:
+Ext.Msg.show({
+ title:'Save Changes?',
+ msg: 'You are closing a tab that has unsaved changes. Would you like to save your changes?',
+ buttons: Ext.Msg.YESNOCANCEL,
+ fn: processResult,
+ animEl: 'elId',
+ icon: Ext.MessageBox.QUESTION
+});
+</code></pre>
+ * @singleton
+ */
+Ext.MessageBox = function(){
+ var dlg, opt, mask, waitTimer,
+ bodyEl, msgEl, textboxEl, textareaEl, progressBar, pp, iconEl, spacerEl,
+ buttons, activeTextEl, bwidth, bufferIcon = '', iconCls = '',
+ buttonNames = ['ok', 'yes', 'no', 'cancel'];
+
+ // private
+ var handleButton = function(button){
+ buttons[button].blur();
+ if(dlg.isVisible()){
+ dlg.hide();
+ handleHide();
+ Ext.callback(opt.fn, opt.scope||window, [button, activeTextEl.dom.value, opt], 1);
+ }
+ };
+
+ // private
+ var handleHide = function(){
+ if(opt && opt.cls){
+ dlg.el.removeClass(opt.cls);
+ }
+ progressBar.reset();
+ };
+
+ // private
+ var handleEsc = function(d, k, e){
+ if(opt && opt.closable !== false){
+ dlg.hide();
+ handleHide();
+ }
+ if(e){
+ e.stopEvent();
+ }
+ };
+
+ // private
+ var updateButtons = function(b){
+ var width = 0,
+ cfg;
+ if(!b){
+ Ext.each(buttonNames, function(name){
+ buttons[name].hide();
+ });
+ return width;
+ }
+ dlg.footer.dom.style.display = '';
+ Ext.iterate(buttons, function(name, btn){
+ cfg = b[name];
+ if(cfg){
+ btn.show();
+ btn.setText(Ext.isString(cfg) ? cfg : Ext.MessageBox.buttonText[name]);
+ width += btn.getEl().getWidth() + 15;
+ }else{
+ btn.hide();
+ }
+ });
+ return width;
+ };
+
+ return {
+ /**
+ * Returns a reference to the underlying {@link Ext.Window} element
+ * @return {Ext.Window} The window
+ */
+ getDialog : function(titleText){
+ if(!dlg){
+ var btns = [];
+
+ buttons = {};
+ Ext.each(buttonNames, function(name){
+ btns.push(buttons[name] = new Ext.Button({
+ text: this.buttonText[name],
+ handler: handleButton.createCallback(name),
+ hideMode: 'offsets'
+ }));
+ }, this);
+ dlg = new Ext.Window({
+ autoCreate : true,
+ title:titleText,
+ resizable:false,
+ constrain:true,
+ constrainHeader:true,
+ minimizable : false,
+ maximizable : false,
+ stateful: false,
+ modal: true,
+ shim:true,
+ buttonAlign:"center",
+ width:400,
+ height:100,
+ minHeight: 80,
+ plain:true,
+ footer:true,
+ closable:true,
+ close : function(){
+ if(opt && opt.buttons && opt.buttons.no && !opt.buttons.cancel){
+ handleButton("no");
+ }else{
+ handleButton("cancel");
+ }
+ },
+ fbar: new Ext.Toolbar({
+ items: btns,
+ enableOverflow: false
+ })
+ });
+ dlg.render(document.body);
+ dlg.getEl().addClass('x-window-dlg');
+ mask = dlg.mask;
+ bodyEl = dlg.body.createChild({
+ html:'<div class="ext-mb-icon"></div><div class="ext-mb-content"><span class="ext-mb-text"></span><br /><div class="ext-mb-fix-cursor"><input type="text" class="ext-mb-input" /><textarea class="ext-mb-textarea"></textarea></div></div>'
+ });