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