Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / pkgs / data-foundation-debug.js
1 /*!
2  * Ext JS Library 3.1.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7
8 /**
9  * @class Ext.data.Api
10  * @extends Object
11  * Ext.data.Api is a singleton designed to manage the data API including methods
12  * for validating a developer's DataProxy API.  Defines variables for CRUD actions
13  * create, read, update and destroy in addition to a mapping of RESTful HTTP methods
14  * GET, POST, PUT and DELETE to CRUD actions.
15  * @singleton
16  */
17 Ext.data.Api = (function() {
18
19     // private validActions.  validActions is essentially an inverted hash of Ext.data.Api.actions, where value becomes the key.
20     // Some methods in this singleton (e.g.: getActions, getVerb) will loop through actions with the code <code>for (var verb in this.actions)</code>
21     // For efficiency, some methods will first check this hash for a match.  Those methods which do acces validActions will cache their result here.
22     // We cannot pre-define this hash since the developer may over-ride the actions at runtime.
23     var validActions = {};
24
25     return {
26         /**
27          * Defined actions corresponding to remote actions:
28          * <pre><code>
29 actions: {
30     create  : 'create',  // Text representing the remote-action to create records on server.
31     read    : 'read',    // Text representing the remote-action to read/load data from server.
32     update  : 'update',  // Text representing the remote-action to update records on server.
33     destroy : 'destroy'  // Text representing the remote-action to destroy records on server.
34 }
35          * </code></pre>
36          * @property actions
37          * @type Object
38          */
39         actions : {
40             create  : 'create',
41             read    : 'read',
42             update  : 'update',
43             destroy : 'destroy'
44         },
45
46         /**
47          * Defined {CRUD action}:{HTTP method} pairs to associate HTTP methods with the
48          * corresponding actions for {@link Ext.data.DataProxy#restful RESTful proxies}.
49          * Defaults to:
50          * <pre><code>
51 restActions : {
52     create  : 'POST',
53     read    : 'GET',
54     update  : 'PUT',
55     destroy : 'DELETE'
56 },
57          * </code></pre>
58          */
59         restActions : {
60             create  : 'POST',
61             read    : 'GET',
62             update  : 'PUT',
63             destroy : 'DELETE'
64         },
65
66         /**
67          * Returns true if supplied action-name is a valid API action defined in <code>{@link #actions}</code> constants
68          * @param {String} action
69          * @param {String[]}(Optional) List of available CRUD actions.  Pass in list when executing multiple times for efficiency.
70          * @return {Boolean}
71          */
72         isAction : function(action) {
73             return (Ext.data.Api.actions[action]) ? true : false;
74         },
75
76         /**
77          * 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
78          * 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
79          * 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
80          * required.  This method will cache discovered KEYS into the private validActions hash.
81          * @param {String} name The runtime name of the action.
82          * @return {String||null} returns the action-key, or verb of the user-action or null if invalid.
83          * @nodoc
84          */
85         getVerb : function(name) {
86             if (validActions[name]) {
87                 return validActions[name];  // <-- found in cache.  return immediately.
88             }
89             for (var verb in this.actions) {
90                 if (this.actions[verb] === name) {
91                     validActions[name] = verb;
92                     break;
93                 }
94             }
95             return (validActions[name] !== undefined) ? validActions[name] : null;
96         },
97
98         /**
99          * Returns true if the supplied API is valid; that is, check that all keys match defined actions
100          * otherwise returns an array of mistakes.
101          * @return {String[]||true}
102          */
103         isValid : function(api){
104             var invalid = [];
105             var crud = this.actions; // <-- cache a copy of the actions.
106             for (var action in api) {
107                 if (!(action in crud)) {
108                     invalid.push(action);
109                 }
110             }
111             return (!invalid.length) ? true : invalid;
112         },
113
114         /**
115          * Returns true if the supplied verb upon the supplied proxy points to a unique url in that none of the other api-actions
116          * point to the same url.  The question is important for deciding whether to insert the "xaction" HTTP parameter within an
117          * Ajax request.  This method is used internally and shouldn't generally need to be called directly.
118          * @param {Ext.data.DataProxy} proxy
119          * @param {String} verb
120          * @return {Boolean}
121          */
122         hasUniqueUrl : function(proxy, verb) {
123             var url = (proxy.api[verb]) ? proxy.api[verb].url : null;
124             var unique = true;
125             for (var action in proxy.api) {
126                 if ((unique = (action === verb) ? true : (proxy.api[action].url != url) ? true : false) === false) {
127                     break;
128                 }
129             }
130             return unique;
131         },
132
133         /**
134          * This method is used internally by <tt>{@link Ext.data.DataProxy DataProxy}</tt> and should not generally need to be used directly.
135          * Each action of a DataProxy api can be initially defined as either a String or an Object.  When specified as an object,
136          * one can explicitly define the HTTP method (GET|POST) to use for each CRUD action.  This method will prepare the supplied API, setting
137          * each action to the Object form.  If your API-actions do not explicitly define the HTTP method, the "method" configuration-parameter will
138          * be used.  If the method configuration parameter is not specified, POST will be used.
139          <pre><code>
140 new Ext.data.HttpProxy({
141     method: "POST",     // <-- default HTTP method when not specified.
142     api: {
143         create: 'create.php',
144         load: 'read.php',
145         save: 'save.php',
146         destroy: 'destroy.php'
147     }
148 });
149
150 // Alternatively, one can use the object-form to specify the API
151 new Ext.data.HttpProxy({
152     api: {
153         load: {url: 'read.php', method: 'GET'},
154         create: 'create.php',
155         destroy: 'destroy.php',
156         save: 'update.php'
157     }
158 });
159         </code></pre>
160          *
161          * @param {Ext.data.DataProxy} proxy
162          */
163         prepare : function(proxy) {
164             if (!proxy.api) {
165                 proxy.api = {}; // <-- No api?  create a blank one.
166             }
167             for (var verb in this.actions) {
168                 var action = this.actions[verb];
169                 proxy.api[action] = proxy.api[action] || proxy.url || proxy.directFn;
170                 if (typeof(proxy.api[action]) == 'string') {
171                     proxy.api[action] = {
172                         url: proxy.api[action],
173                         method: (proxy.restful === true) ? Ext.data.Api.restActions[action] : undefined
174                     };
175                 }
176             }
177         },
178
179         /**
180          * Prepares a supplied Proxy to be RESTful.  Sets the HTTP method for each api-action to be one of
181          * GET, POST, PUT, DELETE according to the defined {@link #restActions}.
182          * @param {Ext.data.DataProxy} proxy
183          */
184         restify : function(proxy) {
185             proxy.restful = true;
186             for (var verb in this.restActions) {
187                 proxy.api[this.actions[verb]].method = this.restActions[verb];
188             }
189             // TODO: perhaps move this interceptor elsewhere?  like into DataProxy, perhaps?  Placed here
190             // to satisfy initial 3.0 final release of REST features.
191             proxy.onWrite = proxy.onWrite.createInterceptor(function(action, o, response, rs) {
192                 var reader = o.reader;
193                 var res = new Ext.data.Response({
194                     action: action,
195                     raw: response
196                 });
197
198                 switch (response.status) {
199                     case 200:   // standard 200 response, send control back to HttpProxy#onWrite by returning true from this intercepted #onWrite
200                         return true;
201                         break;
202                     case 201:   // entity created but no response returned
203                         res.success = true;
204                         break;
205                     case 204:  // no-content.  Create a fake response.
206                         res.success = true;
207                         res.data = null;
208                         break;
209                     default:
210                         return true;
211                         break;
212                 }
213                 if (res.success === true) {
214                     this.fireEvent("write", this, action, res.data, res, rs, o.request.arg);
215                 } else {
216                     this.fireEvent('exception', this, 'remote', action, o, res, rs);
217                 }
218                 o.request.callback.call(o.request.scope, res.data, res, res.success);
219
220                 return false;   // <-- false to prevent intercepted function from running.
221             }, proxy);
222         }
223     };
224 })();
225
226 /**
227  * Ext.data.Response
228  * Experimental.  Do not use directly.
229  */
230 Ext.data.Response = function(params, response) {
231     Ext.apply(this, params, {
232         raw: response
233     });
234 };
235 Ext.data.Response.prototype = {
236     message : null,
237     success : false,
238     status : null,
239     root : null,
240     raw : null,
241
242     getMessage : function() {
243         return this.message;
244     },
245     getSuccess : function() {
246         return this.success;
247     },
248     getStatus : function() {
249         return this.status
250     },
251     getRoot : function() {
252         return this.root;
253     },
254     getRawResponse : function() {
255         return this.raw;
256     }
257 };
258
259 /**
260  * @class Ext.data.Api.Error
261  * @extends Ext.Error
262  * Error class for Ext.data.Api errors
263  */
264 Ext.data.Api.Error = Ext.extend(Ext.Error, {
265     constructor : function(message, arg) {
266         this.arg = arg;
267         Ext.Error.call(this, message);
268     },
269     name: 'Ext.data.Api'
270 });
271 Ext.apply(Ext.data.Api.Error.prototype, {
272     lang: {
273         '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.',
274         'invalid': 'received an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions defined in Ext.data.Api.actions',
275         'invalid-url': 'Invalid url.  Please review your proxy configuration.',
276         'execute': 'Attempted to execute an unknown action.  Valid API actions are defined in Ext.data.Api.actions"'
277     }
278 });
279
280
281 \r
282 /**\r
283  * @class Ext.data.SortTypes\r
284  * @singleton\r
285  * Defines the default sorting (casting?) comparison functions used when sorting data.\r
286  */\r
287 Ext.data.SortTypes = {\r
288     /**\r
289      * Default sort that does nothing\r
290      * @param {Mixed} s The value being converted\r
291      * @return {Mixed} The comparison value\r
292      */\r
293     none : function(s){\r
294         return s;\r
295     },\r
296     \r
297     /**\r
298      * The regular expression used to strip tags\r
299      * @type {RegExp}\r
300      * @property\r
301      */\r
302     stripTagsRE : /<\/?[^>]+>/gi,\r
303     \r
304     /**\r
305      * Strips all HTML tags to sort on text only\r
306      * @param {Mixed} s The value being converted\r
307      * @return {String} The comparison value\r
308      */\r
309     asText : function(s){\r
310         return String(s).replace(this.stripTagsRE, "");\r
311     },\r
312     \r
313     /**\r
314      * Strips all HTML tags to sort on text only - Case insensitive\r
315      * @param {Mixed} s The value being converted\r
316      * @return {String} The comparison value\r
317      */\r
318     asUCText : function(s){\r
319         return String(s).toUpperCase().replace(this.stripTagsRE, "");\r
320     },\r
321     \r
322     /**\r
323      * Case insensitive string\r
324      * @param {Mixed} s The value being converted\r
325      * @return {String} The comparison value\r
326      */\r
327     asUCString : function(s) {\r
328         return String(s).toUpperCase();\r
329     },\r
330     \r
331     /**\r
332      * Date sorting\r
333      * @param {Mixed} s The value being converted\r
334      * @return {Number} The comparison value\r
335      */\r
336     asDate : function(s) {\r
337         if(!s){\r
338             return 0;\r
339         }\r
340         if(Ext.isDate(s)){\r
341             return s.getTime();\r
342         }\r
343         return Date.parse(String(s));\r
344     },\r
345     \r
346     /**\r
347      * Float sorting\r
348      * @param {Mixed} s The value being converted\r
349      * @return {Float} The comparison value\r
350      */\r
351     asFloat : function(s) {\r
352         var val = parseFloat(String(s).replace(/,/g, ""));\r
353         return isNaN(val) ? 0 : val;\r
354     },\r
355     \r
356     /**\r
357      * Integer sorting\r
358      * @param {Mixed} s The value being converted\r
359      * @return {Number} The comparison value\r
360      */\r
361     asInt : function(s) {\r
362         var val = parseInt(String(s).replace(/,/g, ""), 10);\r
363         return isNaN(val) ? 0 : val;\r
364     }\r
365 };/**
366  * @class Ext.data.Record
367  * <p>Instances of this class encapsulate both Record <em>definition</em> information, and Record
368  * <em>value</em> information for use in {@link Ext.data.Store} objects, or any code which needs
369  * to access Records cached in an {@link Ext.data.Store} object.</p>
370  * <p>Constructors for this class are generated by passing an Array of field definition objects to {@link #create}.
371  * Instances are usually only created by {@link Ext.data.Reader} implementations when processing unformatted data
372  * objects.</p>
373  * <p>Note that an instance of a Record class may only belong to one {@link Ext.data.Store Store} at a time.
374  * In order to copy data from one Store to another, use the {@link #copy} method to create an exact
375  * copy of the Record, and insert the new instance into the other Store.</p>
376  * <p>When serializing a Record for submission to the server, be aware that it contains many private
377  * properties, and also a reference to its owning Store which in turn holds references to its Records.
378  * This means that a whole Record may not be encoded using {@link Ext.util.JSON.encode}. Instead, use the
379  * <code>{@link #data}</code> and <code>{@link #id}</code> properties.</p>
380  * <p>Record objects generated by this constructor inherit all the methods of Ext.data.Record listed below.</p>
381  * @constructor
382  * <p>This constructor should not be used to create Record objects. Instead, use {@link #create} to
383  * generate a subclass of Ext.data.Record configured with information about its constituent fields.<p>
384  * <p><b>The generated constructor has the same signature as this constructor.</b></p>
385  * @param {Object} data (Optional) An object, the properties of which provide values for the new Record's
386  * fields. If not specified the <code>{@link Ext.data.Field#defaultValue defaultValue}</code>
387  * for each field will be assigned.
388  * @param {Object} id (Optional) The id of the Record. The id is used by the
389  * {@link Ext.data.Store} object which owns the Record to index its collection
390  * of Records (therefore this id should be unique within each store). If an
391  * <code>id</code> is not specified a <b><code>{@link #phantom}</code></b>
392  * Record will be created with an {@link #Record.id automatically generated id}.
393  */
394 Ext.data.Record = function(data, id){
395     // if no id, call the auto id method
396     this.id = (id || id === 0) ? id : Ext.data.Record.id(this);
397     this.data = data || {};
398 };
399
400 /**
401  * Generate a constructor for a specific Record layout.
402  * @param {Array} o An Array of <b>{@link Ext.data.Field Field}</b> definition objects.
403  * The constructor generated by this method may be used to create new Record instances. The data
404  * object must contain properties named after the {@link Ext.data.Field field}
405  * <b><tt>{@link Ext.data.Field#name}s</tt></b>.  Example usage:<pre><code>
406 // create a Record constructor from a description of the fields
407 var TopicRecord = Ext.data.Record.create([ // creates a subclass of Ext.data.Record
408     {{@link Ext.data.Field#name name}: 'title', {@link Ext.data.Field#mapping mapping}: 'topic_title'},
409     {name: 'author', mapping: 'username', allowBlank: false},
410     {name: 'totalPosts', mapping: 'topic_replies', type: 'int'},
411     {name: 'lastPost', mapping: 'post_time', type: 'date'},
412     {name: 'lastPoster', mapping: 'user2'},
413     {name: 'excerpt', mapping: 'post_text', allowBlank: false},
414     // In the simplest case, if no properties other than <tt>name</tt> are required,
415     // a field definition may consist of just a String for the field name.
416     'signature'
417 ]);
418
419 // create Record instance
420 var myNewRecord = new TopicRecord(
421     {
422         title: 'Do my job please',
423         author: 'noobie',
424         totalPosts: 1,
425         lastPost: new Date(),
426         lastPoster: 'Animal',
427         excerpt: 'No way dude!',
428         signature: ''
429     },
430     id // optionally specify the id of the record otherwise {@link #Record.id one is auto-assigned}
431 );
432 myStore.{@link Ext.data.Store#add add}(myNewRecord);
433 </code></pre>
434  * @method create
435  * @return {function} A constructor which is used to create new Records according
436  * to the definition. The constructor has the same signature as {@link #Record}.
437  * @static
438  */
439 Ext.data.Record.create = function(o){
440     var f = Ext.extend(Ext.data.Record, {});
441     var p = f.prototype;
442     p.fields = new Ext.util.MixedCollection(false, function(field){
443         return field.name;
444     });
445     for(var i = 0, len = o.length; i < len; i++){
446         p.fields.add(new Ext.data.Field(o[i]));
447     }
448     f.getField = function(name){
449         return p.fields.get(name);
450     };
451     return f;
452 };
453
454 Ext.data.Record.PREFIX = 'ext-record';
455 Ext.data.Record.AUTO_ID = 1;
456 Ext.data.Record.EDIT = 'edit';
457 Ext.data.Record.REJECT = 'reject';
458 Ext.data.Record.COMMIT = 'commit';
459
460
461 /**
462  * Generates a sequential id. This method is typically called when a record is {@link #create}d
463  * and {@link #Record no id has been specified}. The returned id takes the form:
464  * <tt>&#123;PREFIX}-&#123;AUTO_ID}</tt>.<div class="mdetail-params"><ul>
465  * <li><b><tt>PREFIX</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.PREFIX</tt>
466  * (defaults to <tt>'ext-record'</tt>)</p></li>
467  * <li><b><tt>AUTO_ID</tt></b> : String<p class="sub-desc"><tt>Ext.data.Record.AUTO_ID</tt>
468  * (defaults to <tt>1</tt> initially)</p></li>
469  * </ul></div>
470  * @param {Record} rec The record being created.  The record does not exist, it's a {@link #phantom}.
471  * @return {String} auto-generated string id, <tt>"ext-record-i++'</tt>;
472  */
473 Ext.data.Record.id = function(rec) {
474     rec.phantom = true;
475     return [Ext.data.Record.PREFIX, '-', Ext.data.Record.AUTO_ID++].join('');
476 };
477
478 Ext.data.Record.prototype = {
479     /**
480      * <p><b>This property is stored in the Record definition's <u>prototype</u></b></p>
481      * A MixedCollection containing the defined {@link Ext.data.Field Field}s for this Record.  Read-only.
482      * @property fields
483      * @type Ext.util.MixedCollection
484      */
485     /**
486      * An object hash representing the data for this Record. Every field name in the Record definition
487      * is represented by a property of that name in this object. Note that unless you specified a field
488      * with {@link Ext.data.Field#name name} "id" in the Record definition, this will <b>not</b> contain
489      * an <tt>id</tt> property.
490      * @property data
491      * @type {Object}
492      */
493     /**
494      * The unique ID of the Record {@link #Record as specified at construction time}.
495      * @property id
496      * @type {Object}
497      */
498     /**
499      * <p><b>Only present if this Record was created by an {@link Ext.data.XmlReader XmlReader}</b>.</p>
500      * <p>The XML element which was the source of the data for this Record.</p>
501      * @property node
502      * @type {XMLElement}
503      */
504     /**
505      * <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>
506      * <p>The Array or object which was the source of the data for this Record.</p>
507      * @property json
508      * @type {Array|Object}
509      */
510     /**
511      * Readonly flag - true if this Record has been modified.
512      * @type Boolean
513      */
514     dirty : false,
515     editing : false,
516     error : null,
517     /**
518      * This object contains a key and value storing the original values of all modified
519      * fields or is null if no fields have been modified.
520      * @property modified
521      * @type {Object}
522      */
523     modified : null,
524     /**
525      * <tt>true</tt> when the record does not yet exist in a server-side database (see
526      * {@link #markDirty}).  Any record which has a real database pk set as its id property
527      * is NOT a phantom -- it's real.
528      * @property phantom
529      * @type {Boolean}
530      */
531     phantom : false,
532
533     // private
534     join : function(store){
535         /**
536          * The {@link Ext.data.Store} to which this Record belongs.
537          * @property store
538          * @type {Ext.data.Store}
539          */
540         this.store = store;
541     },
542
543     /**
544      * Set the {@link Ext.data.Field#name named field} to the specified value.  For example:
545      * <pre><code>
546 // record has a field named 'firstname'
547 var Employee = Ext.data.Record.{@link #create}([
548     {name: 'firstname'},
549     ...
550 ]);
551
552 // update the 2nd record in the store:
553 var rec = myStore.{@link Ext.data.Store#getAt getAt}(1);
554
555 // set the value (shows dirty flag):
556 rec.set('firstname', 'Betty');
557
558 // commit the change (removes dirty flag):
559 rec.{@link #commit}();
560
561 // update the record in the store, bypass setting dirty flag,
562 // and do not store the change in the {@link Ext.data.Store#getModifiedRecords modified records}
563 rec.{@link #data}['firstname'] = 'Wilma'; // updates record, but not the view
564 rec.{@link #commit}(); // updates the view
565      * </code></pre>
566      * <b>Notes</b>:<div class="mdetail-params"><ul>
567      * <li>If the store has a writer and <code>autoSave=true</code>, each set()
568      * will execute an XHR to the server.</li>
569      * <li>Use <code>{@link #beginEdit}</code> to prevent the store's <code>update</code>
570      * event firing while using set().</li>
571      * <li>Use <code>{@link #endEdit}</code> to have the store's <code>update</code>
572      * event fire.</li>
573      * </ul></div>
574      * @param {String} name The {@link Ext.data.Field#name name of the field} to set.
575      * @param {String/Object/Array} value The value to set the field to.
576      */
577     set : function(name, value){
578         var encode = Ext.isPrimitive(value) ? String : Ext.encode;
579         if(encode(this.data[name]) == encode(value)) {
580             return;
581         }        
582         this.dirty = true;
583         if(!this.modified){
584             this.modified = {};
585         }
586         if(this.modified[name] === undefined){
587             this.modified[name] = this.data[name];
588         }
589         this.data[name] = value;
590         if(!this.editing){
591             this.afterEdit();
592         }
593     },
594
595     // private
596     afterEdit : function(){
597         if(this.store){
598             this.store.afterEdit(this);
599         }
600     },
601
602     // private
603     afterReject : function(){
604         if(this.store){
605             this.store.afterReject(this);
606         }
607     },
608
609     // private
610     afterCommit : function(){
611         if(this.store){
612             this.store.afterCommit(this);
613         }
614     },
615
616     /**
617      * Get the value of the {@link Ext.data.Field#name named field}.
618      * @param {String} name The {@link Ext.data.Field#name name of the field} to get the value of.
619      * @return {Object} The value of the field.
620      */
621     get : function(name){
622         return this.data[name];
623     },
624
625     /**
626      * Begin an edit. While in edit mode, no events (e.g.. the <code>update</code> event)
627      * are relayed to the containing store.
628      * See also: <code>{@link #endEdit}</code> and <code>{@link #cancelEdit}</code>.
629      */
630     beginEdit : function(){
631         this.editing = true;
632         this.modified = this.modified || {};
633     },
634
635     /**
636      * Cancels all changes made in the current edit operation.
637      */
638     cancelEdit : function(){
639         this.editing = false;
640         delete this.modified;
641     },
642
643     /**
644      * End an edit. If any data was modified, the containing store is notified
645      * (ie, the store's <code>update</code> event will fire).
646      */
647     endEdit : function(){
648         this.editing = false;
649         if(this.dirty){
650             this.afterEdit();
651         }
652     },
653
654     /**
655      * Usually called by the {@link Ext.data.Store} which owns the Record.
656      * Rejects all changes made to the Record since either creation, or the last commit operation.
657      * Modified fields are reverted to their original values.
658      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
659      * to have their code notified of reject operations.</p>
660      * @param {Boolean} silent (optional) True to skip notification of the owning
661      * store of the change (defaults to false)
662      */
663     reject : function(silent){
664         var m = this.modified;
665         for(var n in m){
666             if(typeof m[n] != "function"){
667                 this.data[n] = m[n];
668             }
669         }
670         this.dirty = false;
671         delete this.modified;
672         this.editing = false;
673         if(silent !== true){
674             this.afterReject();
675         }
676     },
677
678     /**
679      * Usually called by the {@link Ext.data.Store} which owns the Record.
680      * Commits all changes made to the Record since either creation, or the last commit operation.
681      * <p>Developers should subscribe to the {@link Ext.data.Store#update} event
682      * to have their code notified of commit operations.</p>
683      * @param {Boolean} silent (optional) True to skip notification of the owning
684      * store of the change (defaults to false)
685      */
686     commit : function(silent){
687         this.dirty = false;
688         delete this.modified;
689         this.editing = false;
690         if(silent !== true){
691             this.afterCommit();
692         }
693     },
694
695     /**
696      * Gets a hash of only the fields that have been modified since this Record was created or commited.
697      * @return Object
698      */
699     getChanges : function(){
700         var m = this.modified, cs = {};
701         for(var n in m){
702             if(m.hasOwnProperty(n)){
703                 cs[n] = this.data[n];
704             }
705         }
706         return cs;
707     },
708
709     // private
710     hasError : function(){
711         return this.error !== null;
712     },
713
714     // private
715     clearError : function(){
716         this.error = null;
717     },
718
719     /**
720      * Creates a copy (clone) of this Record.
721      * @param {String} id (optional) A new Record id, defaults to the id
722      * of the record being copied. See <code>{@link #id}</code>. 
723      * To generate a phantom record with a new id use:<pre><code>
724 var rec = record.copy(); // clone the record
725 Ext.data.Record.id(rec); // automatically generate a unique sequential id
726      * </code></pre>
727      * @return {Record}
728      */
729     copy : function(newId) {
730         return new this.constructor(Ext.apply({}, this.data), newId || this.id);
731     },
732
733     /**
734      * Returns <tt>true</tt> if the passed field name has been <code>{@link #modified}</code>
735      * since the load or last commit.
736      * @param {String} fieldName {@link Ext.data.Field.{@link Ext.data.Field#name}
737      * @return {Boolean}
738      */
739     isModified : function(fieldName){
740         return !!(this.modified && this.modified.hasOwnProperty(fieldName));
741     },
742
743     /**
744      * By default returns <tt>false</tt> if any {@link Ext.data.Field field} within the
745      * record configured with <tt>{@link Ext.data.Field#allowBlank} = false</tt> returns
746      * <tt>true</tt> from an {@link Ext}.{@link Ext#isEmpty isempty} test.
747      * @return {Boolean}
748      */
749     isValid : function() {
750         return this.fields.find(function(f) {
751             return (f.allowBlank === false && Ext.isEmpty(this.data[f.name])) ? true : false;
752         },this) ? false : true;
753     },
754
755     /**
756      * <p>Marks this <b>Record</b> as <code>{@link #dirty}</code>.  This method
757      * is used interally when adding <code>{@link #phantom}</code> records to a
758      * {@link Ext.data.Store#writer writer enabled store}.</p>
759      * <br><p>Marking a record <code>{@link #dirty}</code> causes the phantom to
760      * be returned by {@link Ext.data.Store#getModifiedRecords} where it will
761      * have a create action composed for it during {@link Ext.data.Store#save store save}
762      * operations.</p>
763      */
764     markDirty : function(){
765         this.dirty = true;
766         if(!this.modified){
767             this.modified = {};
768         }
769         this.fields.each(function(f) {
770             this.modified[f.name] = this.data[f.name];
771         },this);
772     }
773 };
774 /**
775  * @class Ext.StoreMgr
776  * @extends Ext.util.MixedCollection
777  * The default global group of stores.
778  * @singleton
779  */
780 Ext.StoreMgr = Ext.apply(new Ext.util.MixedCollection(), {
781     /**
782      * @cfg {Object} listeners @hide
783      */
784
785     /**
786      * Registers one or more Stores with the StoreMgr. You do not normally need to register stores
787      * manually.  Any store initialized with a {@link Ext.data.Store#storeId} will be auto-registered. 
788      * @param {Ext.data.Store} store1 A Store instance
789      * @param {Ext.data.Store} store2 (optional)
790      * @param {Ext.data.Store} etc... (optional)
791      */
792     register : function(){
793         for(var i = 0, s; (s = arguments[i]); i++){
794             this.add(s);
795         }
796     },
797
798     /**
799      * Unregisters one or more Stores with the StoreMgr
800      * @param {String/Object} id1 The id of the Store, or a Store instance
801      * @param {String/Object} id2 (optional)
802      * @param {String/Object} etc... (optional)
803      */
804     unregister : function(){
805         for(var i = 0, s; (s = arguments[i]); i++){
806             this.remove(this.lookup(s));
807         }
808     },
809
810     /**
811      * Gets a registered Store by id
812      * @param {String/Object} id The id of the Store, or a Store instance
813      * @return {Ext.data.Store}
814      */
815     lookup : function(id){
816         if(Ext.isArray(id)){
817             var fields = ['field1'], expand = !Ext.isArray(id[0]);
818             if(!expand){
819                 for(var i = 2, len = id[0].length; i <= len; ++i){
820                     fields.push('field' + i);
821                 }
822             }
823             return new Ext.data.ArrayStore({
824                 fields: fields,
825                 data: id,
826                 expandData: expand,
827                 autoDestroy: true,
828                 autoCreated: true
829
830             });
831         }
832         return Ext.isObject(id) ? (id.events ? id : Ext.create(id, 'store')) : this.get(id);
833     },
834
835     // getKey implementation for MixedCollection
836     getKey : function(o){
837          return o.storeId;
838     }
839 });/**
840  * @class Ext.data.Store
841  * @extends Ext.util.Observable
842  * <p>The Store class encapsulates a client side cache of {@link Ext.data.Record Record}
843  * objects which provide input data for Components such as the {@link Ext.grid.GridPanel GridPanel},
844  * the {@link Ext.form.ComboBox ComboBox}, or the {@link Ext.DataView DataView}.</p>
845  * <p><u>Retrieving Data</u></p>
846  * <p>A Store object may access a data object using:<div class="mdetail-params"><ul>
847  * <li>{@link #proxy configured implementation} of {@link Ext.data.DataProxy DataProxy}</li>
848  * <li>{@link #data} to automatically pass in data</li>
849  * <li>{@link #loadData} to manually pass in data</li>
850  * </ul></div></p>
851  * <p><u>Reading Data</u></p>
852  * <p>A Store object has no inherent knowledge of the format of the data object (it could be
853  * an Array, XML, or JSON). A Store object uses an appropriate {@link #reader configured implementation}
854  * of a {@link Ext.data.DataReader DataReader} to create {@link Ext.data.Record Record} instances from the data
855  * object.</p>
856  * <p><u>Store Types</u></p>
857  * <p>There are several implementations of Store available which are customized for use with
858  * a specific DataReader implementation.  Here is an example using an ArrayStore which implicitly
859  * creates a reader commensurate to an Array data object.</p>
860  * <pre><code>
861 var myStore = new Ext.data.ArrayStore({
862     fields: ['fullname', 'first'],
863     idIndex: 0 // id for each record will be the first element
864 });
865  * </code></pre>
866  * <p>For custom implementations create a basic {@link Ext.data.Store} configured as needed:</p>
867  * <pre><code>
868 // create a {@link Ext.data.Record Record} constructor:
869 var rt = Ext.data.Record.create([
870     {name: 'fullname'},
871     {name: 'first'}
872 ]);
873 var myStore = new Ext.data.Store({
874     // explicitly create reader
875     reader: new Ext.data.ArrayReader(
876         {
877             idIndex: 0  // id for each record will be the first element
878         },
879         rt // recordType
880     )
881 });
882  * </code></pre>
883  * <p>Load some data into store (note the data object is an array which corresponds to the reader):</p>
884  * <pre><code>
885 var myData = [
886     [1, 'Fred Flintstone', 'Fred'],  // note that id for the record is the first element
887     [2, 'Barney Rubble', 'Barney']
888 ];
889 myStore.loadData(myData);
890  * </code></pre>
891  * <p>Records are cached and made available through accessor functions.  An example of adding
892  * a record to the store:</p>
893  * <pre><code>
894 var defaultData = {
895     fullname: 'Full Name',
896     first: 'First Name'
897 };
898 var recId = 100; // provide unique id for the record
899 var r = new myStore.recordType(defaultData, ++recId); // create new record
900 myStore.{@link #insert}(0, r); // insert a new record into the store (also see {@link #add})
901  * </code></pre>
902  * <p><u>Writing Data</u></p>
903  * <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>
904  * along with <a href="http://extjs.com/deploy/dev/examples/restful/restful.html">RESTful features.</a>
905  * @constructor
906  * Creates a new Store.
907  * @param {Object} config A config object containing the objects needed for the Store to access data,
908  * and read the data into Records.
909  * @xtype store
910  */
911 Ext.data.Store = Ext.extend(Ext.util.Observable, {
912     /**
913      * @cfg {String} storeId If passed, the id to use to register with the <b>{@link Ext.StoreMgr StoreMgr}</b>.
914      * <p><b>Note</b>: if a (deprecated) <tt>{@link #id}</tt> is specified it will supersede the <tt>storeId</tt>
915      * assignment.</p>
916      */
917     /**
918      * @cfg {String} url If a <tt>{@link #proxy}</tt> is not specified the <tt>url</tt> will be used to
919      * implicitly configure a {@link Ext.data.HttpProxy HttpProxy} if an <tt>url</tt> is specified.
920      * Typically this option, or the <code>{@link #data}</code> option will be specified.
921      */
922     /**
923      * @cfg {Boolean/Object} autoLoad If <tt>{@link #data}</tt> is not specified, and if <tt>autoLoad</tt>
924      * is <tt>true</tt> or an <tt>Object</tt>, this store's {@link #load} method is automatically called
925      * after creation. If the value of <tt>autoLoad</tt> is an <tt>Object</tt>, this <tt>Object</tt> will
926      * be passed to the store's {@link #load} method.
927      */
928     /**
929      * @cfg {Ext.data.DataProxy} proxy The {@link Ext.data.DataProxy DataProxy} object which provides
930      * access to a data object.  See <code>{@link #url}</code>.
931      */
932     /**
933      * @cfg {Array} data An inline data object readable by the <code>{@link #reader}</code>.
934      * Typically this option, or the <code>{@link #url}</code> option will be specified.
935      */
936     /**
937      * @cfg {Ext.data.DataReader} reader The {@link Ext.data.DataReader Reader} object which processes the
938      * data object and returns an Array of {@link Ext.data.Record} objects which are cached keyed by their
939      * <b><tt>{@link Ext.data.Record#id id}</tt></b> property.
940      */
941     /**
942      * @cfg {Ext.data.DataWriter} writer
943      * <p>The {@link Ext.data.DataWriter Writer} object which processes a record object for being written
944      * to the server-side database.</p>
945      * <br><p>When a writer is installed into a Store the {@link #add}, {@link #remove}, and {@link #update}
946      * events on the store are monitored in order to remotely {@link #createRecords create records},
947      * {@link #destroyRecord destroy records}, or {@link #updateRecord update records}.</p>
948      * <br><p>The proxy for this store will relay any {@link #writexception} events to this store.</p>
949      * <br><p>Sample implementation:
950      * <pre><code>
951 var writer = new {@link Ext.data.JsonWriter}({
952     encode: true,
953     writeAllFields: true // write all fields, not just those that changed
954 });
955
956 // Typical Store collecting the Proxy, Reader and Writer together.
957 var store = new Ext.data.Store({
958     storeId: 'user',
959     root: 'records',
960     proxy: proxy,
961     reader: reader,
962     writer: writer,     // <-- plug a DataWriter into the store just as you would a Reader
963     paramsAsHash: true,
964     autoSave: false    // <-- false to delay executing create, update, destroy requests
965                         //     until specifically told to do so.
966 });
967      * </code></pre></p>
968      */
969     writer : undefined,
970     /**
971      * @cfg {Object} baseParams
972      * <p>An object containing properties which are to be sent as parameters
973      * for <i>every</i> HTTP request.</p>
974      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p>
975      * <p><b>Note</b>: <code>baseParams</code> may be superseded by any <code>params</code>
976      * specified in a <code>{@link #load}</code> request, see <code>{@link #load}</code>
977      * for more details.</p>
978      * This property may be modified after creation using the <code>{@link #setBaseParam}</code>
979      * method.
980      * @property
981      */
982     /**
983      * @cfg {Object} sortInfo A config object to specify the sort order in the request of a Store's
984      * {@link #load} operation.  Note that for local sorting, the <tt>direction</tt> property is
985      * case-sensitive. See also {@link #remoteSort} and {@link #paramNames}.
986      * For example:<pre><code>
987 sortInfo: {
988     field: 'fieldName',
989     direction: 'ASC' // or 'DESC' (case sensitive for local sorting)
990 }
991 </code></pre>
992      */
993     /**
994      * @cfg {boolean} remoteSort <tt>true</tt> if sorting is to be handled by requesting the <tt>{@link #proxy Proxy}</tt>
995      * to provide a refreshed version of the data object in sorted order, as opposed to sorting the Record cache
996      * in place (defaults to <tt>false</tt>).
997      * <p>If <tt>remoteSort</tt> is <tt>true</tt>, then clicking on a {@link Ext.grid.Column Grid Column}'s
998      * {@link Ext.grid.Column#header header} causes the current page to be requested from the server appending
999      * the following two parameters to the <b><tt>{@link #load params}</tt></b>:<div class="mdetail-params"><ul>
1000      * <li><b><tt>sort</tt></b> : String<p class="sub-desc">The <tt>name</tt> (as specified in the Record's
1001      * {@link Ext.data.Field Field definition}) of the field to sort on.</p></li>
1002      * <li><b><tt>dir</tt></b> : String<p class="sub-desc">The direction of the sort, 'ASC' or 'DESC' (case-sensitive).</p></li>
1003      * </ul></div></p>
1004      */
1005     remoteSort : false,
1006
1007     /**
1008      * @cfg {Boolean} autoDestroy <tt>true</tt> to destroy the store when the component the store is bound
1009      * to is destroyed (defaults to <tt>false</tt>).
1010      * <p><b>Note</b>: this should be set to true when using stores that are bound to only 1 component.</p>
1011      */
1012     autoDestroy : false,
1013
1014     /**
1015      * @cfg {Boolean} pruneModifiedRecords <tt>true</tt> to clear all modified record information each time
1016      * the store is loaded or when a record is removed (defaults to <tt>false</tt>). See {@link #getModifiedRecords}
1017      * for the accessor method to retrieve the modified records.
1018      */
1019     pruneModifiedRecords : false,
1020
1021     /**
1022      * Contains the last options object used as the parameter to the {@link #load} method. See {@link #load}
1023      * for the details of what this may contain. This may be useful for accessing any params which were used
1024      * to load the current Record cache.
1025      * @property
1026      */
1027     lastOptions : null,
1028
1029     /**
1030      * @cfg {Boolean} autoSave
1031      * <p>Defaults to <tt>true</tt> causing the store to automatically {@link #save} records to
1032      * the server when a record is modified (ie: becomes 'dirty'). Specify <tt>false</tt> to manually call {@link #save}
1033      * to send all modifiedRecords to the server.</p>
1034      * <br><p><b>Note</b>: each CRUD action will be sent as a separate request.</p>
1035      */
1036     autoSave : true,
1037
1038     /**
1039      * @cfg {Boolean} batch
1040      * <p>Defaults to <tt>true</tt> (unless <code>{@link #restful}:true</code>). Multiple
1041      * requests for each CRUD action (CREATE, READ, UPDATE and DESTROY) will be combined
1042      * and sent as one transaction. Only applies when <code>{@link #autoSave}</code> is set
1043      * to <tt>false</tt>.</p>
1044      * <br><p>If Store is RESTful, the DataProxy is also RESTful, and a unique transaction is
1045      * generated for each record.</p>
1046      */
1047     batch : true,
1048
1049     /**
1050      * @cfg {Boolean} restful
1051      * Defaults to <tt>false</tt>.  Set to <tt>true</tt> to have the Store and the set
1052      * Proxy operate in a RESTful manner. The store will automatically generate GET, POST,
1053      * PUT and DELETE requests to the server. The HTTP method used for any given CRUD
1054      * action is described in {@link Ext.data.Api#restActions}.  For additional information
1055      * see {@link Ext.data.DataProxy#restful}.
1056      * <p><b>Note</b>: if <code>{@link #restful}:true</code> <code>batch</code> will
1057      * internally be set to <tt>false</tt>.</p>
1058      */
1059     restful: false,
1060
1061     /**
1062      * @cfg {Object} paramNames
1063      * <p>An object containing properties which specify the names of the paging and
1064      * sorting parameters passed to remote servers when loading blocks of data. By default, this
1065      * object takes the following form:</p><pre><code>
1066 {
1067     start : 'start',  // The parameter name which specifies the start row
1068     limit : 'limit',  // The parameter name which specifies number of rows to return
1069     sort : 'sort',    // The parameter name which specifies the column to sort on
1070     dir : 'dir'       // The parameter name which specifies the sort direction
1071 }
1072 </code></pre>
1073      * <p>The server must produce the requested data block upon receipt of these parameter names.
1074      * If different parameter names are required, this property can be overriden using a configuration
1075      * property.</p>
1076      * <p>A {@link Ext.PagingToolbar PagingToolbar} bound to this Store uses this property to determine
1077      * the parameter names to use in its {@link #load requests}.
1078      */
1079     paramNames : undefined,
1080
1081     /**
1082      * @cfg {Object} defaultParamNames
1083      * Provides the default values for the {@link #paramNames} property. To globally modify the parameters
1084      * for all stores, this object should be changed on the store prototype.
1085      */
1086     defaultParamNames : {
1087         start : 'start',
1088         limit : 'limit',
1089         sort : 'sort',
1090         dir : 'dir'
1091     },
1092
1093     // private
1094     batchKey : '_ext_batch_',
1095
1096     constructor : function(config){
1097         this.data = new Ext.util.MixedCollection(false);
1098         this.data.getKey = function(o){
1099             return o.id;
1100         };
1101         /**
1102          * See the <code>{@link #baseParams corresponding configuration option}</code>
1103          * for a description of this property.
1104          * To modify this property see <code>{@link #setBaseParam}</code>.
1105          * @property
1106          */
1107         this.baseParams = {};
1108
1109         // temporary removed-records cache
1110         this.removed = [];
1111
1112         if(config && config.data){
1113             this.inlineData = config.data;
1114             delete config.data;
1115         }
1116
1117         Ext.apply(this, config);
1118
1119         this.paramNames = Ext.applyIf(this.paramNames || {}, this.defaultParamNames);
1120
1121         if((this.url || this.api) && !this.proxy){
1122             this.proxy = new Ext.data.HttpProxy({url: this.url, api: this.api});
1123         }
1124         // If Store is RESTful, so too is the DataProxy
1125         if (this.restful === true && this.proxy) {
1126             // When operating RESTfully, a unique transaction is generated for each record.
1127             // TODO might want to allow implemention of faux REST where batch is possible using RESTful routes only.
1128             this.batch = false;
1129             Ext.data.Api.restify(this.proxy);
1130         }
1131
1132         if(this.reader){ // reader passed
1133             if(!this.recordType){
1134                 this.recordType = this.reader.recordType;
1135             }
1136             if(this.reader.onMetaChange){
1137                 this.reader.onMetaChange = this.reader.onMetaChange.createSequence(this.onMetaChange, this);
1138             }
1139             if (this.writer) { // writer passed
1140                 if (this.writer instanceof(Ext.data.DataWriter) === false) {    // <-- config-object instead of instance.
1141                     this.writer = this.buildWriter(this.writer);
1142                 }
1143                 this.writer.meta = this.reader.meta;
1144                 this.pruneModifiedRecords = true;
1145             }
1146         }
1147
1148         /**
1149          * The {@link Ext.data.Record Record} constructor as supplied to (or created by) the
1150          * {@link Ext.data.DataReader Reader}. Read-only.
1151          * <p>If the Reader was constructed by passing in an Array of {@link Ext.data.Field} definition objects,
1152          * instead of a Record constructor, it will implicitly create a Record constructor from that Array (see
1153          * {@link Ext.data.Record}.{@link Ext.data.Record#create create} for additional details).</p>
1154          * <p>This property may be used to create new Records of the type held in this Store, for example:</p><pre><code>
1155     // create the data store
1156     var store = new Ext.data.ArrayStore({
1157         autoDestroy: true,
1158         fields: [
1159            {name: 'company'},
1160            {name: 'price', type: 'float'},
1161            {name: 'change', type: 'float'},
1162            {name: 'pctChange', type: 'float'},
1163            {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
1164         ]
1165     });
1166     store.loadData(myData);
1167
1168     // create the Grid
1169     var grid = new Ext.grid.EditorGridPanel({
1170         store: store,
1171         colModel: new Ext.grid.ColumnModel({
1172             columns: [
1173                 {id:'company', header: 'Company', width: 160, dataIndex: 'company'},
1174                 {header: 'Price', renderer: 'usMoney', dataIndex: 'price'},
1175                 {header: 'Change', renderer: change, dataIndex: 'change'},
1176                 {header: '% Change', renderer: pctChange, dataIndex: 'pctChange'},
1177                 {header: 'Last Updated', width: 85,
1178                     renderer: Ext.util.Format.dateRenderer('m/d/Y'),
1179                     dataIndex: 'lastChange'}
1180             ],
1181             defaults: {
1182                 sortable: true,
1183                 width: 75
1184             }
1185         }),
1186         autoExpandColumn: 'company', // match the id specified in the column model
1187         height:350,
1188         width:600,
1189         title:'Array Grid',
1190         tbar: [{
1191             text: 'Add Record',
1192             handler : function(){
1193                 var defaultData = {
1194                     change: 0,
1195                     company: 'New Company',
1196                     lastChange: (new Date()).clearTime(),
1197                     pctChange: 0,
1198                     price: 10
1199                 };
1200                 var recId = 3; // provide unique id
1201                 var p = new store.recordType(defaultData, recId); // create new record
1202                 grid.stopEditing();
1203                 store.{@link #insert}(0, p); // insert a new record into the store (also see {@link #add})
1204                 grid.startEditing(0, 0);
1205             }
1206         }]
1207     });
1208          * </code></pre>
1209          * @property recordType
1210          * @type Function
1211          */
1212
1213         if(this.recordType){
1214             /**
1215              * A {@link Ext.util.MixedCollection MixedCollection} containing the defined {@link Ext.data.Field Field}s
1216              * for the {@link Ext.data.Record Records} stored in this Store. Read-only.
1217              * @property fields
1218              * @type Ext.util.MixedCollection
1219              */
1220             this.fields = this.recordType.prototype.fields;
1221         }
1222         this.modified = [];
1223
1224         this.addEvents(
1225             /**
1226              * @event datachanged
1227              * Fires when the data cache has changed in a bulk manner (e.g., it has been sorted, filtered, etc.) and a
1228              * widget that is using this Store as a Record cache should refresh its view.
1229              * @param {Store} this
1230              */
1231             'datachanged',
1232             /**
1233              * @event metachange
1234              * Fires when this store's reader provides new metadata (fields). This is currently only supported for JsonReaders.
1235              * @param {Store} this
1236              * @param {Object} meta The JSON metadata
1237              */
1238             'metachange',
1239             /**
1240              * @event add
1241              * Fires when Records have been {@link #add}ed to the Store
1242              * @param {Store} this
1243              * @param {Ext.data.Record[]} records The array of Records added
1244              * @param {Number} index The index at which the record(s) were added
1245              */
1246             'add',
1247             /**
1248              * @event remove
1249              * Fires when a Record has been {@link #remove}d from the Store
1250              * @param {Store} this
1251              * @param {Ext.data.Record} record The Record that was removed
1252              * @param {Number} index The index at which the record was removed
1253              */
1254             'remove',
1255             /**
1256              * @event update
1257              * Fires when a Record has been updated
1258              * @param {Store} this
1259              * @param {Ext.data.Record} record The Record that was updated
1260              * @param {String} operation The update operation being performed.  Value may be one of:
1261              * <pre><code>
1262      Ext.data.Record.EDIT
1263      Ext.data.Record.REJECT
1264      Ext.data.Record.COMMIT
1265              * </code></pre>
1266              */
1267             'update',
1268             /**
1269              * @event clear
1270              * Fires when the data cache has been cleared.
1271              * @param {Store} this
1272              * @param {Record[]} The records that were cleared.
1273              */
1274             'clear',
1275             /**
1276              * @event exception
1277              * <p>Fires if an exception occurs in the Proxy during a remote request.
1278              * This event is relayed through the corresponding {@link Ext.data.DataProxy}.
1279              * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
1280              * for additional details.
1281              * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#exception exception}
1282              * for description.
1283              */
1284             'exception',
1285             /**
1286              * @event beforeload
1287              * Fires before a request is made for a new data object.  If the beforeload handler returns
1288              * <tt>false</tt> the {@link #load} action will be canceled.
1289              * @param {Store} this
1290              * @param {Object} options The loading options that were specified (see {@link #load} for details)
1291              */
1292             'beforeload',
1293             /**
1294              * @event load
1295              * Fires after a new set of Records has been loaded.
1296              * @param {Store} this
1297              * @param {Ext.data.Record[]} records The Records that were loaded
1298              * @param {Object} options The loading options that were specified (see {@link #load} for details)
1299              */
1300             'load',
1301             /**
1302              * @event loadexception
1303              * <p>This event is <b>deprecated</b> in favor of the catch-all <b><code>{@link #exception}</code></b>
1304              * event instead.</p>
1305              * <p>This event is relayed through the corresponding {@link Ext.data.DataProxy}.
1306              * See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
1307              * for additional details.
1308              * @param {misc} misc See {@link Ext.data.DataProxy}.{@link Ext.data.DataProxy#loadexception loadexception}
1309              * for description.
1310              */
1311             'loadexception',
1312             /**
1313              * @event beforewrite
1314              * @param {Ext.data.Store} store
1315              * @param {String} action [Ext.data.Api.actions.create|update|destroy]
1316              * @param {Record/Array[Record]} rs
1317              * @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)
1318              * @param {Object} arg The callback's arg object passed to the {@link #request} function
1319              */
1320             'beforewrite',
1321             /**
1322              * @event write
1323              * Fires if the server returns 200 after an Ext.data.Api.actions CRUD action.
1324              * Success of the action is determined in the <code>result['successProperty']</code>property (<b>NOTE</b> for RESTful stores,
1325              * a simple 20x response is sufficient for the actions "destroy" and "update".  The "create" action should should return 200 along with a database pk).
1326              * @param {Ext.data.Store} store
1327              * @param {String} action [Ext.data.Api.actions.create|update|destroy]
1328              * @param {Object} result The 'data' picked-out out of the response for convenience.
1329              * @param {Ext.Direct.Transaction} res
1330              * @param {Record/Record[]} rs Store's records, the subject(s) of the write-action
1331              */
1332             'write',
1333             /**
1334              * @event beforesave
1335              * Fires before a save action is called. A save encompasses destroying records, updating records and creating records.
1336              * @param {Ext.data.Store} store
1337              * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
1338              * with an array of records for each action.
1339              */
1340             'beforesave',
1341             /**
1342              * @event save
1343              * Fires after a save is completed. A save encompasses destroying records, updating records and creating records.
1344              * @param {Ext.data.Store} store
1345              * @param {Number} batch The identifier for the batch that was saved.
1346              * @param {Object} data An object containing the data that is to be saved. The object will contain a key for each appropriate action,
1347              * with an array of records for each action.
1348              */
1349             'save'
1350
1351         );
1352
1353         if(this.proxy){
1354             // TODO remove deprecated loadexception with ext-3.0.1
1355             this.relayEvents(this.proxy,  ['loadexception', 'exception']);
1356         }
1357         // With a writer set for the Store, we want to listen to add/remove events to remotely create/destroy records.
1358         if (this.writer) {
1359             this.on({
1360                 scope: this,
1361                 add: this.createRecords,
1362                 remove: this.destroyRecord,
1363                 update: this.updateRecord,
1364                 clear: this.onClear
1365             });
1366         }
1367
1368         this.sortToggle = {};
1369         if(this.sortField){
1370             this.setDefaultSort(this.sortField, this.sortDir);
1371         }else if(this.sortInfo){
1372             this.setDefaultSort(this.sortInfo.field, this.sortInfo.direction);
1373         }
1374
1375         Ext.data.Store.superclass.constructor.call(this);
1376
1377         if(this.id){
1378             this.storeId = this.id;
1379             delete this.id;
1380         }
1381         if(this.storeId){
1382             Ext.StoreMgr.register(this);
1383         }
1384         if(this.inlineData){
1385             this.loadData(this.inlineData);
1386             delete this.inlineData;
1387         }else if(this.autoLoad){
1388             this.load.defer(10, this, [
1389                 typeof this.autoLoad == 'object' ?
1390                     this.autoLoad : undefined]);
1391         }
1392         // used internally to uniquely identify a batch
1393         this.batchCounter = 0;
1394         this.batches = {};
1395     },
1396
1397     /**
1398      * builds a DataWriter instance when Store constructor is provided with a writer config-object instead of an instace.
1399      * @param {Object} config Writer configuration
1400      * @return {Ext.data.DataWriter}
1401      * @private
1402      */
1403     buildWriter : function(config) {
1404         var klass = undefined;
1405         type = (config.format || 'json').toLowerCase();
1406         switch (type) {
1407             case 'json':
1408                 klass = Ext.data.JsonWriter;
1409                 break;
1410             case 'xml':
1411                 klass = Ext.data.XmlWriter;
1412                 break;
1413             default:
1414                 klass = Ext.data.JsonWriter;
1415         }
1416         return new klass(config);
1417     },
1418
1419     /**
1420      * Destroys the store.
1421      */
1422     destroy : function(){
1423         if(!this.isDestroyed){
1424             if(this.storeId){
1425                 Ext.StoreMgr.unregister(this);
1426             }
1427             this.clearData();
1428             this.data = null;
1429             Ext.destroy(this.proxy);
1430             this.reader = this.writer = null;
1431             this.purgeListeners();
1432             this.isDestroyed = true;
1433         }
1434     },
1435
1436     /**
1437      * Add Records to the Store and fires the {@link #add} event.  To add Records
1438      * to the store from a remote source use <code>{@link #load}({add:true})</code>.
1439      * See also <code>{@link #recordType}</code> and <code>{@link #insert}</code>.
1440      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects
1441      * to add to the cache. See {@link #recordType}.
1442      */
1443     add : function(records){
1444         records = [].concat(records);
1445         if(records.length < 1){
1446             return;
1447         }
1448         for(var i = 0, len = records.length; i < len; i++){
1449             records[i].join(this);
1450         }
1451         var index = this.data.length;
1452         this.data.addAll(records);
1453         if(this.snapshot){
1454             this.snapshot.addAll(records);
1455         }
1456         this.fireEvent('add', this, records, index);
1457     },
1458
1459     /**
1460      * (Local sort only) Inserts the passed Record into the Store at the index where it
1461      * should go based on the current sort information.
1462      * @param {Ext.data.Record} record
1463      */
1464     addSorted : function(record){
1465         var index = this.findInsertIndex(record);
1466         this.insert(index, record);
1467     },
1468
1469     /**
1470      * Remove Records from the Store and fires the {@link #remove} event.
1471      * @param {Ext.data.Record/Ext.data.Record[]} record The record object or array of records to remove from the cache.
1472      */
1473     remove : function(record){
1474         if(Ext.isArray(record)){
1475             Ext.each(record, function(r){
1476                 this.remove(r);
1477             }, this);
1478         }
1479         var index = this.data.indexOf(record);
1480         if(index > -1){
1481             record.join(null);
1482             this.data.removeAt(index);
1483         }
1484         if(this.pruneModifiedRecords){
1485             this.modified.remove(record);
1486         }
1487         if(this.snapshot){
1488             this.snapshot.remove(record);
1489         }
1490         if(index > -1){
1491             this.fireEvent('remove', this, record, index);
1492         }
1493     },
1494
1495     /**
1496      * Remove a Record from the Store at the specified index. Fires the {@link #remove} event.
1497      * @param {Number} index The index of the record to remove.
1498      */
1499     removeAt : function(index){
1500         this.remove(this.getAt(index));
1501     },
1502
1503     /**
1504      * Remove all Records from the Store and fires the {@link #clear} event.
1505      * @param {Boolean} silent [false] Defaults to <tt>false</tt>.  Set <tt>true</tt> to not fire clear event.
1506      */
1507     removeAll : function(silent){
1508         var items = [];
1509         this.each(function(rec){
1510             items.push(rec);
1511         });
1512         this.clearData();
1513         if(this.snapshot){
1514             this.snapshot.clear();
1515         }
1516         if(this.pruneModifiedRecords){
1517             this.modified = [];
1518         }
1519         if (silent !== true) {  // <-- prevents write-actions when we just want to clear a store.
1520             this.fireEvent('clear', this, items);
1521         }
1522     },
1523
1524     // private
1525     onClear: function(store, records){
1526         Ext.each(records, function(rec, index){
1527             this.destroyRecord(this, rec, index);
1528         }, this);
1529     },
1530
1531     /**
1532      * Inserts Records into the Store at the given index and fires the {@link #add} event.
1533      * See also <code>{@link #add}</code> and <code>{@link #addSorted}</code>.
1534      * @param {Number} index The start index at which to insert the passed Records.
1535      * @param {Ext.data.Record[]} records An Array of Ext.data.Record objects to add to the cache.
1536      */
1537     insert : function(index, records){
1538         records = [].concat(records);
1539         for(var i = 0, len = records.length; i < len; i++){
1540             this.data.insert(index, records[i]);
1541             records[i].join(this);
1542         }
1543         if(this.snapshot){
1544             this.snapshot.addAll(records);
1545         }
1546         this.fireEvent('add', this, records, index);
1547     },
1548
1549     /**
1550      * Get the index within the cache of the passed Record.
1551      * @param {Ext.data.Record} record The Ext.data.Record object to find.
1552      * @return {Number} The index of the passed Record. Returns -1 if not found.
1553      */
1554     indexOf : function(record){
1555         return this.data.indexOf(record);
1556     },
1557
1558     /**
1559      * Get the index within the cache of the Record with the passed id.
1560      * @param {String} id The id of the Record to find.
1561      * @return {Number} The index of the Record. Returns -1 if not found.
1562      */
1563     indexOfId : function(id){
1564         return this.data.indexOfKey(id);
1565     },
1566
1567     /**
1568      * Get the Record with the specified id.
1569      * @param {String} id The id of the Record to find.
1570      * @return {Ext.data.Record} The Record with the passed id. Returns undefined if not found.
1571      */
1572     getById : function(id){
1573         return (this.snapshot || this.data).key(id);
1574     },
1575
1576     /**
1577      * Get the Record at the specified index.
1578      * @param {Number} index The index of the Record to find.
1579      * @return {Ext.data.Record} The Record at the passed index. Returns undefined if not found.
1580      */
1581     getAt : function(index){
1582         return this.data.itemAt(index);
1583     },
1584
1585     /**
1586      * Returns a range of Records between specified indices.
1587      * @param {Number} startIndex (optional) The starting index (defaults to 0)
1588      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
1589      * @return {Ext.data.Record[]} An array of Records
1590      */
1591     getRange : function(start, end){
1592         return this.data.getRange(start, end);
1593     },
1594
1595     // private
1596     storeOptions : function(o){
1597         o = Ext.apply({}, o);
1598         delete o.callback;
1599         delete o.scope;
1600         this.lastOptions = o;
1601     },
1602
1603     // private
1604     clearData: function(){
1605         this.data.each(function(rec) {
1606             rec.join(null);
1607         });
1608         this.data.clear();
1609     },
1610
1611     /**
1612      * <p>Loads the Record cache from the configured <tt>{@link #proxy}</tt> using the configured <tt>{@link #reader}</tt>.</p>
1613      * <br><p>Notes:</p><div class="mdetail-params"><ul>
1614      * <li><b><u>Important</u></b>: loading is asynchronous! This call will return before the new data has been
1615      * loaded. To perform any post-processing where information from the load call is required, specify
1616      * the <tt>callback</tt> function to be called, or use a {@link Ext.util.Observable#listeners a 'load' event handler}.</li>
1617      * <li>If using {@link Ext.PagingToolbar remote paging}, the first load call must specify the <tt>start</tt> and <tt>limit</tt>
1618      * properties in the <code>options.params</code> property to establish the initial position within the
1619      * dataset, and the number of Records to cache on each read from the Proxy.</li>
1620      * <li>If using {@link #remoteSort remote sorting}, the configured <code>{@link #sortInfo}</code>
1621      * will be automatically included with the posted parameters according to the specified
1622      * <code>{@link #paramNames}</code>.</li>
1623      * </ul></div>
1624      * @param {Object} options An object containing properties which control loading options:<ul>
1625      * <li><b><tt>params</tt></b> :Object<div class="sub-desc"><p>An object containing properties to pass as HTTP
1626      * parameters to a remote data source. <b>Note</b>: <code>params</code> will override any
1627      * <code>{@link #baseParams}</code> of the same name.</p>
1628      * <p>Parameters are encoded as standard HTTP parameters using {@link Ext#urlEncode}.</p></div></li>
1629      * <li><b>callback</b> : Function<div class="sub-desc"><p>A function to be called after the Records
1630      * have been loaded. The callback is called after the load event is fired, and is passed the following arguments:<ul>
1631      * <li>r : Ext.data.Record[] An Array of Records loaded.</li>
1632      * <li>options : Options object from the load call.</li>
1633      * <li>success : Boolean success indicator.</li></ul></p></div></li>
1634      * <li><b>scope</b> : Object<div class="sub-desc"><p>Scope with which to call the callback (defaults
1635      * to the Store object)</p></div></li>
1636      * <li><b>add</b> : Boolean<div class="sub-desc"><p>Indicator to append loaded records rather than
1637      * replace the current cache.  <b>Note</b>: see note for <tt>{@link #loadData}</tt></p></div></li>
1638      * </ul>
1639      * @return {Boolean} If the <i>developer</i> provided <tt>{@link #beforeload}</tt> event handler returns
1640      * <tt>false</tt>, the load call will abort and will return <tt>false</tt>; otherwise will return <tt>true</tt>.
1641      */
1642     load : function(options) {
1643         options = options || {};
1644         this.storeOptions(options);
1645         if(this.sortInfo && this.remoteSort){
1646             var pn = this.paramNames;
1647             options.params = options.params || {};
1648             options.params[pn.sort] = this.sortInfo.field;
1649             options.params[pn.dir] = this.sortInfo.direction;
1650         }
1651         try {
1652             return this.execute('read', null, options); // <-- null represents rs.  No rs for load actions.
1653         } catch(e) {
1654             this.handleException(e);
1655             return false;
1656         }
1657     },
1658
1659     /**
1660      * updateRecord  Should not be used directly.  This method will be called automatically if a Writer is set.
1661      * Listens to 'update' event.
1662      * @param {Object} store
1663      * @param {Object} record
1664      * @param {Object} action
1665      * @private
1666      */
1667     updateRecord : function(store, record, action) {
1668         if (action == Ext.data.Record.EDIT && this.autoSave === true && (!record.phantom || (record.phantom && record.isValid()))) {
1669             this.save();
1670         }
1671     },
1672
1673     /**
1674      * Should not be used directly.  Store#add will call this automatically if a Writer is set
1675      * @param {Object} store
1676      * @param {Object} rs
1677      * @param {Object} index
1678      * @private
1679      */
1680     createRecords : function(store, rs, index) {
1681         for (var i = 0, len = rs.length; i < len; i++) {
1682             if (rs[i].phantom && rs[i].isValid()) {
1683                 rs[i].markDirty();  // <-- Mark new records dirty
1684                 this.modified.push(rs[i]);  // <-- add to modified
1685             }
1686         }
1687         if (this.autoSave === true) {
1688             this.save();
1689         }
1690     },
1691
1692     /**
1693      * Destroys a record or records.  Should not be used directly.  It's called by Store#remove if a Writer is set.
1694      * @param {Store} this
1695      * @param {Ext.data.Record/Ext.data.Record[]}
1696      * @param {Number} index
1697      * @private
1698      */
1699     destroyRecord : function(store, record, index) {
1700         if (this.modified.indexOf(record) != -1) {  // <-- handled already if @cfg pruneModifiedRecords == true
1701             this.modified.remove(record);
1702         }
1703         if (!record.phantom) {
1704             this.removed.push(record);
1705
1706             // since the record has already been removed from the store but the server request has not yet been executed,
1707             // must keep track of the last known index this record existed.  If a server error occurs, the record can be
1708             // put back into the store.  @see Store#createCallback where the record is returned when response status === false
1709             record.lastIndex = index;
1710
1711             if (this.autoSave === true) {
1712                 this.save();
1713             }
1714         }
1715     },
1716
1717     /**
1718      * This method should generally not be used directly.  This method is called internally
1719      * by {@link #load}, or if a Writer is set will be called automatically when {@link #add},
1720      * {@link #remove}, or {@link #update} events fire.
1721      * @param {String} action Action name ('read', 'create', 'update', or 'destroy')
1722      * @param {Record/Record[]} rs
1723      * @param {Object} options
1724      * @throws Error
1725      * @private
1726      */
1727     execute : function(action, rs, options, /* private */ batch) {
1728         // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
1729         if (!Ext.data.Api.isAction(action)) {
1730             throw new Ext.data.Api.Error('execute', action);
1731         }
1732         // make sure options has a fresh, new params hash
1733         options = Ext.applyIf(options||{}, {
1734             params: {}
1735         });
1736         if(batch !== undefined){
1737             this.addToBatch(batch);
1738         }
1739         // have to separate before-events since load has a different signature than create,destroy and save events since load does not
1740         // include the rs (record resultset) parameter.  Capture return values from the beforeaction into doRequest flag.
1741         var doRequest = true;
1742
1743         if (action === 'read') {
1744             Ext.applyIf(options.params, this.baseParams);
1745             doRequest = this.fireEvent('beforeload', this, options);
1746         }
1747         else {
1748             // if Writer is configured as listful, force single-record rs to be [{}] instead of {}
1749             // TODO Move listful rendering into DataWriter where the @cfg is defined.  Should be easy now.
1750             if (this.writer.listful === true && this.restful !== true) {
1751                 rs = (Ext.isArray(rs)) ? rs : [rs];
1752             }
1753             // if rs has just a single record, shift it off so that Writer writes data as '{}' rather than '[{}]'
1754             else if (Ext.isArray(rs) && rs.length == 1) {
1755                 rs = rs.shift();
1756             }
1757             // Write the action to options.params
1758             if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
1759                 this.writer.apply(options.params, this.baseParams, action, rs);
1760             }
1761         }
1762         if (doRequest !== false) {
1763             // Send request to proxy.
1764             if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
1765                 options.params.xaction = action;    // <-- really old, probaby unecessary.
1766             }
1767             // Note:  Up until this point we've been dealing with 'action' as a key from Ext.data.Api.actions.
1768             // We'll flip it now and send the value into DataProxy#request, since it's the value which maps to
1769             // the user's configured DataProxy#api
1770             // TODO Refactor all Proxies to accept an instance of Ext.data.Request (not yet defined) instead of this looooooong list
1771             // of params.  This method is an artifact from Ext2.
1772             this.proxy.request(Ext.data.Api.actions[action], rs, options.params, this.reader, this.createCallback(action, rs, batch), this, options);
1773         }
1774         return doRequest;
1775     },
1776
1777     /**
1778      * Saves all pending changes to the store.  If the commensurate Ext.data.Api.actions action is not configured, then
1779      * the configured <code>{@link #url}</code> will be used.
1780      * <pre>
1781      * change            url
1782      * ---------------   --------------------
1783      * removed records   Ext.data.Api.actions.destroy
1784      * phantom records   Ext.data.Api.actions.create
1785      * {@link #getModifiedRecords modified records}  Ext.data.Api.actions.update
1786      * </pre>
1787      * @TODO:  Create extensions of Error class and send associated Record with thrown exceptions.
1788      * e.g.:  Ext.data.DataReader.Error or Ext.data.Error or Ext.data.DataProxy.Error, etc.
1789      * @return {Number} batch Returns a number to uniquely identify the "batch" of saves occurring. -1 will be returned
1790      * if there are no items to save or the save was cancelled.
1791      */
1792     save : function() {
1793         if (!this.writer) {
1794             throw new Ext.data.Store.Error('writer-undefined');
1795         }
1796
1797         var queue = [],
1798             len,
1799             trans,
1800             batch,
1801             data = {};
1802         // DESTROY:  First check for removed records.  Records in this.removed are guaranteed non-phantoms.  @see Store#remove
1803         if(this.removed.length){
1804             queue.push(['destroy', this.removed]);
1805         }
1806
1807         // Check for modified records. Use a copy so Store#rejectChanges will work if server returns error.
1808         var rs = [].concat(this.getModifiedRecords());
1809         if(rs.length){
1810             // CREATE:  Next check for phantoms within rs.  splice-off and execute create.
1811             var phantoms = [];
1812             for(var i = rs.length-1; i >= 0; i--){
1813                 if(rs[i].phantom === true){
1814                     var rec = rs.splice(i, 1).shift();
1815                     if(rec.isValid()){
1816                         phantoms.push(rec);
1817                     }
1818                 }else if(!rs[i].isValid()){ // <-- while we're here, splice-off any !isValid real records
1819                     rs.splice(i,1);
1820                 }
1821             }
1822             // If we have valid phantoms, create them...
1823             if(phantoms.length){
1824                 queue.push(['create', phantoms]);
1825             }
1826
1827             // UPDATE:  And finally, if we're still here after splicing-off phantoms and !isValid real records, update the rest...
1828             if(rs.length){
1829                 queue.push(['update', rs]);
1830             }
1831         }
1832         len = queue.length;
1833         if(len){
1834             batch = ++this.batchCounter;
1835             for(var i = 0; i < len; ++i){
1836                 trans = queue[i];
1837                 data[trans[0]] = trans[1];
1838             }
1839             if(this.fireEvent('beforesave', this, data) !== false){
1840                 for(var i = 0; i < len; ++i){
1841                     trans = queue[i];
1842                     this.doTransaction(trans[0], trans[1], batch);
1843                 }
1844                 return batch;
1845             }
1846         }
1847         return -1;
1848     },
1849
1850     // private.  Simply wraps call to Store#execute in try/catch.  Defers to Store#handleException on error.  Loops if batch: false
1851     doTransaction : function(action, rs, batch) {
1852         function transaction(records) {
1853             try{
1854                 this.execute(action, records, undefined, batch);
1855             }catch (e){
1856                 this.handleException(e);
1857             }
1858         }
1859         if(this.batch === false){
1860             for(var i = 0, len = rs.length; i < len; i++){
1861                 transaction.call(this, rs[i]);
1862             }
1863         }else{
1864             transaction.call(this, rs);
1865         }
1866     },
1867
1868     // private
1869     addToBatch : function(batch){
1870         var b = this.batches,
1871             key = this.batchKey + batch,
1872             o = b[key];
1873
1874         if(!o){
1875             b[key] = o = {
1876                 id: batch,
1877                 count: 0,
1878                 data: {}
1879             }
1880         }
1881         ++o.count;
1882     },
1883
1884     removeFromBatch : function(batch, action, data){
1885         var b = this.batches,
1886             key = this.batchKey + batch,
1887             o = b[key],
1888             data,
1889             arr;
1890
1891
1892         if(o){
1893             arr = o.data[action] || [];
1894             o.data[action] = arr.concat(data);
1895             if(o.count === 1){
1896                 data = o.data;
1897                 delete b[key];
1898                 this.fireEvent('save', this, batch, data);
1899             }else{
1900                 --o.count;
1901             }
1902         }
1903     },
1904
1905     // @private callback-handler for remote CRUD actions
1906     // Do not override -- override loadRecords, onCreateRecords, onDestroyRecords and onUpdateRecords instead.
1907     createCallback : function(action, rs, batch) {
1908         var actions = Ext.data.Api.actions;
1909         return (action == 'read') ? this.loadRecords : function(data, response, success) {
1910             // calls: onCreateRecords | onUpdateRecords | onDestroyRecords
1911             this['on' + Ext.util.Format.capitalize(action) + 'Records'](success, rs, [].concat(data));
1912             // If success === false here, exception will have been called in DataProxy
1913             if (success === true) {
1914                 this.fireEvent('write', this, action, data, response, rs);
1915             }
1916             this.removeFromBatch(batch, action, data);
1917         };
1918     },
1919
1920     // Clears records from modified array after an exception event.
1921     // NOTE:  records are left marked dirty.  Do we want to commit them even though they were not updated/realized?
1922     // TODO remove this method?
1923     clearModified : function(rs) {
1924         if (Ext.isArray(rs)) {
1925             for (var n=rs.length-1;n>=0;n--) {
1926                 this.modified.splice(this.modified.indexOf(rs[n]), 1);
1927             }
1928         } else {
1929             this.modified.splice(this.modified.indexOf(rs), 1);
1930         }
1931     },
1932
1933     // remap record ids in MixedCollection after records have been realized.  @see Store#onCreateRecords, @see DataReader#realize
1934     reMap : function(record) {
1935         if (Ext.isArray(record)) {
1936             for (var i = 0, len = record.length; i < len; i++) {
1937                 this.reMap(record[i]);
1938             }
1939         } else {
1940             delete this.data.map[record._phid];
1941             this.data.map[record.id] = record;
1942             var index = this.data.keys.indexOf(record._phid);
1943             this.data.keys.splice(index, 1, record.id);
1944             delete record._phid;
1945         }
1946     },
1947
1948     // @protected onCreateRecord proxy callback for create action
1949     onCreateRecords : function(success, rs, data) {
1950         if (success === true) {
1951             try {
1952                 this.reader.realize(rs, data);
1953                 this.reMap(rs);
1954             }
1955             catch (e) {
1956                 this.handleException(e);
1957                 if (Ext.isArray(rs)) {
1958                     // Recurse to run back into the try {}.  DataReader#realize splices-off the rs until empty.
1959                     this.onCreateRecords(success, rs, data);
1960                 }
1961             }
1962         }
1963     },
1964
1965     // @protected, onUpdateRecords proxy callback for update action
1966     onUpdateRecords : function(success, rs, data) {
1967         if (success === true) {
1968             try {
1969                 this.reader.update(rs, data);
1970             } catch (e) {
1971                 this.handleException(e);
1972                 if (Ext.isArray(rs)) {
1973                     // Recurse to run back into the try {}.  DataReader#update splices-off the rs until empty.
1974                     this.onUpdateRecords(success, rs, data);
1975                 }
1976             }
1977         }
1978     },
1979
1980     // @protected onDestroyRecords proxy callback for destroy action
1981     onDestroyRecords : function(success, rs, data) {
1982         // splice each rec out of this.removed
1983         rs = (rs instanceof Ext.data.Record) ? [rs] : [].concat(rs);
1984         for (var i=0,len=rs.length;i<len;i++) {
1985             this.removed.splice(this.removed.indexOf(rs[i]), 1);
1986         }
1987         if (success === false) {
1988             // put records back into store if remote destroy fails.
1989             // @TODO: Might want to let developer decide.
1990             for (i=rs.length-1;i>=0;i--) {
1991                 this.insert(rs[i].lastIndex, rs[i]);    // <-- lastIndex set in Store#destroyRecord
1992             }
1993         }
1994     },
1995
1996     // protected handleException.  Possibly temporary until Ext framework has an exception-handler.
1997     handleException : function(e) {
1998         // @see core/Error.js
1999         Ext.handleError(e);
2000     },
2001
2002     /**
2003      * <p>Reloads the Record cache from the configured Proxy using the configured
2004      * {@link Ext.data.Reader Reader} and the options from the last load operation
2005      * performed.</p>
2006      * <p><b>Note</b>: see the Important note in {@link #load}.</p>
2007      * @param {Object} options <p>(optional) An <tt>Object</tt> containing
2008      * {@link #load loading options} which may override the {@link #lastOptions options}
2009      * used in the last {@link #load} operation. See {@link #load} for details
2010      * (defaults to <tt>null</tt>, in which case the {@link #lastOptions} are
2011      * used).</p>
2012      * <br><p>To add new params to the existing params:</p><pre><code>
2013 lastOptions = myStore.lastOptions;
2014 Ext.apply(lastOptions.params, {
2015     myNewParam: true
2016 });
2017 myStore.reload(lastOptions);
2018      * </code></pre>
2019      */
2020     reload : function(options){
2021         this.load(Ext.applyIf(options||{}, this.lastOptions));
2022     },
2023
2024     // private
2025     // Called as a callback by the Reader during a load operation.
2026     loadRecords : function(o, options, success){
2027         if (this.isDestroyed === true) {
2028             return;
2029         }
2030         if(!o || success === false){
2031             if(success !== false){
2032                 this.fireEvent('load', this, [], options);
2033             }
2034             if(options.callback){
2035                 options.callback.call(options.scope || this, [], options, false, o);
2036             }
2037             return;
2038         }
2039         var r = o.records, t = o.totalRecords || r.length;
2040         if(!options || options.add !== true){
2041             if(this.pruneModifiedRecords){
2042                 this.modified = [];
2043             }
2044             for(var i = 0, len = r.length; i < len; i++){
2045                 r[i].join(this);
2046             }
2047             if(this.snapshot){
2048                 this.data = this.snapshot;
2049                 delete this.snapshot;
2050             }
2051             this.clearData();
2052             this.data.addAll(r);
2053             this.totalLength = t;
2054             this.applySort();
2055             this.fireEvent('datachanged', this);
2056         }else{
2057             this.totalLength = Math.max(t, this.data.length+r.length);
2058             this.add(r);
2059         }
2060         this.fireEvent('load', this, r, options);
2061         if(options.callback){
2062             options.callback.call(options.scope || this, r, options, true);
2063         }
2064     },
2065
2066     /**
2067      * Loads data from a passed data block and fires the {@link #load} event. A {@link Ext.data.Reader Reader}
2068      * which understands the format of the data must have been configured in the constructor.
2069      * @param {Object} data The data block from which to read the Records.  The format of the data expected
2070      * is dependent on the type of {@link Ext.data.Reader Reader} that is configured and should correspond to
2071      * that {@link Ext.data.Reader Reader}'s <tt>{@link Ext.data.Reader#readRecords}</tt> parameter.
2072      * @param {Boolean} append (Optional) <tt>true</tt> to append the new Records rather the default to replace
2073      * the existing cache.
2074      * <b>Note</b>: that Records in a Store are keyed by their {@link Ext.data.Record#id id}, so added Records
2075      * with ids which are already present in the Store will <i>replace</i> existing Records. Only Records with
2076      * new, unique ids will be added.
2077      */
2078     loadData : function(o, append){
2079         var r = this.reader.readRecords(o);
2080         this.loadRecords(r, {add: append}, true);
2081     },
2082
2083     /**
2084      * Gets the number of cached records.
2085      * <p>If using paging, this may not be the total size of the dataset. If the data object
2086      * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
2087      * the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
2088      * @return {Number} The number of Records in the Store's cache.
2089      */
2090     getCount : function(){
2091         return this.data.length || 0;
2092     },
2093
2094     /**
2095      * Gets the total number of records in the dataset as returned by the server.
2096      * <p>If using paging, for this to be accurate, the data object used by the {@link #reader Reader}
2097      * must contain the dataset size. For remote data sources, the value for this property
2098      * (<tt>totalProperty</tt> for {@link Ext.data.JsonReader JsonReader},
2099      * <tt>totalRecords</tt> for {@link Ext.data.XmlReader XmlReader}) shall be returned by a query on the server.
2100      * <b>Note</b>: see the Important note in {@link #load}.</p>
2101      * @return {Number} The number of Records as specified in the data object passed to the Reader
2102      * by the Proxy.
2103      * <p><b>Note</b>: this value is not updated when changing the contents of the Store locally.</p>
2104      */
2105     getTotalCount : function(){
2106         return this.totalLength || 0;
2107     },
2108
2109     /**
2110      * Returns an object describing the current sort state of this Store.
2111      * @return {Object} The sort state of the Store. An object with two properties:<ul>
2112      * <li><b>field : String<p class="sub-desc">The name of the field by which the Records are sorted.</p></li>
2113      * <li><b>direction : String<p class="sub-desc">The sort order, 'ASC' or 'DESC' (case-sensitive).</p></li>
2114      * </ul>
2115      * See <tt>{@link #sortInfo}</tt> for additional details.
2116      */
2117     getSortState : function(){
2118         return this.sortInfo;
2119     },
2120
2121     // private
2122     applySort : function(){
2123         if(this.sortInfo && !this.remoteSort){
2124             var s = this.sortInfo, f = s.field;
2125             this.sortData(f, s.direction);
2126         }
2127     },
2128
2129     // private
2130     sortData : function(f, direction){
2131         direction = direction || 'ASC';
2132         var st = this.fields.get(f).sortType;
2133         var fn = function(r1, r2){
2134             var v1 = st(r1.data[f]), v2 = st(r2.data[f]);
2135             return v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
2136         };
2137         this.data.sort(direction, fn);
2138         if(this.snapshot && this.snapshot != this.data){
2139             this.snapshot.sort(direction, fn);
2140         }
2141     },
2142
2143     /**
2144      * Sets the default sort column and order to be used by the next {@link #load} operation.
2145      * @param {String} fieldName The name of the field to sort by.
2146      * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
2147      */
2148     setDefaultSort : function(field, dir){
2149         dir = dir ? dir.toUpperCase() : 'ASC';
2150         this.sortInfo = {field: field, direction: dir};
2151         this.sortToggle[field] = dir;
2152     },
2153
2154     /**
2155      * Sort the Records.
2156      * If remote sorting is used, the sort is performed on the server, and the cache is reloaded. If local
2157      * sorting is used, the cache is sorted internally. See also {@link #remoteSort} and {@link #paramNames}.
2158      * @param {String} fieldName The name of the field to sort by.
2159      * @param {String} dir (optional) The sort order, 'ASC' or 'DESC' (case-sensitive, defaults to <tt>'ASC'</tt>)
2160      */
2161     sort : function(fieldName, dir){
2162         var f = this.fields.get(fieldName);
2163         if(!f){
2164             return false;
2165         }
2166         if(!dir){
2167             if(this.sortInfo && this.sortInfo.field == f.name){ // toggle sort dir
2168                 dir = (this.sortToggle[f.name] || 'ASC').toggle('ASC', 'DESC');
2169             }else{
2170                 dir = f.sortDir;
2171             }
2172         }
2173         var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
2174         var si = (this.sortInfo) ? this.sortInfo : null;
2175
2176         this.sortToggle[f.name] = dir;
2177         this.sortInfo = {field: f.name, direction: dir};
2178         if(!this.remoteSort){
2179             this.applySort();
2180             this.fireEvent('datachanged', this);
2181         }else{
2182             if (!this.load(this.lastOptions)) {
2183                 if (st) {
2184                     this.sortToggle[f.name] = st;
2185                 }
2186                 if (si) {
2187                     this.sortInfo = si;
2188                 }
2189             }
2190         }
2191     },
2192
2193     /**
2194      * Calls the specified function for each of the {@link Ext.data.Record Records} in the cache.
2195      * @param {Function} fn The function to call. The {@link Ext.data.Record Record} is passed as the first parameter.
2196      * Returning <tt>false</tt> aborts and exits the iteration.
2197      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
2198      * Defaults to the current {@link Ext.data.Record Record} in the iteration.
2199      */
2200     each : function(fn, scope){
2201         this.data.each(fn, scope);
2202     },
2203
2204     /**
2205      * Gets all {@link Ext.data.Record records} modified since the last commit.  Modified records are
2206      * persisted across load operations (e.g., during paging). <b>Note</b>: deleted records are not
2207      * included.  See also <tt>{@link #pruneModifiedRecords}</tt> and
2208      * {@link Ext.data.Record}<tt>{@link Ext.data.Record#markDirty markDirty}.</tt>.
2209      * @return {Ext.data.Record[]} An array of {@link Ext.data.Record Records} containing outstanding
2210      * modifications.  To obtain modified fields within a modified record see
2211      *{@link Ext.data.Record}<tt>{@link Ext.data.Record#modified modified}.</tt>.
2212      */
2213     getModifiedRecords : function(){
2214         return this.modified;
2215     },
2216
2217     // private
2218     createFilterFn : function(property, value, anyMatch, caseSensitive){
2219         if(Ext.isEmpty(value, false)){
2220             return false;
2221         }
2222         value = this.data.createValueMatcher(value, anyMatch, caseSensitive);
2223         return function(r){
2224             return value.test(r.data[property]);
2225         };
2226     },
2227
2228     /**
2229      * Sums the value of <tt>property</tt> for each {@link Ext.data.Record record} between <tt>start</tt>
2230      * and <tt>end</tt> and returns the result.
2231      * @param {String} property A field in each record
2232      * @param {Number} start (optional) The record index to start at (defaults to <tt>0</tt>)
2233      * @param {Number} end (optional) The last record index to include (defaults to length - 1)
2234      * @return {Number} The sum
2235      */
2236     sum : function(property, start, end){
2237         var rs = this.data.items, v = 0;
2238         start = start || 0;
2239         end = (end || end === 0) ? end : rs.length-1;
2240
2241         for(var i = start; i <= end; i++){
2242             v += (rs[i].data[property] || 0);
2243         }
2244         return v;
2245     },
2246
2247     /**
2248      * Filter the {@link Ext.data.Record records} by a specified property.
2249      * @param {String} field A field on your records
2250      * @param {String/RegExp} value Either a string that the field should begin with, or a RegExp to test
2251      * against the field.
2252      * @param {Boolean} anyMatch (optional) <tt>true</tt> to match any part not just the beginning
2253      * @param {Boolean} caseSensitive (optional) <tt>true</tt> for case sensitive comparison
2254      */
2255     filter : function(property, value, anyMatch, caseSensitive){
2256         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2257         return fn ? this.filterBy(fn) : this.clearFilter();
2258     },
2259
2260     /**
2261      * Filter by a function. The specified function will be called for each
2262      * Record in this Store. If the function returns <tt>true</tt> the Record is included,
2263      * otherwise it is filtered out.
2264      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2265      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2266      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2267      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2268      * </ul>
2269      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
2270      */
2271     filterBy : function(fn, scope){
2272         this.snapshot = this.snapshot || this.data;
2273         this.data = this.queryBy(fn, scope||this);
2274         this.fireEvent('datachanged', this);
2275     },
2276
2277     /**
2278      * Query the records by a specified property.
2279      * @param {String} field A field on your records
2280      * @param {String/RegExp} value Either a string that the field
2281      * should begin with, or a RegExp to test against the field.
2282      * @param {Boolean} anyMatch (optional) True to match any part not just the beginning
2283      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
2284      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
2285      */
2286     query : function(property, value, anyMatch, caseSensitive){
2287         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2288         return fn ? this.queryBy(fn) : this.data.clone();
2289     },
2290
2291     /**
2292      * Query the cached records in this Store using a filtering function. The specified function
2293      * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
2294      * included in the results.
2295      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2296      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2297      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2298      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2299      * </ul>
2300      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
2301      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
2302      **/
2303     queryBy : function(fn, scope){
2304         var data = this.snapshot || this.data;
2305         return data.filterBy(fn, scope||this);
2306     },
2307
2308     /**
2309      * Finds the index of the first matching Record in this store by a specific field value.
2310      * @param {String} fieldName The name of the Record field to test.
2311      * @param {String/RegExp} value Either a string that the field value
2312      * should begin with, or a RegExp to test against the field.
2313      * @param {Number} startIndex (optional) The index to start searching at
2314      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
2315      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
2316      * @return {Number} The matched index or -1
2317      */
2318     find : function(property, value, start, anyMatch, caseSensitive){
2319         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive);
2320         return fn ? this.data.findIndexBy(fn, null, start) : -1;
2321     },
2322
2323     /**
2324      * Finds the index of the first matching Record in this store by a specific field value.
2325      * @param {String} fieldName The name of the Record field to test.
2326      * @param {Mixed} value The value to match the field against.
2327      * @param {Number} startIndex (optional) The index to start searching at
2328      * @return {Number} The matched index or -1
2329      */
2330     findExact: function(property, value, start){
2331         return this.data.findIndexBy(function(rec){
2332             return rec.get(property) === value;
2333         }, this, start);
2334     },
2335
2336     /**
2337      * Find the index of the first matching Record in this Store by a function.
2338      * If the function returns <tt>true</tt> it is considered a match.
2339      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
2340      * <li><b>record</b> : Ext.data.Record<p class="sub-desc">The {@link Ext.data.Record record}
2341      * to test for filtering. Access field values using {@link Ext.data.Record#get}.</p></li>
2342      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
2343      * </ul>
2344      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
2345      * @param {Number} startIndex (optional) The index to start searching at
2346      * @return {Number} The matched index or -1
2347      */
2348     findBy : function(fn, scope, start){
2349         return this.data.findIndexBy(fn, scope, start);
2350     },
2351
2352     /**
2353      * Collects unique values for a particular dataIndex from this store.
2354      * @param {String} dataIndex The property to collect
2355      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
2356      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
2357      * @return {Array} An array of the unique values
2358      **/
2359     collect : function(dataIndex, allowNull, bypassFilter){
2360         var d = (bypassFilter === true && this.snapshot) ?
2361                 this.snapshot.items : this.data.items;
2362         var v, sv, r = [], l = {};
2363         for(var i = 0, len = d.length; i < len; i++){
2364             v = d[i].data[dataIndex];
2365             sv = String(v);
2366             if((allowNull || !Ext.isEmpty(v)) && !l[sv]){
2367                 l[sv] = true;
2368                 r[r.length] = v;
2369             }
2370         }
2371         return r;
2372     },
2373
2374     /**
2375      * Revert to a view of the Record cache with no filtering applied.
2376      * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
2377      * {@link #datachanged} event.
2378      */
2379     clearFilter : function(suppressEvent){
2380         if(this.isFiltered()){
2381             this.data = this.snapshot;
2382             delete this.snapshot;
2383             if(suppressEvent !== true){
2384                 this.fireEvent('datachanged', this);
2385             }
2386         }
2387     },
2388
2389     /**
2390      * Returns true if this store is currently filtered
2391      * @return {Boolean}
2392      */
2393     isFiltered : function(){
2394         return this.snapshot && this.snapshot != this.data;
2395     },
2396
2397     // private
2398     afterEdit : function(record){
2399         if(this.modified.indexOf(record) == -1){
2400             this.modified.push(record);
2401         }
2402         this.fireEvent('update', this, record, Ext.data.Record.EDIT);
2403     },
2404
2405     // private
2406     afterReject : function(record){
2407         this.modified.remove(record);
2408         this.fireEvent('update', this, record, Ext.data.Record.REJECT);
2409     },
2410
2411     // private
2412     afterCommit : function(record){
2413         this.modified.remove(record);
2414         this.fireEvent('update', this, record, Ext.data.Record.COMMIT);
2415     },
2416
2417     /**
2418      * Commit all Records with {@link #getModifiedRecords outstanding changes}. To handle updates for changes,
2419      * subscribe to the Store's {@link #update update event}, and perform updating when the third parameter is
2420      * Ext.data.Record.COMMIT.
2421      */
2422     commitChanges : function(){
2423         var m = this.modified.slice(0);
2424         this.modified = [];
2425         for(var i = 0, len = m.length; i < len; i++){
2426             m[i].commit();
2427         }
2428     },
2429
2430     /**
2431      * {@link Ext.data.Record#reject Reject} outstanding changes on all {@link #getModifiedRecords modified records}.
2432      */
2433     rejectChanges : function(){
2434         var m = this.modified.slice(0);
2435         this.modified = [];
2436         for(var i = 0, len = m.length; i < len; i++){
2437             m[i].reject();
2438         }
2439         var m = this.removed.slice(0).reverse();
2440         this.removed = [];
2441         for(var i = 0, len = m.length; i < len; i++){
2442             this.insert(m[i].lastIndex||0, m[i]);
2443             m[i].reject();
2444         }
2445     },
2446
2447     // private
2448     onMetaChange : function(meta){
2449         this.recordType = this.reader.recordType;
2450         this.fields = this.recordType.prototype.fields;
2451         delete this.snapshot;
2452         if(this.reader.meta.sortInfo){
2453             this.sortInfo = this.reader.meta.sortInfo;
2454         }else if(this.sortInfo  && !this.fields.get(this.sortInfo.field)){
2455             delete this.sortInfo;
2456         }
2457         if(this.writer){
2458             this.writer.meta = this.reader.meta;
2459         }
2460         this.modified = [];
2461         this.fireEvent('metachange', this, this.reader.meta);
2462     },
2463
2464     // private
2465     findInsertIndex : function(record){
2466         this.suspendEvents();
2467         var data = this.data.clone();
2468         this.data.add(record);
2469         this.applySort();
2470         var index = this.data.indexOf(record);
2471         this.data = data;
2472         this.resumeEvents();
2473         return index;
2474     },
2475
2476     /**
2477      * Set the value for a property name in this store's {@link #baseParams}.  Usage:</p><pre><code>
2478 myStore.setBaseParam('foo', {bar:3});
2479 </code></pre>
2480      * @param {String} name Name of the property to assign
2481      * @param {Mixed} value Value to assign the <tt>name</tt>d property
2482      **/
2483     setBaseParam : function (name, value){
2484         this.baseParams = this.baseParams || {};
2485         this.baseParams[name] = value;
2486     }
2487 });
2488
2489 Ext.reg('store', Ext.data.Store);
2490
2491 /**
2492  * @class Ext.data.Store.Error
2493  * @extends Ext.Error
2494  * Store Error extension.
2495  * @param {String} name
2496  */
2497 Ext.data.Store.Error = Ext.extend(Ext.Error, {
2498     name: 'Ext.data.Store'
2499 });
2500 Ext.apply(Ext.data.Store.Error.prototype, {
2501     lang: {
2502         'writer-undefined' : 'Attempted to execute a write-action without a DataWriter installed.'
2503     }
2504 });
2505 /**
2506  * @class Ext.data.Field
2507  * <p>This class encapsulates the field definition information specified in the field definition objects
2508  * passed to {@link Ext.data.Record#create}.</p>
2509  * <p>Developers do not need to instantiate this class. Instances are created by {@link Ext.data.Record.create}
2510  * and cached in the {@link Ext.data.Record#fields fields} property of the created Record constructor's <b>prototype.</b></p>
2511  */
2512 Ext.data.Field = function(config){
2513     if(typeof config == "string"){
2514         config = {name: config};
2515     }
2516     Ext.apply(this, config);
2517
2518     if(!this.type){
2519         this.type = "auto";
2520     }
2521
2522     var st = Ext.data.SortTypes;
2523     // named sortTypes are supported, here we look them up
2524     if(typeof this.sortType == "string"){
2525         this.sortType = st[this.sortType];
2526     }
2527
2528     // set default sortType for strings and dates
2529     if(!this.sortType){
2530         switch(this.type){
2531             case "string":
2532                 this.sortType = st.asUCString;
2533                 break;
2534             case "date":
2535                 this.sortType = st.asDate;
2536                 break;
2537             default:
2538                 this.sortType = st.none;
2539         }
2540     }
2541
2542     // define once
2543     var stripRe = /[\$,%]/g;
2544
2545     // prebuilt conversion function for this field, instead of
2546     // switching every time we're reading a value
2547     if(!this.convert){
2548         var cv, dateFormat = this.dateFormat;
2549         switch(this.type){
2550             case "":
2551             case "auto":
2552             case undefined:
2553                 cv = function(v){ return v; };
2554                 break;
2555             case "string":
2556                 cv = function(v){ return (v === undefined || v === null) ? '' : String(v); };
2557                 break;
2558             case "int":
2559                 cv = function(v){
2560                     return v !== undefined && v !== null && v !== '' ?
2561                         parseInt(String(v).replace(stripRe, ""), 10) : '';
2562                     };
2563                 break;
2564             case "float":
2565                 cv = function(v){
2566                     return v !== undefined && v !== null && v !== '' ?
2567                         parseFloat(String(v).replace(stripRe, ""), 10) : '';
2568                     };
2569                 break;
2570             case "bool":
2571                 cv = function(v){ return v === true || v === "true" || v == 1; };
2572                 break;
2573             case "date":
2574                 cv = function(v){
2575                     if(!v){
2576                         return '';
2577                     }
2578                     if(Ext.isDate(v)){
2579                         return v;
2580                     }
2581                     if(dateFormat){
2582                         if(dateFormat == "timestamp"){
2583                             return new Date(v*1000);
2584                         }
2585                         if(dateFormat == "time"){
2586                             return new Date(parseInt(v, 10));
2587                         }
2588                         return Date.parseDate(v, dateFormat);
2589                     }
2590                     var parsed = Date.parse(v);
2591                     return parsed ? new Date(parsed) : null;
2592                 };
2593                 break;
2594             default:
2595                 cv = function(v){ return v; };
2596                 break;
2597
2598         }
2599         this.convert = cv;
2600     }
2601 };
2602
2603 Ext.data.Field.prototype = {
2604     /**
2605      * @cfg {String} name
2606      * The name by which the field is referenced within the Record. This is referenced by, for example,
2607      * the <tt>dataIndex</tt> property in column definition objects passed to {@link Ext.grid.ColumnModel}.
2608      * <p>Note: In the simplest case, if no properties other than <tt>name</tt> are required, a field
2609      * definition may consist of just a String for the field name.</p>
2610      */
2611     /**
2612      * @cfg {String} type
2613      * (Optional) The data type for conversion to displayable value if <tt>{@link Ext.data.Field#convert convert}</tt>
2614      * has not been specified. Possible values are
2615      * <div class="mdetail-params"><ul>
2616      * <li>auto (Default, implies no conversion)</li>
2617      * <li>string</li>
2618      * <li>int</li>
2619      * <li>float</li>
2620      * <li>boolean</li>
2621      * <li>date</li></ul></div>
2622      */
2623     /**
2624      * @cfg {Function} convert
2625      * (Optional) A function which converts the value provided by the Reader into an object that will be stored
2626      * in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
2627      * <li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
2628      * the configured <tt>{@link Ext.data.Field#defaultValue defaultValue}</tt>.</div></li>
2629      * <li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
2630      * Depending on the Reader type, this could be an Array ({@link Ext.data.ArrayReader ArrayReader}), an object
2631      *  ({@link Ext.data.JsonReader JsonReader}), or an XML element ({@link Ext.data.XMLReader XMLReader}).</div></li>
2632      * </ul></div>
2633      * <pre><code>
2634 // example of convert function
2635 function fullName(v, record){
2636     return record.name.last + ', ' + record.name.first;
2637 }
2638
2639 function location(v, record){
2640     return !record.city ? '' : (record.city + ', ' + record.state);
2641 }
2642
2643 var Dude = Ext.data.Record.create([
2644     {name: 'fullname',  convert: fullName},
2645     {name: 'firstname', mapping: 'name.first'},
2646     {name: 'lastname',  mapping: 'name.last'},
2647     {name: 'city', defaultValue: 'homeless'},
2648     'state',
2649     {name: 'location',  convert: location}
2650 ]);
2651
2652 // create the data store
2653 var store = new Ext.data.Store({
2654     reader: new Ext.data.JsonReader(
2655         {
2656             idProperty: 'key',
2657             root: 'daRoot',
2658             totalProperty: 'total'
2659         },
2660         Dude  // recordType
2661     )
2662 });
2663
2664 var myData = [
2665     { key: 1,
2666       name: { first: 'Fat',    last:  'Albert' }
2667       // notice no city, state provided in data object
2668     },
2669     { key: 2,
2670       name: { first: 'Barney', last:  'Rubble' },
2671       city: 'Bedrock', state: 'Stoneridge'
2672     },
2673     { key: 3,
2674       name: { first: 'Cliff',  last:  'Claven' },
2675       city: 'Boston',  state: 'MA'
2676     }
2677 ];
2678      * </code></pre>
2679      */
2680     /**
2681      * @cfg {String} dateFormat
2682      * (Optional) A format string for the {@link Date#parseDate Date.parseDate} function, or "timestamp" if the
2683      * value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
2684      * javascript millisecond timestamp.
2685      */
2686     dateFormat: null,
2687     /**
2688      * @cfg {Mixed} defaultValue
2689      * (Optional) The default value used <b>when a Record is being created by a {@link Ext.data.Reader Reader}</b>
2690      * when the item referenced by the <tt>{@link Ext.data.Field#mapping mapping}</tt> does not exist in the data
2691      * object (i.e. undefined). (defaults to "")
2692      */
2693     defaultValue: "",
2694     /**
2695      * @cfg {String/Number} mapping
2696      * <p>(Optional) A path expression for use by the {@link Ext.data.DataReader} implementation
2697      * that is creating the {@link Ext.data.Record Record} to extract the Field value from the data object.
2698      * If the path expression is the same as the field name, the mapping may be omitted.</p>
2699      * <p>The form of the mapping expression depends on the Reader being used.</p>
2700      * <div class="mdetail-params"><ul>
2701      * <li>{@link Ext.data.JsonReader}<div class="sub-desc">The mapping is a string containing the javascript
2702      * 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>
2703      * <li>{@link Ext.data.XmlReader}<div class="sub-desc">The mapping is an {@link Ext.DomQuery} path to the data
2704      * item relative to the DOM element that represents the {@link Ext.data.XmlReader#record record}. Defaults to the field name.</div></li>
2705      * <li>{@link Ext.data.ArrayReader}<div class="sub-desc">The mapping is a number indicating the Array index
2706      * of the field's value. Defaults to the field specification's Array position.</div></li>
2707      * </ul></div>
2708      * <p>If a more complex value extraction strategy is required, then configure the Field with a {@link #convert}
2709      * function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
2710      * return the desired data.</p>
2711      */
2712     mapping: null,
2713     /**
2714      * @cfg {Function} sortType
2715      * (Optional) A function which converts a Field's value to a comparable value in order to ensure
2716      * correct sort ordering. Predefined functions are provided in {@link Ext.data.SortTypes}. A custom
2717      * sort example:<pre><code>
2718 // current sort     after sort we want
2719 // +-+------+          +-+------+
2720 // |1|First |          |1|First |
2721 // |2|Last  |          |3|Second|
2722 // |3|Second|          |2|Last  |
2723 // +-+------+          +-+------+
2724
2725 sortType: function(value) {
2726    switch (value.toLowerCase()) // native toLowerCase():
2727    {
2728       case 'first': return 1;
2729       case 'second': return 2;
2730       default: return 3;
2731    }
2732 }
2733      * </code></pre>
2734      */
2735     sortType : null,
2736     /**
2737      * @cfg {String} sortDir
2738      * (Optional) Initial direction to sort (<tt>"ASC"</tt> or  <tt>"DESC"</tt>).  Defaults to
2739      * <tt>"ASC"</tt>.
2740      */
2741     sortDir : "ASC",
2742     /**
2743      * @cfg {Boolean} allowBlank
2744      * (Optional) Used for validating a {@link Ext.data.Record record}, defaults to <tt>true</tt>.
2745      * An empty value here will cause {@link Ext.data.Record}.{@link Ext.data.Record#isValid isValid}
2746      * to evaluate to <tt>false</tt>.
2747      */
2748     allowBlank : true
2749 };/**\r
2750  * @class Ext.data.DataReader\r
2751  * Abstract base class for reading structured data from a data source and converting\r
2752  * it into an object containing {@link Ext.data.Record} objects and metadata for use\r
2753  * by an {@link Ext.data.Store}.  This class is intended to be extended and should not\r
2754  * be created directly. For existing implementations, see {@link Ext.data.ArrayReader},\r
2755  * {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}.\r
2756  * @constructor Create a new DataReader\r
2757  * @param {Object} meta Metadata configuration options (implementation-specific).\r
2758  * @param {Array/Object} recordType\r
2759  * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which\r
2760  * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}\r
2761  * constructor created using {@link Ext.data.Record#create}.</p>\r
2762  */\r
2763 Ext.data.DataReader = function(meta, recordType){\r
2764     /**\r
2765      * This DataReader's configured metadata as passed to the constructor.\r
2766      * @type Mixed\r
2767      * @property meta\r
2768      */\r
2769     this.meta = meta;\r
2770     /**\r
2771      * @cfg {Array/Object} fields\r
2772      * <p>Either an Array of {@link Ext.data.Field Field} definition objects (which\r
2773      * will be passed to {@link Ext.data.Record#create}, or a {@link Ext.data.Record Record}\r
2774      * constructor created from {@link Ext.data.Record#create}.</p>\r
2775      */\r
2776     this.recordType = Ext.isArray(recordType) ?\r
2777         Ext.data.Record.create(recordType) : recordType;\r
2778
2779     // if recordType defined make sure extraction functions are defined\r
2780     if (this.recordType){\r
2781         this.buildExtractors();\r
2782     }
2783 };\r
2784 \r
2785 Ext.data.DataReader.prototype = {\r
2786     /**\r
2787      * @cfg {String} messageProperty [undefined] Optional name of a property within a server-response that represents a user-feedback message.\r
2788      */\r
2789     /**\r
2790      * Abstract method created in extension's buildExtractors impl.\r
2791      */\r
2792     getTotal: Ext.emptyFn,\r
2793     /**\r
2794      * Abstract method created in extension's buildExtractors impl.\r
2795      */\r
2796     getRoot: Ext.emptyFn,\r
2797     /**\r
2798      * Abstract method created in extension's buildExtractors impl.\r
2799      */\r
2800     getMessage: Ext.emptyFn,\r
2801     /**\r
2802      * Abstract method created in extension's buildExtractors impl.\r
2803      */\r
2804     getSuccess: Ext.emptyFn,\r
2805     /**\r
2806      * Abstract method created in extension's buildExtractors impl.\r
2807      */\r
2808     getId: Ext.emptyFn,\r
2809     /**\r
2810      * Abstract method, overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}\r
2811      */\r
2812     buildExtractors : Ext.emptyFn,\r
2813     /**\r
2814      * Abstract method overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}\r
2815      */\r
2816     extractData : Ext.emptyFn,\r
2817     /**\r
2818      * Abstract method overridden in DataReader extensions such as {@link Ext.data.JsonReader} and {@link Ext.data.XmlReader}\r
2819      */\r
2820     extractValues : Ext.emptyFn,\r
2821 \r
2822     /**\r
2823      * Used for un-phantoming a record after a successful database insert.  Sets the records pk along with new data from server.\r
2824      * You <b>must</b> return at least the database pk using the idProperty defined in your DataReader configuration.  The incoming\r
2825      * data from server will be merged with the data in the local record.\r
2826      * In addition, you <b>must</b> return record-data from the server in the same order received.\r
2827      * Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be suppressed.\r
2828      * @param {Record/Record[]} record The phantom record to be realized.\r
2829      * @param {Object/Object[]} data The new record data to apply.  Must include the primary-key from database defined in idProperty field.\r
2830      */\r
2831     realize: function(rs, data){\r
2832         if (Ext.isArray(rs)) {\r
2833             for (var i = rs.length - 1; i >= 0; i--) {\r
2834                 // recurse\r
2835                 if (Ext.isArray(data)) {\r
2836                     this.realize(rs.splice(i,1).shift(), data.splice(i,1).shift());\r
2837                 }\r
2838                 else {\r
2839                     // weird...rs is an array but data isn't??  recurse but just send in the whole invalid data object.\r
2840                     // the else clause below will detect !this.isData and throw exception.\r
2841                     this.realize(rs.splice(i,1).shift(), data);\r
2842                 }\r
2843             }\r
2844         }\r
2845         else {\r
2846             // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.\r
2847             if (Ext.isArray(data) && data.length == 1) {\r
2848                 data = data.shift();\r
2849             }\r
2850             if (!this.isData(data)) {\r
2851                 // TODO: Let exception-handler choose to commit or not rather than blindly rs.commit() here.\r
2852                 //rs.commit();\r
2853                 throw new Ext.data.DataReader.Error('realize', rs);\r
2854             }\r
2855             rs.phantom = false; // <-- That's what it's all about\r
2856             rs._phid = rs.id;  // <-- copy phantom-id -> _phid, so we can remap in Store#onCreateRecords\r
2857             rs.id = this.getId(data);\r
2858 \r
2859             rs.fields.each(function(f) {\r
2860                 if (data[f.name] !== f.defaultValue) {\r
2861                     rs.data[f.name] = data[f.name];\r
2862                 }\r
2863             });\r
2864             rs.commit();\r
2865         }\r
2866     },\r
2867 \r
2868     /**\r
2869      * Used for updating a non-phantom or "real" record's data with fresh data from server after remote-save.\r
2870      * If returning data from multiple-records after a batch-update, you <b>must</b> return record-data from the server in\r
2871      * the same order received.  Will perform a commit as well, un-marking dirty-fields.  Store's "update" event will be\r
2872      * suppressed as the record receives fresh new data-hash\r
2873      * @param {Record/Record[]} rs\r
2874      * @param {Object/Object[]} data\r
2875      */\r
2876     update : function(rs, data) {\r
2877         if (Ext.isArray(rs)) {\r
2878             for (var i=rs.length-1; i >= 0; i--) {\r
2879                 if (Ext.isArray(data)) {\r
2880                     this.update(rs.splice(i,1).shift(), data.splice(i,1).shift());\r
2881                 }\r
2882                 else {\r
2883                     // weird...rs is an array but data isn't??  recurse but just send in the whole data object.\r
2884                     // the else clause below will detect !this.isData and throw exception.\r
2885                     this.update(rs.splice(i,1).shift(), data);\r
2886                 }\r
2887             }\r
2888         }\r
2889         else {\r
2890             // If rs is NOT an array but data IS, see if data contains just 1 record.  If so extract it and carry on.\r
2891             if (Ext.isArray(data) && data.length == 1) {\r
2892                 data = data.shift();\r
2893             }\r
2894             if (this.isData(data)) {\r
2895                 rs.fields.each(function(f) {\r
2896                     if (data[f.name] !== f.defaultValue) {\r
2897                         rs.data[f.name] = data[f.name];\r
2898                     }\r
2899                 });\r
2900             }\r
2901             rs.commit();\r
2902         }\r
2903     },\r
2904 \r
2905     /**\r
2906      * returns extracted, type-cast rows of data.  Iterates to call #extractValues for each row\r
2907      * @param {Object[]/Object} data-root from server response\r
2908      * @param {Boolean} returnRecords [false] Set true to return instances of Ext.data.Record\r
2909      * @private\r
2910      */\r
2911     extractData : function(root, returnRecords) {\r
2912         // A bit ugly this, too bad the Record's raw data couldn't be saved in a common property named "raw" or something.\r
2913         var rawName = (this instanceof Ext.data.JsonReader) ? 'json' : 'node';\r
2914 \r
2915         var rs = [];\r
2916 \r
2917         // Had to add Check for XmlReader, #isData returns true if root is an Xml-object.  Want to check in order to re-factor\r
2918         // #extractData into DataReader base, since the implementations are almost identical for JsonReader, XmlReader\r
2919         if (this.isData(root) && !(this instanceof Ext.data.XmlReader)) {\r
2920             root = [root];\r
2921         }\r
2922         var f       = this.recordType.prototype.fields,\r
2923             fi      = f.items,\r
2924             fl      = f.length,\r
2925             rs      = [];\r
2926         if (returnRecords === true) {\r
2927             var Record = this.recordType;\r
2928             for (var i = 0; i < root.length; i++) {\r
2929                 var n = root[i];\r
2930                 var record = new Record(this.extractValues(n, fi, fl), this.getId(n));\r
2931                 record[rawName] = n;    // <-- There's implementation of ugly bit, setting the raw record-data.\r
2932                 rs.push(record);\r
2933             }\r
2934         }\r
2935         else {\r
2936             for (var i = 0; i < root.length; i++) {\r
2937                 var data = this.extractValues(root[i], fi, fl);\r
2938                 data[this.meta.idProperty] = this.getId(root[i]);\r
2939                 rs.push(data);\r
2940             }\r
2941         }\r
2942         return rs;\r
2943     },\r
2944 \r
2945     /**\r
2946      * Returns true if the supplied data-hash <b>looks</b> and quacks like data.  Checks to see if it has a key\r
2947      * corresponding to idProperty defined in your DataReader config containing non-empty pk.\r
2948      * @param {Object} data\r
2949      * @return {Boolean}\r
2950      */\r
2951     isData : function(data) {\r
2952         return (data && Ext.isObject(data) && !Ext.isEmpty(this.getId(data))) ? true : false;\r
2953     },\r
2954 \r
2955     // private function a store will createSequence upon\r
2956     onMetaChange : function(meta){\r
2957         delete this.ef;\r
2958         this.meta = meta;\r
2959         this.recordType = Ext.data.Record.create(meta.fields);\r
2960         this.buildExtractors();\r
2961     }\r
2962 };\r
2963 \r
2964 /**\r
2965  * @class Ext.data.DataReader.Error\r
2966  * @extends Ext.Error\r
2967  * General error class for Ext.data.DataReader\r
2968  */\r
2969 Ext.data.DataReader.Error = Ext.extend(Ext.Error, {\r
2970     constructor : function(message, arg) {\r
2971         this.arg = arg;\r
2972         Ext.Error.call(this, message);\r
2973     },\r
2974     name: 'Ext.data.DataReader'\r
2975 });\r
2976 Ext.apply(Ext.data.DataReader.Error.prototype, {\r
2977     lang : {\r
2978         'update': "#update received invalid data from server.  Please see docs for DataReader#update and review your DataReader configuration.",\r
2979         'realize': "#realize was called with invalid remote-data.  Please see the docs for DataReader#realize and review your DataReader configuration.",\r
2980         'invalid-response': "#readResponse received an invalid response from the server."\r
2981     }\r
2982 });\r
2983 /**
2984  * @class Ext.data.DataWriter
2985  * <p>Ext.data.DataWriter facilitates create, update, and destroy actions between
2986  * an Ext.data.Store and a server-side framework. A Writer enabled Store will
2987  * automatically manage the Ajax requests to perform CRUD actions on a Store.</p>
2988  * <p>Ext.data.DataWriter is an abstract base class which is intended to be extended
2989  * and should not be created directly. For existing implementations, see
2990  * {@link Ext.data.JsonWriter}.</p>
2991  * <p>Creating a writer is simple:</p>
2992  * <pre><code>
2993 var writer = new Ext.data.JsonWriter({
2994     encode: false   // &lt;--- false causes data to be printed to jsonData config-property of Ext.Ajax#reqeust
2995 });
2996  * </code></pre>
2997  * * <p>Same old JsonReader as Ext-2.x:</p>
2998  * <pre><code>
2999 var reader = new Ext.data.JsonReader({idProperty: 'id'}, [{name: 'first'}, {name: 'last'}, {name: 'email'}]);
3000  * </code></pre>
3001  *
3002  * <p>The proxy for a writer enabled store can be configured with a simple <code>url</code>:</p>
3003  * <pre><code>
3004 // Create a standard HttpProxy instance.
3005 var proxy = new Ext.data.HttpProxy({
3006     url: 'app.php/users'    // &lt;--- Supports "provides"-type urls, such as '/users.json', '/products.xml' (Hello Rails/Merb)
3007 });
3008  * </code></pre>
3009  * <p>For finer grained control, the proxy may also be configured with an <code>API</code>:</p>
3010  * <pre><code>
3011 // Maximum flexibility with the API-configuration
3012 var proxy = new Ext.data.HttpProxy({
3013     api: {
3014         read    : 'app.php/users/read',
3015         create  : 'app.php/users/create',
3016         update  : 'app.php/users/update',
3017         destroy : {  // &lt;--- Supports object-syntax as well
3018             url: 'app.php/users/destroy',
3019             method: "DELETE"
3020         }
3021     }
3022 });
3023  * </code></pre>
3024  * <p>Pulling it all together into a Writer-enabled Store:</p>
3025  * <pre><code>
3026 var store = new Ext.data.Store({
3027     proxy: proxy,
3028     reader: reader,
3029     writer: writer,
3030     autoLoad: true,
3031     autoSave: true  // -- Cell-level updates.
3032 });
3033  * </code></pre>
3034  * <p>Initiating write-actions <b>automatically</b>, using the existing Ext2.0 Store/Record API:</p>
3035  * <pre><code>
3036 var rec = store.getAt(0);
3037 rec.set('email', 'foo@bar.com');  // &lt;--- Immediately initiates an UPDATE action through configured proxy.
3038
3039 store.remove(rec);  // &lt;---- Immediately initiates a DESTROY action through configured proxy.
3040  * </code></pre>
3041  * <p>For <b>record/batch</b> updates, use the Store-configuration {@link Ext.data.Store#autoSave autoSave:false}</p>
3042  * <pre><code>
3043 var store = new Ext.data.Store({
3044     proxy: proxy,
3045     reader: reader,
3046     writer: writer,
3047     autoLoad: true,
3048     autoSave: false  // -- disable cell-updates
3049 });
3050
3051 var urec = store.getAt(0);
3052 urec.set('email', 'foo@bar.com');
3053
3054 var drec = store.getAt(1);
3055 store.remove(drec);
3056
3057 // Push the button!
3058 store.save();
3059  * </code></pre>
3060  * @constructor Create a new DataWriter
3061  * @param {Object} meta Metadata configuration options (implementation-specific)
3062  * @param {Object} recordType Either an Array of field definition objects as specified
3063  * in {@link Ext.data.Record#create}, or an {@link Ext.data.Record} object created
3064  * using {@link Ext.data.Record#create}.
3065  */
3066 Ext.data.DataWriter = function(config){
3067     Ext.apply(this, config);
3068 };
3069 Ext.data.DataWriter.prototype = {
3070
3071     /**
3072      * @cfg {Boolean} writeAllFields
3073      * <tt>false</tt> by default.  Set <tt>true</tt> to have DataWriter return ALL fields of a modified
3074      * record -- not just those that changed.
3075      * <tt>false</tt> to have DataWriter only request modified fields from a record.
3076      */
3077     writeAllFields : false,
3078     /**
3079      * @cfg {Boolean} listful
3080      * <tt>false</tt> by default.  Set <tt>true</tt> to have the DataWriter <b>always</b> write HTTP params as a list,
3081      * even when acting upon a single record.
3082      */
3083     listful : false,    // <-- listful is actually not used internally here in DataWriter.  @see Ext.data.Store#execute.
3084
3085     /**
3086      * 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},
3087      * Where the first parameter is the <i>receiver</i> of paramaters and the second, baseParams, <i>the source</i>.
3088      * @param {Object} params The request-params receiver.
3089      * @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}.
3090      * @param {String} action [{@link Ext.data.Api#actions create|update|destroy}]
3091      * @param {Record/Record[]} rs The recordset to write, the subject(s) of the write action.
3092      */
3093     apply : function(params, baseParams, action, rs) {
3094         var data    = [],
3095         renderer    = action + 'Record';
3096         // TODO implement @cfg listful here
3097         if (Ext.isArray(rs)) {
3098             Ext.each(rs, function(rec){
3099                 data.push(this[renderer](rec));
3100             }, this);
3101         }
3102         else if (rs instanceof Ext.data.Record) {
3103             data = this[renderer](rs);
3104         }
3105         this.render(params, baseParams, data);
3106     },
3107
3108     /**
3109      * abstract method meant to be overridden by all DataWriter extensions.  It's the extension's job to apply the "data" to the "params".
3110      * The data-object provided to render is populated with data according to the meta-info defined in the user's DataReader config,
3111      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]
3112      * @param {Record[]} rs Store recordset
3113      * @param {Object} params Http params to be sent to server.
3114      * @param {Object} data object populated according to DataReader meta-data.
3115      */
3116     render : Ext.emptyFn,
3117
3118     /**
3119      * @cfg {Function} updateRecord Abstract method that should be implemented in all subclasses
3120      * (e.g.: {@link Ext.data.JsonWriter#updateRecord JsonWriter.updateRecord}
3121      */
3122     updateRecord : Ext.emptyFn,
3123
3124     /**
3125      * @cfg {Function} createRecord Abstract method that should be implemented in all subclasses
3126      * (e.g.: {@link Ext.data.JsonWriter#createRecord JsonWriter.createRecord})
3127      */
3128     createRecord : Ext.emptyFn,
3129
3130     /**
3131      * @cfg {Function} destroyRecord Abstract method that should be implemented in all subclasses
3132      * (e.g.: {@link Ext.data.JsonWriter#destroyRecord JsonWriter.destroyRecord})
3133      */
3134     destroyRecord : Ext.emptyFn,
3135
3136     /**
3137      * Converts a Record to a hash, taking into account the state of the Ext.data.Record along with configuration properties
3138      * related to its rendering, such as {@link #writeAllFields}, {@link Ext.data.Record#phantom phantom}, {@link Ext.data.Record#getChanges getChanges} and
3139      * {@link Ext.data.DataReader#idProperty idProperty}
3140      * @param {Ext.data.Record}
3141      * @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.
3142      * @return {Object}
3143      * @protected
3144      * TODO Implement excludes/only configuration with 2nd param?
3145      */
3146     toHash : function(rec, config) {
3147         var map = rec.fields.map,
3148             data = {},
3149             raw = (this.writeAllFields === false && rec.phantom === false) ? rec.getChanges() : rec.data,
3150             m;
3151         Ext.iterate(raw, function(prop, value){
3152             if((m = map[prop])){
3153                 data[m.mapping ? m.mapping : m.name] = value;
3154             }
3155         });
3156         // 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.
3157         // We can tell its not auto-increment if the user defined a DataReader field for it *and* that field's value is non-empty.
3158         // we could also do a RegExp here for the Ext.data.Record AUTO_ID prefix.
3159         if (rec.phantom) {
3160             if (rec.fields.containsKey(this.meta.idProperty) && Ext.isEmpty(rec.data[this.meta.idProperty])) {
3161                 delete data[this.meta.idProperty];
3162             }
3163         } else {
3164             data[this.meta.idProperty] = rec.id
3165         }
3166         return data;
3167     },
3168
3169     /**
3170      * Converts a {@link Ext.data.DataWriter#toHash Hashed} {@link Ext.data.Record} to fields-array array suitable
3171      * for encoding to xml via XTemplate, eg:
3172 <code><pre>&lt;tpl for=".">&lt;{name}>{value}&lt;/{name}&lt;/tpl></pre></code>
3173      * eg, <b>non-phantom</b>:
3174 <code><pre>{id: 1, first: 'foo', last: 'bar'} --> [{name: 'id', value: 1}, {name: 'first', value: 'foo'}, {name: 'last', value: 'bar'}]</pre></code>
3175      * {@link Ext.data.Record#phantom Phantom} records will have had their idProperty omitted in {@link #toHash} if determined to be auto-generated.
3176      * Non AUTOINCREMENT pks should have been protected.
3177      * @param {Hash} data Hashed by Ext.data.DataWriter#toHash
3178      * @return {[Object]} Array of attribute-objects.
3179      * @protected
3180      */
3181     toArray : function(data) {
3182         var fields = [];
3183         Ext.iterate(data, function(k, v) {fields.push({name: k, value: v});},this);
3184         return fields;
3185     }
3186 };/**\r
3187  * @class Ext.data.DataProxy\r
3188  * @extends Ext.util.Observable\r
3189  * <p>Abstract base class for implementations which provide retrieval of unformatted data objects.\r
3190  * This class is intended to be extended and should not be created directly. For existing implementations,\r
3191  * see {@link Ext.data.DirectProxy}, {@link Ext.data.HttpProxy}, {@link Ext.data.ScriptTagProxy} and\r
3192  * {@link Ext.data.MemoryProxy}.</p>\r
3193  * <p>DataProxy implementations are usually used in conjunction with an implementation of {@link Ext.data.DataReader}\r
3194  * (of the appropriate type which knows how to parse the data object) to provide a block of\r
3195  * {@link Ext.data.Records} to an {@link Ext.data.Store}.</p>\r
3196  * <p>The parameter to a DataProxy constructor may be an {@link Ext.data.Connection} or can also be the\r
3197  * config object to an {@link Ext.data.Connection}.</p>\r
3198  * <p>Custom implementations must implement either the <code><b>doRequest</b></code> method (preferred) or the\r
3199  * <code>load</code> method (deprecated). See\r
3200  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#doRequest doRequest} or\r
3201  * {@link Ext.data.HttpProxy}.{@link Ext.data.HttpProxy#load load} for additional details.</p>\r
3202  * <p><b><u>Example 1</u></b></p>\r
3203  * <pre><code>\r
3204 proxy: new Ext.data.ScriptTagProxy({\r
3205     {@link Ext.data.Connection#url url}: 'http://extjs.com/forum/topics-remote.php'\r
3206 }),\r
3207  * </code></pre>\r
3208  * <p><b><u>Example 2</u></b></p>\r
3209  * <pre><code>\r
3210 proxy : new Ext.data.HttpProxy({\r
3211     {@link Ext.data.Connection#method method}: 'GET',\r
3212     {@link Ext.data.HttpProxy#prettyUrls prettyUrls}: false,\r
3213     {@link Ext.data.Connection#url url}: 'local/default.php', // see options parameter for {@link Ext.Ajax#request}\r
3214     {@link #api}: {\r
3215         // all actions except the following will use above url\r
3216         create  : 'local/new.php',\r
3217         update  : 'local/update.php'\r
3218     }\r
3219 }),\r
3220  * </code></pre>\r
3221  * <p>And <b>new in Ext version 3</b>, attach centralized event-listeners upon the DataProxy class itself!  This is a great place\r
3222  * to implement a <i>messaging system</i> to centralize your application's user-feedback and error-handling.</p>\r
3223  * <pre><code>\r
3224 // Listen to all "beforewrite" event fired by all proxies.\r
3225 Ext.data.DataProxy.on('beforewrite', function(proxy, action) {\r
3226     console.log('beforewrite: ', action);\r
3227 });\r
3228 \r
3229 // Listen to "write" event fired by all proxies\r
3230 Ext.data.DataProxy.on('write', function(proxy, action, data, res, rs) {\r
3231     console.info('write: ', action);\r
3232 });\r
3233 \r
3234 // Listen to "exception" event fired by all proxies\r
3235 Ext.data.DataProxy.on('exception', function(proxy, type, action) {\r
3236     console.error(type + action + ' exception);\r
3237 });\r
3238  * </code></pre>\r
3239  * <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}.\r
3240  */\r
3241 Ext.data.DataProxy = function(conn){\r
3242     // make sure we have a config object here to support ux proxies.\r
3243     // All proxies should now send config into superclass constructor.\r
3244     conn = conn || {};\r
3245 \r
3246     // This line caused a bug when people use custom Connection object having its own request method.\r
3247     // http://extjs.com/forum/showthread.php?t=67194.  Have to set DataProxy config\r
3248     //Ext.applyIf(this, conn);\r
3249 \r
3250     this.api     = conn.api;\r
3251     this.url     = conn.url;\r
3252     this.restful = conn.restful;\r
3253     this.listeners = conn.listeners;\r
3254 \r
3255     // deprecated\r
3256     this.prettyUrls = conn.prettyUrls;\r
3257 \r
3258     /**\r
3259      * @cfg {Object} api\r
3260      * Specific urls to call on CRUD action methods "read", "create", "update" and "destroy".\r
3261      * Defaults to:<pre><code>\r
3262 api: {\r
3263     read    : undefined,\r
3264     create  : undefined,\r
3265     update  : undefined,\r
3266     destroy : undefined\r
3267 }\r
3268      * </code></pre>\r
3269      * <p>The url is built based upon the action being executed <tt>[load|create|save|destroy]</tt>\r
3270      * using the commensurate <tt>{@link #api}</tt> property, or if undefined default to the\r
3271      * configured {@link Ext.data.Store}.{@link Ext.data.Store#url url}.</p><br>\r
3272      * <p>For example:</p>\r
3273      * <pre><code>\r
3274 api: {\r
3275     load :    '/controller/load',\r
3276     create :  '/controller/new',  // Server MUST return idProperty of new record\r
3277     save :    '/controller/update',\r
3278     destroy : '/controller/destroy_action'\r
3279 }\r
3280 \r
3281 // Alternatively, one can use the object-form to specify each API-action\r
3282 api: {\r
3283     load: {url: 'read.php', method: 'GET'},\r
3284     create: 'create.php',\r
3285     destroy: 'destroy.php',\r
3286     save: 'update.php'\r
3287 }\r
3288      * </code></pre>\r
3289      * <p>If the specific URL for a given CRUD action is undefined, the CRUD action request\r
3290      * will be directed to the configured <tt>{@link Ext.data.Connection#url url}</tt>.</p>\r
3291      * <br><p><b>Note</b>: To modify the URL for an action dynamically the appropriate API\r
3292      * property should be modified before the action is requested using the corresponding before\r
3293      * action event.  For example to modify the URL associated with the load action:\r
3294      * <pre><code>\r
3295 // modify the url for the action\r
3296 myStore.on({\r
3297     beforeload: {\r
3298         fn: function (store, options) {\r
3299             // use <tt>{@link Ext.data.HttpProxy#setUrl setUrl}</tt> to change the URL for *just* this request.\r
3300             store.proxy.setUrl('changed1.php');\r
3301 \r
3302             // set optional second parameter to true to make this URL change\r
3303             // permanent, applying this URL for all subsequent requests.\r
3304             store.proxy.setUrl('changed1.php', true);\r
3305 \r
3306             // Altering the proxy API should be done using the public\r
3307             // method <tt>{@link Ext.data.DataProxy#setApi setApi}</tt>.\r
3308             store.proxy.setApi('read', 'changed2.php');\r
3309 \r
3310             // Or set the entire API with a config-object.\r
3311             // When using the config-object option, you must redefine the <b>entire</b>\r
3312             // API -- not just a specific action of it.\r
3313             store.proxy.setApi({\r
3314                 read    : 'changed_read.php',\r
3315                 create  : 'changed_create.php',\r
3316                 update  : 'changed_update.php',\r
3317                 destroy : 'changed_destroy.php'\r
3318             });\r
3319         }\r
3320     }\r
3321 });\r
3322      * </code></pre>\r
3323      * </p>\r
3324      */\r
3325 \r
3326     this.addEvents(\r
3327         /**\r
3328          * @event exception\r
3329          * <p>Fires if an exception occurs in the Proxy during a remote request. This event is relayed\r
3330          * through a corresponding {@link Ext.data.Store}.{@link Ext.data.Store#exception exception},\r
3331          * so any Store instance may observe this event.</p>\r
3332          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
3333          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of exception events from <b>all</b>\r
3334          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
3335          * <p>This event can be fired for one of two reasons:</p>\r
3336          * <div class="mdetail-params"><ul>\r
3337          * <li>remote-request <b>failed</b> : <div class="sub-desc">\r
3338          * The server did not return status === 200.\r
3339          * </div></li>\r
3340          * <li>remote-request <b>succeeded</b> : <div class="sub-desc">\r
3341          * The remote-request succeeded but the reader could not read the response.\r
3342          * This means the server returned data, but the configured Reader threw an\r
3343          * error while reading the response.  In this case, this event will be\r
3344          * raised and the caught error will be passed along into this event.\r
3345          * </div></li>\r
3346          * </ul></div>\r
3347          * <br><p>This event fires with two different contexts based upon the 2nd\r
3348          * parameter <tt>type [remote|response]</tt>.  The first four parameters\r
3349          * are identical between the two contexts -- only the final two parameters\r
3350          * differ.</p>\r
3351          * @param {DataProxy} this The proxy that sent the request\r
3352          * @param {String} type\r
3353          * <p>The value of this parameter will be either <tt>'response'</tt> or <tt>'remote'</tt>.</p>\r
3354          * <div class="mdetail-params"><ul>\r
3355          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
3356          * <p>An <b>invalid</b> response from the server was returned: either 404,\r
3357          * 500 or the response meta-data does not match that defined in the DataReader\r
3358          * (e.g.: root, idProperty, successProperty).</p>\r
3359          * </div></li>\r
3360          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
3361          * <p>A <b>valid</b> response was returned from the server having\r
3362          * successProperty === false.  This response might contain an error-message\r
3363          * sent from the server.  For example, the user may have failed\r
3364          * authentication/authorization or a database validation error occurred.</p>\r
3365          * </div></li>\r
3366          * </ul></div>\r
3367          * @param {String} action Name of the action (see {@link Ext.data.Api#actions}.\r
3368          * @param {Object} options The options for the action that were specified in the {@link #request}.\r
3369          * @param {Object} response\r
3370          * <p>The value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
3371          * <div class="mdetail-params"><ul>\r
3372          * <li><b><tt>'response'</tt></b> : <div class="sub-desc">\r
3373          * <p>The raw browser response object (e.g.: XMLHttpRequest)</p>\r
3374          * </div></li>\r
3375          * <li><b><tt>'remote'</tt></b> : <div class="sub-desc">\r
3376          * <p>The decoded response object sent from the server.</p>\r
3377          * </div></li>\r
3378          * </ul></div>\r
3379          * @param {Mixed} arg\r
3380          * <p>The type and value of this parameter depends on the value of the <code>type</code> parameter:</p>\r
3381          * <div class="mdetail-params"><ul>\r
3382          * <li><b><tt>'response'</tt></b> : Error<div class="sub-desc">\r
3383          * <p>The JavaScript Error object caught if the configured Reader could not read the data.\r
3384          * If the remote request returns success===false, this parameter will be null.</p>\r
3385          * </div></li>\r
3386          * <li><b><tt>'remote'</tt></b> : Record/Record[]<div class="sub-desc">\r
3387          * <p>This parameter will only exist if the <tt>action</tt> was a <b>write</b> action\r
3388          * (Ext.data.Api.actions.create|update|destroy).</p>\r
3389          * </div></li>\r
3390          * </ul></div>\r
3391          */\r
3392         'exception',\r
3393         /**\r
3394          * @event beforeload\r
3395          * Fires before a request to retrieve a data object.\r
3396          * @param {DataProxy} this The proxy for the request\r
3397          * @param {Object} params The params object passed to the {@link #request} function\r
3398          */\r
3399         'beforeload',\r
3400         /**\r
3401          * @event load\r
3402          * Fires before the load method's callback is called.\r
3403          * @param {DataProxy} this The proxy for the request\r
3404          * @param {Object} o The request transaction object\r
3405          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
3406          */\r
3407         'load',\r
3408         /**\r
3409          * @event loadexception\r
3410          * <p>This event is <b>deprecated</b>.  The signature of the loadexception event\r
3411          * varies depending on the proxy, use the catch-all {@link #exception} event instead.\r
3412          * This event will fire in addition to the {@link #exception} event.</p>\r
3413          * @param {misc} misc See {@link #exception}.\r
3414          * @deprecated\r
3415          */\r
3416         'loadexception',\r
3417         /**\r
3418          * @event beforewrite\r
3419          * <p>Fires before a request is generated for one of the actions Ext.data.Api.actions.create|update|destroy</p>\r
3420          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
3421          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of beforewrite events from <b>all</b>\r
3422          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
3423          * @param {DataProxy} this The proxy for the request\r
3424          * @param {String} action [Ext.data.Api.actions.create|update|destroy]\r
3425          * @param {Record/Array[Record]} rs The Record(s) to create|update|destroy.\r
3426          * @param {Object} params The request <code>params</code> object.  Edit <code>params</code> to add parameters to the request.\r
3427          */\r
3428         'beforewrite',\r
3429         /**\r
3430          * @event write\r
3431          * <p>Fires before the request-callback is called</p>\r
3432          * <p>In addition to being fired through the DataProxy instance that raised the event, this event is also fired\r
3433          * through the Ext.data.DataProxy <i>class</i> to allow for centralized processing of write events from <b>all</b>\r
3434          * DataProxies by attaching a listener to the Ext.data.Proxy class itself.</p>\r
3435          * @param {DataProxy} this The proxy that sent the request\r
3436          * @param {String} action [Ext.data.Api.actions.create|upate|destroy]\r
3437          * @param {Object} data The data object extracted from the server-response\r
3438          * @param {Object} response The decoded response from server\r
3439          * @param {Record/Record{}} rs The records from Store\r
3440          * @param {Object} options The callback's <tt>options</tt> property as passed to the {@link #request} function\r
3441          */\r
3442         'write'\r
3443     );\r
3444     Ext.data.DataProxy.superclass.constructor.call(this);\r
3445 \r
3446     // Prepare the proxy api.  Ensures all API-actions are defined with the Object-form.\r
3447     try {\r
3448         Ext.data.Api.prepare(this);\r
3449     } catch (e) {\r
3450         if (e instanceof Ext.data.Api.Error) {\r
3451             e.toConsole();\r
3452         }\r
3453     }\r
3454     // relay each proxy's events onto Ext.data.DataProxy class for centralized Proxy-listening\r
3455     Ext.data.DataProxy.relayEvents(this, ['beforewrite', 'write', 'exception']);\r
3456 };\r
3457 \r
3458 Ext.extend(Ext.data.DataProxy, Ext.util.Observable, {\r
3459     /**\r
3460      * @cfg {Boolean} restful\r
3461      * <p>Defaults to <tt>false</tt>.  Set to <tt>true</tt> to operate in a RESTful manner.</p>\r
3462      * <br><p> Note: this parameter will automatically be set to <tt>true</tt> if the\r
3463      * {@link Ext.data.Store} it is plugged into is set to <code>restful: true</code>. If the\r
3464      * Store is RESTful, there is no need to set this option on the proxy.</p>\r
3465      * <br><p>RESTful implementations enable the serverside framework to automatically route\r
3466      * actions sent to one url based upon the HTTP method, for example:\r
3467      * <pre><code>\r
3468 store: new Ext.data.Store({\r
3469     restful: true,\r
3470     proxy: new Ext.data.HttpProxy({url:'/users'}); // all requests sent to /users\r
3471     ...\r
3472 )}\r
3473      * </code></pre>\r
3474      * If there is no <code>{@link #api}</code> specified in the configuration of the proxy,\r
3475      * all requests will be marshalled to a single RESTful url (/users) so the serverside\r
3476      * framework can inspect the HTTP Method and act accordingly:\r
3477      * <pre>\r
3478 <u>Method</u>   <u>url</u>        <u>action</u>\r
3479 POST     /users     create\r
3480 GET      /users     read\r
3481 PUT      /users/23  update\r
3482 DESTROY  /users/23  delete\r
3483      * </pre></p>\r
3484      * <p>If set to <tt>true</tt>, a {@link Ext.data.Record#phantom non-phantom} record's\r
3485      * {@link Ext.data.Record#id id} will be appended to the url. Some MVC (e.g., Ruby on Rails,\r
3486      * Merb and Django) support segment based urls where the segments in the URL follow the\r
3487      * Model-View-Controller approach:<pre><code>\r
3488      * someSite.com/controller/action/id\r
3489      * </code></pre>\r
3490      * Where the segments in the url are typically:<div class="mdetail-params"><ul>\r
3491      * <li>The first segment : represents the controller class that should be invoked.</li>\r
3492      * <li>The second segment : represents the class function, or method, that should be called.</li>\r
3493      * <li>The third segment : represents the ID (a variable typically passed to the method).</li>\r
3494      * </ul></div></p>\r
3495      * <br><p>Refer to <code>{@link Ext.data.DataProxy#api}</code> for additional information.</p>\r
3496      */\r
3497     restful: false,\r
3498 \r
3499     /**\r
3500      * <p>Redefines the Proxy's API or a single action of an API. Can be called with two method signatures.</p>\r
3501      * <p>If called with an object as the only parameter, the object should redefine the <b>entire</b> API, e.g.:</p><pre><code>\r
3502 proxy.setApi({\r
3503     read    : '/users/read',\r
3504     create  : '/users/create',\r
3505     update  : '/users/update',\r
3506     destroy : '/users/destroy'\r
3507 });\r
3508 </code></pre>\r
3509      * <p>If called with two parameters, the first parameter should be a string specifying the API action to\r
3510      * redefine and the second parameter should be the URL (or function if using DirectProxy) to call for that action, e.g.:</p><pre><code>\r
3511 proxy.setApi(Ext.data.Api.actions.read, '/users/new_load_url');\r
3512 </code></pre>\r
3513      * @param {String/Object} api An API specification object, or the name of an action.\r
3514      * @param {String/Function} url The URL (or function if using DirectProxy) to call for the action.\r
3515      */\r
3516     setApi : function() {\r
3517         if (arguments.length == 1) {\r
3518             var valid = Ext.data.Api.isValid(arguments[0]);\r
3519             if (valid === true) {\r
3520                 this.api = arguments[0];\r
3521             }\r
3522             else {\r
3523                 throw new Ext.data.Api.Error('invalid', valid);\r
3524             }\r
3525         }\r
3526         else if (arguments.length == 2) {\r
3527             if (!Ext.data.Api.isAction(arguments[0])) {\r
3528                 throw new Ext.data.Api.Error('invalid', arguments[0]);\r
3529             }\r
3530             this.api[arguments[0]] = arguments[1];\r
3531         }\r
3532         Ext.data.Api.prepare(this);\r
3533     },\r
3534 \r
3535     /**\r
3536      * Returns true if the specified action is defined as a unique action in the api-config.\r
3537      * request.  If all API-actions are routed to unique urls, the xaction parameter is unecessary.  However, if no api is defined\r
3538      * and all Proxy actions are routed to DataProxy#url, the server-side will require the xaction parameter to perform a switch to\r
3539      * the corresponding code for CRUD action.\r
3540      * @param {String [Ext.data.Api.CREATE|READ|UPDATE|DESTROY]} action\r
3541      * @return {Boolean}\r
3542      */\r
3543     isApiAction : function(action) {\r
3544         return (this.api[action]) ? true : false;\r
3545     },\r
3546 \r
3547     /**\r
3548      * All proxy actions are executed through this method.  Automatically fires the "before" + action event\r
3549      * @param {String} action Name of the action\r
3550      * @param {Ext.data.Record/Ext.data.Record[]/null} rs Will be null when action is 'load'\r
3551      * @param {Object} params\r
3552      * @param {Ext.data.DataReader} reader\r
3553      * @param {Function} callback\r
3554      * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the Proxy object.\r
3555      * @param {Object} options Any options specified for the action (e.g. see {@link Ext.data.Store#load}.\r
3556      */\r
3557     request : function(action, rs, params, reader, callback, scope, options) {\r
3558         if (!this.api[action] && !this.load) {\r
3559             throw new Ext.data.DataProxy.Error('action-undefined', action);\r
3560         }\r
3561         params = params || {};\r
3562         if ((action === Ext.data.Api.actions.read) ? this.fireEvent("beforeload", this, params) : this.fireEvent("beforewrite", this, action, rs, params) !== false) {\r
3563             this.doRequest.apply(this, arguments);\r
3564         }\r
3565         else {\r
3566             callback.call(scope || this, null, options, false);\r
3567         }\r
3568     },\r
3569 \r
3570 \r
3571     /**\r
3572      * <b>Deprecated</b> load method using old method signature. See {@doRequest} for preferred method.\r
3573      * @deprecated\r
3574      * @param {Object} params\r
3575      * @param {Object} reader\r
3576      * @param {Object} callback\r
3577      * @param {Object} scope\r
3578      * @param {Object} arg\r
3579      */\r
3580     load : null,\r
3581 \r
3582     /**\r
3583      * @cfg {Function} doRequest Abstract method that should be implemented in all subclasses.  <b>Note:</b> Should only be used by custom-proxy developers.\r
3584      * (e.g.: {@link Ext.data.HttpProxy#doRequest HttpProxy.doRequest},\r
3585      * {@link Ext.data.DirectProxy#doRequest DirectProxy.doRequest}).\r
3586      */\r
3587     doRequest : function(action, rs, params, reader, callback, scope, options) {\r
3588         // default implementation of doRequest for backwards compatibility with 2.0 proxies.\r
3589         // If we're executing here, the action is probably "load".\r
3590         // Call with the pre-3.0 method signature.\r
3591         this.load(params, reader, callback, scope, options);\r
3592     },\r
3593 \r
3594     /**\r
3595      * @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}.\r
3596      * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.\r
3597      * @param {Object} o The request transaction object\r
3598      * @param {Object} res The server response\r
3599      * @fires loadexception (deprecated)\r
3600      * @fires exception\r
3601      * @fires load\r
3602      * @protected\r
3603      */\r
3604     onRead : Ext.emptyFn,\r
3605     /**\r
3606      * @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}.\r
3607      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
3608      * @param {Object} trans The request transaction object\r
3609      * @param {Object} res The server response\r
3610      * @fires exception\r
3611      * @fires write\r
3612      * @protected\r
3613      */\r
3614     onWrite : Ext.emptyFn,\r
3615     /**\r
3616      * buildUrl\r
3617      * Sets the appropriate url based upon the action being executed.  If restful is true, and only a single record is being acted upon,\r
3618      * url will be built Rails-style, as in "/controller/action/32".  restful will aply iff the supplied record is an\r
3619      * instance of Ext.data.Record rather than an Array of them.\r
3620      * @param {String} action The api action being executed [read|create|update|destroy]\r
3621      * @param {Ext.data.Record/Array[Ext.data.Record]} The record or Array of Records being acted upon.\r
3622      * @return {String} url\r
3623      * @private\r
3624      */\r
3625     buildUrl : function(action, record) {\r
3626         record = record || null;\r
3627 \r
3628         // conn.url gets nullified after each request.  If it's NOT null here, that means the user must have intervened with a call\r
3629         // to DataProxy#setUrl or DataProxy#setApi and changed it before the request was executed.  If that's the case, use conn.url,\r
3630         // otherwise, build the url from the api or this.url.\r
3631         var url = (this.conn && this.conn.url) ? this.conn.url : (this.api[action]) ? this.api[action].url : this.url;\r
3632         if (!url) {\r
3633             throw new Ext.data.Api.Error('invalid-url', action);\r
3634         }\r
3635 \r
3636         // look for urls having "provides" suffix used in some MVC frameworks like Rails/Merb and others.  The provides suffice informs\r
3637         // the server what data-format the client is dealing with and returns data in the same format (eg: application/json, application/xml, etc)\r
3638         // e.g.: /users.json, /users.xml, etc.\r
3639         // with restful routes, we need urls like:\r
3640         // PUT /users/1.json\r
3641         // DELETE /users/1.json\r
3642         var provides = null;\r
3643         var m = url.match(/(.*)(\.json|\.xml|\.html)$/);\r
3644         if (m) {\r
3645             provides = m[2];    // eg ".json"\r
3646             url      = m[1];    // eg: "/users"\r
3647         }\r
3648         // prettyUrls is deprectated in favor of restful-config\r
3649         if ((this.restful === true || this.prettyUrls === true) && record instanceof Ext.data.Record && !record.phantom) {\r
3650             url += '/' + record.id;\r
3651         }\r
3652         return (provides === null) ? url : url + provides;\r
3653     },\r
3654 \r
3655     /**\r
3656      * Destroys the proxy by purging any event listeners and cancelling any active requests.\r
3657      */\r
3658     destroy: function(){\r
3659         this.purgeListeners();\r
3660     }\r
3661 });\r
3662 \r
3663 // Apply the Observable prototype to the DataProxy class so that proxy instances can relay their\r
3664 // events to the class.  Allows for centralized listening of all proxy instances upon the DataProxy class.\r
3665 Ext.apply(Ext.data.DataProxy, Ext.util.Observable.prototype);\r
3666 Ext.util.Observable.call(Ext.data.DataProxy);\r
3667 \r
3668 /**\r
3669  * @class Ext.data.DataProxy.Error\r
3670  * @extends Ext.Error\r
3671  * DataProxy Error extension.\r
3672  * constructor\r
3673  * @param {String} name\r
3674  * @param {Record/Array[Record]/Array}\r
3675  */\r
3676 Ext.data.DataProxy.Error = Ext.extend(Ext.Error, {\r
3677     constructor : function(message, arg) {\r
3678         this.arg = arg;\r
3679         Ext.Error.call(this, message);\r
3680     },\r
3681     name: 'Ext.data.DataProxy'\r
3682 });\r
3683 Ext.apply(Ext.data.DataProxy.Error.prototype, {\r
3684     lang: {\r
3685         'action-undefined': "DataProxy attempted to execute an API-action but found an undefined url / function.  Please review your Proxy url/api-configuration.",\r
3686         'api-invalid': 'Recieved an invalid API-configuration.  Please ensure your proxy API-configuration contains only the actions from Ext.data.Api.actions.'\r
3687     }\r
3688 });\r
3689 \r
3690 \r
3691 /**
3692  * @class Ext.data.Request
3693  * A simple Request class used internally to the data package to provide more generalized remote-requests
3694  * to a DataProxy.
3695  * TODO Not yet implemented.  Implement in Ext.data.Store#execute
3696  */
3697 Ext.data.Request = function(params) {
3698     Ext.apply(this, params);
3699 };
3700 Ext.data.Request.prototype = {
3701     /**
3702      * @cfg {String} action
3703      */
3704     action : undefined,
3705     /**
3706      * @cfg {Ext.data.Record[]/Ext.data.Record} rs The Store recordset associated with the request.
3707      */
3708     rs : undefined,
3709     /**
3710      * @cfg {Object} params HTTP request params
3711      */
3712     params: undefined,
3713     /**
3714      * @cfg {Function} callback The function to call when request is complete
3715      */
3716     callback : Ext.emptyFn,
3717     /**
3718      * @cfg {Object} scope The scope of the callback funtion
3719      */
3720     scope : undefined,
3721     /**
3722      * @cfg {Ext.data.DataReader} reader The DataReader instance which will parse the received response
3723      */
3724     reader : undefined
3725 };
3726 /**
3727  * @class Ext.data.Response
3728  * A generic response class to normalize response-handling internally to the framework.
3729  */
3730 Ext.data.Response = function(params) {
3731     Ext.apply(this, params);
3732 };
3733 Ext.data.Response.prototype = {
3734     /**
3735      * @cfg {String} action {@link Ext.data.Api#actions}
3736      */
3737     action: undefined,
3738     /**
3739      * @cfg {Boolean} success
3740      */
3741     success : undefined,
3742     /**
3743      * @cfg {String} message
3744      */
3745     message : undefined,
3746     /**
3747      * @cfg {Array/Object} data
3748      */
3749     data: undefined,
3750     /**
3751      * @cfg {Object} raw The raw response returned from server-code
3752      */
3753     raw: undefined,
3754     /**
3755      * @cfg {Ext.data.Record/Ext.data.Record[]} records related to the Request action
3756      */
3757     records: undefined
3758 };
3759 /**\r
3760  * @class Ext.data.ScriptTagProxy\r
3761  * @extends Ext.data.DataProxy\r
3762  * An implementation of Ext.data.DataProxy that reads a data object from a URL which may be in a domain\r
3763  * other than the originating domain of the running page.<br>\r
3764  * <p>\r
3765  * <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\r
3766  * of the running page, you must use this class, rather than HttpProxy.</b><br>\r
3767  * <p>\r
3768  * The content passed back from a server resource requested by a ScriptTagProxy <b>must</b> be executable JavaScript\r
3769  * source code because it is used as the source inside a &lt;script> tag.<br>\r
3770  * <p>\r
3771  * In order for the browser to process the returned data, the server must wrap the data object\r
3772  * with a call to a callback function, the name of which is passed as a parameter by the ScriptTagProxy.\r
3773  * Below is a Java example for a servlet which returns data for either a ScriptTagProxy, or an HttpProxy\r
3774  * depending on whether the callback name was passed:\r
3775  * <p>\r
3776  * <pre><code>\r
3777 boolean scriptTag = false;\r
3778 String cb = request.getParameter("callback");\r
3779 if (cb != null) {\r
3780     scriptTag = true;\r
3781     response.setContentType("text/javascript");\r
3782 } else {\r
3783     response.setContentType("application/x-json");\r
3784 }\r
3785 Writer out = response.getWriter();\r
3786 if (scriptTag) {\r
3787     out.write(cb + "(");\r
3788 }\r
3789 out.print(dataBlock.toJsonString());\r
3790 if (scriptTag) {\r
3791     out.write(");");\r
3792 }\r
3793 </code></pre>\r
3794  * <p>Below is a PHP example to do the same thing:</p><pre><code>\r
3795 $callback = $_REQUEST['callback'];\r
3796 \r
3797 // Create the output object.\r
3798 $output = array('a' => 'Apple', 'b' => 'Banana');\r
3799 \r
3800 //start output\r
3801 if ($callback) {\r
3802     header('Content-Type: text/javascript');\r
3803     echo $callback . '(' . json_encode($output) . ');';\r
3804 } else {\r
3805     header('Content-Type: application/x-json');\r
3806     echo json_encode($output);\r
3807 }\r
3808 </code></pre>\r
3809  *\r
3810  * @constructor\r
3811  * @param {Object} config A configuration object.\r
3812  */\r
3813 Ext.data.ScriptTagProxy = function(config){\r
3814     Ext.apply(this, config);\r
3815 \r
3816     Ext.data.ScriptTagProxy.superclass.constructor.call(this, config);\r
3817 \r
3818     this.head = document.getElementsByTagName("head")[0];\r
3819 \r
3820     /**\r
3821      * @event loadexception\r
3822      * <b>Deprecated</b> in favor of 'exception' event.\r
3823      * Fires if an exception occurs in the Proxy during data loading.  This event can be fired for one of two reasons:\r
3824      * <ul><li><b>The load call timed out.</b>  This means the load callback did not execute within the time limit\r
3825      * specified by {@link #timeout}.  In this case, this event will be raised and the\r
3826      * fourth parameter (read error) will be null.</li>\r
3827      * <li><b>The load succeeded but the reader could not read the response.</b>  This means the server returned\r
3828      * data, but the configured Reader threw an error while reading the data.  In this case, this event will be\r
3829      * raised and the caught error will be passed along as the fourth parameter of this event.</li></ul>\r
3830      * Note that this event is also relayed through {@link Ext.data.Store}, so you can listen for it directly\r
3831      * on any Store instance.\r
3832      * @param {Object} this\r
3833      * @param {Object} options The loading options that were specified (see {@link #load} for details).  If the load\r
3834      * call timed out, this parameter will be null.\r
3835      * @param {Object} arg The callback's arg object passed to the {@link #load} function\r
3836      * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data.\r
3837      * If the remote request returns success: false, this parameter will be null.\r
3838      */\r
3839 };\r
3840 \r
3841 Ext.data.ScriptTagProxy.TRANS_ID = 1000;\r
3842 \r
3843 Ext.extend(Ext.data.ScriptTagProxy, Ext.data.DataProxy, {\r
3844     /**\r
3845      * @cfg {String} url The URL from which to request the data object.\r
3846      */\r
3847     /**\r
3848      * @cfg {Number} timeout (optional) The number of milliseconds to wait for a response. Defaults to 30 seconds.\r
3849      */\r
3850     timeout : 30000,\r
3851     /**\r
3852      * @cfg {String} callbackParam (Optional) The name of the parameter to pass to the server which tells\r
3853      * the server the name of the callback function set up by the load call to process the returned data object.\r
3854      * Defaults to "callback".<p>The server-side processing must read this parameter value, and generate\r
3855      * javascript output which calls this named function passing the data object as its only parameter.\r
3856      */\r
3857     callbackParam : "callback",\r
3858     /**\r
3859      *  @cfg {Boolean} nocache (optional) Defaults to true. Disable caching by adding a unique parameter\r
3860      * name to the request.\r
3861      */\r
3862     nocache : true,\r
3863 \r
3864     /**\r
3865      * HttpProxy implementation of DataProxy#doRequest\r
3866      * @param {String} action\r
3867      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is <tt>read</tt>, rs will be null\r
3868      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
3869      * for the request to the remote server.\r
3870      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
3871      * object into a block of Ext.data.Records.\r
3872      * @param {Function} callback The function into which to pass the block of Ext.data.Records.\r
3873      * The function must be passed <ul>\r
3874      * <li>The Record block object</li>\r
3875      * <li>The "arg" argument from the load function</li>\r
3876      * <li>A boolean success indicator</li>\r
3877      * </ul>\r
3878      * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.\r
3879      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
3880      */\r
3881     doRequest : function(action, rs, params, reader, callback, scope, arg) {\r
3882         var p = Ext.urlEncode(Ext.apply(params, this.extraParams));\r
3883 \r
3884         var url = this.buildUrl(action, rs);\r
3885         if (!url) {\r
3886             throw new Ext.data.Api.Error('invalid-url', url);\r
3887         }\r
3888         url = Ext.urlAppend(url, p);\r
3889 \r
3890         if(this.nocache){\r
3891             url = Ext.urlAppend(url, '_dc=' + (new Date().getTime()));\r
3892         }\r
3893         var transId = ++Ext.data.ScriptTagProxy.TRANS_ID;\r
3894         var trans = {\r
3895             id : transId,\r
3896             action: action,\r
3897             cb : "stcCallback"+transId,\r
3898             scriptId : "stcScript"+transId,\r
3899             params : params,\r
3900             arg : arg,\r
3901             url : url,\r
3902             callback : callback,\r
3903             scope : scope,\r
3904             reader : reader\r
3905         };\r
3906         window[trans.cb] = this.createCallback(action, rs, trans);\r
3907         url += String.format("&{0}={1}", this.callbackParam, trans.cb);\r
3908         if(this.autoAbort !== false){\r
3909             this.abort();\r
3910         }\r
3911 \r
3912         trans.timeoutId = this.handleFailure.defer(this.timeout, this, [trans]);\r
3913 \r
3914         var script = document.createElement("script");\r
3915         script.setAttribute("src", url);\r
3916         script.setAttribute("type", "text/javascript");\r
3917         script.setAttribute("id", trans.scriptId);\r
3918         this.head.appendChild(script);\r
3919 \r
3920         this.trans = trans;\r
3921     },\r
3922 \r
3923     // @private createCallback\r
3924     createCallback : function(action, rs, trans) {\r
3925         var self = this;\r
3926         return function(res) {\r
3927             self.trans = false;\r
3928             self.destroyTrans(trans, true);\r
3929             if (action === Ext.data.Api.actions.read) {\r
3930                 self.onRead.call(self, action, trans, res);\r
3931             } else {\r
3932                 self.onWrite.call(self, action, trans, res, rs);\r
3933             }\r
3934         };\r
3935     },\r
3936     /**\r
3937      * Callback for read actions\r
3938      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
3939      * @param {Object} trans The request transaction object\r
3940      * @param {Object} res The server response\r
3941      * @protected\r
3942      */\r
3943     onRead : function(action, trans, res) {\r
3944         var result;\r
3945         try {\r
3946             result = trans.reader.readRecords(res);\r
3947         }catch(e){\r
3948             // @deprecated: fire loadexception\r
3949             this.fireEvent("loadexception", this, trans, res, e);\r
3950 \r
3951             this.fireEvent('exception', this, 'response', action, trans, res, e);\r
3952             trans.callback.call(trans.scope||window, null, trans.arg, false);\r
3953             return;\r
3954         }\r
3955         if (result.success === false) {\r
3956             // @deprecated: fire old loadexception for backwards-compat.\r
3957             this.fireEvent('loadexception', this, trans, res);\r
3958 \r
3959             this.fireEvent('exception', this, 'remote', action, trans, res, null);\r
3960         } else {\r
3961             this.fireEvent("load", this, res, trans.arg);\r
3962         }\r
3963         trans.callback.call(trans.scope||window, result, trans.arg, result.success);\r
3964     },\r
3965     /**\r
3966      * Callback for write actions\r
3967      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
3968      * @param {Object} trans The request transaction object\r
3969      * @param {Object} res The server response\r
3970      * @protected\r
3971      */\r
3972     onWrite : function(action, trans, response, rs) {\r
3973         var reader = trans.reader;\r
3974         try {\r
3975             // though we already have a response object here in STP, run through readResponse to catch any meta-data exceptions.\r
3976             var res = reader.readResponse(action, response);\r
3977         } catch (e) {\r
3978             this.fireEvent('exception', this, 'response', action, trans, res, e);\r
3979             trans.callback.call(trans.scope||window, null, res, false);\r
3980             return;\r
3981         }\r
3982         if(!res.success === true){\r
3983             this.fireEvent('exception', this, 'remote', action, trans, res, rs);\r
3984             trans.callback.call(trans.scope||window, null, res, false);\r
3985             return;\r
3986         }\r
3987         this.fireEvent("write", this, action, res.data, res, rs, trans.arg );\r
3988         trans.callback.call(trans.scope||window, res.data, res, true);\r
3989     },\r
3990 \r
3991     // private\r
3992     isLoading : function(){\r
3993         return this.trans ? true : false;\r
3994     },\r
3995 \r
3996     /**\r
3997      * Abort the current server request.\r
3998      */\r
3999     abort : function(){\r
4000         if(this.isLoading()){\r
4001             this.destroyTrans(this.trans);\r
4002         }\r
4003     },\r
4004 \r
4005     // private\r
4006     destroyTrans : function(trans, isLoaded){\r
4007         this.head.removeChild(document.getElementById(trans.scriptId));\r
4008         clearTimeout(trans.timeoutId);\r
4009         if(isLoaded){\r
4010             window[trans.cb] = undefined;\r
4011             try{\r
4012                 delete window[trans.cb];\r
4013             }catch(e){}\r
4014         }else{\r
4015             // if hasn't been loaded, wait for load to remove it to prevent script error\r
4016             window[trans.cb] = function(){\r
4017                 window[trans.cb] = undefined;\r
4018                 try{\r
4019                     delete window[trans.cb];\r
4020                 }catch(e){}\r
4021             };\r
4022         }\r
4023     },\r
4024 \r
4025     // private\r
4026     handleFailure : function(trans){\r
4027         this.trans = false;\r
4028         this.destroyTrans(trans, false);\r
4029         if (trans.action === Ext.data.Api.actions.read) {\r
4030             // @deprecated firing loadexception\r
4031             this.fireEvent("loadexception", this, null, trans.arg);\r
4032         }\r
4033 \r
4034         this.fireEvent('exception', this, 'response', trans.action, {\r
4035             response: null,\r
4036             options: trans.arg\r
4037         });\r
4038         trans.callback.call(trans.scope||window, null, trans.arg, false);\r
4039     },\r
4040 \r
4041     // inherit docs\r
4042     destroy: function(){\r
4043         this.abort();\r
4044         Ext.data.ScriptTagProxy.superclass.destroy.call(this);\r
4045     }\r
4046 });/**\r
4047  * @class Ext.data.HttpProxy\r
4048  * @extends Ext.data.DataProxy\r
4049  * <p>An implementation of {@link Ext.data.DataProxy} that processes data requests within the same\r
4050  * domain of the originating page.</p>\r
4051  * <p><b>Note</b>: this class cannot be used to retrieve data from a domain other\r
4052  * than the domain from which the running page was served. For cross-domain requests, use a\r
4053  * {@link Ext.data.ScriptTagProxy ScriptTagProxy}.</p>\r
4054  * <p>Be aware that to enable the browser to parse an XML document, the server must set\r
4055  * the Content-Type header in the HTTP response to "<tt>text/xml</tt>".</p>\r
4056  * @constructor\r
4057  * @param {Object} conn\r
4058  * An {@link Ext.data.Connection} object, or options parameter to {@link Ext.Ajax#request}.\r
4059  * <p>Note that if this HttpProxy is being used by a {@link Ext.data.Store Store}, then the\r
4060  * Store's call to {@link #load} will override any specified <tt>callback</tt> and <tt>params</tt>\r
4061  * options. In this case, use the Store's {@link Ext.data.Store#events events} to modify parameters,\r
4062  * or react to loading events. The Store's {@link Ext.data.Store#baseParams baseParams} may also be\r
4063  * used to pass parameters known at instantiation time.</p>\r
4064  * <p>If an options parameter is passed, the singleton {@link Ext.Ajax} object will be used to make\r
4065  * the request.</p>\r
4066  */\r
4067 Ext.data.HttpProxy = function(conn){\r
4068     Ext.data.HttpProxy.superclass.constructor.call(this, conn);\r
4069 \r
4070     /**\r
4071      * The Connection object (Or options parameter to {@link Ext.Ajax#request}) which this HttpProxy\r
4072      * uses to make requests to the server. Properties of this object may be changed dynamically to\r
4073      * change the way data is requested.\r
4074      * @property\r
4075      */\r
4076     this.conn = conn;\r
4077 \r
4078     // nullify the connection url.  The url param has been copied to 'this' above.  The connection\r
4079     // url will be set during each execution of doRequest when buildUrl is called.  This makes it easier for users to override the\r
4080     // connection url during beforeaction events (ie: beforeload, beforewrite, etc).\r
4081     // Url is always re-defined during doRequest.\r
4082     this.conn.url = null;\r
4083 \r
4084     this.useAjax = !conn || !conn.events;\r
4085 \r
4086     // A hash containing active requests, keyed on action [Ext.data.Api.actions.create|read|update|destroy]\r
4087     var actions = Ext.data.Api.actions;\r
4088     this.activeRequest = {};\r
4089     for (var verb in actions) {\r
4090         this.activeRequest[actions[verb]] = undefined;\r
4091     }\r
4092 };\r
4093 \r
4094 Ext.extend(Ext.data.HttpProxy, Ext.data.DataProxy, {\r
4095     /**\r
4096      * Return the {@link Ext.data.Connection} object being used by this Proxy.\r
4097      * @return {Connection} The Connection object. This object may be used to subscribe to events on\r
4098      * a finer-grained basis than the DataProxy events.\r
4099      */\r
4100     getConnection : function() {\r
4101         return this.useAjax ? Ext.Ajax : this.conn;\r
4102     },\r
4103 \r
4104     /**\r
4105      * Used for overriding the url used for a single request.  Designed to be called during a beforeaction event.  Calling setUrl\r
4106      * will override any urls set via the api configuration parameter.  Set the optional parameter makePermanent to set the url for\r
4107      * all subsequent requests.  If not set to makePermanent, the next request will use the same url or api configuration defined\r
4108      * in the initial proxy configuration.\r
4109      * @param {String} url\r
4110      * @param {Boolean} makePermanent (Optional) [false]\r
4111      *\r
4112      * (e.g.: beforeload, beforesave, etc).\r
4113      */\r
4114     setUrl : function(url, makePermanent) {\r
4115         this.conn.url = url;\r
4116         if (makePermanent === true) {\r
4117             this.url = url;\r
4118             this.api = null;\r
4119             Ext.data.Api.prepare(this);\r
4120         }\r
4121     },\r
4122 \r
4123     /**\r
4124      * HttpProxy implementation of DataProxy#doRequest\r
4125      * @param {String} action The crud action type (create, read, update, destroy)\r
4126      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null\r
4127      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
4128      * for the request to the remote server.\r
4129      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
4130      * object into a block of Ext.data.Records.\r
4131      * @param {Function} callback\r
4132      * <div class="sub-desc"><p>A function to be called after the request.\r
4133      * The <tt>callback</tt> is passed the following arguments:<ul>\r
4134      * <li><tt>r</tt> : Ext.data.Record[] The block of Ext.data.Records.</li>\r
4135      * <li><tt>options</tt>: Options object from the action request</li>\r
4136      * <li><tt>success</tt>: Boolean success indicator</li></ul></p></div>\r
4137      * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.\r
4138      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
4139      * @protected\r
4140      */\r
4141     doRequest : function(action, rs, params, reader, cb, scope, arg) {\r
4142         var  o = {\r
4143             method: (this.api[action]) ? this.api[action]['method'] : undefined,\r
4144             request: {\r
4145                 callback : cb,\r
4146                 scope : scope,\r
4147                 arg : arg\r
4148             },\r
4149             reader: reader,\r
4150             callback : this.createCallback(action, rs),\r
4151             scope: this\r
4152         };\r
4153 \r
4154         // If possible, transmit data using jsonData || xmlData on Ext.Ajax.request (An installed DataWriter would have written it there.).\r
4155         // Use std HTTP params otherwise.\r
4156         if (params.jsonData) {\r
4157             o.jsonData = params.jsonData;\r
4158         } else if (params.xmlData) {\r
4159             o.xmlData = params.xmlData;\r
4160         } else {\r
4161             o.params = params || {};\r
4162         }\r
4163         // Set the connection url.  If this.conn.url is not null here,\r
4164         // the user must have overridden the url during a beforewrite/beforeload event-handler.\r
4165         // this.conn.url is nullified after each request.\r
4166         this.conn.url = this.buildUrl(action, rs);\r
4167 \r
4168         if(this.useAjax){\r
4169 \r
4170             Ext.applyIf(o, this.conn);\r
4171 \r
4172             // If a currently running request is found for this action, abort it.\r
4173             if (this.activeRequest[action]) {\r
4174                 ////\r
4175                 // Disabled aborting activeRequest while implementing REST.  activeRequest[action] will have to become an array\r
4176                 // TODO ideas anyone?\r
4177                 //\r
4178                 //Ext.Ajax.abort(this.activeRequest[action]);\r
4179             }\r
4180             this.activeRequest[action] = Ext.Ajax.request(o);\r
4181         }else{\r
4182             this.conn.request(o);\r
4183         }\r
4184         // request is sent, nullify the connection url in preparation for the next request\r
4185         this.conn.url = null;\r
4186     },\r
4187 \r
4188     /**\r
4189      * Returns a callback function for a request.  Note a special case is made for the\r
4190      * read action vs all the others.\r
4191      * @param {String} action [create|update|delete|load]\r
4192      * @param {Ext.data.Record[]} rs The Store-recordset being acted upon\r
4193      * @private\r
4194      */\r
4195     createCallback : function(action, rs) {\r
4196         return function(o, success, response) {\r
4197             this.activeRequest[action] = undefined;\r
4198             if (!success) {\r
4199                 if (action === Ext.data.Api.actions.read) {\r
4200                     // @deprecated: fire loadexception for backwards compat.\r
4201                     // TODO remove in 3.1\r
4202                     this.fireEvent('loadexception', this, o, response);\r
4203                 }\r
4204                 this.fireEvent('exception', this, 'response', action, o, response);\r
4205                 o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
4206                 return;\r
4207             }\r
4208             if (action === Ext.data.Api.actions.read) {\r
4209                 this.onRead(action, o, response);\r
4210             } else {\r
4211                 this.onWrite(action, o, response, rs);\r
4212             }\r
4213         }\r
4214     },\r
4215 \r
4216     /**\r
4217      * Callback for read action\r
4218      * @param {String} action Action name as per {@link Ext.data.Api.actions#read}.\r
4219      * @param {Object} o The request transaction object\r
4220      * @param {Object} res The server response\r
4221      * @fires loadexception (deprecated)\r
4222      * @fires exception\r
4223      * @fires load\r
4224      * @protected\r
4225      */\r
4226     onRead : function(action, o, response) {\r
4227         var result;\r
4228         try {\r
4229             result = o.reader.read(response);\r
4230         }catch(e){\r
4231             // @deprecated: fire old loadexception for backwards-compat.\r
4232             // TODO remove in 3.1\r
4233             this.fireEvent('loadexception', this, o, response, e);\r
4234 \r
4235             this.fireEvent('exception', this, 'response', action, o, response, e);\r
4236             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
4237             return;\r
4238         }\r
4239         if (result.success === false) {\r
4240             // @deprecated: fire old loadexception for backwards-compat.\r
4241             // TODO remove in 3.1\r
4242             this.fireEvent('loadexception', this, o, response);\r
4243 \r
4244             // Get DataReader read-back a response-object to pass along to exception event\r
4245             var res = o.reader.readResponse(action, response);\r
4246             this.fireEvent('exception', this, 'remote', action, o, res, null);\r
4247         }\r
4248         else {\r
4249             this.fireEvent('load', this, o, o.request.arg);\r
4250         }\r
4251         // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance\r
4252         // the calls to request.callback(...) in each will have to be made identical.\r
4253         // NOTE reader.readResponse does not currently return Ext.data.Response\r
4254         o.request.callback.call(o.request.scope, result, o.request.arg, result.success);\r
4255     },\r
4256     /**\r
4257      * Callback for write actions\r
4258      * @param {String} action [Ext.data.Api.actions.create|read|update|destroy]\r
4259      * @param {Object} trans The request transaction object\r
4260      * @param {Object} res The server response\r
4261      * @fires exception\r
4262      * @fires write\r
4263      * @protected\r
4264      */\r
4265     onWrite : function(action, o, response, rs) {\r
4266         var reader = o.reader;\r
4267         var res;\r
4268         try {\r
4269             res = reader.readResponse(action, response);\r
4270         } catch (e) {\r
4271             this.fireEvent('exception', this, 'response', action, o, response, e);\r
4272             o.request.callback.call(o.request.scope, null, o.request.arg, false);\r
4273             return;\r
4274         }\r
4275         if (res.success === false) {\r
4276             this.fireEvent('exception', this, 'remote', action, o, res, rs);\r
4277         } else {\r
4278             this.fireEvent('write', this, action, res.data, res, rs, o.request.arg);\r
4279         }\r
4280         // TODO refactor onRead, onWrite to be more generalized now that we're dealing with Ext.data.Response instance\r
4281         // the calls to request.callback(...) in each will have to be made similar.\r
4282         // NOTE reader.readResponse does not currently return Ext.data.Response\r
4283         o.request.callback.call(o.request.scope, res.data, res, res.success);\r
4284     },\r
4285 \r
4286     // inherit docs\r
4287     destroy: function(){\r
4288         if(!this.useAjax){\r
4289             this.conn.abort();\r
4290         }else if(this.activeRequest){\r
4291             var actions = Ext.data.Api.actions;\r
4292             for (var verb in actions) {\r
4293                 if(this.activeRequest[actions[verb]]){\r
4294                     Ext.Ajax.abort(this.activeRequest[actions[verb]]);\r
4295                 }\r
4296             }\r
4297         }\r
4298         Ext.data.HttpProxy.superclass.destroy.call(this);\r
4299     }\r
4300 });/**\r
4301  * @class Ext.data.MemoryProxy\r
4302  * @extends Ext.data.DataProxy\r
4303  * An implementation of Ext.data.DataProxy that simply passes the data specified in its constructor\r
4304  * to the Reader when its load method is called.\r
4305  * @constructor\r
4306  * @param {Object} data The data object which the Reader uses to construct a block of Ext.data.Records.\r
4307  */\r
4308 Ext.data.MemoryProxy = function(data){\r
4309     // Must define a dummy api with "read" action to satisfy DataProxy#doRequest and Ext.data.Api#prepare *before* calling super\r
4310     var api = {};\r
4311     api[Ext.data.Api.actions.read] = true;\r
4312     Ext.data.MemoryProxy.superclass.constructor.call(this, {\r
4313         api: api\r
4314     });\r
4315     this.data = data;\r
4316 };\r
4317 \r
4318 Ext.extend(Ext.data.MemoryProxy, Ext.data.DataProxy, {\r
4319     /**\r
4320      * @event loadexception\r
4321      * Fires if an exception occurs in the Proxy during data loading. Note that this event is also relayed\r
4322      * through {@link Ext.data.Store}, so you can listen for it directly on any Store instance.\r
4323      * @param {Object} this\r
4324      * @param {Object} arg The callback's arg object passed to the {@link #load} function\r
4325      * @param {Object} null This parameter does not apply and will always be null for MemoryProxy\r
4326      * @param {Error} e The JavaScript Error object caught if the configured Reader could not read the data\r
4327      */\r
4328 \r
4329        /**\r
4330      * MemoryProxy implementation of DataProxy#doRequest\r
4331      * @param {String} action\r
4332      * @param {Ext.data.Record/Ext.data.Record[]} rs If action is load, rs will be null\r
4333      * @param {Object} params An object containing properties which are to be used as HTTP parameters\r
4334      * for the request to the remote server.\r
4335      * @param {Ext.data.DataReader} reader The Reader object which converts the data\r
4336      * object into a block of Ext.data.Records.\r
4337      * @param {Function} callback The function into which to pass the block of Ext.data.Records.\r
4338      * The function must be passed <ul>\r
4339      * <li>The Record block object</li>\r
4340      * <li>The "arg" argument from the load function</li>\r
4341      * <li>A boolean success indicator</li>\r
4342      * </ul>\r
4343      * @param {Object} scope The scope (<code>this</code> reference) in which the callback function is executed. Defaults to the browser window.\r
4344      * @param {Object} arg An optional argument which is passed to the callback as its second parameter.\r
4345      */\r
4346     doRequest : function(action, rs, params, reader, callback, scope, arg) {\r
4347         // No implementation for CRUD in MemoryProxy.  Assumes all actions are 'load'\r
4348         params = params || {};\r
4349         var result;\r
4350         try {\r
4351             result = reader.readRecords(this.data);\r
4352         }catch(e){\r
4353             // @deprecated loadexception\r
4354             this.fireEvent("loadexception", this, null, arg, e);\r
4355 \r
4356             this.fireEvent('exception', this, 'response', action, arg, null, e);\r
4357             callback.call(scope, null, arg, false);\r
4358             return;\r
4359         }\r
4360         callback.call(scope, result, arg, true);\r
4361     }\r
4362 });