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