]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
fc3a05b3228418077ba05ecf8d8b3b497ee3fcec
[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.name;
769                 grid.modifyColumnFlex(col, val);
770             }
771
772             grid.modifyColumnPos = function(col, diff) {
773                 var srcIdx, targetIdx;
774                 angular.forEach(grid.columnsProvider.columns,
775                     function(c, i) { if (c.name == col.name) srcIdx = i });
776
777                 targetIdx = srcIdx + diff;
778                 if (targetIdx < 0) {
779                     targetIdx = 0;
780                 } else if (targetIdx >= grid.columnsProvider.columns.length) {
781                     // Target index follows the last visible column.
782                     var lastVisible = 0;
783                     angular.forEach(grid.columnsProvider.columns, 
784                         function(column, idx) {
785                             if (column.visible) lastVisible = idx;
786                         }
787                     );
788
789                     // When moving a column (down) causes one or more
790                     // visible columns to shuffle forward, our column
791                     // moves into the slot of the last visible column.
792                     // Otherwise, put it into the slot directly following 
793                     // the last visible column.
794                     targetIdx = 
795                         srcIdx <= lastVisible ? lastVisible : lastVisible + 1;
796                 }
797
798                 // Splice column out of old position, insert at new position.
799                 grid.columnsProvider.columns.splice(srcIdx, 1);
800                 grid.columnsProvider.columns.splice(targetIdx, 0, col);
801             }
802
803             $scope.modifyColumnPos = function(col, diff) {
804                 $scope.lastModColumn = col.name;
805                 return grid.modifyColumnPos(col, diff);
806             }
807
808
809             // handles click, control-click, and shift-click
810             $scope.handleRowClick = function($event, item) {
811                 var index = grid.indexValue(item);
812
813                 var origSelected = Object.keys($scope.selected);
814
815                 if (!$scope.canMultiSelect) {
816                     grid.selectOneItem(index);
817                     grid.lastSelectedItemIndex = index;
818                     return;
819                 }
820
821                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
822                     // control-click
823                     if (grid.toggleSelectOneItem(index)) 
824                         grid.lastSelectedItemIndex = index;
825
826                 } else if ($event.shiftKey) { 
827                     // shift-click
828
829                     if (!grid.lastSelectedItemIndex || 
830                             index == grid.lastSelectedItemIndex) {
831                         grid.selectOneItem(index);
832                         grid.lastSelectedItemIndex = index;
833
834                     } else {
835
836                         var selecting = false;
837                         var ascending = grid.itemComesBefore(
838                             grid.lastSelectedItemIndex, item);
839                         var startPos = 
840                             grid.indexOf(grid.lastSelectedItemIndex);
841
842                         // update to new last-selected
843                         grid.lastSelectedItemIndex = index;
844
845                         // select each row between the last selected and 
846                         // currently selected items
847                         while (true) {
848                             startPos += ascending ? 1 : -1;
849                             var curItem = $scope.items[startPos];
850                             if (!curItem) break;
851                             var curIdx = grid.indexValue(curItem);
852                             $scope.selected[curIdx] = true;
853                             if (curIdx == index) break; // all done
854                         }
855                         $scope.selected = angular.copy($scope.selected);
856                     }
857                         
858                 } else {
859                     grid.selectOneItem(index);
860                     grid.lastSelectedItemIndex = index;
861                 }
862             }
863
864             // Builds a sort expression from column sort priorities.
865             // called on page load and any time the priorities are modified.
866             grid.compileSort = function() {
867                 var sortList = grid.columnsProvider.columns.filter(
868                     function(col) { return Number(col.sort) != 0 }
869                 ).sort( 
870                     function(a, b) { 
871                         if (Math.abs(a.sort) < Math.abs(b.sort))
872                             return -1;
873                         return 1;
874                     }
875                 );
876
877                 if (sortList.length) {
878                     grid.dataProvider.sort = sortList.map(function(col) {
879                         var blob = {};
880                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
881                         return blob;
882                     });
883                 }
884             }
885
886             // builds a sort expression using a single column, 
887             // toggling between ascending and descending sort.
888             $scope.quickSort = function(col_name) {
889                 var sort = grid.dataProvider.sort;
890                 if (sort && sort.length &&
891                     sort[0] == col_name) {
892                     var blob = {};
893                     blob[col_name] = 'desc';
894                     grid.dataProvider.sort = [blob];
895                 } else {
896                     grid.dataProvider.sort = [col_name];
897                 }
898
899                 grid.offset = 0;
900                 grid.collect();
901             }
902
903             // show / hide the grid configuration row
904             $scope.toggleConfDisplay = function() {
905                 if ($scope.showGridConf) {
906                     $scope.showGridConf = false;
907                     if (grid.columnsProvider.hasSortableColumn()) {
908                         // only refresh the grid if the user has the
909                         // ability to modify the sort priorities.
910                         grid.compileSort();
911                         grid.offset = 0;
912                         grid.collect();
913                     }
914                 } else {
915                     $scope.showGridConf = true;
916                 }
917
918                 delete $scope.lastModColumn;
919                 $scope.gridColumnPickerIsOpen = false;
920             }
921
922             // called when a dragged column is dropped onto itself
923             // or any other column
924             grid.onColumnDrop = function(target) {
925                 if (angular.isUndefined(target)) return;
926                 if (target == grid.dragColumn) return;
927                 var srcIdx, targetIdx, srcCol;
928                 angular.forEach(grid.columnsProvider.columns,
929                     function(col, idx) {
930                         if (col.name == grid.dragColumn) {
931                             srcIdx = idx;
932                             srcCol = col;
933                         } else if (col.name == target) {
934                             targetIdx = idx;
935                         }
936                     }
937                 );
938
939                 if (srcIdx < targetIdx) targetIdx--;
940
941                 // move src column from old location to new location in 
942                 // the columns array, then force a page refresh
943                 grid.columnsProvider.columns.splice(srcIdx, 1);
944                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
945                 $scope.$apply(); 
946             }
947
948             // prepares a string for inclusion within a CSV document
949             // by escaping commas and quotes and removing newlines.
950             grid.csvDatum = function(str) {
951                 str = ''+str;
952                 if (!str) return '';
953                 str = str.replace(/\n/g, '');
954                 if (str.match(/\,/) || str.match(/"/)) {                                     
955                     str = str.replace(/"/g, '""');
956                     str = '"' + str + '"';                                           
957                 } 
958                 return str;
959             }
960
961             /** Export the full data set as CSV.
962              *  Flow of events:
963              *  1. User clicks the 'download csv' link
964              *  2. All grid data is retrieved asychronously
965              *  3. Once all data is all present and CSV-ized, the download 
966              *     attributes are linked to the href.
967              *  4. The href .click() action is prgrammatically fired again,
968              *     telling the browser to download the data, now that the
969              *     data is available for download.
970              *  5 Once downloaded, the href attributes are reset.
971              */
972             grid.csvExportInProgress = false;
973             $scope.generateCSVExportURL = function($event) {
974
975                 if (grid.csvExportInProgress) {
976                     // This is secondary href click handler.  Give the
977                     // browser a moment to start the download, then reset
978                     // the CSV download attributes / state.
979                     $timeout(
980                         function() {
981                             $scope.csvExportURL = '';
982                             $scope.csvExportFileName = ''; 
983                             grid.csvExportInProgress = false;
984                         }, 500
985                     );
986                     return;
987                 } 
988
989                 grid.csvExportInProgress = true;
990                 $scope.gridColumnPickerIsOpen = false;
991
992                 // let the file name describe the grid
993                 $scope.csvExportFileName = 
994                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
995                     .replace(/\s+/g, '_') + '_' + $scope.page();
996
997                 // toss the CSV into a Blob and update the export URL
998                 grid.generateCSV().then(function(csv) {
999                     var blob = new Blob([csv], {type : 'text/plain'});
1000                     $scope.csvExportURL = 
1001                         ($window.URL || $window.webkitURL).createObjectURL(blob);
1002
1003                     // Fire the 2nd click event now that the browser has
1004                     // information on how to download the CSV file.
1005                     $timeout(function() {$event.target.click()});
1006                 });
1007             }
1008
1009             /*
1010              * TODO: does this serve any purpose given we can 
1011              * print formatted HTML?  If so, generateCSV() now
1012              * returns a promise, needs light refactoring...
1013             $scope.printCSV = function() {
1014                 $scope.gridColumnPickerIsOpen = false;
1015                 egCore.print.print({
1016                     context : 'default', 
1017                     content : grid.generateCSV(),
1018                     content_type : 'text/plain'
1019                 });
1020             }
1021             */
1022
1023             // Given a row item and column definition, extract the
1024             // text content for printing.  Templated columns must be
1025             // processed and parsed as HTML, then boiled down to their 
1026             // text content.
1027             grid.getItemTextContent = function(item, col) {
1028                 var val;
1029                 if (col.template) {
1030                     val = $scope.translateCellTemplate(col, item);
1031                     if (val) {
1032                         var node = new DOMParser()
1033                             .parseFromString(val, 'text/html');
1034                         val = $(node).text();
1035                     }
1036                 } else {
1037                     val = grid.dataProvider.itemFieldValue(item, col);
1038                     val = $filter('egGridValueFilter')(val, col, item);
1039                 }
1040                 return val;
1041             }
1042
1043             /**
1044              * Fetches all grid data and transates each item into a simple
1045              * key-value pair of column name => text-value.
1046              * Included in the response for convenience is the list of 
1047              * currently visible column definitions.
1048              * TODO: currently fetches a maximum of 10k rows.  Does this
1049              * need to be configurable?
1050              */
1051             grid.getAllItemsAsText = function() {
1052                 var text_items = [];
1053
1054                 // we don't know the total number of rows we're about
1055                 // to retrieve, but we can indicate the number retrieved
1056                 // so far as each item arrives.
1057                 egProgressDialog.open({value : 0});
1058
1059                 var visible_cols = grid.columnsProvider.columns.filter(
1060                     function(c) { return c.visible });
1061
1062                 return grid.dataProvider.get(0, 10000).then(
1063                     function() { 
1064                         return {items : text_items, columns : visible_cols};
1065                     }, 
1066                     null,
1067                     function(item) { 
1068                         egProgressDialog.increment();
1069                         var text_item = {};
1070                         angular.forEach(visible_cols, function(col) {
1071                             text_item[col.name] = 
1072                                 grid.getItemTextContent(item, col);
1073                         });
1074                         text_items.push(text_item);
1075                     }
1076                 ).finally(egProgressDialog.close);
1077             }
1078
1079             // Fetch "all" of the grid data, translate it into print-friendly 
1080             // text, and send it to the printer service.
1081             $scope.printHTML = function() {
1082                 $scope.gridColumnPickerIsOpen = false;
1083                 return grid.getAllItemsAsText().then(function(text_items) {
1084                     return egCore.print.print({
1085                         template : 'grid_html',
1086                         scope : text_items
1087                     });
1088                 });
1089             }
1090
1091             $scope.showColumnDialog = function() {
1092                 return $uibModal.open({
1093                     templateUrl: './share/t_grid_columns',
1094                     backdrop: 'static',
1095                     size : 'lg',
1096                     controller: ['$scope', '$uibModalInstance',
1097                         function($dialogScope, $uibModalInstance) {
1098                             $dialogScope.modifyColumnPos = $scope.modifyColumnPos;
1099                             $dialogScope.disableMultiSort = $scope.disableMultiSort;
1100                             $dialogScope.columns = $scope.columns;
1101
1102                             // Push visible columns to the top of the list
1103                             $dialogScope.elevateVisible = function() {
1104                                 var new_cols = [];
1105                                 angular.forEach($dialogScope.columns, function(col) {
1106                                     if (col.visible) new_cols.push(col);
1107                                 });
1108                                 angular.forEach($dialogScope.columns, function(col) {
1109                                     if (!col.visible) new_cols.push(col);
1110                                 });
1111
1112                                 // Update all references to the list of columns
1113                                 $dialogScope.columns = 
1114                                     $scope.columns = 
1115                                     grid.columnsProvider.columns = 
1116                                     new_cols;
1117                             }
1118
1119                             $dialogScope.toggle = function(col) {
1120                                 col.visible = !Boolean(col.visible);
1121                             }
1122                             $dialogScope.ok = $dialogScope.cancel = function() {
1123                                 delete $scope.lastModColumn;
1124                                 $uibModalInstance.close()
1125                             }
1126                         }
1127                     ]
1128                 });
1129             },
1130
1131             // generates CSV for the currently visible grid contents
1132             grid.generateCSV = function() {
1133                 return grid.getAllItemsAsText().then(function(text_items) {
1134                     var columns = text_items.columns;
1135                     var items = text_items.items;
1136                     var csvStr = '';
1137
1138                     // column headers
1139                     angular.forEach(columns, function(col) {
1140                         csvStr += grid.csvDatum(col.label);
1141                         csvStr += ',';
1142                     });
1143
1144                     csvStr = csvStr.replace(/,$/,'\n');
1145
1146                     // items
1147                     angular.forEach(items, function(item) {
1148                         angular.forEach(columns, function(col) {
1149                             csvStr += grid.csvDatum(item[col.name]);
1150                             csvStr += ',';
1151                         });
1152                         csvStr = csvStr.replace(/,$/,'\n');
1153                     });
1154
1155                     return csvStr;
1156                 });
1157             }
1158
1159             // Interpolate the value for column.linkpath within the context
1160             // of the row item to generate the final link URL.
1161             $scope.generateLinkPath = function(col, item) {
1162                 return egCore.strings.$replace(col.linkpath, {item : item});
1163             }
1164
1165             // If a column provides its own HTML template, translate it,
1166             // using the current item for the template scope.
1167             // note: $sce is required to avoid security restrictions and
1168             // is OK here, since the template comes directly from a
1169             // local HTML template (not user input).
1170             $scope.translateCellTemplate = function(col, item) {
1171                 var html = egCore.strings.$replace(col.template, {item : item});
1172                 return $sce.trustAsHtml(html);
1173             }
1174
1175             $scope.collect = function() { grid.collect() }
1176
1177             // asks the dataProvider for a page of data
1178             grid.collect = function() {
1179
1180                 // avoid firing the collect if there is nothing to collect.
1181                 if (grid.selfManagedData && !grid.dataProvider.query) return;
1182
1183                 if (grid.collecting) return; // avoid parallel collect()
1184                 grid.collecting = true;
1185
1186                 console.debug('egGrid.collect() offset=' 
1187                     + grid.offset + '; limit=' + grid.limit);
1188
1189                 // ensure all of our dropdowns are closed
1190                 // TODO: git rid of these and just use dropdown-toggle, 
1191                 // which is more reliable.
1192                 $scope.gridColumnPickerIsOpen = false;
1193                 $scope.gridRowCountIsOpen = false;
1194                 $scope.gridPageSelectIsOpen = false;
1195
1196                 $scope.items = [];
1197                 $scope.selected = {};
1198
1199                 // Inform the caller we've asked the data provider
1200                 // for data.  This is useful for knowing when collection
1201                 // has started (e.g. to display a progress dialg) when 
1202                 // using the stock (flattener) data provider, where the 
1203                 // user is not directly defining a get() handler.
1204                 if (grid.controls.collectStarted)
1205                     grid.controls.collectStarted(grid.offset, grid.limit);
1206
1207                 grid.dataProvider.get(grid.offset, grid.limit).then(
1208                 function() {
1209                     if (grid.controls.allItemsRetrieved)
1210                         grid.controls.allItemsRetrieved();
1211                 },
1212                 null, 
1213                 function(item) {
1214                     if (item) {
1215                         $scope.items.push(item)
1216                         if (grid.controls.itemRetrieved)
1217                             grid.controls.itemRetrieved(item);
1218                         if ($scope.selectAll)
1219                             $scope.selected[grid.indexValue(item)] = true
1220                     }
1221                 }).finally(function() { 
1222                     console.debug('egGrid.collect() complete');
1223                     grid.collecting = false 
1224                     $scope.selected = angular.copy($scope.selected);
1225                 });
1226             }
1227
1228             grid.init();
1229         }]
1230     };
1231 })
1232
1233 /**
1234  * eg-grid-field : used for collecting custom field data from the templates.
1235  * This directive does not direct display, it just passes data up to the 
1236  * parent grid.
1237  */
1238 .directive('egGridField', function() {
1239     return {
1240         require : '^egGrid',
1241         restrict : 'AE',
1242         scope : {
1243             flesher: '=', // optional; function that can flesh a linked field, given the value
1244             comparator: '=', // optional; function that can sort the thing at the end of 'path' 
1245             name  : '@', // required; unique name
1246             path  : '@', // optional; flesh path
1247             ignore: '@', // optional; fields to ignore when path is a wildcard
1248             label : '@', // optional; display label
1249             flex  : '@',  // optional; default flex width
1250             align  : '@',  // optional; default alignment, left/center/right
1251             dateformat : '@', // optional: passed down to egGridValueFilter
1252             datecontext: '@', // optional: passed down to egGridValueFilter to choose TZ
1253             datefilter: '@', // optional: passed down to egGridValueFilter to choose specialized date filters
1254             dateonlyinterval: '@', // optional: passed down to egGridValueFilter to choose a "better" format
1255
1256             // if a field is part of an IDL object, but we are unable to
1257             // determine the class, because it's nested within a hash
1258             // (i.e. we can't navigate directly to the object via the IDL),
1259             // idlClass lets us specify the class.  This is particularly
1260             // useful for nested wildcard fields.
1261             parentIdlClass : '@', 
1262
1263             // optional: for non-IDL columns, specifying a datatype
1264             // lets the caller control which display filter is used.
1265             // datatype should match the standard IDL datatypes.
1266             datatype : '@',
1267
1268             // optional hash of functions that can be imported into
1269             // the directive's scope; meant for cases where the "compiled"
1270             // attribute is set
1271             handlers : '='
1272         },
1273         link : function(scope, element, attrs, egGridCtrl) {
1274
1275             // boolean fields are presented as value-less attributes
1276             angular.forEach(
1277                 [
1278                     'visible', 
1279                     'compiled', 
1280                     'hidden', 
1281                     'sortable', 
1282                     'nonsortable',
1283                     'multisortable',
1284                     'nonmultisortable',
1285                     'required' // if set, always fetch data for this column
1286                 ],
1287                 function(field) {
1288                     if (angular.isDefined(attrs[field]))
1289                         scope[field] = true;
1290                 }
1291             );
1292
1293             // any HTML content within the field is its custom template
1294             var tmpl = element.html();
1295             if (tmpl && !tmpl.match(/^\s*$/))
1296                 scope.template = tmpl
1297
1298             egGridCtrl.columnsProvider.add(scope);
1299             scope.$destroy();
1300         }
1301     };
1302 })
1303
1304 /**
1305  * eg-grid-action : used for specifying actions which may be applied
1306  * to items within the grid.
1307  */
1308 .directive('egGridAction', function() {
1309     return {
1310         require : '^egGrid',
1311         restrict : 'AE',
1312         transclude : true,
1313         scope : {
1314             group   : '@', // Action group, ungrouped if not set
1315             label   : '@', // Action label
1316             handler : '=',  // Action function handler
1317             hide    : '=',
1318             disabled : '=', // function
1319             divider : '='
1320         },
1321         link : function(scope, element, attrs, egGridCtrl) {
1322             egGridCtrl.addAction({
1323                 hide  : scope.hide,
1324                 group : scope.group,
1325                 label : scope.label,
1326                 divider : scope.divider,
1327                 handler : scope.handler,
1328                 disabled : scope.disabled,
1329             });
1330             scope.$destroy();
1331         }
1332     };
1333 })
1334
1335 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1336
1337     function ColumnsProvider(args) {
1338         var cols = this;
1339         cols.columns = [];
1340         cols.stockVisible = [];
1341         cols.idlClass = args.idlClass;
1342         cols.clientSort = args.clientSort;
1343         cols.defaultToHidden = args.defaultToHidden;
1344         cols.defaultToNoSort = args.defaultToNoSort;
1345         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1346         cols.defaultDateFormat = args.defaultDateFormat;
1347         cols.defaultDateContext = args.defaultDateContext;
1348
1349         // resets column width, visibility, and sort behavior
1350         // Visibility resets to the visibility settings defined in the 
1351         // template (i.e. the original egGridField values).
1352         cols.reset = function() {
1353             angular.forEach(cols.columns, function(col) {
1354                 col.align = 'left';
1355                 col.flex = 2;
1356                 col.sort = 0;
1357                 if (cols.stockVisible.indexOf(col.name) > -1) {
1358                     col.visible = true;
1359                 } else {
1360                     col.visible = false;
1361                 }
1362             });
1363         }
1364
1365         // returns true if any columns are sortable
1366         cols.hasSortableColumn = function() {
1367             return cols.columns.filter(
1368                 function(col) {
1369                     return col.sortable || col.multisortable;
1370                 }
1371             ).length > 0;
1372         }
1373
1374         cols.showAllColumns = function() {
1375             angular.forEach(cols.columns, function(column) {
1376                 column.visible = true;
1377             });
1378         }
1379
1380         cols.hideAllColumns = function() {
1381             angular.forEach(cols.columns, function(col) {
1382                 delete col.visible;
1383             });
1384         }
1385
1386         cols.indexOf = function(name) {
1387             for (var i = 0; i < cols.columns.length; i++) {
1388                 if (cols.columns[i].name == name) 
1389                     return i;
1390             }
1391             return -1;
1392         }
1393
1394         cols.findColumn = function(name) {
1395             return cols.columns[cols.indexOf(name)];
1396         }
1397
1398         cols.compileAutoColumns = function() {
1399             var idl_class = egCore.idl.classes[cols.idlClass];
1400
1401             angular.forEach(
1402                 idl_class.fields,
1403                 function(field) {
1404                     if (field.virtual) return;
1405                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1406                         // if the field is a link and the linked class has a
1407                         // "selector" field specified, use the selector field
1408                         // as the display field for the columns.
1409                         // flattener will take care of the fleshing.
1410                         if (field['class']) {
1411                             var selector_field = egCore.idl.classes[field['class']].fields
1412                                 .filter(function(f) { return Boolean(f.selector) })[0];
1413                             if (selector_field) {
1414                                 field.path = field.name + '.' + selector_field.selector;
1415                             }
1416                         }
1417                     }
1418                     cols.add(field, true);
1419                 }
1420             );
1421         }
1422
1423         // if a column definition has a path with a wildcard, create
1424         // columns for all non-virtual fields at the specified 
1425         // position in the path.
1426         cols.expandPath = function(colSpec) {
1427
1428             var ignoreList = [];
1429             if (colSpec.ignore)
1430                 ignoreList = colSpec.ignore.split(' ');
1431
1432             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1433             var class_obj;
1434             var idl_field;
1435
1436             if (colSpec.parentIdlClass) {
1437                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1438             } else {
1439                 class_obj = egCore.idl.classes[cols.idlClass];
1440             }
1441             var idl_parent = class_obj;
1442             var old_field_label = '';
1443
1444             if (!class_obj) return;
1445
1446             //console.debug('egGrid: auto dotpath is: ' + dotpath);
1447             var path_parts = dotpath.split(/\./);
1448
1449             // find the IDL class definition for the last element in the
1450             // path before the .*
1451             // an empty path_parts means expand the root class
1452             if (path_parts) {
1453                 var old_field;
1454                 for (var path_idx in path_parts) {
1455                     old_field = idl_field;
1456
1457                     var part = path_parts[path_idx];
1458                     idl_field = class_obj.field_map[part];
1459
1460                     // unless we're at the end of the list, this field should
1461                     // link to another class.
1462                     if (idl_field && idl_field['class'] && (
1463                         idl_field.datatype == 'link' || 
1464                         idl_field.datatype == 'org_unit')) {
1465                         if (old_field_label) old_field_label += ' : ';
1466                         old_field_label += idl_field.label;
1467                         class_obj = egCore.idl.classes[idl_field['class']];
1468                         if (old_field) idl_parent = old_field;
1469                     } else {
1470                         if (path_idx < (path_parts.length - 1)) {
1471                             // we ran out of classes to hop through before
1472                             // we ran out of path components
1473                             console.error("egGrid: invalid IDL path: " + dotpath);
1474                         }
1475                     }
1476                 }
1477             }
1478
1479             if (class_obj) {
1480                 angular.forEach(class_obj.fields, function(field) {
1481
1482                     // Only show wildcard fields where we have data to show
1483                     // Virtual and un-fleshed links will not have any data.
1484                     if (field.virtual ||
1485                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1486                         ignoreList.indexOf(field.name) > -1
1487                     )
1488                         return;
1489
1490                     var col = cols.cloneFromScope(colSpec);
1491                     col.path = (dotpath ? dotpath + '.' + field.name : field.name);
1492
1493                     // log line below is very chatty.  disable until needed.
1494                     // console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_parent));
1495                     cols.add(col, false, true, 
1496                         {idl_parent : idl_parent, idl_field : field, idl_class : class_obj, field_parent_label : old_field_label });
1497                 });
1498
1499                 cols.columns = cols.columns.sort(
1500                     function(a, b) {
1501                         if (a.explicit) return -1;
1502                         if (b.explicit) return 1;
1503
1504                         if (a.idlclass && b.idlclass) {
1505                             if (a.idlclass < b.idlclass) return -1;
1506                             if (b.idlclass < a.idlclass) return 1;
1507                         }
1508
1509                         if (a.path && b.path && a.path.lastIndexOf('.') && b.path.lastIndexOf('.')) {
1510                             if (a.path.substring(0, a.path.lastIndexOf('.')) < b.path.substring(0, b.path.lastIndexOf('.'))) return -1;
1511                             if (b.path.substring(0, b.path.lastIndexOf('.')) < a.path.substring(0, a.path.lastIndexOf('.'))) return 1;
1512                         }
1513
1514                         if (a.label && b.label) {
1515                             if (a.label < b.label) return -1;
1516                             if (b.label < a.label) return 1;
1517                         }
1518
1519                         return a.name < b.name ? -1 : 1;
1520                     }
1521                 );
1522
1523
1524             } else {
1525                 console.error(
1526                     "egGrid: wildcard path does not resolve to an object: "
1527                     + dotpath);
1528             }
1529         }
1530
1531         // angular.clone(scopeObject) is not permittable.  Manually copy
1532         // the fields over that we need (so the scope object can go away).
1533         cols.cloneFromScope = function(colSpec) {
1534             return {
1535                 flesher  : colSpec.flesher,
1536                 comparator  : colSpec.comparator,
1537                 name  : colSpec.name,
1538                 label : colSpec.label,
1539                 path  : colSpec.path,
1540                 align  : colSpec.align || 'left',
1541                 flex  : Number(colSpec.flex) || 2,
1542                 sort  : Number(colSpec.sort) || 0,
1543                 required : colSpec.required,
1544                 linkpath : colSpec.linkpath,
1545                 template : colSpec.template,
1546                 visible  : colSpec.visible,
1547                 compiled : colSpec.compiled,
1548                 handlers : colSpec.handlers,
1549                 hidden   : colSpec.hidden,
1550                 datatype : colSpec.datatype,
1551                 sortable : colSpec.sortable,
1552                 nonsortable      : colSpec.nonsortable,
1553                 multisortable    : colSpec.multisortable,
1554                 nonmultisortable : colSpec.nonmultisortable,
1555                 dateformat       : colSpec.dateformat,
1556                 datecontext      : colSpec.datecontext,
1557                 datefilter      : colSpec.datefilter,
1558                 dateonlyinterval : colSpec.dateonlyinterval,
1559                 parentIdlClass   : colSpec.parentIdlClass
1560             };
1561         }
1562
1563
1564         // Add a column to the columns collection.
1565         // Columns may come from a slim eg-columns-field or 
1566         // directly from the IDL.
1567         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1568
1569             // First added column with the specified path takes precedence.
1570             // This allows for specific definitions followed by wildcard
1571             // definitions.  If a match is found, back out.
1572             if (cols.columns.filter(function(c) {
1573                 return (c.path == colSpec.path) })[0]) {
1574                 console.debug('skipping pre-existing column ' + colSpec.path);
1575                 return;
1576             }
1577
1578             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1579
1580             if (column.path && column.path.match(/\*$/)) 
1581                 return cols.expandPath(colSpec);
1582
1583             if (!fromExpand) column.explicit = true;
1584
1585             if (!column.name) column.name = column.path;
1586             if (!column.path) column.path = column.name;
1587
1588             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1589                 column.visible = true;
1590
1591             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1592                 column.sortable = true;
1593
1594             if (column.multisortable || 
1595                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1596                 column.multisortable = true;
1597
1598             if (cols.defaultDateFormat && ! column.dateformat) {
1599                 column.dateformat = cols.defaultDateFormat;
1600             }
1601
1602             if (cols.defaultDateOnlyInterval && ! column.dateonlyinterval) {
1603                 column.dateonlyinterval = cols.defaultDateOnlyInterval;
1604             }
1605
1606             if (cols.defaultDateContext && ! column.datecontext) {
1607                 column.datecontext = cols.defaultDateContext;
1608             }
1609
1610             if (cols.defaultDateFilter && ! column.datefilter) {
1611                 column.datefilter = cols.defaultDateFilter;
1612             }
1613
1614             cols.columns.push(column);
1615
1616             // Track which columns are visible by default in case we
1617             // need to reset column visibility
1618             if (column.visible) 
1619                 cols.stockVisible.push(column.name);
1620
1621             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1622
1623             // lookup the matching IDL field
1624             if (!idl_info && cols.idlClass) 
1625                 idl_info = cols.idlFieldFromPath(column.path);
1626
1627             if (!idl_info) {
1628                 // column is not represented within the IDL
1629                 column.adhoc = true; 
1630                 return; 
1631             }
1632
1633             column.datatype = idl_info.idl_field.datatype;
1634             
1635             if (!column.label) {
1636                 column.label = idl_info.idl_field.label || column.name;
1637             }
1638
1639             if (fromExpand && idl_info.idl_class) {
1640                 column.idlclass = '';
1641                 if (idl_info.field_parent_label && idl_info.idl_parent.label != idl_info.idl_class.label) {
1642                     column.idlclass = (idl_info.field_parent_label || idl_info.idl_parent.label || idl_info.idl_parent.name);
1643                 } else {
1644                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1645                 }
1646             }
1647         },
1648
1649         // finds the IDL field from the dotpath, using the columns
1650         // idlClass as the base.
1651         cols.idlFieldFromPath = function(dotpath) {
1652             var class_obj = egCore.idl.classes[cols.idlClass];
1653             if (!dotpath) return null;
1654
1655             var path_parts = dotpath.split(/\./);
1656
1657             var idl_parent;
1658             var idl_field;
1659             for (var path_idx in path_parts) {
1660                 var part = path_parts[path_idx];
1661                 idl_parent = idl_field;
1662                 idl_field = class_obj.field_map[part];
1663
1664                 if (idl_field) {
1665                     if (idl_field['class'] && (
1666                         idl_field.datatype == 'link' || 
1667                         idl_field.datatype == 'org_unit')) {
1668                         class_obj = egCore.idl.classes[idl_field['class']];
1669                     }
1670                 } else {
1671                     return null;
1672                 }
1673             }
1674
1675             return {
1676                 idl_parent: idl_parent,
1677                 idl_field : idl_field,
1678                 idl_class : class_obj
1679             };
1680         }
1681     }
1682
1683     return {
1684         instance : function(args) { return new ColumnsProvider(args) }
1685     }
1686 }])
1687
1688
1689 /*
1690  * Generic data provider template class.  This is basically an abstract
1691  * class factory service whose instances can be locally modified to 
1692  * meet the needs of each individual grid.
1693  */
1694 .factory('egGridDataProvider', 
1695            ['$q','$timeout','$filter','egCore',
1696     function($q , $timeout , $filter , egCore) {
1697
1698         function GridDataProvider(args) {
1699             var gridData = this;
1700             if (!args) args = {};
1701
1702             gridData.sort = [];
1703             gridData.get = args.get;
1704             gridData.query = args.query;
1705             gridData.idlClass = args.idlClass;
1706             gridData.columnsProvider = args.columnsProvider;
1707
1708             // Delivers a stream of array data via promise.notify()
1709             // Useful for passing an array of data to egGrid.get()
1710             // If a count is provided, the array will be trimmed to
1711             // the range defined by count and offset
1712             gridData.arrayNotifier = function(arr, offset, count) {
1713                 if (!arr || arr.length == 0) return $q.when();
1714
1715                 if (gridData.columnsProvider.clientSort
1716                     && gridData.sort
1717                     && gridData.sort.length > 0
1718                 ) {
1719                     var sorter_cache = [];
1720                     arr.sort(function(a,b) {
1721                         for (var si = 0; si < gridData.sort.length; si++) {
1722                             if (!sorter_cache[si]) { // Build sort structure on first comparison, reuse thereafter
1723                                 var field = gridData.sort[si];
1724                                 var dir = 'asc';
1725
1726                                 if (angular.isObject(field)) {
1727                                     dir = Object.values(field)[0];
1728                                     field = Object.keys(field)[0];
1729                                 }
1730
1731                                 var path = gridData.columnsProvider.findColumn(field).path || field;
1732                                 var comparator = gridData.columnsProvider.findColumn(field).comparator ||
1733                                     function (x,y) { if (x < y) return -1; if (x > y) return 1; return 0 };
1734
1735                                 sorter_cache[si] = {
1736                                     field       : path,
1737                                     dir         : dir,
1738                                     comparator  : comparator
1739                                 };
1740                             }
1741
1742                             var sc = sorter_cache[si];
1743
1744                             var af,bf;
1745
1746                             if (a._isfieldmapper || angular.isFunction(a[sc.field])) {
1747                                 try {af = a[sc.field](); bf = b[sc.field]() } catch (e) {};
1748                             } else {
1749                                 af = a[sc.field]; bf = b[sc.field];
1750                             }
1751                             if (af === undefined && sc.field.indexOf('.') > -1) { // assume an object, not flat path
1752                                 var parts = sc.field.split('.');
1753                                 af = a;
1754                                 bf = b;
1755                                 angular.forEach(parts, function (p) {
1756                                     if (af) {
1757                                         if (af._isfieldmapper || angular.isFunction(af[p])) af = af[p]();
1758                                         else af = af[p];
1759                                     }
1760                                     if (bf) {
1761                                         if (bf._isfieldmapper || angular.isFunction(bf[p])) bf = bf[p]();
1762                                         else bf = bf[p];
1763                                     }
1764                                 });
1765                             }
1766
1767                             if (af === undefined) af = null;
1768                             if (bf === undefined) bf = null;
1769
1770                             if (af === null && bf !== null) return 1;
1771                             if (bf === null && af !== null) return -1;
1772
1773                             if (!(bf === null && af === null)) {
1774                                 var partial = sc.comparator(af,bf);
1775                                 if (partial) {
1776                                     if (sc.dir == 'desc') {
1777                                         if (partial > 0) return -1;
1778                                         return 1;
1779                                     }
1780                                     return partial;
1781                                 }
1782                             }
1783                         }
1784
1785                         return 0;
1786                     });
1787                 }
1788
1789                 if (count) arr = arr.slice(offset, offset + count);
1790                 var def = $q.defer();
1791                 // promise notifications are only witnessed when delivered
1792                 // after the caller has his hands on the promise object
1793                 $timeout(function() {
1794                     angular.forEach(arr, def.notify);
1795                     def.resolve();
1796                 });
1797                 return def.promise;
1798             }
1799
1800             // Calls the grid refresh function.  Once instantiated, the
1801             // grid will replace this function with it's own refresh()
1802             gridData.refresh = function(noReset) { }
1803
1804             if (!gridData.get) {
1805                 // returns a promise whose notify() delivers items
1806                 gridData.get = function(index, count) {
1807                     console.error("egGridDataProvider.get() not implemented");
1808                 }
1809             }
1810
1811             // attempts a flat field lookup first.  If the column is not
1812             // found on the top-level object, attempts a nested lookup
1813             // TODO: consider a caching layer to speed up template 
1814             // rendering, particularly for nested objects?
1815             gridData.itemFieldValue = function(item, column) {
1816                 var val;
1817                 if (column.name in item) {
1818                     if (typeof item[column.name] == 'function') {
1819                         val = item[column.name]();
1820                     } else {
1821                         val = item[column.name];
1822                     }
1823                 } else {
1824                     val = gridData.nestedItemFieldValue(item, column);
1825                 }
1826
1827                 return val;
1828             }
1829
1830             // TODO: deprecate me
1831             gridData.flatItemFieldValue = function(item, column) {
1832                 console.warn('gridData.flatItemFieldValue deprecated; '
1833                     + 'leave provider.itemFieldValue unset');
1834                 return item[column.name];
1835             }
1836
1837             // given an object and a dot-separated path to a field,
1838             // extract the value of the field.  The path can refer
1839             // to function names or object attributes.  If the final
1840             // value is an IDL field, run the value through its
1841             // corresponding output filter.
1842             gridData.nestedItemFieldValue = function(obj, column) {
1843                 item = obj; // keep a copy around
1844
1845                 if (obj === null || obj === undefined || obj === '') return '';
1846                 if (!column.path) return obj;
1847
1848                 var idl_field;
1849                 var parts = column.path.split('.');
1850
1851                 angular.forEach(parts, function(step, idx) {
1852                     // object is not fleshed to the expected extent
1853                     if (typeof obj != 'object') {
1854                         if (typeof obj != 'undefined' && column.flesher) {
1855                             obj = column.flesher(obj, column, item);
1856                         } else {
1857                             obj = '';
1858                             return;
1859                         }
1860                     }
1861
1862                     if (!obj) return '';
1863
1864                     var cls = obj.classname;
1865                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1866                         idl_field = class_obj.field_map[step];
1867                         obj = obj[step] ? obj[step]() : '';
1868                     } else {
1869                         if (angular.isFunction(obj[step])) {
1870                             obj = obj[step]();
1871                         } else {
1872                             obj = obj[step];
1873                         }
1874                     }
1875                 });
1876
1877                 // We found a nested IDL object which may or may not have 
1878                 // been configured as a top-level column.  Grab the datatype.
1879                 if (idl_field && !column.datatype) 
1880                     column.datatype = idl_field.datatype;
1881
1882                 if (obj === null || obj === undefined || obj === '') return '';
1883                 return obj;
1884             }
1885         }
1886
1887         return {
1888             instance : function(args) {
1889                 return new GridDataProvider(args);
1890             }
1891         };
1892     }
1893 ])
1894
1895
1896 // Factory service for egGridDataManager instances, which are
1897 // responsible for collecting flattened grid data.
1898 .factory('egGridFlatDataProvider', 
1899            ['$q','egCore','egGridDataProvider',
1900     function($q , egCore , egGridDataProvider) {
1901
1902         return {
1903             instance : function(args) {
1904                 var provider = egGridDataProvider.instance(args);
1905
1906                 provider.get = function(offset, count) {
1907
1908                     // no query means no call
1909                     if (!provider.query || 
1910                             angular.equals(provider.query, {})) 
1911                         return $q.when();
1912
1913                     // find all of the currently visible columns
1914                     var queryFields = {}
1915                     angular.forEach(provider.columnsProvider.columns, 
1916                         function(col) {
1917                             // only query IDL-tracked columns
1918                             if (!col.adhoc && col.name && col.path && (col.required || col.visible))
1919                                 queryFields[col.name] = col.path;
1920                         }
1921                     );
1922
1923                     return egCore.net.request(
1924                         'open-ils.fielder',
1925                         'open-ils.fielder.flattened_search',
1926                         egCore.auth.token(), provider.idlClass, 
1927                         queryFields, provider.query,
1928                         {   sort : provider.sort,
1929                             limit : count,
1930                             offset : offset
1931                         }
1932                     );
1933                 }
1934                 //provider.itemFieldValue = provider.flatItemFieldValue;
1935                 return provider;
1936             }
1937         };
1938     }
1939 ])
1940
1941 .directive('egGridColumnDragSource', function() {
1942     return {
1943         restrict : 'A',
1944         require : '^egGrid',
1945         link : function(scope, element, attrs, egGridCtrl) {
1946             angular.element(element).attr('draggable', 'true');
1947
1948             element.bind('dragstart', function(e) {
1949                 egGridCtrl.dragColumn = attrs.column;
1950                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1951                 egGridCtrl.colResizeDir = 0;
1952
1953                 if (egGridCtrl.dragType == 'move') {
1954                     // style the column getting moved
1955                     angular.element(e.target).addClass(
1956                         'eg-grid-column-move-handle-active');
1957                 }
1958             });
1959
1960             element.bind('dragend', function(e) {
1961                 if (egGridCtrl.dragType == 'move') {
1962                     angular.element(e.target).removeClass(
1963                         'eg-grid-column-move-handle-active');
1964                 }
1965             });
1966         }
1967     };
1968 })
1969
1970 .directive('egGridColumnDragDest', function() {
1971     return {
1972         restrict : 'A',
1973         require : '^egGrid',
1974         link : function(scope, element, attrs, egGridCtrl) {
1975
1976             element.bind('dragover', function(e) { // required for drop
1977                 e.stopPropagation();
1978                 e.preventDefault();
1979                 e.dataTransfer.dropEffect = 'move';
1980
1981                 if (egGridCtrl.colResizeDir == 0) return; // move
1982
1983                 var cols = egGridCtrl.columnsProvider;
1984                 var srcCol = egGridCtrl.dragColumn;
1985                 var srcColIdx = cols.indexOf(srcCol);
1986
1987                 if (egGridCtrl.colResizeDir == -1) {
1988                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1989                         egGridCtrl.modifyColumnFlex(
1990                             egGridCtrl.columnsProvider.findColumn(
1991                                 egGridCtrl.dragColumn), -1);
1992                         if (cols.columns[srcColIdx+1]) {
1993                             // source column shrinks by one, column to the
1994                             // right grows by one.
1995                             egGridCtrl.modifyColumnFlex(
1996                                 cols.columns[srcColIdx+1], 1);
1997                         }
1998                         scope.$apply();
1999                     }
2000                 } else {
2001                     if (cols.indexOf(attrs.column) > srcColIdx) {
2002                         egGridCtrl.modifyColumnFlex( 
2003                             egGridCtrl.columnsProvider.findColumn(
2004                                 egGridCtrl.dragColumn), 1);
2005                         if (cols.columns[srcColIdx+1]) {
2006                             // source column grows by one, column to the 
2007                             // right grows by one.
2008                             egGridCtrl.modifyColumnFlex(
2009                                 cols.columns[srcColIdx+1], -1);
2010                         }
2011
2012                         scope.$apply();
2013                     }
2014                 }
2015             });
2016
2017             element.bind('dragenter', function(e) {
2018                 e.stopPropagation();
2019                 e.preventDefault();
2020                 if (egGridCtrl.dragType == 'move') {
2021                     angular.element(e.target).addClass('eg-grid-col-hover');
2022                 } else {
2023                     // resize grips are on the right side of each column.
2024                     // dragenter will either occur on the source column 
2025                     // (dragging left) or the column to the right.
2026                     if (egGridCtrl.colResizeDir == 0) {
2027                         if (egGridCtrl.dragColumn == attrs.column) {
2028                             egGridCtrl.colResizeDir = -1; // west
2029                         } else {
2030                             egGridCtrl.colResizeDir = 1; // east
2031                         }
2032                     }
2033                 }
2034             });
2035
2036             element.bind('dragleave', function(e) {
2037                 e.stopPropagation();
2038                 e.preventDefault();
2039                 if (egGridCtrl.dragType == 'move') {
2040                     angular.element(e.target).removeClass('eg-grid-col-hover');
2041                 }
2042             });
2043
2044             element.bind('drop', function(e) {
2045                 e.stopPropagation();
2046                 e.preventDefault();
2047                 egGridCtrl.colResizeDir = 0;
2048                 if (egGridCtrl.dragType == 'move') {
2049                     angular.element(e.target).removeClass('eg-grid-col-hover');
2050                     egGridCtrl.onColumnDrop(attrs.column); // move the column
2051                 }
2052             });
2053         }
2054     };
2055 })
2056  
2057 .directive('egGridMenuItem', function() {
2058     return {
2059         restrict : 'AE',
2060         require : '^egGrid',
2061         scope : {
2062             label : '@',  
2063             checkbox : '@',  
2064             checked : '=',  
2065             standalone : '=',  
2066             handler : '=', // onclick handler function
2067             divider : '=', // if true, show a divider only
2068             handlerData : '=', // if set, passed as second argument to handler
2069             disabled : '=', // function
2070             hidden : '=' // function
2071         },
2072         link : function(scope, element, attrs, egGridCtrl) {
2073             egGridCtrl.addMenuItem({
2074                 checkbox : scope.checkbox,
2075                 checked : scope.checked ? true : false,
2076                 label : scope.label,
2077                 standalone : scope.standalone ? true : false,
2078                 handler : scope.handler,
2079                 divider : scope.divider,
2080                 disabled : scope.disabled,
2081                 hidden : scope.hidden,
2082                 handlerData : scope.handlerData
2083             });
2084             scope.$destroy();
2085         }
2086     };
2087 })
2088
2089 /* https://stackoverflow.com/questions/17343696/adding-an-ng-click-event-inside-a-filter/17344875#17344875 */
2090 .directive('compile', ['$compile', function ($compile) {
2091     return function(scope, element, attrs) {
2092       // pass through column defs from grid cell's scope
2093       scope.col = scope.$parent.col;
2094       scope.$watch(
2095         function(scope) {
2096           // watch the 'compile' expression for changes
2097           return scope.$eval(attrs.compile);
2098         },
2099         function(value) {
2100           // when the 'compile' expression changes
2101           // assign it into the current DOM
2102           element.html(value);
2103
2104           // compile the new DOM and link it to the current
2105           // scope.
2106           // NOTE: we only compile .childNodes so that
2107           // we don't get into infinite loop compiling ourselves
2108           $compile(element.contents())(scope);
2109         }
2110     );
2111   };
2112 }])
2113
2114
2115
2116 /**
2117  * Translates bare IDL object values into display values.
2118  * 1. Passes dates through the angular date filter
2119  * 2. Translates bools to Booleans so the browser can display translated 
2120  *    value.  (Though we could manually translate instead..)
2121  * Others likely to follow...
2122  */
2123 .filter('egGridValueFilter', ['$filter','egCore', function($filter,egCore) {
2124     function traversePath(obj,path) {
2125         var list = path.split('.');
2126         for (var part in path) {
2127             if (obj[path]) obj = obj[path]
2128             else return null;
2129         }
2130         return obj;
2131     }
2132
2133     var GVF = function(value, column, item) {
2134         switch(column.datatype) {
2135             case 'bool':
2136                 switch(value) {
2137                     // Browser will translate true/false for us
2138                     case 't' : 
2139                     case '1' :  // legacy
2140                     case true:
2141                         return ''+true;
2142                     case 'f' : 
2143                     case '0' :  // legacy
2144                     case false:
2145                         return ''+false;
2146                     // value may be null,  '', etc.
2147                     default : return '';
2148                 }
2149             case 'timestamp':
2150                 var interval = angular.isFunction(item[column.dateonlyinterval])
2151                     ? item[column.dateonlyinterval]()
2152                     : item[column.dateonlyinterval];
2153
2154                 if (column.dateonlyinterval && !interval) // try it as a dotted path
2155                     interval = traversePath(item, column.dateonlyinterval);
2156
2157                 var context = angular.isFunction(item[column.datecontext])
2158                     ? item[column.datecontext]()
2159                     : item[column.datecontext];
2160
2161                 if (column.datecontext && !context) // try it as a dotted path
2162                     context = traversePath(item, column.datecontext);
2163
2164                 var date_filter = column.datefilter || 'egOrgDateInContext';
2165
2166                 return $filter(date_filter)(value, column.dateformat, context, interval);
2167             case 'money':
2168                 return $filter('currency')(value);
2169             default:
2170                 return value;
2171         }
2172     };
2173
2174     GVF.$stateful = true;
2175     return GVF;
2176 }]);
2177