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