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