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