]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
14181062f1b719b5927655928e0af3b4623567c8
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / grid.js
1 angular.module('egGridMod', 
2     ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
3
4 .directive('egGrid', function() {
5     return {
6         restrict : 'AE',
7         transclude : true,
8         scope : {
9
10             // IDL class hint (e.g. "aou")
11             idlClass : '@',
12
13             // default page size
14             pageSize : '@',
15
16             // if true, grid columns are derived from all non-virtual
17             // fields on the base idlClass
18             autoFields : '@',
19
20             // grid preferences will be stored / retrieved with this key
21             persistKey : '@',
22
23             // field whose value is unique and may be used for item
24             // reference / lookup.  This will usually be someting like
25             // "id".  This is not needed when using autoFields, since we
26             // can determine the primary key directly from the IDL.
27             idField : '@',
28
29             // Reference to externally provided egGridDataProvider
30             itemsProvider : '=',
31
32             // comma-separated list of supported or disabled grid features
33             // supported features:
34             //  -display : columns are hidden by default
35             //  -sort    : columns are unsortable by default 
36             //  -multisort : sort priorities config disabled by default
37             //  -multiselect : only one row at a time can be selected;
38             //                 choosing this also disables the checkbox
39             //                 column
40             features : '@',
41
42             // optional primary grid label
43             mainLabel : '@',
44
45             // if true, use the IDL class label as the mainLabel
46             autoLabel : '=', 
47
48             // optional context menu label
49             menuLabel : '@',
50
51             // Hash of control functions.
52             //
53             //  These functions are defined by the calling scope and 
54             //  invoked as-is by the grid w/ the specified parameters.
55             //
56             //  itemRetrieved     : function(item) {}
57             //  allItemsRetrieved : function() {}
58             //
59             //  ---
60             //  If defined, the grid will watch the return value from
61             //  the function defined at watchQuery on each digest and 
62             //  re-draw the grid when query changes occur.
63             //
64             //  watchQuery : function() { /* return grid query */ }
65             //
66             //  ---------------
67             //  These functions are defined by the grid and thus
68             //  replace any values defined for these attributes from the
69             //  calling scope.
70             //
71             //  activateItem  : function(item) {}
72             //  allItems      : function(allItems) {}
73             //  selectedItems : function(selected) {}
74             //  selectItems   : function(ids) {}
75             //  setQuery      : function(queryStruct) {} // causes reload
76             //  setSort       : function(sortSturct) {} // causes reload
77             gridControls : '=',
78         },
79
80         // TODO: avoid hard-coded url
81         templateUrl : '/eg/staff/share/t_autogrid', 
82
83         link : function(scope, element, attrs) {     
84             // link() is called after page compilation, which means our
85             // eg-grid-field's have been parsed and loaded.  Now it's 
86             // safe to perform our initial page load.
87
88             // load auto fields after eg-grid-field's so they are not clobbered
89             scope.handleAutoFields();
90             scope.collect();
91
92             scope.grid_element = element;
93             $(element)
94                 .find('.eg-grid-content-body')
95                 .bind('contextmenu', scope.showActionContextMenu);
96         },
97
98         controller : [
99                     '$scope','$q','egCore','egGridFlatDataProvider','$location',
100                     'egGridColumnsProvider','$filter','$window','$sce','$timeout',
101             function($scope,  $q , egCore,  egGridFlatDataProvider , $location,
102                      egGridColumnsProvider , $filter , $window , $sce , $timeout) {
103
104             var grid = this;
105
106             grid.init = function() {
107                 grid.offset = 0;
108                 $scope.items = [];
109                 $scope.showGridConf = false;
110                 grid.totalCount = -1;
111                 $scope.selected = {};
112                 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
113                 $scope.menuItems = []; // global actions
114
115                 // remove some unneeded values from the scope to reduce bloat
116
117                 grid.idlClass = $scope.idlClass;
118                 delete $scope.idlClass;
119
120                 grid.persistKey = $scope.persistKey;
121                 delete $scope.persistKey;
122
123                 var stored_limit = 0;
124                 if (grid.persistKey) {
125                     var stored_limit = Number(
126                         egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
127                     );
128                 }
129                 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
130
131                 grid.indexField = $scope.idField;
132                 delete $scope.idField;
133
134                 grid.dataProvider = $scope.itemsProvider;
135
136                 var features = ($scope.features) ? 
137                     $scope.features.split(',') : [];
138                 delete $scope.features;
139
140                 if (!grid.indexField && grid.idlClass)
141                     grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
142
143                 grid.columnsProvider = egGridColumnsProvider.instance({
144                     idlClass : grid.idlClass,
145                     defaultToHidden : (features.indexOf('-display') > -1),
146                     defaultToNoSort : (features.indexOf('-sort') > -1),
147                     defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
148                 });
149                 $scope.canMultiSelect = (features.indexOf('-multiselect') == -1);
150
151                 $scope.handleAutoFields = function() {
152                     if ($scope.autoFields) {
153                         if (grid.autoLabel) {
154                             $scope.mainLabel = 
155                                 egCore.idl.classes[grid.idlClass].label;
156                         }
157                         grid.columnsProvider.compileAutoColumns();
158                         delete $scope.autoFields;
159                     }
160                 }
161    
162                 if (!grid.dataProvider) {
163                     // no provider, um, provided.
164                     // Use a flat data provider
165
166                     grid.selfManagedData = true;
167                     grid.dataProvider = egGridFlatDataProvider.instance({
168                         indexField : grid.indexField,
169                         idlClass : grid.idlClass,
170                         columnsProvider : grid.columnsProvider,
171                         query : $scope.query
172                     });
173                 }
174
175                 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
176                 $scope.indexValue = function(item) {
177                     return grid.indexValue(item)
178                 };
179
180                 grid.applyControlFunctions();
181
182                 grid.loadConfig().then(function() { 
183                     // link columns to scope after loadConfig(), since it
184                     // replaces the columns array.
185                     $scope.columns = grid.columnsProvider.columns;
186                 });
187
188                 // NOTE: grid.collect() is first called from link(), not here.
189             }
190
191             // link our control functions into the gridControls 
192             // scope object so the caller can access them.
193             grid.applyControlFunctions = function() {
194
195                 // we use some of these controls internally, so sett
196                 // them up even if the caller doesn't request them.
197                 var controls = $scope.gridControls || {};
198
199                 // link in the control functions
200                 controls.selectedItems = function() {
201                     return grid.getSelectedItems()
202                 }
203
204                 controls.allItems = function() {
205                     return $scope.items;
206                 }
207
208                 controls.selectItems = function(ids) {
209                     if (!ids) return;
210                     $scope.selected = {};
211                     angular.forEach(ids, function(i) {
212                         $scope.selected[''+i] = true;
213                     });
214                 }
215
216                 // if the caller provided a functional setQuery,
217                 // extract the value before replacing it
218                 if (controls.setQuery) {
219                     grid.dataProvider.query = 
220                         controls.setQuery();
221                 }
222
223                 controls.setQuery = function(query) {
224                     grid.dataProvider.query = query;
225                     controls.refresh();
226                 }
227
228                 if (controls.watchQuery) {
229                     // capture the initial query value
230                     grid.dataProvider.query = controls.watchQuery();
231
232                     // watch for changes
233                     $scope.gridWatchQuery = controls.watchQuery;
234                     $scope.$watch('gridWatchQuery()', function(newv) {
235                         controls.setQuery(newv);
236                     }, true);
237                 }
238
239                 // if the caller provided a functional setSort
240                 // extract the value before replacing it
241                 grid.dataProvider.sort = 
242                     controls.setSort ?  controls.setSort() : [];
243
244                 controls.setSort = function(sort) {
245                     controls.refresh();
246                 }
247
248                 controls.refresh = function(noReset) {
249                     if (!noReset) grid.offset = 0;
250                     grid.collect();
251                 }
252
253                 controls.setLimit = function(limit,forget) {
254                     if (!forget && grid.persistKey)
255                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
256                     grid.limit = limit;
257                 }
258                 controls.getLimit = function() {
259                     return grid.limit;
260                 }
261                 controls.setOffset = function(offset) {
262                     grid.offset = offset;
263                 }
264                 controls.getOffset = function() {
265                     return grid.offset;
266                 }
267
268                 grid.dataProvider.refresh = controls.refresh;
269                 grid.controls = controls;
270             }
271
272             // If a menu item provides its own HTML template, translate it,
273             // using the menu item for the template scope.
274             // note: $sce is required to avoid security restrictions and
275             // is OK here, since the template comes directly from a
276             // local HTML template (not user input).
277             $scope.translateMenuItemTemplate = function(item) {
278                 var html = egCore.strings.$replace(item.template, {item : item});
279                 return $sce.trustAsHtml(html);
280             }
281
282             // add a new (global) grid menu item
283             grid.addMenuItem = function(item) {
284                 $scope.menuItems.push(item);
285                 var handler = item.handler;
286                 item.handler = function() {
287                     $scope.gridMenuIsOpen = false; // close menu
288                     if (handler) {
289                         handler(item, 
290                             item.handlerData, grid.getSelectedItems());
291                     }
292                 }
293             }
294
295             // add a selected-items action
296             grid.addAction = function(act) {
297                 var done = false;
298                 $scope.actionGroups.forEach(function(g){
299                     if (g.label === act.group) {
300                         g.actions.push(act);
301                         done = true;
302                     }
303                 });
304                 if (!done) {
305                     $scope.actionGroups.push({
306                         label : act.group,
307                         actions : [ act ]
308                     });
309                 }
310             }
311
312             // remove the stored column configuration preferenc, then recover 
313             // the column visibility information from the initial page load.
314             $scope.resetColumns = function() {
315                 $scope.gridColumnPickerIsOpen = false;
316                 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
317                 .then(function() {
318                     grid.columnsProvider.reset(); 
319                     if (grid.selfManagedData) grid.collect();
320                 });
321             }
322
323             $scope.showAllColumns = function() {
324                 $scope.gridColumnPickerIsOpen = false;
325                 grid.columnsProvider.showAllColumns();
326                 if (grid.selfManagedData) grid.collect();
327             }
328
329             $scope.hideAllColumns = function() {
330                 $scope.gridColumnPickerIsOpen = false;
331                 grid.columnsProvider.hideAllColumns();
332                 // note: no need to fetch new data if no columns are visible
333             }
334
335             $scope.toggleColumnVisibility = function(col) {
336                 $scope.gridColumnPickerIsOpen = false;
337                 col.visible = !col.visible;
338
339                 // egGridFlatDataProvider only retrieves data to be
340                 // displayed.  When column visibility changes, it's
341                 // necessary to fetch the newly visible column data.
342                 if (grid.selfManagedData) grid.collect();
343             }
344
345             // save the columns configuration (position, sort, width) to
346             // eg.grid.<persist-key>
347             $scope.saveConfig = function() {
348                 $scope.gridColumnPickerIsOpen = false;
349
350                 if (!grid.persistKey) {
351                     console.warn(
352                         "Cannot save settings without a grid persist-key");
353                     return;
354                 }
355
356                 // only store information about visible columns.
357                 var conf = grid.columnsProvider.columns.filter(
358                     function(col) {return Boolean(col.visible) });
359
360                 // now scrunch the data down to just the needed info
361                 conf = conf.map(function(col) {
362                     var c = {name : col.name}
363                     // Apart from the name, only store non-default values.
364                     // No need to store col.visible, since that's implicit
365                     if (col.align != 'left') c.align = col.align;
366                     if (col.flex != 2) c.flex = col.flex;
367                     if (Number(col.sort)) c.sort = Number(c.sort);
368                     return c;
369                 });
370
371                 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
372                 .then(function() { 
373                     // Save operation performed from the grid configuration UI.
374                     // Hide the configuration UI and re-draw w/ sort applied
375                     if ($scope.showGridConf) 
376                         $scope.toggleConfDisplay();
377                 });
378             }
379
380             // load the columns configuration (position, sort, width) from
381             // eg.grid.<persist-key> and apply the loaded settings to the
382             // columns on our columnsProvider
383             grid.loadConfig = function() {
384                 if (!grid.persistKey) return $q.when();
385
386                 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
387                 .then(function(conf) {
388                     if (!conf) return;
389
390                     var columns = grid.columnsProvider.columns;
391                     var new_cols = [];
392
393                     angular.forEach(conf, function(col) {
394                         var grid_col = columns.filter(
395                             function(c) {return c.name == col.name})[0];
396
397                         if (!grid_col) {
398                             // saved column does not match a column in the 
399                             // current grid.  skip it.
400                             return;
401                         }
402
403                         grid_col.align = col.align || 'left';
404                         grid_col.flex = col.flex || 2;
405                         grid_col.sort = col.sort || 0;
406                         // all saved columns are assumed to be true
407                         grid_col.visible = true;
408                         new_cols.push(grid_col);
409                     });
410
411                     // columns which are not expressed within the saved 
412                     // configuration are marked as non-visible and 
413                     // appended to the end of the new list of columns.
414                     angular.forEach(columns, function(col) {
415                         var found = conf.filter(
416                             function(c) {return (c.name == col.name)})[0];
417                         if (!found) {
418                             col.visible = false;
419                             new_cols.push(col);
420                         }
421                     });
422
423                     grid.columnsProvider.columns = new_cols;
424                     grid.compileSort();
425                 });
426             }
427
428             $scope.onContextMenu = function($event) {
429                 var col = angular.element($event.target).attr('column');
430                 console.log('selected column ' + col);
431             }
432
433             $scope.page = function() {
434                 return (grid.offset / grid.limit) + 1;
435             }
436
437             $scope.goToPage = function(page) {
438                 page = Number(page);
439                 if (angular.isNumber(page) && page > 0) {
440                     grid.offset = (page - 1) * grid.limit;
441                     grid.collect();
442                 }
443             }
444
445             $scope.offset = function(o) {
446                 if (angular.isNumber(o))
447                     grid.offset = o;
448                 return grid.offset 
449             }
450
451             $scope.limit = function(l) { 
452                 if (angular.isNumber(l)) {
453                     if (grid.persistKey)
454                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
455                     grid.limit = l;
456                 }
457                 return grid.limit 
458             }
459
460             $scope.onFirstPage = function() {
461                 return grid.offset == 0;
462             }
463
464             $scope.hasNextPage = function() {
465                 // we have less data than requested, there must
466                 // not be any more pages
467                 if (grid.count() < grid.limit) return false;
468
469                 // if the total count is not known, assume that a full
470                 // page of data implies more pages are available.
471                 if (grid.totalCount == -1) return true;
472
473                 // we have a full page of data, but is there more?
474                 return grid.totalCount > (grid.offset + grid.count());
475             }
476
477             $scope.incrementPage = function() {
478                 grid.offset += grid.limit;
479                 grid.collect();
480             }
481
482             $scope.decrementPage = function() {
483                 if (grid.offset < grid.limit) {
484                     grid.offset = 0;
485                 } else {
486                     grid.offset -= grid.limit;
487                 }
488                 grid.collect();
489             }
490
491             // number of items loaded for the current page of results
492             grid.count = function() {
493                 return $scope.items.length;
494             }
495
496             // returns the unique identifier value for the provided item
497             // for internal consistency, indexValue is always coerced 
498             // into a string.
499             grid.indexValue = function(item) {
500                 if (angular.isObject(item)) {
501                     if (item !== null) {
502                         if (angular.isFunction(item[grid.indexField]))
503                             return ''+item[grid.indexField]();
504                         return ''+item[grid.indexField]; // flat data
505                     }
506                 }
507                 // passed a non-object; assume it's an index
508                 return ''+item; 
509             }
510
511             // fires the hide handler function for a context action
512             $scope.actionHide = function(action) {
513                 if (!action.hide) {
514                     return false;
515                 }
516                 return action.hide(action);
517             }
518
519             // fires the disable handler function for a context action
520             $scope.actionDisable = function(action) {
521                 if (!action.disabled) {
522                     return false;
523                 }
524                 return action.disabled(action);
525             }
526
527             // fires the action handler function for a context action
528             $scope.actionLauncher = function(action) {
529                 if (!action.handler) {
530                     console.error(
531                         'No handler specified for "' + action.label + '"');
532                 } else {
533
534                     try {
535                         action.handler(grid.getSelectedItems());
536                     } catch(E) {
537                         console.error('Error executing handler for "' 
538                             + action.label + '" => ' + E + "\n" + E.stack);
539                     }
540
541                     if ($scope.action_context_showing) $scope.hideActionContextMenu();
542                 }
543
544             }
545
546             $scope.hideActionContextMenu = function () {
547                 $($scope.menu_dom).css({
548                     display: '',
549                     width: $scope.action_context_width,
550                     top: $scope.action_context_y,
551                     left: $scope.action_context_x
552                 });
553                 $($scope.action_context_parent).append($scope.menu_dom);
554                 $scope.action_context_oldy = $scope.action_context_oldx = 0;
555                 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
556                 $scope.action_context_showing = false;
557             }
558
559             $scope.action_context_showing = false;
560             $scope.showActionContextMenu = function ($event) {
561
562                 // Have to gather these here, instead of inside link()
563                 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
564                 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
565
566                 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
567                     $event.target.click();
568
569                 if (!$scope.action_context_showing) {
570                     $scope.action_context_width = $($scope.menu_dom).css('width');
571                     $scope.action_context_y = $($scope.menu_dom).css('top');
572                     $scope.action_context_x = $($scope.menu_dom).css('left');
573                     $scope.action_context_showing = true;
574                     $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
575
576                     $('body').append($($scope.menu_dom));
577                     $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
578                 }
579
580                 $($scope.menu_dom).css({
581                     display: 'block',
582                     width: $scope.action_context_width,
583                     top: $event.pageY,
584                     left: $event.pageX
585                 });
586
587                 return false;
588             }
589
590             // returns the list of selected item objects
591             grid.getSelectedItems = function() {
592                 return $scope.items.filter(
593                     function(item) {
594                         return Boolean($scope.selected[grid.indexValue(item)]);
595                     }
596                 );
597             }
598
599             grid.getItemByIndex = function(index) {
600                 for (var i = 0; i < $scope.items.length; i++) {
601                     var item = $scope.items[i];
602                     if (grid.indexValue(item) == index) 
603                         return item;
604                 }
605             }
606
607             // selects one row after deselecting all of the others
608             grid.selectOneItem = function(index) {
609                 $scope.selected = {};
610                 $scope.selected[index] = true;
611             }
612
613             // selects or deselects an item, without affecting the others.
614             // returns true if the item is selected; false if de-selected.
615             grid.toggleSelectOneItem = function(index) {
616                 if ($scope.selected[index]) {
617                     delete $scope.selected[index];
618                     return false;
619                 } else {
620                     return $scope.selected[index] = true;
621                 }
622             }
623
624             grid.selectAllItems = function() {
625                 angular.forEach($scope.items, function(item) {
626                     $scope.selected[grid.indexValue(item)] = true
627                 });
628             }
629
630             $scope.$watch('selectAll', function(newVal) {
631                 if (newVal) {
632                     grid.selectAllItems();
633                 } else {
634                     $scope.selected = {};
635                 }
636             });
637
638             // returns true if item1 appears in the list before item2;
639             // false otherwise.  this is slightly more efficient that
640             // finding the position of each then comparing them.
641             // item1 / item2 may be an item or an item index
642             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
643                 var idx1 = grid.indexValue(itemOrIndex1);
644                 var idx2 = grid.indexValue(itemOrIndex2);
645
646                 // use for() for early exit
647                 for (var i = 0; i < $scope.items.length; i++) {
648                     var idx = grid.indexValue($scope.items[i]);
649                     if (idx == idx1) return true;
650                     if (idx == idx2) return false;
651                 }
652                 return false;
653             }
654
655             // 0-based position of item in the current data set
656             grid.indexOf = function(item) {
657                 var idx = grid.indexValue(item);
658                 for (var i = 0; i < $scope.items.length; i++) {
659                     if (grid.indexValue($scope.items[i]) == idx)
660                         return i;
661                 }
662                 return -1;
663             }
664
665             grid.modifyColumnFlex = function(column, val) {
666                 column.flex += val;
667                 // prevent flex:0;  use hiding instead
668                 if (column.flex < 1)
669                     column.flex = 1;
670             }
671             $scope.modifyColumnFlex = function(col, val) {
672                 grid.modifyColumnFlex(col, val);
673             }
674
675             // handles click, control-click, and shift-click
676             $scope.handleRowClick = function($event, item) {
677                 var index = grid.indexValue(item);
678
679                 var origSelected = Object.keys($scope.selected);
680
681                 if (!$scope.canMultiSelect) {
682                     grid.selectOneItem(index);
683                     grid.lastSelectedItemIndex = index;
684                     return;
685                 }
686
687                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
688                     // control-click
689                     if (grid.toggleSelectOneItem(index)) 
690                         grid.lastSelectedItemIndex = index;
691
692                 } else if ($event.shiftKey) { 
693                     // shift-click
694
695                     if (!grid.lastSelectedItemIndex || 
696                             index == grid.lastSelectedItemIndex) {
697                         grid.selectOneItem(index);
698                         grid.lastSelectedItemIndex = index;
699
700                     } else {
701
702                         var selecting = false;
703                         var ascending = grid.itemComesBefore(
704                             grid.lastSelectedItemIndex, item);
705                         var startPos = 
706                             grid.indexOf(grid.lastSelectedItemIndex);
707
708                         // update to new last-selected
709                         grid.lastSelectedItemIndex = index;
710
711                         // select each row between the last selected and 
712                         // currently selected items
713                         while (true) {
714                             startPos += ascending ? 1 : -1;
715                             var curItem = $scope.items[startPos];
716                             if (!curItem) break;
717                             var curIdx = grid.indexValue(curItem);
718                             $scope.selected[curIdx] = true;
719                             if (curIdx == index) break; // all done
720                         }
721                     }
722                         
723                 } else {
724                     grid.selectOneItem(index);
725                     grid.lastSelectedItemIndex = index;
726                 }
727             }
728
729             // Builds a sort expression from column sort priorities.
730             // called on page load and any time the priorities are modified.
731             grid.compileSort = function() {
732                 var sortList = grid.columnsProvider.columns.filter(
733                     function(col) { return Number(col.sort) != 0 }
734                 ).sort( 
735                     function(a, b) { 
736                         if (Math.abs(a.sort) < Math.abs(b.sort))
737                             return -1;
738                         return 1;
739                     }
740                 );
741
742                 if (sortList.length) {
743                     grid.dataProvider.sort = sortList.map(function(col) {
744                         var blob = {};
745                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
746                         return blob;
747                     });
748                 }
749             }
750
751             // builds a sort expression using a single column, 
752             // toggling between ascending and descending sort.
753             $scope.quickSort = function(col_name) {
754                 var sort = grid.dataProvider.sort;
755                 if (sort && sort.length &&
756                     sort[0] == col_name) {
757                     var blob = {};
758                     blob[col_name] = 'desc';
759                     grid.dataProvider.sort = [blob];
760                 } else {
761                     grid.dataProvider.sort = [col_name];
762                 }
763
764                 grid.offset = 0;
765                 grid.collect();
766             }
767
768             // show / hide the grid configuration row
769             $scope.toggleConfDisplay = function() {
770                 if ($scope.showGridConf) {
771                     $scope.showGridConf = false;
772                     if (grid.columnsProvider.hasSortableColumn()) {
773                         // only refresh the grid if the user has the
774                         // ability to modify the sort priorities.
775                         grid.compileSort();
776                         grid.offset = 0;
777                         grid.collect();
778                     }
779                 } else {
780                     $scope.showGridConf = true;
781                 }
782
783                 $scope.gridColumnPickerIsOpen = false;
784             }
785
786             // called when a dragged column is dropped onto itself
787             // or any other column
788             grid.onColumnDrop = function(target) {
789                 if (angular.isUndefined(target)) return;
790                 if (target == grid.dragColumn) return;
791                 var srcIdx, targetIdx, srcCol;
792                 angular.forEach(grid.columnsProvider.columns,
793                     function(col, idx) {
794                         if (col.name == grid.dragColumn) {
795                             srcIdx = idx;
796                             srcCol = col;
797                         } else if (col.name == target) {
798                             targetIdx = idx;
799                         }
800                     }
801                 );
802
803                 if (srcIdx < targetIdx) targetIdx--;
804
805                 // move src column from old location to new location in 
806                 // the columns array, then force a page refresh
807                 grid.columnsProvider.columns.splice(srcIdx, 1);
808                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
809                 $scope.$apply(); 
810             }
811
812             // prepares a string for inclusion within a CSV document
813             // by escaping commas and quotes and removing newlines.
814             grid.csvDatum = function(str) {
815                 str = ''+str;
816                 if (!str) return '';
817                 str = str.replace(/\n/g, '');
818                 if (str.match(/\,/) || str.match(/"/)) {                                     
819                     str = str.replace(/"/g, '""');
820                     str = '"' + str + '"';                                           
821                 } 
822                 return str;
823             }
824
825             // sets the download file name and inserts the current CSV
826             // into a Blob URL for browser download.
827             $scope.generateCSVExportURL = function() {
828                 $scope.gridColumnPickerIsOpen = false;
829
830                 // let the file name describe the grid
831                 $scope.csvExportFileName = 
832                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
833                     .replace(/\s+/g, '_') + '_' + $scope.page();
834
835                 // toss the CSV into a Blob and update the export URL
836                 var csv = grid.generateCSV();
837                 var blob = new Blob([csv], {type : 'text/plain'});
838                 $scope.csvExportURL = 
839                     ($window.URL || $window.webkitURL).createObjectURL(blob);
840             }
841
842             $scope.printCSV = function() {
843                 $scope.gridColumnPickerIsOpen = false;
844                 egCore.print.print({
845                     context : 'default', 
846                     content : grid.generateCSV(),
847                     content_type : 'text/plain'
848                 });
849             }
850
851             // generates CSV for the currently visible grid contents
852             grid.generateCSV = function() {
853                 var csvStr = '';
854                 var colCount = grid.columnsProvider.columns.length;
855
856                 // columns
857                 angular.forEach(grid.columnsProvider.columns,
858                     function(col) {
859                         if (!col.visible) return;
860                         csvStr += grid.csvDatum(col.label);
861                         csvStr += ',';
862                     }
863                 );
864
865                 csvStr = csvStr.replace(/,$/,'\n');
866
867                 // items
868                 angular.forEach($scope.items, function(item) {
869                     angular.forEach(grid.columnsProvider.columns, 
870                         function(col) {
871                             if (!col.visible) return;
872                             // bare value
873                             var val = grid.dataProvider.itemFieldValue(item, col);
874                             // filtered value (dates, etc.)
875                             val = $filter('egGridValueFilter')(val, col);
876                             csvStr += grid.csvDatum(val);
877                             csvStr += ',';
878                         }
879                     );
880                     csvStr = csvStr.replace(/,$/,'\n');
881                 });
882
883                 return csvStr;
884             }
885
886             // Interpolate the value for column.linkpath within the context
887             // of the row item to generate the final link URL.
888             $scope.generateLinkPath = function(col, item) {
889                 return egCore.strings.$replace(col.linkpath, {item : item});
890             }
891
892             // If a column provides its own HTML template, translate it,
893             // using the current item for the template scope.
894             // note: $sce is required to avoid security restrictions and
895             // is OK here, since the template comes directly from a
896             // local HTML template (not user input).
897             $scope.translateCellTemplate = function(col, item) {
898                 var html = egCore.strings.$replace(col.template, {item : item});
899                 return $sce.trustAsHtml(html);
900             }
901
902             $scope.collect = function() { grid.collect() }
903
904             // asks the dataProvider for a page of data
905             grid.collect = function() {
906
907                 // avoid firing the collect if there is nothing to collect.
908                 if (grid.selfManagedData && !grid.dataProvider.query) return;
909
910                 if (grid.collecting) return; // avoid parallel collect()
911                 grid.collecting = true;
912
913                 console.debug('egGrid.collect() offset=' 
914                     + grid.offset + '; limit=' + grid.limit);
915
916                 // ensure all of our dropdowns are closed
917                 // TODO: git rid of these and just use dropdown-toggle, 
918                 // which is more reliable.
919                 $scope.gridColumnPickerIsOpen = false;
920                 $scope.gridRowCountIsOpen = false;
921                 $scope.gridPageSelectIsOpen = false;
922
923                 $scope.items = [];
924                 $scope.selected = {};
925                 grid.dataProvider.get(grid.offset, grid.limit).then(
926                 function() {
927                     if (grid.controls.allItemsRetrieved)
928                         grid.controls.allItemsRetrieved();
929                 },
930                 null, 
931                 function(item) {
932                     if (item) {
933                         $scope.items.push(item)
934                         if (grid.controls.itemRetrieved)
935                             grid.controls.itemRetrieved(item);
936                     }
937                 }).finally(function() { 
938                     console.debug('egGrid.collect() complete');
939                     grid.collecting = false 
940                 });
941             }
942
943             grid.init();
944         }]
945     };
946 })
947
948 /**
949  * eg-grid-field : used for collecting custom field data from the templates.
950  * This directive does not direct display, it just passes data up to the 
951  * parent grid.
952  */
953 .directive('egGridField', function() {
954     return {
955         require : '^egGrid',
956         restrict : 'AE',
957         scope : {
958             name  : '@', // required; unique name
959             path  : '@', // optional; flesh path
960             ignore: '@', // optional; fields to ignore when path is a wildcard
961             label : '@', // optional; display label
962             flex  : '@',  // optional; default flex width
963             align  : '@',  // optional; default alignment, left/center/right
964             dateformat : '@', // optional: passed down to egGridValueFilter
965
966             // if a field is part of an IDL object, but we are unable to
967             // determine the class, because it's nested within a hash
968             // (i.e. we can't navigate directly to the object via the IDL),
969             // idlClass lets us specify the class.  This is particularly
970             // useful for nested wildcard fields.
971             parentIdlClass : '@', 
972
973             // optional: for non-IDL columns, specifying a datatype
974             // lets the caller control which display filter is used.
975             // datatype should match the standard IDL datatypes.
976             datatype : '@'
977         },
978         link : function(scope, element, attrs, egGridCtrl) {
979
980             // boolean fields are presented as value-less attributes
981             angular.forEach(
982                 [
983                     'visible', 
984                     'hidden', 
985                     'sortable', 
986                     'nonsortable',
987                     'multisortable',
988                     'nonmultisortable',
989                     'required' // if set, always fetch data for this column
990                 ],
991                 function(field) {
992                     if (angular.isDefined(attrs[field]))
993                         scope[field] = true;
994                 }
995             );
996
997             // any HTML content within the field is its custom template
998             var tmpl = element.html();
999             if (tmpl && !tmpl.match(/^\s*$/))
1000                 scope.template = tmpl
1001
1002             egGridCtrl.columnsProvider.add(scope);
1003             scope.$destroy();
1004         }
1005     };
1006 })
1007
1008 /**
1009  * eg-grid-action : used for specifying actions which may be applied
1010  * to items within the grid.
1011  */
1012 .directive('egGridAction', function() {
1013     return {
1014         require : '^egGrid',
1015         restrict : 'AE',
1016         transclude : true,
1017         scope : {
1018             group   : '@', // Action group, ungrouped if not set
1019             label   : '@', // Action label
1020             handler : '=',  // Action function handler
1021             hide    : '=',
1022             disabled : '=', // function
1023             divider : '='
1024         },
1025         link : function(scope, element, attrs, egGridCtrl) {
1026             egGridCtrl.addAction({
1027                 hide  : scope.hide,
1028                 group : scope.group,
1029                 label : scope.label,
1030                 divider : scope.divider,
1031                 handler : scope.handler,
1032                 disabled : scope.disabled,
1033             });
1034             scope.$destroy();
1035         }
1036     };
1037 })
1038
1039 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1040
1041     function ColumnsProvider(args) {
1042         var cols = this;
1043         cols.columns = [];
1044         cols.stockVisible = [];
1045         cols.idlClass = args.idlClass;
1046         cols.defaultToHidden = args.defaultToHidden;
1047         cols.defaultToNoSort = args.defaultToNoSort;
1048         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1049
1050         // resets column width, visibility, and sort behavior
1051         // Visibility resets to the visibility settings defined in the 
1052         // template (i.e. the original egGridField values).
1053         cols.reset = function() {
1054             angular.forEach(cols.columns, function(col) {
1055                 col.align = 'left';
1056                 col.flex = 2;
1057                 col.sort = 0;
1058                 if (cols.stockVisible.indexOf(col.name) > -1) {
1059                     col.visible = true;
1060                 } else {
1061                     col.visible = false;
1062                 }
1063             });
1064         }
1065
1066         // returns true if any columns are sortable
1067         cols.hasSortableColumn = function() {
1068             return cols.columns.filter(
1069                 function(col) {
1070                     return col.sortable || col.multisortable;
1071                 }
1072             ).length > 0;
1073         }
1074
1075         cols.showAllColumns = function() {
1076             angular.forEach(cols.columns, function(column) {
1077                 column.visible = true;
1078             });
1079         }
1080
1081         cols.hideAllColumns = function() {
1082             angular.forEach(cols.columns, function(col) {
1083                 delete col.visible;
1084             });
1085         }
1086
1087         cols.indexOf = function(name) {
1088             for (var i = 0; i < cols.columns.length; i++) {
1089                 if (cols.columns[i].name == name) 
1090                     return i;
1091             }
1092             return -1;
1093         }
1094
1095         cols.findColumn = function(name) {
1096             return cols.columns[cols.indexOf(name)];
1097         }
1098
1099         cols.compileAutoColumns = function() {
1100             var idl_class = egCore.idl.classes[cols.idlClass];
1101
1102             angular.forEach(
1103                 idl_class.fields.sort(
1104                     function(a, b) { return a.name < b.name ? -1 : 1 }),
1105                 function(field) {
1106                     if (field.virtual) return;
1107                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1108                         // if the field is a link and the linked class has a
1109                         // "selector" field specified, use the selector field
1110                         // as the display field for the columns.
1111                         // flattener will take care of the fleshing.
1112                         if (field['class']) {
1113                             var selector_field = egCore.idl.classes[field['class']].fields
1114                                 .filter(function(f) { return Boolean(f.selector) })[0];
1115                             if (selector_field) {
1116                                 field.path = field.name + '.' + selector_field.selector;
1117                             }
1118                         }
1119                     }
1120                     cols.add(field, true);
1121                 }
1122             );
1123         }
1124
1125         // if a column definition has a path with a wildcard, create
1126         // columns for all non-virtual fields at the specified 
1127         // position in the path.
1128         cols.expandPath = function(colSpec) {
1129
1130             var ignoreList = [];
1131             if (colSpec.ignore)
1132                 ignoreList = colSpec.ignore.split(' ');
1133
1134             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1135             var class_obj;
1136             var idl_field;
1137
1138             if (colSpec.parentIdlClass) {
1139                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1140             } else {
1141                 class_obj = egCore.idl.classes[cols.idlClass];
1142             }
1143
1144             if (!class_obj) return;
1145
1146             console.debug('egGrid: auto dotpath is: ' + dotpath);
1147             var path_parts = dotpath.split(/\./);
1148
1149             // find the IDL class definition for the last element in the
1150             // path before the .*
1151             // an empty path_parts means expand the root class
1152             if (path_parts) {
1153                 for (var path_idx in path_parts) {
1154                     var part = path_parts[path_idx];
1155                     idl_field = class_obj.field_map[part];
1156
1157                     // unless we're at the end of the list, this field should
1158                     // link to another class.
1159                     if (idl_field && idl_field['class'] && (
1160                         idl_field.datatype == 'link' || 
1161                         idl_field.datatype == 'org_unit')) {
1162                         class_obj = egCore.idl.classes[idl_field['class']];
1163                     } else {
1164                         if (path_idx < (path_parts.length - 1)) {
1165                             // we ran out of classes to hop through before
1166                             // we ran out of path components
1167                             console.error("egGrid: invalid IDL path: " + dotpath);
1168                         }
1169                     }
1170                 }
1171             }
1172
1173             if (class_obj) {
1174                 angular.forEach(class_obj.fields, function(field) {
1175
1176                     // Only show wildcard fields where we have data to show
1177                     // Virtual and un-fleshed links will not have any data.
1178                     if (field.virtual ||
1179                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1180                         ignoreList.indexOf(field.name) > -1
1181                     )
1182                         return;
1183
1184                     var col = cols.cloneFromScope(colSpec);
1185                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1186                     console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1187                     cols.add(col, false, true, 
1188                         {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1189                 });
1190
1191                 cols.columns = cols.columns.sort(
1192                     function(a, b) {
1193                         if (a.explicit) return -1;
1194                         if (b.explicit) return 1;
1195                         if (a.idlclass && b.idlclass) {
1196                             return a.idlclass < b.idlclass ? -1 : 1;
1197                             return a.idlclass > b.idlclass ? 1 : -1;
1198                         }
1199                         if (a.path && b.path) {
1200                             return a.path < b.path ? -1 : 1;
1201                             return a.path > b.path ? 1 : -1;
1202                         }
1203
1204                         return a.label < b.label ? -1 : 1;
1205                     }
1206                 );
1207
1208
1209             } else {
1210                 console.error(
1211                     "egGrid: wildcard path does not resolve to an object: "
1212                     + dotpath);
1213             }
1214         }
1215
1216         // angular.clone(scopeObject) is not permittable.  Manually copy
1217         // the fields over that we need (so the scope object can go away).
1218         cols.cloneFromScope = function(colSpec) {
1219             return {
1220                 name  : colSpec.name,
1221                 label : colSpec.label,
1222                 path  : colSpec.path,
1223                 align  : colSpec.align || 'left',
1224                 flex  : Number(colSpec.flex) || 2,
1225                 sort  : Number(colSpec.sort) || 0,
1226                 required : colSpec.required,
1227                 linkpath : colSpec.linkpath,
1228                 template : colSpec.template,
1229                 visible  : colSpec.visible,
1230                 hidden   : colSpec.hidden,
1231                 datatype : colSpec.datatype,
1232                 sortable : colSpec.sortable,
1233                 nonsortable      : colSpec.nonsortable,
1234                 multisortable    : colSpec.multisortable,
1235                 nonmultisortable : colSpec.nonmultisortable,
1236                 dateformat       : colSpec.dateformat,
1237                 parentIdlClass   : colSpec.parentIdlClass
1238             };
1239         }
1240
1241
1242         // Add a column to the columns collection.
1243         // Columns may come from a slim eg-columns-field or 
1244         // directly from the IDL.
1245         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1246
1247             // First added column with the specified path takes precedence.
1248             // This allows for specific definitions followed by wildcard
1249             // definitions.  If a match is found, back out.
1250             if (cols.columns.filter(function(c) {
1251                 return (c.path == colSpec.path) })[0]) {
1252                 console.debug('skipping pre-existing column ' + colSpec.path);
1253                 return;
1254             }
1255
1256             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1257
1258             if (column.path && column.path.match(/\*$/)) 
1259                 return cols.expandPath(colSpec);
1260
1261             if (!fromExpand) column.explicit = true;
1262
1263             if (!column.name) column.name = column.path;
1264             if (!column.path) column.path = column.name;
1265
1266             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1267                 column.visible = true;
1268
1269             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1270                 column.sortable = true;
1271
1272             if (column.multisortable || 
1273                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1274                 column.multisortable = true;
1275
1276             cols.columns.push(column);
1277
1278             // Track which columns are visible by default in case we
1279             // need to reset column visibility
1280             if (column.visible) 
1281                 cols.stockVisible.push(column.name);
1282
1283             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1284
1285             // lookup the matching IDL field
1286             if (!idl_info && cols.idlClass) 
1287                 idl_info = cols.idlFieldFromPath(column.path);
1288
1289             if (!idl_info) {
1290                 // column is not represented within the IDL
1291                 column.adhoc = true; 
1292                 return; 
1293             }
1294
1295             column.datatype = idl_info.idl_field.datatype;
1296             
1297             if (!column.label) {
1298                 column.label = idl_info.idl_field.label || column.name;
1299             }
1300
1301             if (fromExpand && idl_info.idl_class) {
1302                 column.idlclass = '';
1303                 if (idl_info.idl_parent) {
1304                     column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1305                 } else {
1306                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1307                 }
1308             }
1309         },
1310
1311         // finds the IDL field from the dotpath, using the columns
1312         // idlClass as the base.
1313         cols.idlFieldFromPath = function(dotpath) {
1314             var class_obj = egCore.idl.classes[cols.idlClass];
1315             var path_parts = dotpath.split(/\./);
1316
1317             var idl_parent;
1318             var idl_field;
1319             for (var path_idx in path_parts) {
1320                 var part = path_parts[path_idx];
1321                 idl_parent = idl_field;
1322                 idl_field = class_obj.field_map[part];
1323
1324                 if (idl_field && idl_field['class'] && (
1325                     idl_field.datatype == 'link' || 
1326                     idl_field.datatype == 'org_unit')) {
1327                     class_obj = egCore.idl.classes[idl_field['class']];
1328                 }
1329                 // else, path is not in the IDL, which is fine
1330             }
1331
1332             if (!idl_field) return null;
1333
1334             return {
1335                 idl_parent: idl_parent,
1336                 idl_field : idl_field,
1337                 idl_class : class_obj
1338             };
1339         }
1340     }
1341
1342     return {
1343         instance : function(args) { return new ColumnsProvider(args) }
1344     }
1345 }])
1346
1347
1348 /*
1349  * Generic data provider template class.  This is basically an abstract
1350  * class factory service whose instances can be locally modified to 
1351  * meet the needs of each individual grid.
1352  */
1353 .factory('egGridDataProvider', 
1354            ['$q','$timeout','$filter','egCore',
1355     function($q , $timeout , $filter , egCore) {
1356
1357         function GridDataProvider(args) {
1358             var gridData = this;
1359             if (!args) args = {};
1360
1361             gridData.sort = [];
1362             gridData.get = args.get;
1363             gridData.query = args.query;
1364             gridData.idlClass = args.idlClass;
1365             gridData.columnsProvider = args.columnsProvider;
1366
1367             // Delivers a stream of array data via promise.notify()
1368             // Useful for passing an array of data to egGrid.get()
1369             // If a count is provided, the array will be trimmed to
1370             // the range defined by count and offset
1371             gridData.arrayNotifier = function(arr, offset, count) {
1372                 if (!arr || arr.length == 0) return $q.when();
1373                 if (count) arr = arr.slice(offset, offset + count);
1374                 var def = $q.defer();
1375                 // promise notifications are only witnessed when delivered
1376                 // after the caller has his hands on the promise object
1377                 $timeout(function() {
1378                     angular.forEach(arr, def.notify);
1379                     def.resolve();
1380                 });
1381                 return def.promise;
1382             }
1383
1384             // Calls the grid refresh function.  Once instantiated, the
1385             // grid will replace this function with it's own refresh()
1386             gridData.refresh = function(noReset) { }
1387
1388             if (!gridData.get) {
1389                 // returns a promise whose notify() delivers items
1390                 gridData.get = function(index, count) {
1391                     console.error("egGridDataProvider.get() not implemented");
1392                 }
1393             }
1394
1395             // attempts a flat field lookup first.  If the column is not
1396             // found on the top-level object, attempts a nested lookup
1397             // TODO: consider a caching layer to speed up template 
1398             // rendering, particularly for nested objects?
1399             gridData.itemFieldValue = function(item, column) {
1400                 if (column.name in item) {
1401                     if (typeof item[column.name] == 'function') {
1402                         return item[column.name]();
1403                     } else {
1404                         return item[column.name];
1405                     }
1406                 } else {
1407                     return gridData.nestedItemFieldValue(item, column);
1408                 }
1409             }
1410
1411             // TODO: deprecate me
1412             gridData.flatItemFieldValue = function(item, column) {
1413                 console.warn('gridData.flatItemFieldValue deprecated; '
1414                     + 'leave provider.itemFieldValue unset');
1415                 return item[column.name];
1416             }
1417
1418             // given an object and a dot-separated path to a field,
1419             // extract the value of the field.  The path can refer
1420             // to function names or object attributes.  If the final
1421             // value is an IDL field, run the value through its
1422             // corresponding output filter.
1423             gridData.nestedItemFieldValue = function(obj, column) {
1424                 if (obj === null || obj === undefined || obj === '') return '';
1425                 if (!column.path) return obj;
1426
1427                 var idl_field;
1428                 var parts = column.path.split('.');
1429
1430                 angular.forEach(parts, function(step, idx) {
1431                     // object is not fleshed to the expected extent
1432                     if (!obj || typeof obj != 'object') {
1433                         obj = '';
1434                         return;
1435                     }
1436
1437                     var cls = obj.classname;
1438                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1439                         idl_field = class_obj.field_map[step];
1440                         obj = obj[step] ? obj[step]() : '';
1441                     } else {
1442                         if (angular.isFunction(obj[step])) {
1443                             obj = obj[step]();
1444                         } else {
1445                             obj = obj[step];
1446                         }
1447                     }
1448                 });
1449
1450                 // We found a nested IDL object which may or may not have 
1451                 // been configured as a top-level column.  Grab the datatype.
1452                 if (idl_field && !column.datatype) 
1453                     column.datatype = idl_field.datatype;
1454
1455                 if (obj === null || obj === undefined || obj === '') return '';
1456                 return obj;
1457             }
1458         }
1459
1460         return {
1461             instance : function(args) {
1462                 return new GridDataProvider(args);
1463             }
1464         };
1465     }
1466 ])
1467
1468
1469 // Factory service for egGridDataManager instances, which are
1470 // responsible for collecting flattened grid data.
1471 .factory('egGridFlatDataProvider', 
1472            ['$q','egCore','egGridDataProvider',
1473     function($q , egCore , egGridDataProvider) {
1474
1475         return {
1476             instance : function(args) {
1477                 var provider = egGridDataProvider.instance(args);
1478
1479                 provider.get = function(offset, count) {
1480
1481                     // no query means no call
1482                     if (!provider.query || 
1483                             angular.equals(provider.query, {})) 
1484                         return $q.when();
1485
1486                     // find all of the currently visible columns
1487                     var queryFields = {}
1488                     angular.forEach(provider.columnsProvider.columns, 
1489                         function(col) {
1490                             // only query IDL-tracked columns
1491                             if (!col.adhoc && (col.required || col.visible))
1492                                 queryFields[col.name] = col.path;
1493                         }
1494                     );
1495
1496                     return egCore.net.request(
1497                         'open-ils.fielder',
1498                         'open-ils.fielder.flattened_search',
1499                         egCore.auth.token(), provider.idlClass, 
1500                         queryFields, provider.query,
1501                         {   sort : provider.sort,
1502                             limit : count,
1503                             offset : offset
1504                         }
1505                     );
1506                 }
1507                 //provider.itemFieldValue = provider.flatItemFieldValue;
1508                 return provider;
1509             }
1510         };
1511     }
1512 ])
1513
1514 .directive('egGridColumnDragSource', function() {
1515     return {
1516         restrict : 'A',
1517         require : '^egGrid',
1518         link : function(scope, element, attrs, egGridCtrl) {
1519             angular.element(element).attr('draggable', 'true');
1520
1521             element.bind('dragstart', function(e) {
1522                 egGridCtrl.dragColumn = attrs.column;
1523                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1524                 egGridCtrl.colResizeDir = 0;
1525
1526                 if (egGridCtrl.dragType == 'move') {
1527                     // style the column getting moved
1528                     angular.element(e.target).addClass(
1529                         'eg-grid-column-move-handle-active');
1530                 }
1531             });
1532
1533             element.bind('dragend', function(e) {
1534                 if (egGridCtrl.dragType == 'move') {
1535                     angular.element(e.target).removeClass(
1536                         'eg-grid-column-move-handle-active');
1537                 }
1538             });
1539         }
1540     };
1541 })
1542
1543 .directive('egGridColumnDragDest', function() {
1544     return {
1545         restrict : 'A',
1546         require : '^egGrid',
1547         link : function(scope, element, attrs, egGridCtrl) {
1548
1549             element.bind('dragover', function(e) { // required for drop
1550                 e.stopPropagation();
1551                 e.preventDefault();
1552                 e.dataTransfer.dropEffect = 'move';
1553
1554                 if (egGridCtrl.colResizeDir == 0) return; // move
1555
1556                 var cols = egGridCtrl.columnsProvider;
1557                 var srcCol = egGridCtrl.dragColumn;
1558                 var srcColIdx = cols.indexOf(srcCol);
1559
1560                 if (egGridCtrl.colResizeDir == -1) {
1561                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1562                         egGridCtrl.modifyColumnFlex(
1563                             egGridCtrl.columnsProvider.findColumn(
1564                                 egGridCtrl.dragColumn), -1);
1565                         if (cols.columns[srcColIdx+1]) {
1566                             // source column shrinks by one, column to the
1567                             // right grows by one.
1568                             egGridCtrl.modifyColumnFlex(
1569                                 cols.columns[srcColIdx+1], 1);
1570                         }
1571                         scope.$apply();
1572                     }
1573                 } else {
1574                     if (cols.indexOf(attrs.column) > srcColIdx) {
1575                         egGridCtrl.modifyColumnFlex( 
1576                             egGridCtrl.columnsProvider.findColumn(
1577                                 egGridCtrl.dragColumn), 1);
1578                         if (cols.columns[srcColIdx+1]) {
1579                             // source column grows by one, column to the 
1580                             // right grows by one.
1581                             egGridCtrl.modifyColumnFlex(
1582                                 cols.columns[srcColIdx+1], -1);
1583                         }
1584
1585                         scope.$apply();
1586                     }
1587                 }
1588             });
1589
1590             element.bind('dragenter', function(e) {
1591                 e.stopPropagation();
1592                 e.preventDefault();
1593                 if (egGridCtrl.dragType == 'move') {
1594                     angular.element(e.target).addClass('eg-grid-col-hover');
1595                 } else {
1596                     // resize grips are on the right side of each column.
1597                     // dragenter will either occur on the source column 
1598                     // (dragging left) or the column to the right.
1599                     if (egGridCtrl.colResizeDir == 0) {
1600                         if (egGridCtrl.dragColumn == attrs.column) {
1601                             egGridCtrl.colResizeDir = -1; // west
1602                         } else {
1603                             egGridCtrl.colResizeDir = 1; // east
1604                         }
1605                     }
1606                 }
1607             });
1608
1609             element.bind('dragleave', function(e) {
1610                 e.stopPropagation();
1611                 e.preventDefault();
1612                 if (egGridCtrl.dragType == 'move') {
1613                     angular.element(e.target).removeClass('eg-grid-col-hover');
1614                 }
1615             });
1616
1617             element.bind('drop', function(e) {
1618                 e.stopPropagation();
1619                 e.preventDefault();
1620                 egGridCtrl.colResizeDir = 0;
1621                 if (egGridCtrl.dragType == 'move') {
1622                     angular.element(e.target).removeClass('eg-grid-col-hover');
1623                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1624                 }
1625             });
1626         }
1627     };
1628 })
1629  
1630 .directive('egGridMenuItem', function() {
1631     return {
1632         restrict : 'AE',
1633         require : '^egGrid',
1634         scope : {
1635             label : '@',  
1636             checkbox : '@',  
1637             checked : '=',  
1638             standalone : '=',  
1639             handler : '=', // onclick handler function
1640             divider : '=', // if true, show a divider only
1641             handlerData : '=', // if set, passed as second argument to handler
1642             disabled : '=', // function
1643             hidden : '=' // function
1644         },
1645         link : function(scope, element, attrs, egGridCtrl) {
1646             egGridCtrl.addMenuItem({
1647                 checkbox : scope.checkbox,
1648                 checked : scope.checked ? true : false,
1649                 label : scope.label,
1650                 standalone : scope.standalone ? true : false,
1651                 handler : scope.handler,
1652                 divider : scope.divider,
1653                 disabled : scope.disabled,
1654                 hidden : scope.hidden,
1655                 handlerData : scope.handlerData
1656             });
1657             scope.$destroy();
1658         }
1659     };
1660 })
1661
1662
1663
1664 /**
1665  * Translates bare IDL object values into display values.
1666  * 1. Passes dates through the angular date filter
1667  * 2. Translates bools to Booleans so the browser can display translated 
1668  *    value.  (Though we could manually translate instead..)
1669  * Others likely to follow...
1670  */
1671 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1672     return function(value, column) {                                             
1673         switch(column.datatype) {                                                
1674             case 'bool':                                                       
1675                 switch(value) {
1676                     // Browser will translate true/false for us                    
1677                     case 't' : 
1678                     case '1' :  // legacy
1679                     case true:
1680                         return ''+true;
1681                     case 'f' : 
1682                     case '0' :  // legacy
1683                     case false:
1684                         return ''+false;
1685                     // value may be null,  '', etc.
1686                     default : return '';
1687                 }
1688             case 'timestamp':                                                  
1689                 // canned angular date filter FTW                              
1690                 if (!column.dateformat) 
1691                     column.dateformat = 'shortDate';
1692                 return $filter('date')(value, column.dateformat);
1693             case 'money':                                                  
1694                 return $filter('currency')(value);
1695             default:                                                           
1696                 return value;                                                  
1697         }                                                                      
1698     }                                                                          
1699 }]);
1700