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