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