]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/grid.js
c98107566dc341064b7dd86b21f5517af5493f43
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / grid.js
1 angular.module('egGridMod', 
2     ['egCoreMod', 'egUiMod', 'ui.bootstrap'])
3
4 .directive('egGrid', function() {
5     return {
6         restrict : 'AE',
7         transclude : true,
8         scope : {
9
10             // IDL class hint (e.g. "aou")
11             idlClass : '@',
12
13             // default page size
14             pageSize : '@',
15
16             // if true, grid columns are derived from all non-virtual
17             // fields on the base idlClass
18             autoFields : '@',
19
20             // grid preferences will be stored / retrieved with this key
21             persistKey : '@',
22
23             // field whose value is unique and may be used for item
24             // reference / lookup.  This will usually be someting like
25             // "id".  This is not needed when using autoFields, since we
26             // can determine the primary key directly from the IDL.
27             idField : '@',
28
29             // Reference to externally provided egGridDataProvider
30             itemsProvider : '=',
31
32             // comma-separated list of supported or disabled grid features
33             // supported features:
34             //  -display : columns are hidden by default
35             //  -sort    : columns are unsortable by default 
36             //  -multisort : sort priorities config disabled by default
37             features : '@',
38
39             // optional primary grid label
40             mainLabel : '@',
41
42             // if true, use the IDL class label as the mainLabel
43             autoLabel : '=', 
44
45             // optional context menu label
46             menuLabel : '@',
47
48             // Hash of control functions.
49             //
50             //  These functions are defined by the calling scope and 
51             //  invoked as-is by the grid w/ the specified parameters.
52             //
53             //  itemRetrieved     : function(item) {}
54             //  allItemsRetrieved : function() {}
55             //
56             //  ---
57             //  If defined, the grid will watch the return value from
58             //  the function defined at watchQuery on each digest and 
59             //  re-draw the grid when query changes occur.
60             //
61             //  watchQuery : function() { /* return grid query */ }
62             //
63             //  ---------------
64             //  These functions are defined by the grid and thus
65             //  replace any values defined for these attributes from the
66             //  calling scope.
67             //
68             //  activateItem  : function(item) {}
69             //  allItems      : function(allItems) {}
70             //  selectedItems : function(selected) {}
71             //  selectItems   : function(ids) {}
72             //  setQuery      : function(queryStruct) {} // causes reload
73             //  setSort       : function(sortSturct) {} // causes reload
74             gridControls : '=',
75         },
76
77         // TODO: avoid hard-coded url
78         templateUrl : '/eg/staff/share/t_autogrid', 
79
80         link : function(scope, element, attrs) {     
81             // link() is called after page compilation, which means our
82             // eg-grid-field's have been parsed and loaded.  Now it's 
83             // safe to perform our initial page load.
84
85             // load auto fields after eg-grid-field's so they are not clobbered
86             scope.handleAutoFields();
87             scope.collect();
88
89             scope.grid_element = element;
90             $(element)
91                 .find('.eg-grid-content-body')
92                 .bind('contextmenu', scope.showActionContextMenu);
93         },
94
95         controller : [
96                     '$scope','$q','egCore','egGridFlatDataProvider','$location',
97                     'egGridColumnsProvider','$filter','$window','$sce','$timeout',
98             function($scope,  $q , egCore,  egGridFlatDataProvider , $location,
99                      egGridColumnsProvider , $filter , $window , $sce , $timeout) {
100
101             var grid = this;
102
103             grid.init = function() {
104                 grid.offset = 0;
105                 $scope.items = [];
106                 $scope.showGridConf = false;
107                 grid.totalCount = -1;
108                 $scope.selected = {};
109                 $scope.actionGroups = [{actions:[]}]; // Grouped actions for selected items
110                 $scope.menuItems = []; // global actions
111
112                 // remove some unneeded values from the scope to reduce bloat
113
114                 grid.idlClass = $scope.idlClass;
115                 delete $scope.idlClass;
116
117                 grid.persistKey = $scope.persistKey;
118                 delete $scope.persistKey;
119
120                 var stored_limit = 0;
121                 if (grid.persistKey) {
122                     var stored_limit = Number(
123                         egCore.hatch.getLocalItem('eg.grid.' + grid.persistKey + '.limit')
124                     );
125                 }
126                 grid.limit = Number(stored_limit) || Number($scope.pageSize) || 25;
127
128                 grid.indexField = $scope.idField;
129                 delete $scope.idField;
130
131                 grid.dataProvider = $scope.itemsProvider;
132
133                 var features = ($scope.features) ? 
134                     $scope.features.split(',') : [];
135                 delete $scope.features;
136
137                 if (!grid.indexField && grid.idlClass)
138                     grid.indexField = egCore.idl.classes[grid.idlClass].pkey;
139
140                 grid.columnsProvider = egGridColumnsProvider.instance({
141                     idlClass : grid.idlClass,
142                     defaultToHidden : (features.indexOf('-display') > -1),
143                     defaultToNoSort : (features.indexOf('-sort') > -1),
144                     defaultToNoMultiSort : (features.indexOf('-multisort') > -1)
145                 });
146
147                 $scope.handleAutoFields = function() {
148                     if ($scope.autoFields) {
149                         if (grid.autoLabel) {
150                             $scope.mainLabel = 
151                                 egCore.idl.classes[grid.idlClass].label;
152                         }
153                         grid.columnsProvider.compileAutoColumns();
154                         delete $scope.autoFields;
155                     }
156                 }
157    
158                 if (!grid.dataProvider) {
159                     // no provider, um, provided.
160                     // Use a flat data provider
161
162                     grid.selfManagedData = true;
163                     grid.dataProvider = egGridFlatDataProvider.instance({
164                         indexField : grid.indexField,
165                         idlClass : grid.idlClass,
166                         columnsProvider : grid.columnsProvider,
167                         query : $scope.query
168                     });
169                 }
170
171                 $scope.itemFieldValue = grid.dataProvider.itemFieldValue;
172                 $scope.indexValue = function(item) {
173                     return grid.indexValue(item)
174                 };
175
176                 grid.applyControlFunctions();
177
178                 grid.loadConfig().then(function() { 
179                     // link columns to scope after loadConfig(), since it
180                     // replaces the columns array.
181                     $scope.columns = grid.columnsProvider.columns;
182                 });
183
184                 // NOTE: grid.collect() is first called from link(), not here.
185             }
186
187             // link our control functions into the gridControls 
188             // scope object so the caller can access them.
189             grid.applyControlFunctions = function() {
190
191                 // we use some of these controls internally, so sett
192                 // them up even if the caller doesn't request them.
193                 var controls = $scope.gridControls || {};
194
195                 // link in the control functions
196                 controls.selectedItems = function() {
197                     return grid.getSelectedItems()
198                 }
199
200                 controls.allItems = function() {
201                     return $scope.items;
202                 }
203
204                 controls.selectItems = function(ids) {
205                     if (!ids) return;
206                     $scope.selected = {};
207                     angular.forEach(ids, function(i) {
208                         $scope.selected[''+i] = true;
209                     });
210                 }
211
212                 // if the caller provided a functional setQuery,
213                 // extract the value before replacing it
214                 if (controls.setQuery) {
215                     grid.dataProvider.query = 
216                         controls.setQuery();
217                 }
218
219                 controls.setQuery = function(query) {
220                     grid.dataProvider.query = query;
221                     controls.refresh();
222                 }
223
224                 if (controls.watchQuery) {
225                     // capture the initial query value
226                     grid.dataProvider.query = controls.watchQuery();
227
228                     // watch for changes
229                     $scope.gridWatchQuery = controls.watchQuery;
230                     $scope.$watch('gridWatchQuery()', function(newv) {
231                         controls.setQuery(newv);
232                     }, true);
233                 }
234
235                 // if the caller provided a functional setSort
236                 // extract the value before replacing it
237                 grid.dataProvider.sort = 
238                     controls.setSort ?  controls.setSort() : [];
239
240                 controls.setSort = function(sort) {
241                     controls.refresh();
242                 }
243
244                 controls.refresh = function(noReset) {
245                     if (!noReset) grid.offset = 0;
246                     grid.collect();
247                 }
248
249                 controls.setLimit = function(limit,forget) {
250                     if (!forget && grid.persistKey)
251                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', limit);
252                     grid.limit = limit;
253                 }
254                 controls.getLimit = function() {
255                     return grid.limit;
256                 }
257                 controls.setOffset = function(offset) {
258                     grid.offset = offset;
259                 }
260                 controls.getOffset = function() {
261                     return grid.offset;
262                 }
263
264                 grid.dataProvider.refresh = controls.refresh;
265                 grid.controls = controls;
266             }
267
268             // add a new (global) grid menu item
269             grid.addMenuItem = function(item) {
270                 $scope.menuItems.push(item);
271                 var handler = item.handler;
272                 item.handler = function() {
273                     $scope.gridMenuIsOpen = false; // close menu
274                     if (handler) {
275                         handler(item, 
276                             item.handlerData, grid.getSelectedItems());
277                     }
278                 }
279             }
280
281             // add a selected-items action
282             grid.addAction = function(act) {
283                 var done = false;
284                 $scope.actionGroups.forEach(function(g){
285                     if (g.label === act.group) {
286                         g.actions.push(act);
287                         done = true;
288                     }
289                 });
290                 if (!done) {
291                     $scope.actionGroups.push({
292                         label : act.group,
293                         actions : [ act ]
294                     });
295                 }
296             }
297
298             // remove the stored column configuration preferenc, then recover 
299             // the column visibility information from the initial page load.
300             $scope.resetColumns = function() {
301                 $scope.gridColumnPickerIsOpen = false;
302                 egCore.hatch.removeItem('eg.grid.' + grid.persistKey)
303                 .then(function() {
304                     grid.columnsProvider.reset(); 
305                     if (grid.selfManagedData) grid.collect();
306                 });
307             }
308
309             $scope.showAllColumns = function() {
310                 $scope.gridColumnPickerIsOpen = false;
311                 grid.columnsProvider.showAllColumns();
312                 if (grid.selfManagedData) grid.collect();
313             }
314
315             $scope.hideAllColumns = function() {
316                 $scope.gridColumnPickerIsOpen = false;
317                 grid.columnsProvider.hideAllColumns();
318                 // note: no need to fetch new data if no columns are visible
319             }
320
321             $scope.toggleColumnVisibility = function(col) {
322                 $scope.gridColumnPickerIsOpen = false;
323                 col.visible = !col.visible;
324
325                 // egGridFlatDataProvider only retrieves data to be
326                 // displayed.  When column visibility changes, it's
327                 // necessary to fetch the newly visible column data.
328                 if (grid.selfManagedData) grid.collect();
329             }
330
331             // save the columns configuration (position, sort, width) to
332             // eg.grid.<persist-key>
333             $scope.saveConfig = function() {
334                 $scope.gridColumnPickerIsOpen = false;
335
336                 if (!grid.persistKey) {
337                     console.warn(
338                         "Cannot save settings without a grid persist-key");
339                     return;
340                 }
341
342                 // only store information about visible columns.
343                 var conf = grid.columnsProvider.columns.filter(
344                     function(col) {return Boolean(col.visible) });
345
346                 // now scrunch the data down to just the needed info
347                 conf = conf.map(function(col) {
348                     var c = {name : col.name}
349                     // Apart from the name, only store non-default values.
350                     // No need to store col.visible, since that's implicit
351                     if (col.align != 'left') c.align = col.align;
352                     if (col.flex != 2) c.flex = col.flex;
353                     if (Number(col.sort)) c.sort = Number(c.sort);
354                     return c;
355                 });
356
357                 egCore.hatch.setItem('eg.grid.' + grid.persistKey, conf)
358                 .then(function() { 
359                     // Save operation performed from the grid configuration UI.
360                     // Hide the configuration UI and re-draw w/ sort applied
361                     if ($scope.showGridConf) 
362                         $scope.toggleConfDisplay();
363                 });
364             }
365
366             // load the columns configuration (position, sort, width) from
367             // eg.grid.<persist-key> and apply the loaded settings to the
368             // columns on our columnsProvider
369             grid.loadConfig = function() {
370                 if (!grid.persistKey) return $q.when();
371
372                 return egCore.hatch.getItem('eg.grid.' + grid.persistKey)
373                 .then(function(conf) {
374                     if (!conf) return;
375
376                     var columns = grid.columnsProvider.columns;
377                     var new_cols = [];
378
379                     angular.forEach(conf, function(col) {
380                         var grid_col = columns.filter(
381                             function(c) {return c.name == col.name})[0];
382
383                         if (!grid_col) {
384                             // saved column does not match a column in the 
385                             // current grid.  skip it.
386                             return;
387                         }
388
389                         grid_col.align = col.align || 'left';
390                         grid_col.flex = col.flex || 2;
391                         grid_col.sort = col.sort || 0;
392                         // all saved columns are assumed to be true
393                         grid_col.visible = true;
394                         new_cols.push(grid_col);
395                     });
396
397                     // columns which are not expressed within the saved 
398                     // configuration are marked as non-visible and 
399                     // appended to the end of the new list of columns.
400                     angular.forEach(columns, function(col) {
401                         var found = conf.filter(
402                             function(c) {return (c.name == col.name)})[0];
403                         if (!found) {
404                             col.visible = false;
405                             new_cols.push(col);
406                         }
407                     });
408
409                     grid.columnsProvider.columns = new_cols;
410                     grid.compileSort();
411                 });
412             }
413
414             $scope.onContextMenu = function($event) {
415                 var col = angular.element($event.target).attr('column');
416                 console.log('selected column ' + col);
417             }
418
419             $scope.page = function() {
420                 return (grid.offset / grid.limit) + 1;
421             }
422
423             $scope.goToPage = function(page) {
424                 page = Number(page);
425                 if (angular.isNumber(page) && page > 0) {
426                     grid.offset = (page - 1) * grid.limit;
427                     grid.collect();
428                 }
429             }
430
431             $scope.offset = function(o) {
432                 if (angular.isNumber(o))
433                     grid.offset = o;
434                 return grid.offset 
435             }
436
437             $scope.limit = function(l) { 
438                 if (angular.isNumber(l)) {
439                     if (grid.persistKey)
440                         egCore.hatch.setLocalItem('eg.grid.' + grid.persistKey + '.limit', l);
441                     grid.limit = l;
442                 }
443                 return grid.limit 
444             }
445
446             $scope.onFirstPage = function() {
447                 return grid.offset == 0;
448             }
449
450             $scope.hasNextPage = function() {
451                 // we have less data than requested, there must
452                 // not be any more pages
453                 if (grid.count() < grid.limit) return false;
454
455                 // if the total count is not known, assume that a full
456                 // page of data implies more pages are available.
457                 if (grid.totalCount == -1) return true;
458
459                 // we have a full page of data, but is there more?
460                 return grid.totalCount > (grid.offset + grid.count());
461             }
462
463             $scope.incrementPage = function() {
464                 grid.offset += grid.limit;
465                 grid.collect();
466             }
467
468             $scope.decrementPage = function() {
469                 if (grid.offset < grid.limit) {
470                     grid.offset = 0;
471                 } else {
472                     grid.offset -= grid.limit;
473                 }
474                 grid.collect();
475             }
476
477             // number of items loaded for the current page of results
478             grid.count = function() {
479                 return $scope.items.length;
480             }
481
482             // returns the unique identifier value for the provided item
483             // for internal consistency, indexValue is always coerced 
484             // into a string.
485             grid.indexValue = function(item) {
486                 if (angular.isObject(item)) {
487                     if (item !== null) {
488                         if (angular.isFunction(item[grid.indexField]))
489                             return ''+item[grid.indexField]();
490                         return ''+item[grid.indexField]; // flat data
491                     }
492                 }
493                 // passed a non-object; assume it's an index
494                 return ''+item; 
495             }
496
497             // fires the hide handler function for a context action
498             $scope.actionHide = function(action) {
499                 if (!action.hide) {
500                     return false;
501                 }
502                 return action.hide(action);
503             }
504
505             // fires the action handler function for a context action
506             $scope.actionLauncher = function(action) {
507                 if (!action.handler) {
508                     console.error(
509                         'No handler specified for "' + action.label + '"');
510                 } else {
511
512                     try {
513                         action.handler(grid.getSelectedItems());
514                     } catch(E) {
515                         console.error('Error executing handler for "' 
516                             + action.label + '" => ' + E + "\n" + E.stack);
517                     }
518
519                     if ($scope.action_context_showing) $scope.hideActionContextMenu();
520                 }
521
522             }
523
524             $scope.hideActionContextMenu = function () {
525                 $($scope.menu_dom).css({
526                     display: '',
527                     width: $scope.action_context_width,
528                     top: $scope.action_context_y,
529                     left: $scope.action_context_x
530                 });
531                 $($scope.action_context_parent).append($scope.menu_dom);
532                 $scope.action_context_oldy = $scope.action_context_oldx = 0;
533                 $('body').unbind('click.remove_context_menu_'+$scope.action_context_index);
534                 $scope.action_context_showing = false;
535             }
536
537             $scope.action_context_showing = false;
538             $scope.showActionContextMenu = function ($event) {
539
540                 // Have to gather these here, instead of inside link()
541                 if (!$scope.menu_dom) $scope.menu_dom = $($scope.grid_element).find('.grid-action-dropdown')[0];
542                 if (!$scope.action_context_parent) $scope.action_context_parent = $($scope.menu_dom).parent();
543
544                 if (!grid.getSelectedItems().length) // Nothing selected, fire the click event
545                     $event.target.click();
546
547                 if (!$scope.action_context_showing) {
548                     $scope.action_context_width = $($scope.menu_dom).css('width');
549                     $scope.action_context_y = $($scope.menu_dom).css('top');
550                     $scope.action_context_x = $($scope.menu_dom).css('left');
551                     $scope.action_context_showing = true;
552                     $scope.action_context_index = Math.floor((Math.random() * 1000) + 1);
553
554                     $('body').append($($scope.menu_dom));
555                     $('body').bind('click.remove_context_menu_'+$scope.action_context_index, $scope.hideActionContextMenu);
556                 }
557
558                 $($scope.menu_dom).css({
559                     display: 'block',
560                     width: $scope.action_context_width,
561                     top: $event.pageY,
562                     left: $event.pageX
563                 });
564
565                 return false;
566             }
567
568             // returns the list of selected item objects
569             grid.getSelectedItems = function() {
570                 return $scope.items.filter(
571                     function(item) {
572                         return Boolean($scope.selected[grid.indexValue(item)]);
573                     }
574                 );
575             }
576
577             grid.getItemByIndex = function(index) {
578                 for (var i = 0; i < $scope.items.length; i++) {
579                     var item = $scope.items[i];
580                     if (grid.indexValue(item) == index) 
581                         return item;
582                 }
583             }
584
585             // selects one row after deselecting all of the others
586             grid.selectOneItem = function(index) {
587                 $scope.selected = {};
588                 $scope.selected[index] = true;
589             }
590
591             // selects or deselects an item, without affecting the others.
592             // returns true if the item is selected; false if de-selected.
593             grid.toggleSelectOneItem = function(index) {
594                 if ($scope.selected[index]) {
595                     delete $scope.selected[index];
596                     return false;
597                 } else {
598                     return $scope.selected[index] = true;
599                 }
600             }
601
602             grid.selectAllItems = function() {
603                 angular.forEach($scope.items, function(item) {
604                     $scope.selected[grid.indexValue(item)] = true
605                 });
606             }
607
608             $scope.$watch('selectAll', function(newVal) {
609                 if (newVal) {
610                     grid.selectAllItems();
611                 } else {
612                     $scope.selected = {};
613                 }
614             });
615
616             // returns true if item1 appears in the list before item2;
617             // false otherwise.  this is slightly more efficient that
618             // finding the position of each then comparing them.
619             // item1 / item2 may be an item or an item index
620             grid.itemComesBefore = function(itemOrIndex1, itemOrIndex2) {
621                 var idx1 = grid.indexValue(itemOrIndex1);
622                 var idx2 = grid.indexValue(itemOrIndex2);
623
624                 // use for() for early exit
625                 for (var i = 0; i < $scope.items.length; i++) {
626                     var idx = grid.indexValue($scope.items[i]);
627                     if (idx == idx1) return true;
628                     if (idx == idx2) return false;
629                 }
630                 return false;
631             }
632
633             // 0-based position of item in the current data set
634             grid.indexOf = function(item) {
635                 var idx = grid.indexValue(item);
636                 for (var i = 0; i < $scope.items.length; i++) {
637                     if (grid.indexValue($scope.items[i]) == idx)
638                         return i;
639                 }
640                 return -1;
641             }
642
643             grid.modifyColumnFlex = function(column, val) {
644                 column.flex += val;
645                 // prevent flex:0;  use hiding instead
646                 if (column.flex < 1)
647                     column.flex = 1;
648             }
649             $scope.modifyColumnFlex = function(col, val) {
650                 grid.modifyColumnFlex(col, val);
651             }
652
653             // handles click, control-click, and shift-click
654             $scope.handleRowClick = function($event, item) {
655                 var index = grid.indexValue(item);
656
657                 var origSelected = Object.keys($scope.selected);
658
659                 if ($event.ctrlKey || $event.metaKey /* mac command */) {
660                     // control-click
661                     if (grid.toggleSelectOneItem(index)) 
662                         grid.lastSelectedItemIndex = index;
663
664                 } else if ($event.shiftKey) { 
665                     // shift-click
666
667                     if (!grid.lastSelectedItemIndex || 
668                             index == grid.lastSelectedItemIndex) {
669                         grid.selectOneItem(index);
670                         grid.lastSelectedItemIndex = index;
671
672                     } else {
673
674                         var selecting = false;
675                         var ascending = grid.itemComesBefore(
676                             grid.lastSelectedItemIndex, item);
677                         var startPos = 
678                             grid.indexOf(grid.lastSelectedItemIndex);
679
680                         // update to new last-selected
681                         grid.lastSelectedItemIndex = index;
682
683                         // select each row between the last selected and 
684                         // currently selected items
685                         while (true) {
686                             startPos += ascending ? 1 : -1;
687                             var curItem = $scope.items[startPos];
688                             if (!curItem) break;
689                             var curIdx = grid.indexValue(curItem);
690                             $scope.selected[curIdx] = true;
691                             if (curIdx == index) break; // all done
692                         }
693                     }
694                         
695                 } else {
696                     grid.selectOneItem(index);
697                     grid.lastSelectedItemIndex = index;
698                 }
699             }
700
701             // Builds a sort expression from column sort priorities.
702             // called on page load and any time the priorities are modified.
703             grid.compileSort = function() {
704                 var sortList = grid.columnsProvider.columns.filter(
705                     function(col) { return Number(col.sort) != 0 }
706                 ).sort( 
707                     function(a, b) { 
708                         if (Math.abs(a.sort) < Math.abs(b.sort))
709                             return -1;
710                         return 1;
711                     }
712                 );
713
714                 if (sortList.length) {
715                     grid.dataProvider.sort = sortList.map(function(col) {
716                         var blob = {};
717                         blob[col.name] = col.sort < 0 ? 'desc' : 'asc';
718                         return blob;
719                     });
720                 }
721             }
722
723             // builds a sort expression using a single column, 
724             // toggling between ascending and descending sort.
725             $scope.quickSort = function(col_name) {
726                 var sort = grid.dataProvider.sort;
727                 if (sort && sort.length &&
728                     sort[0] == col_name) {
729                     var blob = {};
730                     blob[col_name] = 'desc';
731                     grid.dataProvider.sort = [blob];
732                 } else {
733                     grid.dataProvider.sort = [col_name];
734                 }
735
736                 grid.offset = 0;
737                 grid.collect();
738             }
739
740             // show / hide the grid configuration row
741             $scope.toggleConfDisplay = function() {
742                 if ($scope.showGridConf) {
743                     $scope.showGridConf = false;
744                     if (grid.columnsProvider.hasSortableColumn()) {
745                         // only refresh the grid if the user has the
746                         // ability to modify the sort priorities.
747                         grid.compileSort();
748                         grid.offset = 0;
749                         grid.collect();
750                     }
751                 } else {
752                     $scope.showGridConf = true;
753                 }
754
755                 $scope.gridColumnPickerIsOpen = false;
756             }
757
758             // called when a dragged column is dropped onto itself
759             // or any other column
760             grid.onColumnDrop = function(target) {
761                 if (angular.isUndefined(target)) return;
762                 if (target == grid.dragColumn) return;
763                 var srcIdx, targetIdx, srcCol;
764                 angular.forEach(grid.columnsProvider.columns,
765                     function(col, idx) {
766                         if (col.name == grid.dragColumn) {
767                             srcIdx = idx;
768                             srcCol = col;
769                         } else if (col.name == target) {
770                             targetIdx = idx;
771                         }
772                     }
773                 );
774
775                 if (srcIdx < targetIdx) targetIdx--;
776
777                 // move src column from old location to new location in 
778                 // the columns array, then force a page refresh
779                 grid.columnsProvider.columns.splice(srcIdx, 1);
780                 grid.columnsProvider.columns.splice(targetIdx, 0, srcCol);
781                 $scope.$apply(); 
782             }
783
784             // prepares a string for inclusion within a CSV document
785             // by escaping commas and quotes and removing newlines.
786             grid.csvDatum = function(str) {
787                 str = ''+str;
788                 if (!str) return '';
789                 str = str.replace(/\n/g, '');
790                 if (str.match(/\,/) || str.match(/"/)) {                                     
791                     str = str.replace(/"/g, '""');
792                     str = '"' + str + '"';                                           
793                 } 
794                 return str;
795             }
796
797             // sets the download file name and inserts the current CSV
798             // into a Blob URL for browser download.
799             $scope.generateCSVExportURL = function() {
800                 $scope.gridColumnPickerIsOpen = false;
801
802                 // let the file name describe the grid
803                 $scope.csvExportFileName = 
804                     ($scope.mainLabel || grid.persistKey || 'eg_grid_data')
805                     .replace(/\s+/g, '_') + '_' + $scope.page();
806
807                 // toss the CSV into a Blob and update the export URL
808                 var csv = grid.generateCSV();
809                 var blob = new Blob([csv], {type : 'text/plain'});
810                 $scope.csvExportURL = 
811                     ($window.URL || $window.webkitURL).createObjectURL(blob);
812             }
813
814             $scope.printCSV = function() {
815                 $scope.gridColumnPickerIsOpen = false;
816                 egCore.print.print({
817                     context : 'default', 
818                     content : grid.generateCSV(),
819                     content_type : 'text/plain'
820                 });
821             }
822
823             // generates CSV for the currently visible grid contents
824             grid.generateCSV = function() {
825                 var csvStr = '';
826                 var colCount = grid.columnsProvider.columns.length;
827
828                 // columns
829                 angular.forEach(grid.columnsProvider.columns,
830                     function(col) {
831                         if (!col.visible) return;
832                         csvStr += grid.csvDatum(col.label);
833                         csvStr += ',';
834                     }
835                 );
836
837                 csvStr = csvStr.replace(/,$/,'\n');
838
839                 // items
840                 angular.forEach($scope.items, function(item) {
841                     angular.forEach(grid.columnsProvider.columns, 
842                         function(col) {
843                             if (!col.visible) return;
844                             // bare value
845                             var val = grid.dataProvider.itemFieldValue(item, col);
846                             // filtered value (dates, etc.)
847                             val = $filter('egGridValueFilter')(val, col);
848                             csvStr += grid.csvDatum(val);
849                             csvStr += ',';
850                         }
851                     );
852                     csvStr = csvStr.replace(/,$/,'\n');
853                 });
854
855                 return csvStr;
856             }
857
858             // Interpolate the value for column.linkpath within the context
859             // of the row item to generate the final link URL.
860             $scope.generateLinkPath = function(col, item) {
861                 return egCore.strings.$replace(col.linkpath, {item : item});
862             }
863
864             // If a column provides its own HTML template, translate it,
865             // using the current item for the template scope.
866             // note: $sce is required to avoid security restrictions and
867             // is OK here, since the template comes directly from a
868             // local HTML template (not user input).
869             $scope.translateCellTemplate = function(col, item) {
870                 var html = egCore.strings.$replace(col.template, {item : item});
871                 return $sce.trustAsHtml(html);
872             }
873
874             $scope.collect = function() { grid.collect() }
875
876             // asks the dataProvider for a page of data
877             grid.collect = function() {
878
879                 // avoid firing the collect if there is nothing to collect.
880                 if (grid.selfManagedData && !grid.dataProvider.query) return;
881
882                 if (grid.collecting) return; // avoid parallel collect()
883                 grid.collecting = true;
884
885                 console.debug('egGrid.collect() offset=' 
886                     + grid.offset + '; limit=' + grid.limit);
887
888                 // ensure all of our dropdowns are closed
889                 // TODO: git rid of these and just use dropdown-toggle, 
890                 // which is more reliable.
891                 $scope.gridColumnPickerIsOpen = false;
892                 $scope.gridRowCountIsOpen = false;
893                 $scope.gridPageSelectIsOpen = false;
894
895                 $scope.items = [];
896                 $scope.selected = {};
897                 grid.dataProvider.get(grid.offset, grid.limit).then(
898                 function() {
899                     if (grid.controls.allItemsRetrieved)
900                         grid.controls.allItemsRetrieved();
901                 },
902                 null, 
903                 function(item) {
904                     if (item) {
905                         $scope.items.push(item)
906                         if (grid.controls.itemRetrieved)
907                             grid.controls.itemRetrieved(item);
908                     }
909                 }).finally(function() { 
910                     console.debug('egGrid.collect() complete');
911                     grid.collecting = false 
912                 });
913             }
914
915             grid.init();
916         }]
917     };
918 })
919
920 /**
921  * eg-grid-field : used for collecting custom field data from the templates.
922  * This directive does not direct display, it just passes data up to the 
923  * parent grid.
924  */
925 .directive('egGridField', function() {
926     return {
927         require : '^egGrid',
928         restrict : 'AE',
929         scope : {
930             name  : '@', // required; unique name
931             path  : '@', // optional; flesh path
932             ignore: '@', // optional; fields to ignore when path is a wildcard
933             label : '@', // optional; display label
934             flex  : '@',  // optional; default flex width
935             align  : '@',  // optional; default alignment, left/center/right
936             dateformat : '@', // optional: passed down to egGridValueFilter
937
938             // if a field is part of an IDL object, but we are unable to
939             // determine the class, because it's nested within a hash
940             // (i.e. we can't navigate directly to the object via the IDL),
941             // idlClass lets us specify the class.  This is particularly
942             // useful for nested wildcard fields.
943             parentIdlClass : '@', 
944
945             // optional: for non-IDL columns, specifying a datatype
946             // lets the caller control which display filter is used.
947             // datatype should match the standard IDL datatypes.
948             datatype : '@'
949         },
950         link : function(scope, element, attrs, egGridCtrl) {
951
952             // boolean fields are presented as value-less attributes
953             angular.forEach(
954                 [
955                     'visible', 
956                     'hidden', 
957                     'sortable', 
958                     'nonsortable',
959                     'multisortable',
960                     'nonmultisortable',
961                     'required' // if set, always fetch data for this column
962                 ],
963                 function(field) {
964                     if (angular.isDefined(attrs[field]))
965                         scope[field] = true;
966                 }
967             );
968
969             // any HTML content within the field is its custom template
970             var tmpl = element.html();
971             if (tmpl && !tmpl.match(/^\s*$/))
972                 scope.template = tmpl
973
974             egGridCtrl.columnsProvider.add(scope);
975             scope.$destroy();
976         }
977     };
978 })
979
980 /**
981  * eg-grid-action : used for specifying actions which may be applied
982  * to items within the grid.
983  */
984 .directive('egGridAction', function() {
985     return {
986         require : '^egGrid',
987         restrict : 'AE',
988         transclude : true,
989         scope : {
990             group   : '@', // Action group, ungrouped if not set
991             label   : '@', // Action label
992             handler : '=',  // Action function handler
993             hide    : '=',
994             divider : '='
995         },
996         link : function(scope, element, attrs, egGridCtrl) {
997             egGridCtrl.addAction({
998                 hide  : scope.hide,
999                 group : scope.group,
1000                 label : scope.label,
1001                 divider : scope.divider,
1002                 handler : scope.handler
1003             });
1004             scope.$destroy();
1005         }
1006     };
1007 })
1008
1009 .factory('egGridColumnsProvider', ['egCore', function(egCore) {
1010
1011     function ColumnsProvider(args) {
1012         var cols = this;
1013         cols.columns = [];
1014         cols.stockVisible = [];
1015         cols.idlClass = args.idlClass;
1016         cols.defaultToHidden = args.defaultToHidden;
1017         cols.defaultToNoSort = args.defaultToNoSort;
1018         cols.defaultToNoMultiSort = args.defaultToNoMultiSort;
1019
1020         // resets column width, visibility, and sort behavior
1021         // Visibility resets to the visibility settings defined in the 
1022         // template (i.e. the original egGridField values).
1023         cols.reset = function() {
1024             angular.forEach(cols.columns, function(col) {
1025                 col.align = 'left';
1026                 col.flex = 2;
1027                 col.sort = 0;
1028                 if (cols.stockVisible.indexOf(col.name) > -1) {
1029                     col.visible = true;
1030                 } else {
1031                     col.visible = false;
1032                 }
1033             });
1034         }
1035
1036         // returns true if any columns are sortable
1037         cols.hasSortableColumn = function() {
1038             return cols.columns.filter(
1039                 function(col) {
1040                     return col.sortable || col.multisortable;
1041                 }
1042             ).length > 0;
1043         }
1044
1045         cols.showAllColumns = function() {
1046             angular.forEach(cols.columns, function(column) {
1047                 column.visible = true;
1048             });
1049         }
1050
1051         cols.hideAllColumns = function() {
1052             angular.forEach(cols.columns, function(col) {
1053                 delete col.visible;
1054             });
1055         }
1056
1057         cols.indexOf = function(name) {
1058             for (var i = 0; i < cols.columns.length; i++) {
1059                 if (cols.columns[i].name == name) 
1060                     return i;
1061             }
1062             return -1;
1063         }
1064
1065         cols.findColumn = function(name) {
1066             return cols.columns[cols.indexOf(name)];
1067         }
1068
1069         cols.compileAutoColumns = function() {
1070             var idl_class = egCore.idl.classes[cols.idlClass];
1071
1072             angular.forEach(
1073                 idl_class.fields.sort(
1074                     function(a, b) { return a.name < b.name ? -1 : 1 }),
1075                 function(field) {
1076                     if (field.virtual) return;
1077                     if (field.datatype == 'link' || field.datatype == 'org_unit') {
1078                         // if the field is a link and the linked class has a
1079                         // "selector" field specified, use the selector field
1080                         // as the display field for the columns.
1081                         // flattener will take care of the fleshing.
1082                         if (field['class']) {
1083                             var selector_field = egCore.idl.classes[field['class']].fields
1084                                 .filter(function(f) { return Boolean(f.selector) })[0];
1085                             if (selector_field) {
1086                                 field.path = field.name + '.' + selector_field.selector;
1087                             }
1088                         }
1089                     }
1090                     cols.add(field, true);
1091                 }
1092             );
1093         }
1094
1095         // if a column definition has a path with a wildcard, create
1096         // columns for all non-virtual fields at the specified 
1097         // position in the path.
1098         cols.expandPath = function(colSpec) {
1099
1100             var ignoreList = [];
1101             if (colSpec.ignore)
1102                 ignoreList = colSpec.ignore.split(' ');
1103
1104             var dotpath = colSpec.path.replace(/\.?\*$/,'');
1105             var class_obj;
1106             var idl_field;
1107
1108             if (colSpec.parentIdlClass) {
1109                 class_obj = egCore.idl.classes[colSpec.parentIdlClass];
1110             } else {
1111                 class_obj = egCore.idl.classes[cols.idlClass];
1112             }
1113
1114             if (!class_obj) return;
1115
1116             console.debug('egGrid: auto dotpath is: ' + dotpath);
1117             var path_parts = dotpath.split(/\./);
1118
1119             // find the IDL class definition for the last element in the
1120             // path before the .*
1121             // an empty path_parts means expand the root class
1122             if (path_parts) {
1123                 for (var path_idx in path_parts) {
1124                     var part = path_parts[path_idx];
1125                     idl_field = class_obj.field_map[part];
1126
1127                     // unless we're at the end of the list, this field should
1128                     // link to another class.
1129                     if (idl_field && idl_field['class'] && (
1130                         idl_field.datatype == 'link' || 
1131                         idl_field.datatype == 'org_unit')) {
1132                         class_obj = egCore.idl.classes[idl_field['class']];
1133                     } else {
1134                         if (path_idx < (path_parts.length - 1)) {
1135                             // we ran out of classes to hop through before
1136                             // we ran out of path components
1137                             console.error("egGrid: invalid IDL path: " + dotpath);
1138                         }
1139                     }
1140                 }
1141             }
1142
1143             if (class_obj) {
1144                 angular.forEach(class_obj.fields, function(field) {
1145
1146                     // Only show wildcard fields where we have data to show
1147                     // Virtual and un-fleshed links will not have any data.
1148                     if (field.virtual ||
1149                         (field.datatype == 'link' || field.datatype == 'org_unit') ||
1150                         ignoreList.indexOf(field.name) > -1
1151                     )
1152                         return;
1153
1154                     var col = cols.cloneFromScope(colSpec);
1155                     col.path = dotpath + '.' + field.name;
1156                     console.debug('egGrid: field: ' +field.name + '; parent field: ' + js2JSON(idl_field));
1157                     cols.add(col, false, true, 
1158                         {idl_parent : idl_field, idl_field : field, idl_class : class_obj});
1159                 });
1160
1161                 cols.columns = cols.columns.sort(
1162                     function(a, b) {
1163                         if (a.explicit) return -1;
1164                         if (b.explicit) return 1;
1165                         if (a.idlclass && b.idlclass) {
1166                             return a.idlclass < b.idlclass ? -1 : 1;
1167                             return a.idlclass > b.idlclass ? 1 : -1;
1168                         }
1169                         if (a.path && b.path) {
1170                             return a.path < b.path ? -1 : 1;
1171                             return a.path > b.path ? 1 : -1;
1172                         }
1173
1174                         return a.label < b.label ? -1 : 1;
1175                     }
1176                 );
1177
1178
1179             } else {
1180                 console.error(
1181                     "egGrid: wildcard path does not resolve to an object: "
1182                     + dotpath);
1183             }
1184         }
1185
1186         // angular.clone(scopeObject) is not permittable.  Manually copy
1187         // the fields over that we need (so the scope object can go away).
1188         cols.cloneFromScope = function(colSpec) {
1189             return {
1190                 name  : colSpec.name,
1191                 label : colSpec.label,
1192                 path  : colSpec.path,
1193                 align  : colSpec.align || 'left',
1194                 flex  : Number(colSpec.flex) || 2,
1195                 sort  : Number(colSpec.sort) || 0,
1196                 required : colSpec.required,
1197                 linkpath : colSpec.linkpath,
1198                 template : colSpec.template,
1199                 visible  : colSpec.visible,
1200                 hidden   : colSpec.hidden,
1201                 datatype : colSpec.datatype,
1202                 sortable : colSpec.sortable,
1203                 nonsortable      : colSpec.nonsortable,
1204                 multisortable    : colSpec.multisortable,
1205                 nonmultisortable : colSpec.nonmultisortable,
1206                 dateformat       : colSpec.dateformat,
1207                 parentIdlClass   : colSpec.parentIdlClass
1208             };
1209         }
1210
1211
1212         // Add a column to the columns collection.
1213         // Columns may come from a slim eg-columns-field or 
1214         // directly from the IDL.
1215         cols.add = function(colSpec, fromIDL, fromExpand, idl_info) {
1216
1217             // First added column with the specified path takes precedence.
1218             // This allows for specific definitions followed by wildcard
1219             // definitions.  If a match is found, back out.
1220             if (cols.columns.filter(function(c) {
1221                 return (c.path == colSpec.path) })[0]) {
1222                 console.debug('skipping pre-existing column ' + colSpec.path);
1223                 return;
1224             }
1225
1226             var column = fromExpand ? colSpec : cols.cloneFromScope(colSpec);
1227
1228             if (column.path && column.path.match(/\*$/)) 
1229                 return cols.expandPath(colSpec);
1230
1231             if (!fromExpand) column.explicit = true;
1232
1233             if (!column.name) column.name = column.path;
1234             if (!column.path) column.path = column.name;
1235
1236             if (column.visible || (!cols.defaultToHidden && !column.hidden))
1237                 column.visible = true;
1238
1239             if (column.sortable || (!cols.defaultToNoSort && !column.nonsortable))
1240                 column.sortable = true;
1241
1242             if (column.multisortable || 
1243                 (!cols.defaultToNoMultiSort && !column.nonmultisortable))
1244                 column.multisortable = true;
1245
1246             cols.columns.push(column);
1247
1248             // Track which columns are visible by default in case we
1249             // need to reset column visibility
1250             if (column.visible) 
1251                 cols.stockVisible.push(column.name);
1252
1253             if (fromIDL) return; // directly from egIDL.  nothing left to do.
1254
1255             // lookup the matching IDL field
1256             if (!idl_info && cols.idlClass) 
1257                 idl_info = cols.idlFieldFromPath(column.path);
1258
1259             if (!idl_info) {
1260                 // column is not represented within the IDL
1261                 column.adhoc = true; 
1262                 return; 
1263             }
1264
1265             column.datatype = idl_info.idl_field.datatype;
1266             
1267             if (!column.label) {
1268                 column.label = idl_info.idl_field.label || column.name;
1269             }
1270
1271             if (fromExpand && idl_info.idl_class) {
1272                 column.idlclass = '';
1273                 if (idl_info.idl_parent) {
1274                     column.idlclass = idl_info.idl_parent.label || idl_info.idl_parent.name;
1275                 } else {
1276                     column.idlclass += idl_info.idl_class.label || idl_info.idl_class.name;
1277                 }
1278             }
1279         },
1280
1281         // finds the IDL field from the dotpath, using the columns
1282         // idlClass as the base.
1283         cols.idlFieldFromPath = function(dotpath) {
1284             var class_obj = egCore.idl.classes[cols.idlClass];
1285             var path_parts = dotpath.split(/\./);
1286
1287             var idl_parent;
1288             var idl_field;
1289             for (var path_idx in path_parts) {
1290                 var part = path_parts[path_idx];
1291                 idl_parent = idl_field;
1292                 idl_field = class_obj.field_map[part];
1293
1294                 if (idl_field && idl_field['class'] && (
1295                     idl_field.datatype == 'link' || 
1296                     idl_field.datatype == 'org_unit')) {
1297                     class_obj = egCore.idl.classes[idl_field['class']];
1298                 }
1299                 // else, path is not in the IDL, which is fine
1300             }
1301
1302             if (!idl_field) return null;
1303
1304             return {
1305                 idl_parent: idl_parent,
1306                 idl_field : idl_field,
1307                 idl_class : class_obj
1308             };
1309         }
1310     }
1311
1312     return {
1313         instance : function(args) { return new ColumnsProvider(args) }
1314     }
1315 }])
1316
1317
1318 /*
1319  * Generic data provider template class.  This is basically an abstract
1320  * class factory service whose instances can be locally modified to 
1321  * meet the needs of each individual grid.
1322  */
1323 .factory('egGridDataProvider', 
1324            ['$q','$timeout','$filter','egCore',
1325     function($q , $timeout , $filter , egCore) {
1326
1327         function GridDataProvider(args) {
1328             var gridData = this;
1329             if (!args) args = {};
1330
1331             gridData.sort = [];
1332             gridData.get = args.get;
1333             gridData.query = args.query;
1334             gridData.idlClass = args.idlClass;
1335             gridData.columnsProvider = args.columnsProvider;
1336
1337             // Delivers a stream of array data via promise.notify()
1338             // Useful for passing an array of data to egGrid.get()
1339             // If a count is provided, the array will be trimmed to
1340             // the range defined by count and offset
1341             gridData.arrayNotifier = function(arr, offset, count) {
1342                 if (!arr || arr.length == 0) return $q.when();
1343                 if (count) arr = arr.slice(offset, offset + count);
1344                 var def = $q.defer();
1345                 // promise notifications are only witnessed when delivered
1346                 // after the caller has his hands on the promise object
1347                 $timeout(function() {
1348                     angular.forEach(arr, def.notify);
1349                     def.resolve();
1350                 });
1351                 return def.promise;
1352             }
1353
1354             // Calls the grid refresh function.  Once instantiated, the
1355             // grid will replace this function with it's own refresh()
1356             gridData.refresh = function(noReset) { }
1357
1358             if (!gridData.get) {
1359                 // returns a promise whose notify() delivers items
1360                 gridData.get = function(index, count) {
1361                     console.error("egGridDataProvider.get() not implemented");
1362                 }
1363             }
1364
1365             // attempts a flat field lookup first.  If the column is not
1366             // found on the top-level object, attempts a nested lookup
1367             // TODO: consider a caching layer to speed up template 
1368             // rendering, particularly for nested objects?
1369             gridData.itemFieldValue = function(item, column) {
1370                 if (column.name in item) {
1371                     if (typeof item[column.name] == 'function') {
1372                         return item[column.name]();
1373                     } else {
1374                         return item[column.name];
1375                     }
1376                 } else {
1377                     return gridData.nestedItemFieldValue(item, column);
1378                 }
1379             }
1380
1381             // TODO: deprecate me
1382             gridData.flatItemFieldValue = function(item, column) {
1383                 console.warn('gridData.flatItemFieldValue deprecated; '
1384                     + 'leave provider.itemFieldValue unset');
1385                 return item[column.name];
1386             }
1387
1388             // given an object and a dot-separated path to a field,
1389             // extract the value of the field.  The path can refer
1390             // to function names or object attributes.  If the final
1391             // value is an IDL field, run the value through its
1392             // corresponding output filter.
1393             gridData.nestedItemFieldValue = function(obj, column) {
1394                 if (obj === null || obj === undefined || obj === '') return '';
1395                 if (!column.path) return obj;
1396
1397                 var idl_field;
1398                 var parts = column.path.split('.');
1399
1400                 angular.forEach(parts, function(step, idx) {
1401                     // object is not fleshed to the expected extent
1402                     if (!obj || typeof obj != 'object') {
1403                         obj = '';
1404                         return;
1405                     }
1406
1407                     var cls = obj.classname;
1408                     if (cls && (class_obj = egCore.idl.classes[cls])) {
1409                         idl_field = class_obj.field_map[step];
1410                         obj = obj[step] ? obj[step]() : '';
1411                     } else {
1412                         if (angular.isFunction(obj[step])) {
1413                             obj = obj[step]();
1414                         } else {
1415                             obj = obj[step];
1416                         }
1417                     }
1418                 });
1419
1420                 // We found a nested IDL object which may or may not have 
1421                 // been configured as a top-level column.  Grab the datatype.
1422                 if (idl_field && !column.datatype) 
1423                     column.datatype = idl_field.datatype;
1424
1425                 if (obj === null || obj === undefined || obj === '') return '';
1426                 return obj;
1427             }
1428         }
1429
1430         return {
1431             instance : function(args) {
1432                 return new GridDataProvider(args);
1433             }
1434         };
1435     }
1436 ])
1437
1438
1439 // Factory service for egGridDataManager instances, which are
1440 // responsible for collecting flattened grid data.
1441 .factory('egGridFlatDataProvider', 
1442            ['$q','egCore','egGridDataProvider',
1443     function($q , egCore , egGridDataProvider) {
1444
1445         return {
1446             instance : function(args) {
1447                 var provider = egGridDataProvider.instance(args);
1448
1449                 provider.get = function(offset, count) {
1450
1451                     // no query means no call
1452                     if (!provider.query || 
1453                             angular.equals(provider.query, {})) 
1454                         return $q.when();
1455
1456                     // find all of the currently visible columns
1457                     var queryFields = {}
1458                     angular.forEach(provider.columnsProvider.columns, 
1459                         function(col) {
1460                             // only query IDL-tracked columns
1461                             if (!col.adhoc && (col.required || col.visible))
1462                                 queryFields[col.name] = col.path;
1463                         }
1464                     );
1465
1466                     return egCore.net.request(
1467                         'open-ils.fielder',
1468                         'open-ils.fielder.flattened_search',
1469                         egCore.auth.token(), provider.idlClass, 
1470                         queryFields, provider.query,
1471                         {   sort : provider.sort,
1472                             limit : count,
1473                             offset : offset
1474                         }
1475                     );
1476                 }
1477                 //provider.itemFieldValue = provider.flatItemFieldValue;
1478                 return provider;
1479             }
1480         };
1481     }
1482 ])
1483
1484 .directive('egGridColumnDragSource', function() {
1485     return {
1486         restrict : 'A',
1487         require : '^egGrid',
1488         link : function(scope, element, attrs, egGridCtrl) {
1489             angular.element(element).attr('draggable', 'true');
1490
1491             element.bind('dragstart', function(e) {
1492                 egGridCtrl.dragColumn = attrs.column;
1493                 egGridCtrl.dragType = attrs.dragType || 'move'; // or resize
1494                 egGridCtrl.colResizeDir = 0;
1495
1496                 if (egGridCtrl.dragType == 'move') {
1497                     // style the column getting moved
1498                     angular.element(e.target).addClass(
1499                         'eg-grid-column-move-handle-active');
1500                 }
1501             });
1502
1503             element.bind('dragend', function(e) {
1504                 if (egGridCtrl.dragType == 'move') {
1505                     angular.element(e.target).removeClass(
1506                         'eg-grid-column-move-handle-active');
1507                 }
1508             });
1509         }
1510     };
1511 })
1512
1513 .directive('egGridColumnDragDest', function() {
1514     return {
1515         restrict : 'A',
1516         require : '^egGrid',
1517         link : function(scope, element, attrs, egGridCtrl) {
1518
1519             element.bind('dragover', function(e) { // required for drop
1520                 e.stopPropagation();
1521                 e.preventDefault();
1522                 e.dataTransfer.dropEffect = 'move';
1523
1524                 if (egGridCtrl.colResizeDir == 0) return; // move
1525
1526                 var cols = egGridCtrl.columnsProvider;
1527                 var srcCol = egGridCtrl.dragColumn;
1528                 var srcColIdx = cols.indexOf(srcCol);
1529
1530                 if (egGridCtrl.colResizeDir == -1) {
1531                     if (cols.indexOf(attrs.column) <= srcColIdx) {
1532                         egGridCtrl.modifyColumnFlex(
1533                             egGridCtrl.columnsProvider.findColumn(
1534                                 egGridCtrl.dragColumn), -1);
1535                         if (cols.columns[srcColIdx+1]) {
1536                             // source column shrinks by one, column to the
1537                             // right grows by one.
1538                             egGridCtrl.modifyColumnFlex(
1539                                 cols.columns[srcColIdx+1], 1);
1540                         }
1541                         scope.$apply();
1542                     }
1543                 } else {
1544                     if (cols.indexOf(attrs.column) > srcColIdx) {
1545                         egGridCtrl.modifyColumnFlex( 
1546                             egGridCtrl.columnsProvider.findColumn(
1547                                 egGridCtrl.dragColumn), 1);
1548                         if (cols.columns[srcColIdx+1]) {
1549                             // source column grows by one, column to the 
1550                             // right grows by one.
1551                             egGridCtrl.modifyColumnFlex(
1552                                 cols.columns[srcColIdx+1], -1);
1553                         }
1554
1555                         scope.$apply();
1556                     }
1557                 }
1558             });
1559
1560             element.bind('dragenter', function(e) {
1561                 e.stopPropagation();
1562                 e.preventDefault();
1563                 if (egGridCtrl.dragType == 'move') {
1564                     angular.element(e.target).addClass('eg-grid-col-hover');
1565                 } else {
1566                     // resize grips are on the right side of each column.
1567                     // dragenter will either occur on the source column 
1568                     // (dragging left) or the column to the right.
1569                     if (egGridCtrl.colResizeDir == 0) {
1570                         if (egGridCtrl.dragColumn == attrs.column) {
1571                             egGridCtrl.colResizeDir = -1; // west
1572                         } else {
1573                             egGridCtrl.colResizeDir = 1; // east
1574                         }
1575                     }
1576                 }
1577             });
1578
1579             element.bind('dragleave', function(e) {
1580                 e.stopPropagation();
1581                 e.preventDefault();
1582                 if (egGridCtrl.dragType == 'move') {
1583                     angular.element(e.target).removeClass('eg-grid-col-hover');
1584                 }
1585             });
1586
1587             element.bind('drop', function(e) {
1588                 e.stopPropagation();
1589                 e.preventDefault();
1590                 egGridCtrl.colResizeDir = 0;
1591                 if (egGridCtrl.dragType == 'move') {
1592                     angular.element(e.target).removeClass('eg-grid-col-hover');
1593                     egGridCtrl.onColumnDrop(attrs.column); // move the column
1594                 }
1595             });
1596         }
1597     };
1598 })
1599  
1600 .directive('egGridMenuItem', function() {
1601     return {
1602         restrict : 'AE',
1603         require : '^egGrid',
1604         scope : {
1605             label : '@',  
1606             standalone : '=',  
1607             handler : '=', // onclick handler function
1608             divider : '=', // if true, show a divider only
1609             handlerData : '=', // if set, passed as second argument to handler
1610             disabled : '=', // function
1611             hidden : '=' // function
1612         },
1613         link : function(scope, element, attrs, egGridCtrl) {
1614             egGridCtrl.addMenuItem({
1615                 label : scope.label,
1616                 standalone : scope.standalone ? true : false,
1617                 handler : scope.handler,
1618                 divider : scope.divider,
1619                 disabled : scope.disabled,
1620                 hidden : scope.hidden,
1621                 handlerData : scope.handlerData
1622             });
1623             scope.$destroy();
1624         }
1625     };
1626 })
1627
1628
1629
1630 /**
1631  * Translates bare IDL object values into display values.
1632  * 1. Passes dates through the angular date filter
1633  * 2. Translates bools to Booleans so the browser can display translated 
1634  *    value.  (Though we could manually translate instead..)
1635  * Others likely to follow...
1636  */
1637 .filter('egGridValueFilter', ['$filter', function($filter) {                         
1638     return function(value, column) {                                             
1639         switch(column.datatype) {                                                
1640             case 'bool':                                                       
1641                 switch(value) {
1642                     // Browser will translate true/false for us                    
1643                     case 't' : 
1644                     case '1' :  // legacy
1645                     case true:
1646                         return ''+true;
1647                     case 'f' : 
1648                     case '0' :  // legacy
1649                     case false:
1650                         return ''+false;
1651                     // value may be null,  '', etc.
1652                     default : return '';
1653                 }
1654             case 'timestamp':                                                  
1655                 // canned angular date filter FTW                              
1656                 if (!column.dateformat) 
1657                     column.dateformat = 'shortDate';
1658                 return $filter('date')(value, column.dateformat);
1659             case 'money':                                                  
1660                 return $filter('currency')(value);
1661             default:                                                           
1662                 return value;                                                  
1663         }                                                                      
1664     }                                                                          
1665 }]);
1666