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