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