Upgrade to ExtJS 4.0.1 - Released 05/18/2011
[extjs.git] / src / data / Store.js
1 /**
2  * @author Ed Spencer
3  * @class Ext.data.Store
4  * @extends Ext.data.AbstractStore
5  *
6  * <p>The Store class encapsulates a client side cache of {@link Ext.data.Model Model} objects. Stores load
7  * data via a {@link Ext.data.proxy.Proxy Proxy}, and also provide functions for {@link #sort sorting},
8  * {@link #filter filtering} and querying the {@link Ext.data.Model model} instances contained within it.</p>
9  *
10  * <p>Creating a Store is easy - we just tell it the Model and the Proxy to use to load and save its data:</p>
11  *
12 <pre><code>
13 // Set up a {@link Ext.data.Model model} to use in our Store
14 Ext.define('User', {
15     extend: 'Ext.data.Model',
16     fields: [
17         {name: 'firstName', type: 'string'},
18         {name: 'lastName',  type: 'string'},
19         {name: 'age',       type: 'int'},
20         {name: 'eyeColor',  type: 'string'}
21     ]
22 });
23
24 var myStore = new Ext.data.Store({
25     model: 'User',
26     proxy: {
27         type: 'ajax',
28         url : '/users.json',
29         reader: {
30             type: 'json',
31             root: 'users'
32         }
33     },
34     autoLoad: true
35 });
36 </code></pre>
37
38  * <p>In the example above we configured an AJAX proxy to load data from the url '/users.json'. We told our Proxy
39  * to use a {@link Ext.data.reader.Json JsonReader} to parse the response from the server into Model object -
40  * {@link Ext.data.reader.Json see the docs on JsonReader} for details.</p>
41  *
42  * <p><u>Inline data</u></p>
43  *
44  * <p>Stores can also load data inline. Internally, Store converts each of the objects we pass in as {@link #data}
45  * into Model instances:</p>
46  *
47 <pre><code>
48 new Ext.data.Store({
49     model: 'User',
50     data : [
51         {firstName: 'Ed',    lastName: 'Spencer'},
52         {firstName: 'Tommy', lastName: 'Maintz'},
53         {firstName: 'Aaron', lastName: 'Conran'},
54         {firstName: 'Jamie', lastName: 'Avins'}
55     ]
56 });
57 </code></pre>
58  *
59  * <p>Loading inline data using the method above is great if the data is in the correct format already (e.g. it doesn't need
60  * to be processed by a {@link Ext.data.reader.Reader reader}). If your inline data requires processing to decode the data structure,
61  * use a {@link Ext.data.proxy.Memory MemoryProxy} instead (see the {@link Ext.data.proxy.Memory MemoryProxy} docs for an example).</p>
62  *
63  * <p>Additional data can also be loaded locally using {@link #add}.</p>
64  *
65  * <p><u>Loading Nested Data</u></p>
66  *
67  * <p>Applications often need to load sets of associated data - for example a CRM system might load a User and her Orders.
68  * Instead of issuing an AJAX request for the User and a series of additional AJAX requests for each Order, we can load a nested dataset
69  * and allow the Reader to automatically populate the associated models. Below is a brief example, see the {@link Ext.data.reader.Reader} intro
70  * docs for a full explanation:</p>
71  *
72 <pre><code>
73 var store = new Ext.data.Store({
74     autoLoad: true,
75     model: "User",
76     proxy: {
77         type: 'ajax',
78         url : 'users.json',
79         reader: {
80             type: 'json',
81             root: 'users'
82         }
83     }
84 });
85 </code></pre>
86  *
87  * <p>Which would consume a response like this:</p>
88  *
89 <pre><code>
90 {
91     "users": [
92         {
93             "id": 1,
94             "name": "Ed",
95             "orders": [
96                 {
97                     "id": 10,
98                     "total": 10.76,
99                     "status": "invoiced"
100                 },
101                 {
102                     "id": 11,
103                     "total": 13.45,
104                     "status": "shipped"
105                 }
106             ]
107         }
108     ]
109 }
110 </code></pre>
111  *
112  * <p>See the {@link Ext.data.reader.Reader} intro docs for a full explanation.</p>
113  *
114  * <p><u>Filtering and Sorting</u></p>
115  *
116  * <p>Stores can be sorted and filtered - in both cases either remotely or locally. The {@link #sorters} and {@link #filters} are
117  * held inside {@link Ext.util.MixedCollection MixedCollection} instances to make them easy to manage. Usually it is sufficient to
118  * either just specify sorters and filters in the Store configuration or call {@link #sort} or {@link #filter}:
119  *
120 <pre><code>
121 var store = new Ext.data.Store({
122     model: 'User',
123     sorters: [
124         {
125             property : 'age',
126             direction: 'DESC'
127         },
128         {
129             property : 'firstName',
130             direction: 'ASC'
131         }
132     ],
133
134     filters: [
135         {
136             property: 'firstName',
137             value   : /Ed/
138         }
139     ]
140 });
141 </code></pre>
142  *
143  * <p>The new Store will keep the configured sorters and filters in the MixedCollection instances mentioned above. By default, sorting
144  * and filtering are both performed locally by the Store - see {@link #remoteSort} and {@link #remoteFilter} to allow the server to
145  * perform these operations instead.</p>
146  *
147  * <p>Filtering and sorting after the Store has been instantiated is also easy. Calling {@link #filter} adds another filter to the Store
148  * and automatically filters the dataset (calling {@link #filter} with no arguments simply re-applies all existing filters). Note that by
149  * default {@link #sortOnFilter} is set to true, which means that your sorters are automatically reapplied if using local sorting.</p>
150  *
151 <pre><code>
152 store.filter('eyeColor', 'Brown');
153 </code></pre>
154  *
155  * <p>Change the sorting at any time by calling {@link #sort}:</p>
156  *
157 <pre><code>
158 store.sort('height', 'ASC');
159 </code></pre>
160  *
161  * <p>Note that all existing sorters will be removed in favor of the new sorter data (if {@link #sort} is called with no arguments,
162  * the existing sorters are just reapplied instead of being removed). To keep existing sorters and add new ones, just add them
163  * to the MixedCollection:</p>
164  *
165 <pre><code>
166 store.sorters.add(new Ext.util.Sorter({
167     property : 'shoeSize',
168     direction: 'ASC'
169 }));
170
171 store.sort();
172 </code></pre>
173  *
174  * <p><u>Registering with StoreManager</u></p>
175  *
176  * <p>Any Store that is instantiated with a {@link #storeId} will automatically be registed with the {@link Ext.data.StoreManager StoreManager}.
177  * This makes it easy to reuse the same store in multiple views:</p>
178  *
179  <pre><code>
180 //this store can be used several times
181 new Ext.data.Store({
182     model: 'User',
183     storeId: 'usersStore'
184 });
185
186 new Ext.List({
187     store: 'usersStore',
188
189     //other config goes here
190 });
191
192 new Ext.view.View({
193     store: 'usersStore',
194
195     //other config goes here
196 });
197 </code></pre>
198  *
199  * <p><u>Further Reading</u></p>
200  *
201  * <p>Stores are backed up by an ecosystem of classes that enables their operation. To gain a full understanding of these
202  * pieces and how they fit together, see:</p>
203  *
204  * <ul style="list-style-type: disc; padding-left: 25px">
205  * <li>{@link Ext.data.proxy.Proxy Proxy} - overview of what Proxies are and how they are used</li>
206  * <li>{@link Ext.data.Model Model} - the core class in the data package</li>
207  * <li>{@link Ext.data.reader.Reader Reader} - used by any subclass of {@link Ext.data.proxy.Server ServerProxy} to read a response</li>
208  * </ul>
209  *
210  * @constructor
211  * @param {Object} config Optional config object
212  */
213 Ext.define('Ext.data.Store', {
214     extend: 'Ext.data.AbstractStore',
215
216     alias: 'store.store',
217
218     requires: ['Ext.ModelManager', 'Ext.data.Model', 'Ext.util.Grouper'],
219     uses: ['Ext.data.proxy.Memory'],
220
221     /**
222      * @cfg {Boolean} remoteSort
223      * True to defer any sorting operation to the server. If false, sorting is done locally on the client. Defaults to <tt>false</tt>.
224      */
225     remoteSort: false,
226
227     /**
228      * @cfg {Boolean} remoteFilter
229      * True to defer any filtering operation to the server. If false, filtering is done locally on the client. Defaults to <tt>false</tt>.
230      */
231     remoteFilter: false,
232     
233     /**
234      * @cfg {Boolean} remoteGroup
235      * True if the grouping should apply on the server side, false if it is local only (defaults to false).  If the
236      * grouping is local, it can be applied immediately to the data.  If it is remote, then it will simply act as a
237      * helper, automatically sending the grouping information to the server.
238      */
239     remoteGroup : false,
240
241     /**
242      * @cfg {String/Ext.data.proxy.Proxy/Object} proxy The Proxy to use for this Store. This can be either a string, a config
243      * object or a Proxy instance - see {@link #setProxy} for details.
244      */
245
246     /**
247      * @cfg {Array} data Optional array of Model instances or data objects to load locally. See "Inline data" above for details.
248      */
249
250     /**
251      * @cfg {String} model The {@link Ext.data.Model} associated with this store
252      */
253
254     /**
255      * The (optional) field by which to group data in the store. Internally, grouping is very similar to sorting - the
256      * groupField and {@link #groupDir} are injected as the first sorter (see {@link #sort}). Stores support a single
257      * level of grouping, and groups can be fetched via the {@link #getGroups} method.
258      * @property groupField
259      * @type String
260      */
261     groupField: undefined,
262
263     /**
264      * The direction in which sorting should be applied when grouping. Defaults to "ASC" - the other supported value is "DESC"
265      * @property groupDir
266      * @type String
267      */
268     groupDir: "ASC",
269
270     /**
271      * @cfg {Number} pageSize
272      * The number of records considered to form a 'page'. This is used to power the built-in
273      * paging using the nextPage and previousPage functions. Defaults to 25.
274      */
275     pageSize: 25,
276
277     /**
278      * The page that the Store has most recently loaded (see {@link #loadPage})
279      * @property currentPage
280      * @type Number
281      */
282     currentPage: 1,
283
284     /**
285      * @cfg {Boolean} clearOnPageLoad True to empty the store when loading another page via {@link #loadPage},
286      * {@link #nextPage} or {@link #previousPage} (defaults to true). Setting to false keeps existing records, allowing
287      * large data sets to be loaded one page at a time but rendered all together.
288      */
289     clearOnPageLoad: true,
290
291     /**
292      * True if the Store is currently loading via its Proxy
293      * @property loading
294      * @type Boolean
295      * @private
296      */
297     loading: false,
298
299     /**
300      * @cfg {Boolean} sortOnFilter For local filtering only, causes {@link #sort} to be called whenever {@link #filter} is called,
301      * causing the sorters to be reapplied after filtering. Defaults to true
302      */
303     sortOnFilter: true,
304     
305     /**
306      * @cfg {Boolean} buffered
307      * Allow the store to buffer and pre-fetch pages of records. This is to be used in conjunction with a view will
308      * tell the store to pre-fetch records ahead of a time.
309      */
310     buffered: false,
311     
312     /**
313      * @cfg {Number} purgePageCount 
314      * The number of pages to keep in the cache before purging additional records. A value of 0 indicates to never purge the prefetched data.
315      * This option is only relevant when the {@link #buffered} option is set to true.
316      */
317     purgePageCount: 5,
318
319     isStore: true,
320
321     //documented above
322     constructor: function(config) {
323         config = config || {};
324
325         var me = this,
326             groupers = config.groupers || me.groupers,
327             groupField = config.groupField || me.groupField,
328             proxy,
329             data;
330             
331         if (config.buffered || me.buffered) {
332             me.prefetchData = Ext.create('Ext.util.MixedCollection', false, function(record) {
333                 return record.index;
334             });
335             me.pendingRequests = [];
336             me.pagesRequested = [];
337             
338             me.sortOnLoad = false;
339             me.filterOnLoad = false;
340         }
341             
342         me.addEvents(
343             /**
344              * @event beforeprefetch
345              * Fires before a prefetch occurs. Return false to cancel.
346              * @param {Ext.data.store} this
347              * @param {Ext.data.Operation} operation The associated operation
348              */
349             'beforeprefetch',
350             /**
351              * @event groupchange
352              * Fired whenever the grouping in the grid changes
353              * @param {Ext.data.Store} store The store
354              * @param {Array} groupers The array of grouper objects
355              */
356             'groupchange',
357             /**
358              * @event load
359              * Fires whenever records have been prefetched
360              * @param {Ext.data.store} this
361              * @param {Array} records An array of records
362              * @param {Boolean} successful True if the operation was successful.
363              * @param {Ext.data.Operation} operation The associated operation
364              */
365             'prefetch'
366         );
367         data = config.data || me.data;
368
369         /**
370          * The MixedCollection that holds this store's local cache of records
371          * @property data
372          * @type Ext.util.MixedCollection
373          */
374         me.data = Ext.create('Ext.util.MixedCollection', false, function(record) {
375             return record.internalId;
376         });
377
378         if (data) {
379             me.inlineData = data;
380             delete config.data;
381         }
382         
383         if (!groupers && groupField) {
384             groupers = [{
385                 property : groupField,
386                 direction: config.groupDir || me.groupDir
387             }];
388         }
389         delete config.groupers;
390         
391         /**
392          * The collection of {@link Ext.util.Grouper Groupers} currently applied to this Store
393          * @property groupers
394          * @type Ext.util.MixedCollection
395          */
396         me.groupers = Ext.create('Ext.util.MixedCollection');
397         me.groupers.addAll(me.decodeGroupers(groupers));
398
399         this.callParent([config]);
400         // don't use *config* anymore from here on... use *me* instead...
401         
402         if (me.groupers.items.length) {
403             me.sort(me.groupers.items, 'prepend', false);
404         }
405
406         proxy = me.proxy;
407         data = me.inlineData;
408
409         if (data) {
410             if (proxy instanceof Ext.data.proxy.Memory) {
411                 proxy.data = data;
412                 me.read();
413             } else {
414                 me.add.apply(me, data);
415             }
416
417             me.sort();
418             delete me.inlineData;
419         } else if (me.autoLoad) {
420             Ext.defer(me.load, 10, me, [typeof me.autoLoad === 'object' ? me.autoLoad: undefined]);
421             // Remove the defer call, we may need reinstate this at some point, but currently it's not obvious why it's here.
422             // this.load(typeof this.autoLoad == 'object' ? this.autoLoad : undefined);
423         }
424     },
425     
426     onBeforeSort: function() {
427         this.sort(this.groupers.items, 'prepend', false);
428     },
429     
430     /**
431      * @private
432      * Normalizes an array of grouper objects, ensuring that they are all Ext.util.Grouper instances
433      * @param {Array} groupers The groupers array
434      * @return {Array} Array of Ext.util.Grouper objects
435      */
436     decodeGroupers: function(groupers) {
437         if (!Ext.isArray(groupers)) {
438             if (groupers === undefined) {
439                 groupers = [];
440             } else {
441                 groupers = [groupers];
442             }
443         }
444
445         var length  = groupers.length,
446             Grouper = Ext.util.Grouper,
447             config, i;
448
449         for (i = 0; i < length; i++) {
450             config = groupers[i];
451
452             if (!(config instanceof Grouper)) {
453                 if (Ext.isString(config)) {
454                     config = {
455                         property: config
456                     };
457                 }
458                 
459                 Ext.applyIf(config, {
460                     root     : 'data',
461                     direction: "ASC"
462                 });
463
464                 //support for 3.x style sorters where a function can be defined as 'fn'
465                 if (config.fn) {
466                     config.sorterFn = config.fn;
467                 }
468
469                 //support a function to be passed as a sorter definition
470                 if (typeof config == 'function') {
471                     config = {
472                         sorterFn: config
473                     };
474                 }
475
476                 groupers[i] = new Grouper(config);
477             }
478         }
479
480         return groupers;
481     },
482     
483     /**
484      * Group data in the store
485      * @param {String|Array} groupers Either a string name of one of the fields in this Store's configured {@link Ext.data.Model Model},
486      * or an Array of grouper configurations.
487      * @param {String} direction The overall direction to group the data by. Defaults to "ASC".
488      */
489     group: function(groupers, direction) {
490         var me = this,
491             grouper,
492             newGroupers;
493             
494         if (Ext.isArray(groupers)) {
495             newGroupers = groupers;
496         } else if (Ext.isObject(groupers)) {
497             newGroupers = [groupers];
498         } else if (Ext.isString(groupers)) {
499             grouper = me.groupers.get(groupers);
500
501             if (!grouper) {
502                 grouper = {
503                     property : groupers,
504                     direction: direction
505                 };
506                 newGroupers = [grouper];
507             } else if (direction === undefined) {
508                 grouper.toggle();
509             } else {
510                 grouper.setDirection(direction);
511             }
512         }
513         
514         if (newGroupers && newGroupers.length) {
515             newGroupers = me.decodeGroupers(newGroupers);
516             me.groupers.clear();
517             me.groupers.addAll(newGroupers);
518         }
519         
520         if (me.remoteGroup) {
521             me.load({
522                 scope: me,
523                 callback: me.fireGroupChange
524             });
525         } else {
526             me.sort();
527             me.fireEvent('groupchange', me, me.groupers);
528         }
529     },
530     
531     /**
532      * Clear any groupers in the store
533      */
534     clearGrouping: function(){
535         var me = this;
536         // Clear any groupers we pushed on to the sorters
537         me.groupers.each(function(grouper){
538             me.sorters.remove(grouper);
539         });
540         me.groupers.clear();
541         if (me.remoteGroup) {
542             me.load({
543                 scope: me,
544                 callback: me.fireGroupChange
545             });
546         } else {
547             me.sort();
548             me.fireEvent('groupchange', me, me.groupers);
549         }
550     },
551     
552     /**
553      * Checks if the store is currently grouped
554      * @return {Boolean} True if the store is grouped.
555      */
556     isGrouped: function() {
557         return this.groupers.getCount() > 0;    
558     },
559     
560     /**
561      * Fires the groupchange event. Abstracted out so we can use it
562      * as a callback
563      * @private
564      */
565     fireGroupChange: function(){
566         this.fireEvent('groupchange', this, this.groupers);    
567     },
568
569     /**
570      * Returns an object containing the result of applying grouping to the records in this store. See {@link #groupField},
571      * {@link #groupDir} and {@link #getGroupString}. Example for a store containing records with a color field:
572 <pre><code>
573 var myStore = new Ext.data.Store({
574     groupField: 'color',
575     groupDir  : 'DESC'
576 });
577
578 myStore.getGroups(); //returns:
579 [
580     {
581         name: 'yellow',
582         children: [
583             //all records where the color field is 'yellow'
584         ]
585     },
586     {
587         name: 'red',
588         children: [
589             //all records where the color field is 'red'
590         ]
591     }
592 ]
593 </code></pre>
594      * @param {String} groupName (Optional) Pass in an optional groupName argument to access a specific group as defined by {@link #getGroupString}
595      * @return {Array} The grouped data
596      */
597     getGroups: function(requestGroupString) {
598         var records = this.data.items,
599             length = records.length,
600             groups = [],
601             pointers = {},
602             record,
603             groupStr,
604             group,
605             i;
606
607         for (i = 0; i < length; i++) {
608             record = records[i];
609             groupStr = this.getGroupString(record);
610             group = pointers[groupStr];
611
612             if (group === undefined) {
613                 group = {
614                     name: groupStr,
615                     children: []
616                 };
617
618                 groups.push(group);
619                 pointers[groupStr] = group;
620             }
621
622             group.children.push(record);
623         }
624
625         return requestGroupString ? pointers[requestGroupString] : groups;
626     },
627
628     /**
629      * @private
630      * For a given set of records and a Grouper, returns an array of arrays - each of which is the set of records
631      * matching a certain group.
632      */
633     getGroupsForGrouper: function(records, grouper) {
634         var length = records.length,
635             groups = [],
636             oldValue,
637             newValue,
638             record,
639             group,
640             i;
641
642         for (i = 0; i < length; i++) {
643             record = records[i];
644             newValue = grouper.getGroupString(record);
645
646             if (newValue !== oldValue) {
647                 group = {
648                     name: newValue,
649                     grouper: grouper,
650                     records: []
651                 };
652                 groups.push(group);
653             }
654
655             group.records.push(record);
656
657             oldValue = newValue;
658         }
659
660         return groups;
661     },
662
663     /**
664      * @private
665      * This is used recursively to gather the records into the configured Groupers. The data MUST have been sorted for
666      * this to work properly (see {@link #getGroupData} and {@link #getGroupsForGrouper}) Most of the work is done by
667      * {@link #getGroupsForGrouper} - this function largely just handles the recursion.
668      * @param {Array} records The set or subset of records to group
669      * @param {Number} grouperIndex The grouper index to retrieve
670      * @return {Array} The grouped records
671      */
672     getGroupsForGrouperIndex: function(records, grouperIndex) {
673         var me = this,
674             groupers = me.groupers,
675             grouper = groupers.getAt(grouperIndex),
676             groups = me.getGroupsForGrouper(records, grouper),
677             length = groups.length,
678             i;
679
680         if (grouperIndex + 1 < groupers.length) {
681             for (i = 0; i < length; i++) {
682                 groups[i].children = me.getGroupsForGrouperIndex(groups[i].records, grouperIndex + 1);
683             }
684         }
685
686         for (i = 0; i < length; i++) {
687             groups[i].depth = grouperIndex;
688         }
689
690         return groups;
691     },
692
693     /**
694      * @private
695      * <p>Returns records grouped by the configured {@link #groupers grouper} configuration. Sample return value (in
696      * this case grouping by genre and then author in a fictional books dataset):</p>
697 <pre><code>
698 [
699     {
700         name: 'Fantasy',
701         depth: 0,
702         records: [
703             //book1, book2, book3, book4
704         ],
705         children: [
706             {
707                 name: 'Rowling',
708                 depth: 1,
709                 records: [
710                     //book1, book2
711                 ]
712             },
713             {
714                 name: 'Tolkein',
715                 depth: 1,
716                 records: [
717                     //book3, book4
718                 ]
719             }
720         ]
721     }
722 ]
723 </code></pre>
724      * @param {Boolean} sort True to call {@link #sort} before finding groups. Sorting is required to make grouping
725      * function correctly so this should only be set to false if the Store is known to already be sorted correctly
726      * (defaults to true)
727      * @return {Array} The group data
728      */
729     getGroupData: function(sort) {
730         var me = this;
731         if (sort !== false) {
732             me.sort();
733         }
734
735         return me.getGroupsForGrouperIndex(me.data.items, 0);
736     },
737
738     /**
739      * <p>Returns the string to group on for a given model instance. The default implementation of this method returns
740      * the model's {@link #groupField}, but this can be overridden to group by an arbitrary string. For example, to
741      * group by the first letter of a model's 'name' field, use the following code:</p>
742 <pre><code>
743 new Ext.data.Store({
744     groupDir: 'ASC',
745     getGroupString: function(instance) {
746         return instance.get('name')[0];
747     }
748 });
749 </code></pre>
750      * @param {Ext.data.Model} instance The model instance
751      * @return {String} The string to compare when forming groups
752      */
753     getGroupString: function(instance) {
754         var group = this.groupers.first();
755         if (group) {
756             return instance.get(group.property);
757         }
758         return '';
759     },
760     /**
761      * Inserts Model instances into the Store at the given index and fires the {@link #add} event.
762      * See also <code>{@link #add}</code>.
763      * @param {Number} index The start index at which to insert the passed Records.
764      * @param {Ext.data.Model[]} records An Array of Ext.data.Model objects to add to the cache.
765      */
766     insert: function(index, records) {
767         var me = this,
768             sync = false,
769             i,
770             record,
771             len;
772
773         records = [].concat(records);
774         for (i = 0, len = records.length; i < len; i++) {
775             record = me.createModel(records[i]);
776             record.set(me.modelDefaults);
777             // reassign the model in the array in case it wasn't created yet
778             records[i] = record;
779             
780             me.data.insert(index + i, record);
781             record.join(me);
782
783             sync = sync || record.phantom === true;
784         }
785
786         if (me.snapshot) {
787             me.snapshot.addAll(records);
788         }
789
790         me.fireEvent('add', me, records, index);
791         me.fireEvent('datachanged', me);
792         if (me.autoSync && sync) {
793             me.sync();
794         }
795     },
796
797     /**
798      * Adds Model instances to the Store by instantiating them based on a JavaScript object. When adding already-
799      * instantiated Models, use {@link #insert} instead. The instances will be added at the end of the existing collection.
800      * This method accepts either a single argument array of Model instances or any number of model instance arguments.
801      * Sample usage:
802      *
803 <pre><code>
804 myStore.add({some: 'data'}, {some: 'other data'});
805 </code></pre>
806      *
807      * @param {Object} data The data for each model
808      * @return {Array} The array of newly created model instances
809      */
810     add: function(records) {
811         //accept both a single-argument array of records, or any number of record arguments
812         if (!Ext.isArray(records)) {
813             records = Array.prototype.slice.apply(arguments);
814         }
815
816         var me = this,
817             i = 0,
818             length = records.length,
819             record;
820
821         for (; i < length; i++) {
822             record = me.createModel(records[i]);
823             // reassign the model in the array in case it wasn't created yet
824             records[i] = record;
825         }
826
827         me.insert(me.data.length, records);
828
829         return records;
830     },
831
832     /**
833      * Converts a literal to a model, if it's not a model already
834      * @private
835      * @param record {Ext.data.Model/Object} The record to create
836      * @return {Ext.data.Model}
837      */
838     createModel: function(record) {
839         if (!record.isModel) {
840             record = Ext.ModelManager.create(record, this.model);
841         }
842
843         return record;
844     },
845
846     /**
847      * Calls the specified function for each of the {@link Ext.data.Model Records} in the cache.
848      * @param {Function} fn The function to call. The {@link Ext.data.Model Record} is passed as the first parameter.
849      * Returning <tt>false</tt> aborts and exits the iteration.
850      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed.
851      * Defaults to the current {@link Ext.data.Model Record} in the iteration.
852      */
853     each: function(fn, scope) {
854         this.data.each(fn, scope);
855     },
856
857     /**
858      * Removes the given record from the Store, firing the 'remove' event for each instance that is removed, plus a single
859      * 'datachanged' event after removal.
860      * @param {Ext.data.Model/Array} records The Ext.data.Model instance or array of instances to remove
861      */
862     remove: function(records, /* private */ isMove) {
863         if (!Ext.isArray(records)) {
864             records = [records];
865         }
866
867         /*
868          * Pass the isMove parameter if we know we're going to be re-inserting this record
869          */
870         isMove = isMove === true;
871         var me = this,
872             sync = false,
873             i = 0,
874             length = records.length,
875             isPhantom,
876             index,
877             record;
878
879         for (; i < length; i++) {
880             record = records[i];
881             index = me.data.indexOf(record);
882             
883             if (me.snapshot) {
884                 me.snapshot.remove(record);
885             }
886             
887             if (index > -1) {
888                 isPhantom = record.phantom === true;
889                 if (!isMove && !isPhantom) {
890                     // don't push phantom records onto removed
891                     me.removed.push(record);
892                 }
893
894                 record.unjoin(me);
895                 me.data.remove(record);
896                 sync = sync || !isPhantom;
897
898                 me.fireEvent('remove', me, record, index);
899             }
900         }
901
902         me.fireEvent('datachanged', me);
903         if (!isMove && me.autoSync && sync) {
904             me.sync();
905         }
906     },
907
908     /**
909      * Removes the model instance at the given index
910      * @param {Number} index The record index
911      */
912     removeAt: function(index) {
913         var record = this.getAt(index);
914
915         if (record) {
916             this.remove(record);
917         }
918     },
919
920     /**
921      * <p>Loads data into the Store via the configured {@link #proxy}. This uses the Proxy to make an
922      * asynchronous call to whatever storage backend the Proxy uses, automatically adding the retrieved
923      * instances into the Store and calling an optional callback if required. Example usage:</p>
924      *
925 <pre><code>
926 store.load({
927     scope   : this,
928     callback: function(records, operation, success) {
929         //the {@link Ext.data.Operation operation} object contains all of the details of the load operation
930         console.log(records);
931     }
932 });
933 </code></pre>
934      *
935      * <p>If the callback scope does not need to be set, a function can simply be passed:</p>
936      *
937 <pre><code>
938 store.load(function(records, operation, success) {
939     console.log('loaded records');
940 });
941 </code></pre>
942      *
943      * @param {Object/Function} options Optional config object, passed into the Ext.data.Operation object before loading.
944      */
945     load: function(options) {
946         var me = this;
947             
948         options = options || {};
949
950         if (Ext.isFunction(options)) {
951             options = {
952                 callback: options
953             };
954         }
955
956         Ext.applyIf(options, {
957             groupers: me.groupers.items,
958             page: me.currentPage,
959             start: (me.currentPage - 1) * me.pageSize,
960             limit: me.pageSize,
961             addRecords: false
962         });      
963
964         return me.callParent([options]);
965     },
966
967     /**
968      * @private
969      * Called internally when a Proxy has completed a load request
970      */
971     onProxyLoad: function(operation) {
972         var me = this,
973             resultSet = operation.getResultSet(),
974             records = operation.getRecords(),
975             successful = operation.wasSuccessful();
976
977         if (resultSet) {
978             me.totalCount = resultSet.total;
979         }
980
981         if (successful) {
982             me.loadRecords(records, operation);
983         }
984
985         me.loading = false;
986         me.fireEvent('load', me, records, successful);
987
988         //TODO: deprecate this event, it should always have been 'load' instead. 'load' is now documented, 'read' is not.
989         //People are definitely using this so can't deprecate safely until 2.x
990         me.fireEvent('read', me, records, operation.wasSuccessful());
991
992         //this is a callback that would have been passed to the 'read' function and is optional
993         Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
994     },
995     
996     /**
997      * Create any new records when a write is returned from the server.
998      * @private
999      * @param {Array} records The array of new records
1000      * @param {Ext.data.Operation} operation The operation that just completed
1001      * @param {Boolean} success True if the operation was successful
1002      */
1003     onCreateRecords: function(records, operation, success) {
1004         if (success) {
1005             var i = 0,
1006                 data = this.data,
1007                 snapshot = this.snapshot,
1008                 length = records.length,
1009                 originalRecords = operation.records,
1010                 record,
1011                 original,
1012                 index;
1013
1014             /*
1015              * Loop over each record returned from the server. Assume they are
1016              * returned in order of how they were sent. If we find a matching
1017              * record, replace it with the newly created one.
1018              */
1019             for (; i < length; ++i) {
1020                 record = records[i];
1021                 original = originalRecords[i];
1022                 if (original) {
1023                     index = data.indexOf(original);
1024                     if (index > -1) {
1025                         data.removeAt(index);
1026                         data.insert(index, record);
1027                     }
1028                     if (snapshot) {
1029                         index = snapshot.indexOf(original);
1030                         if (index > -1) {
1031                             snapshot.removeAt(index);
1032                             snapshot.insert(index, record);
1033                         }
1034                     }
1035                     record.phantom = false;
1036                     record.join(this);
1037                 }
1038             }
1039         }
1040     },
1041
1042     /**
1043      * Update any records when a write is returned from the server.
1044      * @private
1045      * @param {Array} records The array of updated records
1046      * @param {Ext.data.Operation} operation The operation that just completed
1047      * @param {Boolean} success True if the operation was successful
1048      */
1049     onUpdateRecords: function(records, operation, success){
1050         if (success) {
1051             var i = 0,
1052                 length = records.length,
1053                 data = this.data,
1054                 snapshot = this.snapshot,
1055                 record;
1056
1057             for (; i < length; ++i) {
1058                 record = records[i];
1059                 data.replace(record);
1060                 if (snapshot) {
1061                     snapshot.replace(record);
1062                 }
1063                 record.join(this);
1064             }
1065         }
1066     },
1067
1068     /**
1069      * Remove any records when a write is returned from the server.
1070      * @private
1071      * @param {Array} records The array of removed records
1072      * @param {Ext.data.Operation} operation The operation that just completed
1073      * @param {Boolean} success True if the operation was successful
1074      */
1075     onDestroyRecords: function(records, operation, success){
1076         if (success) {
1077             var me = this,
1078                 i = 0,
1079                 length = records.length,
1080                 data = me.data,
1081                 snapshot = me.snapshot,
1082                 record;
1083
1084             for (; i < length; ++i) {
1085                 record = records[i];
1086                 record.unjoin(me);
1087                 data.remove(record);
1088                 if (snapshot) {
1089                     snapshot.remove(record);
1090                 }
1091             }
1092             me.removed = [];
1093         }
1094     },
1095
1096     //inherit docs
1097     getNewRecords: function() {
1098         return this.data.filterBy(this.filterNew).items;
1099     },
1100
1101     //inherit docs
1102     getUpdatedRecords: function() {
1103         return this.data.filterBy(this.filterUpdated).items;
1104     },
1105
1106     /**
1107      * Filters the loaded set of records by a given set of filters.
1108      * @param {Mixed} filters The set of filters to apply to the data. These are stored internally on the store,
1109      * but the filtering itself is done on the Store's {@link Ext.util.MixedCollection MixedCollection}. See
1110      * MixedCollection's {@link Ext.util.MixedCollection#filter filter} method for filter syntax. Alternatively,
1111      * pass in a property string
1112      * @param {String} value Optional value to filter by (only if using a property string as the first argument)
1113      */
1114     filter: function(filters, value) {
1115         if (Ext.isString(filters)) {
1116             filters = {
1117                 property: filters,
1118                 value: value
1119             };
1120         }
1121
1122         var me = this,
1123             decoded = me.decodeFilters(filters),
1124             i = 0,
1125             doLocalSort = me.sortOnFilter && !me.remoteSort,
1126             length = decoded.length;
1127
1128         for (; i < length; i++) {
1129             me.filters.replace(decoded[i]);
1130         }
1131
1132         if (me.remoteFilter) {
1133             //the load function will pick up the new filters and request the filtered data from the proxy
1134             me.load();
1135         } else {
1136             /**
1137              * A pristine (unfiltered) collection of the records in this store. This is used to reinstate
1138              * records when a filter is removed or changed
1139              * @property snapshot
1140              * @type Ext.util.MixedCollection
1141              */
1142             if (me.filters.getCount()) {
1143                 me.snapshot = me.snapshot || me.data.clone();
1144                 me.data = me.data.filter(me.filters.items);
1145
1146                 if (doLocalSort) {
1147                     me.sort();
1148                 }
1149                 // fire datachanged event if it hasn't already been fired by doSort
1150                 if (!doLocalSort || me.sorters.length < 1) {
1151                     me.fireEvent('datachanged', me);
1152                 }
1153             }
1154         }
1155     },
1156
1157     /**
1158      * Revert to a view of the Record cache with no filtering applied.
1159      * @param {Boolean} suppressEvent If <tt>true</tt> the filter is cleared silently without firing the
1160      * {@link #datachanged} event.
1161      */
1162     clearFilter: function(suppressEvent) {
1163         var me = this;
1164
1165         me.filters.clear();
1166
1167         if (me.remoteFilter) {
1168             me.load();
1169         } else if (me.isFiltered()) {
1170             me.data = me.snapshot.clone();
1171             delete me.snapshot;
1172
1173             if (suppressEvent !== true) {
1174                 me.fireEvent('datachanged', me);
1175             }
1176         }
1177     },
1178
1179     /**
1180      * Returns true if this store is currently filtered
1181      * @return {Boolean}
1182      */
1183     isFiltered: function() {
1184         var snapshot = this.snapshot;
1185         return !! snapshot && snapshot !== this.data;
1186     },
1187
1188     /**
1189      * Filter by a function. The specified function will be called for each
1190      * Record in this Store. If the function returns <tt>true</tt> the Record is included,
1191      * otherwise it is filtered out.
1192      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1193      * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1194      * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1195      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1196      * </ul>
1197      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1198      */
1199     filterBy: function(fn, scope) {
1200         var me = this;
1201
1202         me.snapshot = me.snapshot || me.data.clone();
1203         me.data = me.queryBy(fn, scope || me);
1204         me.fireEvent('datachanged', me);
1205     },
1206
1207     /**
1208      * Query the cached records in this Store using a filtering function. The specified function
1209      * will be called with each record in this Store. If the function returns <tt>true</tt> the record is
1210      * included in the results.
1211      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1212      * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1213      * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1214      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1215      * </ul>
1216      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1217      * @return {MixedCollection} Returns an Ext.util.MixedCollection of the matched records
1218      **/
1219     queryBy: function(fn, scope) {
1220         var me = this,
1221         data = me.snapshot || me.data;
1222         return data.filterBy(fn, scope || me);
1223     },
1224
1225     /**
1226      * Loads an array of data straight into the Store
1227      * @param {Array} data Array of data to load. Any non-model instances will be cast into model instances first
1228      * @param {Boolean} append True to add the records to the existing records in the store, false to remove the old ones first
1229      */
1230     loadData: function(data, append) {
1231         var model = this.model,
1232             length = data.length,
1233             i,
1234             record;
1235
1236         //make sure each data element is an Ext.data.Model instance
1237         for (i = 0; i < length; i++) {
1238             record = data[i];
1239
1240             if (! (record instanceof Ext.data.Model)) {
1241                 data[i] = Ext.ModelManager.create(record, model);
1242             }
1243         }
1244
1245         this.loadRecords(data, {addRecords: append});
1246     },
1247
1248     /**
1249      * Loads an array of {@Ext.data.Model model} instances into the store, fires the datachanged event. This should only usually
1250      * be called internally when loading from the {@link Ext.data.proxy.Proxy Proxy}, when adding records manually use {@link #add} instead
1251      * @param {Array} records The array of records to load
1252      * @param {Object} options {addRecords: true} to add these records to the existing records, false to remove the Store's existing records first
1253      */
1254     loadRecords: function(records, options) {
1255         var me     = this,
1256             i      = 0,
1257             length = records.length;
1258
1259         options = options || {};
1260
1261
1262         if (!options.addRecords) {
1263             delete me.snapshot;
1264             me.data.clear();
1265         }
1266
1267         me.data.addAll(records);
1268
1269         //FIXME: this is not a good solution. Ed Spencer is totally responsible for this and should be forced to fix it immediately.
1270         for (; i < length; i++) {
1271             if (options.start !== undefined) {
1272                 records[i].index = options.start + i;
1273
1274             }
1275             records[i].join(me);
1276         }
1277
1278         /*
1279          * this rather inelegant suspension and resumption of events is required because both the filter and sort functions
1280          * fire an additional datachanged event, which is not wanted. Ideally we would do this a different way. The first
1281          * datachanged event is fired by the call to this.add, above.
1282          */
1283         me.suspendEvents();
1284
1285         if (me.filterOnLoad && !me.remoteFilter) {
1286             me.filter();
1287         }
1288
1289         if (me.sortOnLoad && !me.remoteSort) {
1290             me.sort();
1291         }
1292
1293         me.resumeEvents();
1294         me.fireEvent('datachanged', me, records);
1295     },
1296
1297     // PAGING METHODS
1298     /**
1299      * Loads a given 'page' of data by setting the start and limit values appropriately. Internally this just causes a normal
1300      * load operation, passing in calculated 'start' and 'limit' params
1301      * @param {Number} page The number of the page to load
1302      */
1303     loadPage: function(page) {
1304         var me = this;
1305
1306         me.currentPage = page;
1307
1308         me.read({
1309             page: page,
1310             start: (page - 1) * me.pageSize,
1311             limit: me.pageSize,
1312             addRecords: !me.clearOnPageLoad
1313         });
1314     },
1315
1316     /**
1317      * Loads the next 'page' in the current data set
1318      */
1319     nextPage: function() {
1320         this.loadPage(this.currentPage + 1);
1321     },
1322
1323     /**
1324      * Loads the previous 'page' in the current data set
1325      */
1326     previousPage: function() {
1327         this.loadPage(this.currentPage - 1);
1328     },
1329
1330     // private
1331     clearData: function() {
1332         this.data.each(function(record) {
1333             record.unjoin();
1334         });
1335
1336         this.data.clear();
1337     },
1338     
1339     // Buffering
1340     /**
1341      * Prefetches data the Store using its configured {@link #proxy}.
1342      * @param {Object} options Optional config object, passed into the Ext.data.Operation object before loading.
1343      * See {@link #load}
1344      */
1345     prefetch: function(options) {
1346         var me = this,
1347             operation,
1348             requestId = me.getRequestId();
1349
1350         options = options || {};
1351
1352         Ext.applyIf(options, {
1353             action : 'read',
1354             filters: me.filters.items,
1355             sorters: me.sorters.items,
1356             requestId: requestId
1357         });
1358         me.pendingRequests.push(requestId);
1359
1360         operation = Ext.create('Ext.data.Operation', options);
1361
1362         // HACK to implement loadMask support.
1363         //if (operation.blocking) {
1364         //    me.fireEvent('beforeload', me, operation);
1365         //}
1366         if (me.fireEvent('beforeprefetch', me, operation) !== false) {
1367             me.loading = true;
1368             me.proxy.read(operation, me.onProxyPrefetch, me);
1369         }
1370         
1371         return me;
1372     },
1373     
1374     /**
1375      * Prefetches a page of data.
1376      * @param {Number} page The page to prefetch
1377      * @param {Object} options Optional config object, passed into the Ext.data.Operation object before loading.
1378      * See {@link #load}
1379      * @param
1380      */
1381     prefetchPage: function(page, options) {
1382         var me = this,
1383             pageSize = me.pageSize,
1384             start = (page - 1) * me.pageSize,
1385             end = start + pageSize;
1386         
1387         // Currently not requesting this page and range isn't already satisified 
1388         if (Ext.Array.indexOf(me.pagesRequested, page) === -1 && !me.rangeSatisfied(start, end)) {
1389             options = options || {};
1390             me.pagesRequested.push(page);
1391             Ext.applyIf(options, {
1392                 page : page,
1393                 start: start,
1394                 limit: pageSize,
1395                 callback: me.onWaitForGuarantee,
1396                 scope: me
1397             });
1398             
1399             me.prefetch(options);
1400         }
1401         
1402     },
1403     
1404     /**
1405      * Returns a unique requestId to track requests.
1406      * @private
1407      */
1408     getRequestId: function() {
1409         this.requestSeed = this.requestSeed || 1;
1410         return this.requestSeed++;
1411     },
1412     
1413     /**
1414      * Handles a success pre-fetch
1415      * @private
1416      * @param {Ext.data.Operation} operation The operation that completed
1417      */
1418     onProxyPrefetch: function(operation) {
1419         var me         = this,
1420             resultSet  = operation.getResultSet(),
1421             records    = operation.getRecords(),
1422             
1423             successful = operation.wasSuccessful();
1424         
1425         if (resultSet) {
1426             me.totalCount = resultSet.total;
1427             me.fireEvent('totalcountchange', me.totalCount);
1428         }
1429         
1430         if (successful) {
1431             me.cacheRecords(records, operation);
1432         }
1433         Ext.Array.remove(me.pendingRequests, operation.requestId);
1434         if (operation.page) {
1435             Ext.Array.remove(me.pagesRequested, operation.page);
1436         }
1437         
1438         me.loading = false;
1439         me.fireEvent('prefetch', me, records, successful, operation);
1440         
1441         // HACK to support loadMask
1442         if (operation.blocking) {
1443             me.fireEvent('load', me, records, successful);
1444         }
1445
1446         //this is a callback that would have been passed to the 'read' function and is optional
1447         Ext.callback(operation.callback, operation.scope || me, [records, operation, successful]);
1448     },
1449     
1450     /**
1451      * Caches the records in the prefetch and stripes them with their server-side
1452      * index.
1453      * @private
1454      * @param {Array} records The records to cache
1455      * @param {Ext.data.Operation} The associated operation
1456      */
1457     cacheRecords: function(records, operation) {
1458         var me     = this,
1459             i      = 0,
1460             length = records.length,
1461             start  = operation ? operation.start : 0;
1462         
1463         if (!Ext.isDefined(me.totalCount)) {
1464             me.totalCount = records.length;
1465             me.fireEvent('totalcountchange', me.totalCount);
1466         }
1467         
1468         for (; i < length; i++) {
1469             // this is the true index, not the viewIndex
1470             records[i].index = start + i;
1471         }
1472         
1473         me.prefetchData.addAll(records);
1474         if (me.purgePageCount) {
1475             me.purgeRecords();
1476         }
1477         
1478     },
1479     
1480     
1481     /**
1482      * Purge the least recently used records in the prefetch if the purgeCount
1483      * has been exceeded.
1484      */
1485     purgeRecords: function() {
1486         var me = this,
1487             prefetchCount = me.prefetchData.getCount(),
1488             purgeCount = me.purgePageCount * me.pageSize,
1489             numRecordsToPurge = prefetchCount - purgeCount - 1,
1490             i = 0;
1491
1492         for (; i <= numRecordsToPurge; i++) {
1493             me.prefetchData.removeAt(0);
1494         }
1495     },
1496     
1497     /**
1498      * Determines if the range has already been satisfied in the prefetchData.
1499      * @private
1500      * @param {Number} start The start index
1501      * @param {Number} end The end index in the range
1502      */
1503     rangeSatisfied: function(start, end) {
1504         var me = this,
1505             i = start,
1506             satisfied = true;
1507
1508         for (; i < end; i++) {
1509             if (!me.prefetchData.getByKey(i)) {
1510                 satisfied = false;
1511                 //<debug>
1512                 if (end - i > me.pageSize) {
1513                     Ext.Error.raise("A single page prefetch could never satisfy this request.");
1514                 }
1515                 //</debug>
1516                 break;
1517             }
1518         }
1519         return satisfied;
1520     },
1521     
1522     /**
1523      * Determines the page from a record index
1524      * @param {Number} index The record index
1525      * @return {Number} The page the record belongs to
1526      */
1527     getPageFromRecordIndex: function(index) {
1528         return Math.floor(index / this.pageSize) + 1;
1529     },
1530     
1531     /**
1532      * Handles a guaranteed range being loaded
1533      * @private
1534      */
1535     onGuaranteedRange: function() {
1536         var me = this,
1537             totalCount = me.getTotalCount(),
1538             start = me.requestStart,
1539             end = ((totalCount - 1) < me.requestEnd) ? totalCount - 1 : me.requestEnd,
1540             range = [],
1541             record,
1542             i = start;
1543             
1544         //<debug>
1545         if (start > end) {
1546             Ext.Error.raise("Start (" + start + ") was greater than end (" + end + ")");
1547         }
1548         //</debug>
1549         
1550         if (start !== me.guaranteedStart && end !== me.guaranteedEnd) {
1551             me.guaranteedStart = start;
1552             me.guaranteedEnd = end;
1553             
1554             for (; i <= end; i++) {
1555                 record = me.prefetchData.getByKey(i);
1556                 //<debug>
1557                 if (!record) {
1558                     Ext.Error.raise("Record was not found and store said it was guaranteed");
1559                 }
1560                 //</debug>
1561                 range.push(record);
1562             }
1563             me.fireEvent('guaranteedrange', range, start, end);
1564             if (me.cb) {
1565                 me.cb.call(me.scope || me, range);
1566             }
1567         }
1568         
1569         me.unmask();
1570     },
1571     
1572     // hack to support loadmask
1573     mask: function() {
1574         this.masked = true;
1575         this.fireEvent('beforeload');
1576     },
1577     
1578     // hack to support loadmask
1579     unmask: function() {
1580         if (this.masked) {
1581             this.fireEvent('load');
1582         }
1583     },
1584     
1585     /**
1586      * Returns the number of pending requests out.
1587      */
1588     hasPendingRequests: function() {
1589         return this.pendingRequests.length;
1590     },
1591     
1592     
1593     // wait until all requests finish, until guaranteeing the range.
1594     onWaitForGuarantee: function() {
1595         if (!this.hasPendingRequests()) {
1596             this.onGuaranteedRange();
1597         }
1598     },
1599     
1600     /**
1601      * Guarantee a specific range, this will load the store with a range (that
1602      * must be the pageSize or smaller) and take care of any loading that may
1603      * be necessary.
1604      */
1605     guaranteeRange: function(start, end, cb, scope) {
1606         //<debug>
1607         if (start && end) {
1608             if (end - start > this.pageSize) {
1609                 Ext.Error.raise({
1610                     start: start,
1611                     end: end,
1612                     pageSize: this.pageSize,
1613                     msg: "Requested a bigger range than the specified pageSize"
1614                 });
1615             }
1616         }
1617         //</debug>
1618         
1619         end = (end > this.totalCount) ? this.totalCount - 1 : end;
1620         
1621         var me = this,
1622             i = start,
1623             prefetchData = me.prefetchData,
1624             range = [],
1625             startLoaded = !!prefetchData.getByKey(start),
1626             endLoaded = !!prefetchData.getByKey(end),
1627             startPage = me.getPageFromRecordIndex(start),
1628             endPage = me.getPageFromRecordIndex(end);
1629             
1630         me.cb = cb;
1631         me.scope = scope;
1632
1633         me.requestStart = start;
1634         me.requestEnd = end;
1635         // neither beginning or end are loaded
1636         if (!startLoaded || !endLoaded) {
1637             // same page, lets load it
1638             if (startPage === endPage) {
1639                 me.mask();
1640                 me.prefetchPage(startPage, {
1641                     //blocking: true,
1642                     callback: me.onWaitForGuarantee,
1643                     scope: me
1644                 });
1645             // need to load two pages
1646             } else {
1647                 me.mask();
1648                 me.prefetchPage(startPage, {
1649                     //blocking: true,
1650                     callback: me.onWaitForGuarantee,
1651                     scope: me
1652                 });
1653                 me.prefetchPage(endPage, {
1654                     //blocking: true,
1655                     callback: me.onWaitForGuarantee,
1656                     scope: me
1657                 });
1658             }
1659         // Request was already satisfied via the prefetch
1660         } else {
1661             me.onGuaranteedRange();
1662         }
1663     },
1664     
1665     // because prefetchData is stored by index
1666     // this invalidates all of the prefetchedData
1667     sort: function() {
1668         var me = this,
1669             prefetchData = me.prefetchData,
1670             sorters,
1671             start,
1672             end,
1673             range;
1674             
1675         if (me.buffered) {
1676             if (me.remoteSort) {
1677                 prefetchData.clear();
1678                 me.callParent(arguments);
1679             } else {
1680                 sorters = me.getSorters();
1681                 start = me.guaranteedStart;
1682                 end = me.guaranteedEnd;
1683                 
1684                 if (sorters.length) {
1685                     prefetchData.sort(sorters);
1686                     range = prefetchData.getRange();
1687                     prefetchData.clear();
1688                     me.cacheRecords(range);
1689                     delete me.guaranteedStart;
1690                     delete me.guaranteedEnd;
1691                     me.guaranteeRange(start, end);
1692                 }
1693                 me.callParent(arguments);
1694             }
1695         } else {
1696             me.callParent(arguments);
1697         }
1698     },
1699
1700     // overriden to provide striping of the indexes as sorting occurs.
1701     // this cannot be done inside of sort because datachanged has already
1702     // fired and will trigger a repaint of the bound view.
1703     doSort: function(sorterFn) {
1704         var me = this;
1705         if (me.remoteSort) {
1706             //the load function will pick up the new sorters and request the sorted data from the proxy
1707             me.load();
1708         } else {
1709             me.data.sortBy(sorterFn);
1710             if (!me.buffered) {
1711                 var range = me.getRange(),
1712                     ln = range.length,
1713                     i  = 0;
1714                 for (; i < ln; i++) {
1715                     range[i].index = i;
1716                 }
1717             }
1718             me.fireEvent('datachanged', me);
1719         }
1720     },
1721     
1722     /**
1723      * Finds the index of the first matching Record in this store by a specific field value.
1724      * @param {String} fieldName The name of the Record field to test.
1725      * @param {String/RegExp} value Either a string that the field value
1726      * should begin with, or a RegExp to test against the field.
1727      * @param {Number} startIndex (optional) The index to start searching at
1728      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1729      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1730      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
1731      * @return {Number} The matched index or -1
1732      */
1733     find: function(property, value, start, anyMatch, caseSensitive, exactMatch) {
1734         var fn = this.createFilterFn(property, value, anyMatch, caseSensitive, exactMatch);
1735         return fn ? this.data.findIndexBy(fn, null, start) : -1;
1736     },
1737
1738     /**
1739      * Finds the first matching Record in this store by a specific field value.
1740      * @param {String} fieldName The name of the Record field to test.
1741      * @param {String/RegExp} value Either a string that the field value
1742      * should begin with, or a RegExp to test against the field.
1743      * @param {Number} startIndex (optional) The index to start searching at
1744      * @param {Boolean} anyMatch (optional) True to match any part of the string, not just the beginning
1745      * @param {Boolean} caseSensitive (optional) True for case sensitive comparison
1746      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
1747      * @return {Ext.data.Model} The matched record or null
1748      */
1749     findRecord: function() {
1750         var me = this,
1751             index = me.find.apply(me, arguments);
1752         return index !== -1 ? me.getAt(index) : null;
1753     },
1754
1755     /**
1756      * @private
1757      * Returns a filter function used to test a the given property's value. Defers most of the work to
1758      * Ext.util.MixedCollection's createValueMatcher function
1759      * @param {String} property The property to create the filter function for
1760      * @param {String/RegExp} value The string/regex to compare the property value to
1761      * @param {Boolean} anyMatch True if we don't care if the filter value is not the full value (defaults to false)
1762      * @param {Boolean} caseSensitive True to create a case-sensitive regex (defaults to false)
1763      * @param {Boolean} exactMatch True to force exact match (^ and $ characters added to the regex). Defaults to false.
1764      * Ignored if anyMatch is true.
1765      */
1766     createFilterFn: function(property, value, anyMatch, caseSensitive, exactMatch) {
1767         if (Ext.isEmpty(value)) {
1768             return false;
1769         }
1770         value = this.data.createValueMatcher(value, anyMatch, caseSensitive, exactMatch);
1771         return function(r) {
1772             return value.test(r.data[property]);
1773         };
1774     },
1775
1776     /**
1777      * Finds the index of the first matching Record in this store by a specific field value.
1778      * @param {String} fieldName The name of the Record field to test.
1779      * @param {Mixed} value The value to match the field against.
1780      * @param {Number} startIndex (optional) The index to start searching at
1781      * @return {Number} The matched index or -1
1782      */
1783     findExact: function(property, value, start) {
1784         return this.data.findIndexBy(function(rec) {
1785             return rec.get(property) === value;
1786         },
1787         this, start);
1788     },
1789
1790     /**
1791      * Find the index of the first matching Record in this Store by a function.
1792      * If the function returns <tt>true</tt> it is considered a match.
1793      * @param {Function} fn The function to be called. It will be passed the following parameters:<ul>
1794      * <li><b>record</b> : Ext.data.Model<p class="sub-desc">The {@link Ext.data.Model record}
1795      * to test for filtering. Access field values using {@link Ext.data.Model#get}.</p></li>
1796      * <li><b>id</b> : Object<p class="sub-desc">The ID of the Record passed.</p></li>
1797      * </ul>
1798      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to this Store.
1799      * @param {Number} startIndex (optional) The index to start searching at
1800      * @return {Number} The matched index or -1
1801      */
1802     findBy: function(fn, scope, start) {
1803         return this.data.findIndexBy(fn, scope, start);
1804     },
1805
1806     /**
1807      * Collects unique values for a particular dataIndex from this store.
1808      * @param {String} dataIndex The property to collect
1809      * @param {Boolean} allowNull (optional) Pass true to allow null, undefined or empty string values
1810      * @param {Boolean} bypassFilter (optional) Pass true to collect from all records, even ones which are filtered
1811      * @return {Array} An array of the unique values
1812      **/
1813     collect: function(dataIndex, allowNull, bypassFilter) {
1814         var me = this,
1815             data = (bypassFilter === true && me.snapshot) ? me.snapshot: me.data;
1816
1817         return data.collect(dataIndex, 'data', allowNull);
1818     },
1819
1820     /**
1821      * Gets the number of cached records.
1822      * <p>If using paging, this may not be the total size of the dataset. If the data object
1823      * used by the Reader contains the dataset size, then the {@link #getTotalCount} function returns
1824      * the dataset size.  <b>Note</b>: see the Important note in {@link #load}.</p>
1825      * @return {Number} The number of Records in the Store's cache.
1826      */
1827     getCount: function() {
1828         return this.data.length || 0;
1829     },
1830
1831     /**
1832      * Returns the total number of {@link Ext.data.Model Model} instances that the {@link Ext.data.proxy.Proxy Proxy}
1833      * indicates exist. This will usually differ from {@link #getCount} when using paging - getCount returns the
1834      * number of records loaded into the Store at the moment, getTotalCount returns the number of records that
1835      * could be loaded into the Store if the Store contained all data
1836      * @return {Number} The total number of Model instances available via the Proxy
1837      */
1838     getTotalCount: function() {
1839         return this.totalCount;
1840     },
1841
1842     /**
1843      * Get the Record at the specified index.
1844      * @param {Number} index The index of the Record to find.
1845      * @return {Ext.data.Model} The Record at the passed index. Returns undefined if not found.
1846      */
1847     getAt: function(index) {
1848         return this.data.getAt(index);
1849     },
1850
1851     /**
1852      * Returns a range of Records between specified indices.
1853      * @param {Number} startIndex (optional) The starting index (defaults to 0)
1854      * @param {Number} endIndex (optional) The ending index (defaults to the last Record in the Store)
1855      * @return {Ext.data.Model[]} An array of Records
1856      */
1857     getRange: function(start, end) {
1858         return this.data.getRange(start, end);
1859     },
1860
1861     /**
1862      * Get the Record with the specified id.
1863      * @param {String} id The id of the Record to find.
1864      * @return {Ext.data.Model} The Record with the passed id. Returns undefined if not found.
1865      */
1866     getById: function(id) {
1867         return (this.snapshot || this.data).findBy(function(record) {
1868             return record.getId() === id;
1869         });
1870     },
1871
1872     /**
1873      * Get the index within the cache of the passed Record.
1874      * @param {Ext.data.Model} record The Ext.data.Model object to find.
1875      * @return {Number} The index of the passed Record. Returns -1 if not found.
1876      */
1877     indexOf: function(record) {
1878         return this.data.indexOf(record);
1879     },
1880
1881
1882     /**
1883      * Get the index within the entire dataset. From 0 to the totalCount.
1884      * @param {Ext.data.Model} record The Ext.data.Model object to find.
1885      * @return {Number} The index of the passed Record. Returns -1 if not found.
1886      */
1887     indexOfTotal: function(record) {
1888         return record.index || this.indexOf(record);
1889     },
1890
1891     /**
1892      * Get the index within the cache of the Record with the passed id.
1893      * @param {String} id The id of the Record to find.
1894      * @return {Number} The index of the Record. Returns -1 if not found.
1895      */
1896     indexOfId: function(id) {
1897         return this.data.indexOfKey(id);
1898     },
1899         
1900     /**
1901      * Remove all items from the store.
1902      * @param {Boolean} silent Prevent the `clear` event from being fired.
1903      */
1904     removeAll: function(silent) {
1905         var me = this;
1906
1907         me.clearData();
1908         if (me.snapshot) {
1909             me.snapshot.clear();
1910         }
1911         if (silent !== true) {
1912             me.fireEvent('clear', me);
1913         }
1914     },
1915
1916     /*
1917      * Aggregation methods
1918      */
1919
1920     /**
1921      * Convenience function for getting the first model instance in the store
1922      * @param {Boolean} grouped (Optional) True to perform the operation for each group
1923      * in the store. The value returned will be an object literal with the key being the group
1924      * name and the first record being the value. The grouped parameter is only honored if
1925      * the store has a groupField.
1926      * @return {Ext.data.Model/undefined} The first model instance in the store, or undefined
1927      */
1928     first: function(grouped) {
1929         var me = this;
1930
1931         if (grouped && me.isGrouped()) {
1932             return me.aggregate(function(records) {
1933                 return records.length ? records[0] : undefined;
1934             }, me, true);
1935         } else {
1936             return me.data.first();
1937         }
1938     },
1939
1940     /**
1941      * Convenience function for getting the last model instance in the store
1942      * @param {Boolean} grouped (Optional) True to perform the operation for each group
1943      * in the store. The value returned will be an object literal with the key being the group
1944      * name and the last record being the value. The grouped parameter is only honored if
1945      * the store has a groupField.
1946      * @return {Ext.data.Model/undefined} The last model instance in the store, or undefined
1947      */
1948     last: function(grouped) {
1949         var me = this;
1950
1951         if (grouped && me.isGrouped()) {
1952             return me.aggregate(function(records) {
1953                 var len = records.length;
1954                 return len ? records[len - 1] : undefined;
1955             }, me, true);
1956         } else {
1957             return me.data.last();
1958         }
1959     },
1960
1961     /**
1962      * Sums the value of <tt>property</tt> for each {@link Ext.data.Model record} between <tt>start</tt>
1963      * and <tt>end</tt> and returns the result.
1964      * @param {String} field A field in each record
1965      * @param {Boolean} grouped (Optional) True to perform the operation for each group
1966      * in the store. The value returned will be an object literal with the key being the group
1967      * name and the sum for that group being the value. The grouped parameter is only honored if
1968      * the store has a groupField.
1969      * @return {Number} The sum
1970      */
1971     sum: function(field, grouped) {
1972         var me = this;
1973
1974         if (grouped && me.isGrouped()) {
1975             return me.aggregate(me.getSum, me, true, [field]);
1976         } else {
1977             return me.getSum(me.data.items, field);
1978         }
1979     },
1980
1981     // @private, see sum
1982     getSum: function(records, field) {
1983         var total = 0,
1984             i = 0,
1985             len = records.length;
1986
1987         for (; i < len; ++i) {
1988             total += records[i].get(field);
1989         }
1990
1991         return total;
1992     },
1993
1994     /**
1995      * Gets the count of items in the store.
1996      * @param {Boolean} grouped (Optional) True to perform the operation for each group
1997      * in the store. The value returned will be an object literal with the key being the group
1998      * name and the count for each group being the value. The grouped parameter is only honored if
1999      * the store has a groupField.
2000      * @return {Number} the count
2001      */
2002     count: function(grouped) {
2003         var me = this;
2004
2005         if (grouped && me.isGrouped()) {
2006             return me.aggregate(function(records) {
2007                 return records.length;
2008             }, me, true);
2009         } else {
2010             return me.getCount();
2011         }
2012     },
2013
2014     /**
2015      * Gets the minimum value in the store.
2016      * @param {String} field The field in each record
2017      * @param {Boolean} grouped (Optional) True to perform the operation for each group
2018      * in the store. The value returned will be an object literal with the key being the group
2019      * name and the minimum in the group being the value. The grouped parameter is only honored if
2020      * the store has a groupField.
2021      * @return {Mixed/undefined} The minimum value, if no items exist, undefined.
2022      */
2023     min: function(field, grouped) {
2024         var me = this;
2025
2026         if (grouped && me.isGrouped()) {
2027             return me.aggregate(me.getMin, me, true, [field]);
2028         } else {
2029             return me.getMin(me.data.items, field);
2030         }
2031     },
2032
2033     // @private, see min
2034     getMin: function(records, field){
2035         var i = 1,
2036             len = records.length,
2037             value, min;
2038
2039         if (len > 0) {
2040             min = records[0].get(field);
2041         }
2042
2043         for (; i < len; ++i) {
2044             value = records[i].get(field);
2045             if (value < min) {
2046                 min = value;
2047             }
2048         }
2049         return min;
2050     },
2051
2052     /**
2053      * Gets the maximum value in the store.
2054      * @param {String} field The field in each record
2055      * @param {Boolean} grouped (Optional) True to perform the operation for each group
2056      * in the store. The value returned will be an object literal with the key being the group
2057      * name and the maximum in the group being the value. The grouped parameter is only honored if
2058      * the store has a groupField.
2059      * @return {Mixed/undefined} The maximum value, if no items exist, undefined.
2060      */
2061     max: function(field, grouped) {
2062         var me = this;
2063
2064         if (grouped && me.isGrouped()) {
2065             return me.aggregate(me.getMax, me, true, [field]);
2066         } else {
2067             return me.getMax(me.data.items, field);
2068         }
2069     },
2070
2071     // @private, see max
2072     getMax: function(records, field) {
2073         var i = 1,
2074             len = records.length,
2075             value,
2076             max;
2077
2078         if (len > 0) {
2079             max = records[0].get(field);
2080         }
2081
2082         for (; i < len; ++i) {
2083             value = records[i].get(field);
2084             if (value > max) {
2085                 max = value;
2086             }
2087         }
2088         return max;
2089     },
2090
2091     /**
2092      * Gets the average value in the store.
2093      * @param {String} field The field in each record
2094      * @param {Boolean} grouped (Optional) True to perform the operation for each group
2095      * in the store. The value returned will be an object literal with the key being the group
2096      * name and the group average being the value. The grouped parameter is only honored if
2097      * the store has a groupField.
2098      * @return {Mixed/undefined} The average value, if no items exist, 0.
2099      */
2100     average: function(field, grouped) {
2101         var me = this;
2102         if (grouped && me.isGrouped()) {
2103             return me.aggregate(me.getAverage, me, true, [field]);
2104         } else {
2105             return me.getAverage(me.data.items, field);
2106         }
2107     },
2108
2109     // @private, see average
2110     getAverage: function(records, field) {
2111         var i = 0,
2112             len = records.length,
2113             sum = 0;
2114
2115         if (records.length > 0) {
2116             for (; i < len; ++i) {
2117                 sum += records[i].get(field);
2118             }
2119             return sum / len;
2120         }
2121         return 0;
2122     },
2123
2124     /**
2125      * Runs the aggregate function for all the records in the store.
2126      * @param {Function} fn The function to execute. The function is called with a single parameter,
2127      * an array of records for that group.
2128      * @param {Object} scope (optional) The scope to execute the function in. Defaults to the store.
2129      * @param {Boolean} grouped (Optional) True to perform the operation for each group
2130      * in the store. The value returned will be an object literal with the key being the group
2131      * name and the group average being the value. The grouped parameter is only honored if
2132      * the store has a groupField.
2133      * @param {Array} args (optional) Any arguments to append to the function call
2134      * @return {Object} An object literal with the group names and their appropriate values.
2135      */
2136     aggregate: function(fn, scope, grouped, args) {
2137         args = args || [];
2138         if (grouped && this.isGrouped()) {
2139             var groups = this.getGroups(),
2140                 i = 0,
2141                 len = groups.length,
2142                 out = {},
2143                 group;
2144
2145             for (; i < len; ++i) {
2146                 group = groups[i];
2147                 out[group.name] = fn.apply(scope || this, [group.children].concat(args));
2148             }
2149             return out;
2150         } else {
2151             return fn.apply(scope || this, [this.data.items].concat(args));
2152         }
2153     }
2154 });