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