]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
47632ed696f078fbe288fca7857dd61a14f6cbc3
[working/Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / ui.js
1 /**
2   * UI tools and directives.
3   */
4 angular.module('egUiMod', ['egCoreMod', 'ui.bootstrap'])
5
6
7 /**
8  * <input focus-me="iAmOpen"/>
9  * $scope.iAmOpen = true;
10  */
11 .directive('focusMe', 
12        ['$timeout','$parse', 
13 function($timeout , $parse) {
14     return {
15         link: function(scope, element, attrs) {
16             var model = $parse(attrs.focusMe);
17             scope.$watch(model, function(value) {
18                 if(value === true) 
19                     $timeout(function() {element[0].focus()});
20             });
21             element.bind('blur', function() {
22                 $timeout(function() {
23                     scope.$apply(model.assign(scope, false));
24                 });
25             })
26         }
27     };
28 }])
29
30 /**
31  * <input blur-me="pleaseBlurMe"/>
32  * $scope.pleaseBlurMe = true
33  * Useful for de-focusing when no other obvious focus target exists
34  */
35 .directive('blurMe', 
36        ['$timeout','$parse', 
37 function($timeout , $parse) {
38     return {
39         link: function(scope, element, attrs) {
40             var model = $parse(attrs.blurMe);
41             scope.$watch(model, function(value) {
42                 if(value === true) 
43                     $timeout(function() {element[0].blur()});
44             });
45             element.bind('focus', function() {
46                 $timeout(function() {
47                     scope.$apply(model.assign(scope, false));
48                 });
49             })
50         }
51     };
52 }])
53
54
55 // <input select-me="iWantToBeSelected"/>
56 // $scope.iWantToBeSelected = true;
57 .directive('selectMe', 
58        ['$timeout','$parse', 
59 function($timeout , $parse) {
60     return {
61         link: function(scope, element, attrs) {
62             var model = $parse(attrs.selectMe);
63             scope.$watch(model, function(value) {
64                 if(value === true) 
65                     $timeout(function() {element[0].select()});
66             });
67             element.bind('blur', function() {
68                 $timeout(function() {
69                     scope.$apply(model.assign(scope, false));
70                 });
71             })
72         }
73     };
74 }])
75
76 // <select int-to-str ><option value="1">Value</option></select>
77 // use integer models for string values
78 .directive('intToStr', function() {
79     return {
80         restrict: 'A',
81         require: 'ngModel',
82         link: function(scope, element, attrs, ngModel) {
83             ngModel.$parsers.push(function(value) {
84                 return parseInt(value);
85             });
86             ngModel.$formatters.push(function(value) {
87                 return '' + value;
88             });
89         }
90     };
91 })
92
93 // <input str-to-int value="10"/>
94 .directive('strToInt', function() {
95     return {
96         restrict: 'A',
97         require: 'ngModel',
98         link: function(scope, element, attrs, ngModel) {
99             ngModel.$parsers.push(function(value) {
100                 return '' + value;
101             });
102             ngModel.$formatters.push(function(value) {
103                 return parseInt(value);
104             });
105         }
106     };
107 })
108
109 // <input float-to-str
110 .directive('floatToStr', function() {
111     return {
112         restrict: 'A',
113         require: 'ngModel',
114         link: function(scope, element, attrs, ngModel) {
115             ngModel.$parsers.push(function(value) {
116                 return parseFloat(value);
117             });
118             ngModel.$formatters.push(function(value) {
119                 return '' + value;
120             });
121         }
122     };
123 })
124
125 .directive('strToFloat', function() {
126     return {
127         restrict: 'A',
128         require: 'ngModel',
129         link: function(scope, element, attrs, ngModel) {
130             ngModel.$parsers.push(function(value) {
131                 return '' + value;
132             });
133             ngModel.$formatters.push(function(value) {
134                 return parseFloat(value);
135             });
136         }
137     };
138 })
139
140 // 'reverse' filter 
141 // <div ng-repeat="item in items | reverse">{{item.name}}</div>
142 // http://stackoverflow.com/questions/15266671/angular-ng-repeat-in-reverse
143 // TODO: perhaps this should live elsewhere
144 .filter('reverse', function() {
145     return function(items) {
146         return items.slice().reverse();
147     };
148 })
149
150 // 'date' filter
151 // Overriding the core angular date filter with a moment-js based one for
152 // better timezone and formatting support.
153 .filter('date',function() {
154
155     var formatMap = {
156         short  : 'l LT',
157         medium : 'lll',
158         long   : 'LLL',
159         full   : 'LLLL',
160
161         shortDate  : 'l',
162         mediumDate : 'll',
163         longDate   : 'LL',
164         fullDate   : 'LL',
165
166         shortTime  : 'LT',
167         mediumTime : 'LTS'
168     };
169
170     var formatReplace = [
171         [ /yyyy/g, 'YYYY' ],
172         [ /yy/g,   'YY'   ],
173         [ /y/g,    'Y'    ],
174         [ /ww/g,   'WW'   ],
175         [ /w/g,    'W'    ],
176         [ /dd/g,   'DD'   ],
177         [ /d/g,    'D'    ],
178         [ /sss/g,  'SSS'  ],
179         [ /EEEE/g, 'dddd' ],
180         [ /EEE/g,  'ddd'  ],
181         [ /Z/g,    'ZZ'   ]
182     ];
183
184     return function (date, format, tz) {
185         if (!date) return '';
186
187         if (date == 'now') 
188             date = new Date().toISOString();
189
190         if (format) {
191             var fmt = formatMap[format] || format;
192             angular.forEach(formatReplace, function (r) {
193                 fmt = fmt.replace(r[0],r[1]);
194             });
195         }
196
197         var d = moment(date);
198         if (tz && tz !== '-') d.tz(tz);
199
200         return d.isValid() ? d.format(fmt) : '';
201     }
202
203 })
204
205 // 'egOrgDate' filter
206 // Uses moment.js and moment-timezone.js to put dates into the most appropriate
207 // timezone for a given (optional) org unit based on its lib.timezone setting
208 .filter('egOrgDate',['$filter','egCore',
209              function($filter , egCore) {
210
211     var tzcache = {};
212
213     function eg_date_filter (date, fmt, ouID) {
214         if (ouID) {
215             if (angular.isObject(ouID)) {
216                 if (angular.isFunction(ouID.id)) {
217                     ouID = ouID.id();
218                 } else {
219                     ouID = ouID.id;
220                 }
221             }
222     
223             if (!tzcache[ouID]) {
224                 tzcache[ouID] = '-';
225                 egCore.org.settings('lib.timezone', ouID)
226                 .then(function(s) {
227                     tzcache[ouID] = s['lib.timezone'] || OpenSRF.tz;
228                 });
229             }
230         }
231
232         return $filter('date')(date, fmt, tzcache[ouID]);
233     }
234
235     eg_date_filter.$stateful = true;
236
237     return eg_date_filter;
238 }])
239
240 // 'egOrgDateInContext' filter
241 // Uses the egOrgDate filter to make time and date location aware, and further
242 // modifies the format if one of [short, medium, long, full] to show only the
243 // date if the optional interval parameter is day-granular.  This is
244 // particularly useful for due dates on circulations.
245 .filter('egOrgDateInContext',['$filter','egCore',
246                       function($filter , egCore) {
247
248     function eg_context_date_filter (date, format, orgID, interval) {
249         var fmt = format;
250         if (!fmt) fmt = 'shortDate';
251
252         // if this is a simple, one-word format, and it doesn't say "Date" in it...
253         if (['short','medium','long','full'].filter(function(x){return fmt == x}).length > 0 && interval) {
254             var secs = egCore.date.intervalToSeconds(interval);
255             if (secs !== null && secs % 86400 == 0) fmt += 'Date';
256         }
257
258         return $filter('egOrgDate')(date, fmt, orgID);
259     }
260
261     eg_context_date_filter.$stateful = true;
262
263     return eg_context_date_filter;
264 }])
265
266 // 'egDueDate' filter
267 // Uses the egOrgDateInContext filter to make time and date location aware, but
268 // only if the supplied interval is day-granular.  This is as wrapper for
269 // egOrgDateInContext to be used for circulation due date /only/.
270 .filter('egDueDate',['$filter','egCore',
271                       function($filter , egCore) {
272
273     function eg_context_due_date_filter (date, format, orgID, interval) {
274         if (interval) {
275             var secs = egCore.date.intervalToSeconds(interval);
276             if (secs === null || secs % 86400 != 0) {
277                 orgID = null;
278                 interval = null;
279             }
280         }
281         return $filter('egOrgDateInContext')(date, format, orgID, interval);
282     }
283
284     eg_context_due_date_filter.$stateful = true;
285
286     return eg_context_due_date_filter;
287 }])
288
289 // 'join' filter
290 // TODO: perhaps this should live elsewhere
291 .filter('join', function() {
292     return function(arr,sep) {
293         if (typeof arr == 'object' && arr.constructor == Array) {
294             return arr.join(sep || ',');
295         } else {
296             return '';
297         }
298     };
299 })
300
301 /**
302  * Progress Dialog. 
303  *
304  * egProgressDialog.open();
305  * egProgressDialog.open({value : 0});
306  * egProgressDialog.open({value : 0, max : 123});
307  * egProgressDialog.increment();
308  * egProgressDialog.increment();
309  * egProgressDialog.close();
310  *
311  * Each dialog has 2 numbers, 'max' and 'value'.
312  * The content of these values determines how the dialog displays.  
313  *
314  * There are 3 flavors:
315  *
316  * -- value is set, max is set
317  * determinate: shows a progression with a percent complete.
318  *
319  * -- value is set, max is unset
320  * semi-determinate, with a value report.  Shows a value-less
321  * <progress/>, but shows the value as a number in the dialog.
322  *
323  * This is useful in cases where the total number of items to retrieve
324  * from the server is unknown, but we know how many items we've
325  * retrieved thus far.  It helps to reinforce that something specific
326  * is happening, but we don't know when it will end.
327  *
328  * -- value is unset
329  * indeterminate: shows a generic value-less <progress/> with no 
330  * clear indication of progress.
331  *
332  * Only 1 egProgressDialog instance will be activate at a time.
333  * Each invocation of .open() destroys any existing instance.
334  */
335
336 /* Simple storage class for egProgressDialog data maintenance.
337  * This data lives outside of egProgressDialog so it can be 
338  * directly imported into egProgressDialog's $uibModalInstance.
339  */
340 .factory('egProgressData', [
341     function() {
342         var service = {}; // max/value initially unset
343
344         service.reset = function() {
345             delete service.max;
346             delete service.value;
347         }
348
349         service.hasvalue = function() {
350             return Number.isInteger(service.value);
351         }
352
353         service.hasmax = function() {
354             return Number.isInteger(service.max);
355         }
356
357         service.percent = function() {
358             if (service.hasvalue()  && 
359                 service.hasmax()    && 
360                 service.max > 0     &&
361                 service.value <= service.max)
362                 return Math.floor((service.value / service.max) * 100);
363             return 100;
364         }
365
366         return service;
367     }
368 ])
369
370 .factory('egProgressDialog', [
371             'egProgressData','$uibModal', 
372     function(egProgressData , $uibModal) {
373     var service = {};
374
375     service.open = function(args) {
376         return $uibModal.open({
377             templateUrl: './share/t_progress_dialog',
378             /* backdrop: 'static', */ /* allow 'cancelling' of progress dialog */
379             controller: ['$scope','$uibModalInstance','egProgressData',
380                 function( $scope , $uibModalInstance , egProgressData) {
381                     // Once the new modal instance is available, force-
382                     // kill any other instances
383                     service.close(true); 
384
385                     // Reset to an indeterminate progress bar, 
386                     // overlay with caller values.
387                     egProgressData.reset();
388                     service.update(angular.extend({}, args));
389
390                     service.currentInstance = $uibModalInstance;
391                     $scope.data = egProgressData; // tiny service
392                 }
393             ]
394         });
395     };
396
397     service.close = function(warn) {
398         if (service.currentInstance) {
399             if (warn) {
400                 console.warn("egProgressDialog replacing existing instance. "
401                     + "Only one may be open at a time.");
402             }
403             service.currentInstance.close();
404             delete service.currentInstance;
405         }
406     }
407
408     // Set the current state of the progress bar.
409     service.update = function(args) {
410         if (args.max != undefined) 
411             egProgressData.max = args.max;
412         if (args.value != undefined) 
413             egProgressData.value = args.value;
414     }
415
416     // Increment the current value.  If no amount is specified,
417     // it increments by 1.  Calling increment() on an indetermite
418     // progress bar will force it to be a (semi-)determinate bar.
419     service.increment = function(amt) {
420         if (!Number.isInteger(amt)) amt = 1;
421
422         if (!egProgressData.hasvalue())
423             egProgressData.value = 0;
424
425         egProgressData.value += amt;
426     }
427
428     return service;
429 }])
430
431 /**
432  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
433  *     function() { console.log('alert closed') });
434  */
435 .factory('egAlertDialog', 
436
437         ['$uibModal','$interpolate',
438 function($uibModal , $interpolate) {
439     var service = {};
440
441     service.open = function(message, msg_scope) {
442         return $uibModal.open({
443             templateUrl: './share/t_alert_dialog',
444             backdrop: 'static',
445             controller: ['$scope', '$uibModalInstance',
446                 function($scope, $uibModalInstance) {
447                     $scope.message = $interpolate(message)(msg_scope);
448                     $scope.ok = function() {
449                         if (msg_scope && msg_scope.ok) msg_scope.ok();
450                         $uibModalInstance.close()
451                     }
452                 }
453             ]
454         });
455     }
456
457     return service;
458 }])
459
460 /**
461  * egConfirmDialog.open("some message goes {{here}}", {
462  *  here : 'foo', ok : function() {}, cancel : function() {}},
463  *  'OK', 'Cancel');
464  */
465 .factory('egConfirmDialog', 
466     
467        ['$uibModal','$interpolate',
468 function($uibModal, $interpolate) {
469     var service = {};
470
471     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
472         msg_scope = msg_scope || {};
473         return $uibModal.open({
474             templateUrl: './share/t_confirm_dialog',
475             backdrop: 'static',
476             controller: ['$scope', '$uibModalInstance',
477                 function($scope, $uibModalInstance) {
478                     $scope.title = $interpolate(title)(msg_scope);
479                     $scope.message = $interpolate(message)(msg_scope);
480                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
481                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
482                     $scope.ok = function() {
483                         if (msg_scope.ok) msg_scope.ok();
484                         $uibModalInstance.close()
485                     }
486                     $scope.cancel = function() {
487                         if (msg_scope.cancel) msg_scope.cancel();
488                         $uibModalInstance.dismiss();
489                     }
490                 }
491             ]
492         })
493     }
494
495     return service;
496 }])
497
498 /**
499  * egPromptDialog.open(
500  *    "prompt message goes {{here}}", 
501  *    promptValue,  // optional
502  *    {
503  *      here : 'foo',  
504  *      ok : function(value) {console.log(value)}, 
505  *      cancel : function() {console.log('prompt denied')}
506  *    }
507  *  );
508  */
509 .factory('egPromptDialog', 
510     
511        ['$uibModal','$interpolate',
512 function($uibModal, $interpolate) {
513     var service = {};
514
515     service.open = function(message, promptValue, msg_scope) {
516         return $uibModal.open({
517             templateUrl: './share/t_prompt_dialog',
518             backdrop: 'static',
519             controller: ['$scope', '$uibModalInstance',
520                 function($scope, $uibModalInstance) {
521                     $scope.message = $interpolate(message)(msg_scope);
522                     $scope.args = {value : promptValue || ''};
523                     $scope.focus = true;
524                     $scope.ok = function() {
525                         if (msg_scope && msg_scope.ok) msg_scope.ok($scope.args.value);
526                         $uibModalInstance.close($scope.args);
527                     }
528                     $scope.cancel = function() {
529                         if (msg_scope && msg_scope.cancel) msg_scope.cancel();
530                         $uibModalInstance.dismiss();
531                     }
532                 }
533             ]
534         })
535     }
536
537     return service;
538 }])
539
540 /**
541  * egSelectDialog.open(
542  *    "message goes {{here}}", 
543  *    list,           // ['values','for','dropdown'],
544  *    selectedValue,  // optional
545  *    {
546  *      here : 'foo',
547  *      ok : function(value) {console.log(value)}, 
548  *      cancel : function() {console.log('prompt denied')}
549  *    }
550  *  );
551  */
552 .factory('egSelectDialog', 
553     
554        ['$uibModal','$interpolate',
555 function($uibModal, $interpolate) {
556     var service = {};
557
558     service.open = function(message, inputList, selectedValue, msg_scope) {
559         return $uibModal.open({
560             templateUrl: './share/t_select_dialog',
561             backdrop: 'static',
562             controller: ['$scope', '$uibModalInstance',
563                 function($scope, $uibModalInstance) {
564                     $scope.message = $interpolate(message)(msg_scope);
565                     $scope.args = {
566                         list  : inputList,
567                         value : selectedValue
568                     };
569                     $scope.focus = true;
570                     $scope.ok = function() {
571                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
572                         $uibModalInstance.close()
573                     }
574                     $scope.cancel = function() {
575                         if (msg_scope.cancel) msg_scope.cancel();
576                         $uibModalInstance.dismiss();
577                     }
578                 }
579             ]
580         })
581     }
582
583     return service;
584 }])
585
586 /**
587  * Warn on page unload and give the user a chance to avoid navigating
588  * away from the current page.  
589  * Only one handler is supported per page.
590  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
591  * it renders asynchronously, which allows the page to redirect before
592  * the dialog appears.
593  */
594 .factory('egUnloadPrompt', [
595         '$window','egStrings', 
596 function($window , egStrings) {
597     var service = {attached : false};
598
599     // attach a page/scope unload prompt
600     service.attach = function($scope, msg) {
601         if (service.attached) return;
602         service.attached = true;
603
604         // handle page change
605         $($window).on('beforeunload', function() { 
606             service.clear();
607             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
608         });
609
610         if (!$scope) return;
611
612         // If a scope was provided, attach a scope-change handler,
613         // similar to the page-page prompt.
614         service.locChangeCancel = 
615             $scope.$on('$locationChangeStart', function(evt, next, current) {
616             if (confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) {
617                 // user allowed the page to change.  
618                 // Clear the unload handler.
619                 service.clear();
620             } else {
621                 evt.preventDefault();
622             }
623         });
624     };
625
626     // remove the page unload prompt
627     service.clear = function() {
628         $($window).off('beforeunload');
629         if (service.locChangeCancel)
630             service.locChangeCancel();
631         service.attached = false;
632     }
633
634     return service;
635 }])
636
637 .directive('aDisabled', function() {
638     return {
639         restrict : 'A',
640         compile: function(tElement, tAttrs, transclude) {
641             //Disable ngClick
642             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
643
644             //Toggle "disabled" to class when aDisabled becomes true
645             return function (scope, iElement, iAttrs) {
646                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
647                     if (newValue !== undefined) {
648                         iElement.toggleClass("disabled", newValue);
649                     }
650                 });
651
652                 //Disable href on click
653                 iElement.on("click", function(e) {
654                     if (scope.$eval(iAttrs["aDisabled"])) {
655                         e.preventDefault();
656                     }
657                 });
658             };
659         }
660     };
661 })
662
663 .directive('egBasicComboBox', function() {
664     return {
665         restrict: 'E',
666         replace: true,
667         scope: {
668             list: "=", // list of strings
669             selected: "=",
670             onSelect: "=",
671             egDisabled: "=",
672             allowAll: "@",
673             placeholder: "@",
674             focusMe: "=?"
675         },
676         template:
677             '<div class="input-group">'+
678                 '<input placeholder="{{placeholder}}" type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()" focus-me="focusMe">'+
679                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
680                     '<button type="button" ng-click="showAll()" ng-disabled="egDisabled" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
681                     '<ul class="dropdown-menu dropdown-menu-right">'+
682                         '<li ng-repeat="item in list|filter:selected:compare"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
683                         '<li ng-if="complete_list" class="divider"><span></span></li>'+
684                         '<li ng-if="complete_list" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
685                     '</ul>'+
686                 '</div>'+
687             '</div>',
688         controller: ['$scope','$filter',
689             function( $scope , $filter) {
690
691                 $scope.complete_list = false;
692                 $scope.isopen = false;
693                 $scope.clickedopen = false;
694                 $scope.clickedclosed = null;
695
696                 $scope.compare = function (ex, act) {
697                     if (act === null || act === undefined) return true;
698                     if (act.toString) act = act.toString();
699                     return new RegExp(act.toLowerCase()).test(ex)
700                 }
701
702                 $scope.showAll = function () {
703
704                     $scope.clickedopen = !$scope.clickedopen;
705
706                     if ($scope.clickedclosed === null) {
707                         if (!$scope.clickedopen) {
708                             $scope.clickedclosed = true;
709                         }
710                     } else {
711                         $scope.clickedclosed = !$scope.clickedopen;
712                     }
713
714                     if ($scope.selected && $scope.selected.length > 0) $scope.complete_list = true;
715                     if (!$scope.selected || $scope.selected.length == 0) $scope.complete_list = false;
716                     $scope.makeOpen();
717                 }
718
719                 $scope.makeOpen = function () {
720                     $scope.isopen = $scope.clickedopen || ($filter('filter')(
721                         $scope.list,
722                         $scope.selected
723                     ).length > 0 && $scope.selected.length > 0);
724                     if ($scope.clickedclosed) {
725                         $scope.isopen = false;
726                         $scope.clickedclosed = null;
727                     }
728                 }
729
730                 $scope.changeValue = function (newVal) {
731                     $scope.selected = newVal;
732                     $scope.isopen = false;
733                     $scope.clickedclosed = null;
734                     $scope.clickedopen = false;
735                     if ($scope.selected.length == 0) $scope.complete_list = false;
736                     if ($scope.onSelect) $scope.onSelect();
737                 }
738
739             }
740         ]
741     };
742 })
743
744 /**
745  * Nested org unit selector modeled as a Bootstrap dropdown button.
746  */
747 .directive('egOrgSelector', function() {
748     return {
749         restrict : 'AE',
750         transclude : true,
751         replace : true, // makes styling easier
752         scope : {
753             selected : '=', // defaults to workstation or root org,
754                             // unless the nodefault attibute exists
755
756             // Each org unit is passed into this function and, for
757             // any org units where the response value is true, the
758             // org unit will not be added to the selector.
759             hiddenTest : '=',
760
761             // Each org unit is passed into this function and, for
762             // any org units where the response value is true, the
763             // org unit will not be available for selection.
764             disableTest : '=',
765
766             // if set to true, disable the UI element altogether
767             alldisabled : '@',
768
769             // Caller can either $watch(selected, ..) or register an
770             // onchange handler.
771             onchange : '=',
772
773             // optional primary drop-down button label
774             label : '@',
775
776             // optional name of settings key for persisting
777             // the last selected org unit
778             stickySetting : '@'
779         },
780
781         // any reason to move this into a TT2 template?
782         template : 
783             '<div class="btn-group eg-org-selector" uib-dropdown>'
784             + '<button type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disable_button">'
785              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
786              + '<span class="caret"></span>'
787            + '</button>'
788            + '<ul uib-dropdown-menu class="scrollable-menu">'
789              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
790                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
791                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
792                  + '{{org.shortname}}'
793                + '</a>'
794              + '</li>'
795            + '</ul>'
796           + '</div>',
797
798         controller : ['$scope','$timeout','egCore','egStartup','egLovefield','$q',
799               function($scope , $timeout , egCore , egStartup , egLovefield , $q) {
800
801             if ($scope.alldisabled) {
802                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
803             } else {
804                 $scope.disable_button = false;
805             }
806
807             // avoid linking the full fleshed tree to the scope by 
808             // tossing in a flattened list.
809             // --
810             // Run-time code referencing post-start data should be run
811             // from within a startup block, otherwise accessing this
812             // module before startup completes will lead to failure.
813             //
814             // controller() runs before link().
815             // This post-startup code runs after link().
816             egStartup.go(
817             ).then(
818                 function() {
819                     return egCore.env.classLoaders.aou();
820                 }
821             ).then(
822                 function() {
823
824                     $scope.orgList = egCore.org.list().map(function(org) {
825                         return {
826                             id : org.id(),
827                             shortname : org.shortname(), 
828                             depth : org.ou_type().depth()
829                         }
830                     });
831                     
832     
833                     // Apply default values
834     
835                     if ($scope.stickySetting) {
836                         var orgId = egCore.hatch.getLocalItem($scope.stickySetting);
837                         if (orgId) {
838                             $scope.selected = egCore.org.get(orgId);
839                         }
840                     }
841     
842                     if (!$scope.selected && !$scope.nodefault && egCore.auth.user()) {
843                         $scope.selected = 
844                             egCore.org.get(egCore.auth.user().ws_ou());
845                     }
846     
847                     fire_orgsel_onchange(); // no-op if nothing is selected
848                 }
849             );
850
851             /**
852              * Fire onchange handler after a timeout, so the
853              * $scope.selected value has a chance to propagate to
854              * the page controllers before the onchange fires.  This
855              * way, the caller does not have to manually capture the
856              * $scope.selected value during onchange.
857              */
858             function fire_orgsel_onchange() {
859                 if (!$scope.selected || !$scope.onchange) return;
860                 $timeout(function() {
861                     console.debug(
862                         'egOrgSelector onchange('+$scope.selected.id()+')');
863                     $scope.onchange($scope.selected)
864                 });
865             }
866
867             $scope.getSelectedName = function() {
868                 if ($scope.selected && $scope.selected.shortname)
869                     return $scope.selected.shortname();
870                 return $scope.label;
871             }
872
873             $scope.orgChanged = function(org) {
874                 $scope.selected = egCore.org.get(org.id);
875                 if ($scope.stickySetting) {
876                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
877                 }
878                 fire_orgsel_onchange();
879             }
880
881         }],
882         link : function(scope, element, attrs, egGridCtrl) {
883
884             // boolean fields are presented as value-less attributes
885             angular.forEach(
886                 ['nodefault'],
887                 function(field) {
888                     if (angular.isDefined(attrs[field]))
889                         scope[field] = true;
890                     else
891                         scope[field] = false;
892                 }
893             );
894         }
895     }
896 })
897
898 .directive('nextOnEnter', function () {
899     return function (scope, element, attrs) {
900         element.bind("keydown keypress", function (event) {
901             if(event.which === 13) {
902                 $('#'+attrs.nextOnEnter).focus();
903                 event.preventDefault();
904             }
905         });
906     };
907 })
908
909 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
910 .directive('egEnter', function () {
911     return function (scope, element, attrs) {
912         element.bind("keydown keypress", function (event) {
913             if(event.which === 13) {
914                 scope.$apply(function (){
915                     scope.$eval(attrs.egEnter);
916                 });
917  
918                 event.preventDefault();
919             }
920         });
921     };
922 })
923
924 /*
925 * Handy wrapper directive for uib-datapicker-popup
926 */
927 .directive(
928     'egDateInput', ['egStrings', 'egCore',
929     function(egStrings, egCore) {
930         return {
931             scope : {
932                 id : '@',
933                 closeText : '@',
934                 ngModel : '=',
935                 ngChange : '=',
936                 ngBlur : '=',
937                 minDate : '=?',
938                 maxDate : '=?',
939                 ngDisabled : '=',
940                 ngRequired : '=',
941                 hideDatePicker : '=',
942                 dateFormat : '=?',
943                 outOfRange : '=?',
944                 focusMe : '=?'
945             },
946             require: 'ngModel',
947             templateUrl: './share/t_datetime',
948             replace: true,
949             controller : ['$scope', function($scope) {
950                 $scope.options = {
951                     minDate : $scope.minDate,
952                     maxDate : $scope.maxDate
953                 };
954
955                 var maxDateObj = $scope.maxDate ? new Date($scope.maxDate) : null;
956                 var minDateObj = $scope.minDate ? new Date($scope.minDate) : null;
957
958                 if ($scope.outOfRange !== undefined && (maxDateObj || minDateObj)) {
959                     $scope.$watch('ngModel', function (n,o) {
960                         if (n && n != o) {
961                             var bad = false;
962                             var newdate = new Date(n);
963                             if (maxDateObj && newdate.getTime() > maxDateObj.getTime()) bad = true;
964                             if (minDateObj && newdate.getTime() < minDateObj.getTime()) bad = true;
965                             $scope.outOfRange = bad;
966                         }
967                     });
968                 }
969             }],
970             link : function(scope, elm, attrs) {
971                 if (!scope.closeText)
972                     scope.closeText = egStrings.EG_DATE_INPUT_CLOSE_TEXT;
973
974                 if ('showTimePicker' in attrs)
975                     scope.showTimePicker = true;
976
977                 var default_format = 'mediumDate';
978                 egCore.org.settings(['format.date']).then(function(set) {
979                     default_format = set['format.date'];
980                     scope.date_format = (scope.dateFormat) ?
981                         scope.dateFormat :
982                         default_format;
983                 });
984             }
985         };
986     }
987 ])
988
989 /*
990  *  egFmValueSelector - widget for selecting a value from list specified
991  *                      by IDL class
992  */
993 .directive('egFmValueSelector', function() {
994     return {
995         restrict : 'E',
996         transclude : true,
997         scope : {
998             idlClass : '@',
999             ngModel : '=',
1000
1001             // optional filter for refining the set of rows that
1002             // get returned. Example:
1003             //
1004             // filter="{'column':{'=':null}}"
1005             filter : '=',
1006
1007             // optional name of settings key for persisting
1008             // the last selected value
1009             stickySetting : '@',
1010
1011             // optional OU setting for fetching default value;
1012             // used only if sticky setting not set
1013             ouSetting : '@'
1014         },
1015         require: 'ngModel',
1016         templateUrl : './share/t_fm_value_selector',
1017         controller : ['$scope','egCore', function($scope , egCore) {
1018
1019             $scope.org = egCore.org; // for use in the link function
1020             $scope.auth = egCore.auth; // for use in the link function
1021             $scope.hatch = egCore.hatch // for use in the link function
1022
1023             function flatten_linked_values(cls, list) {
1024                 var results = [];
1025                 var fields = egCore.idl.classes[cls].fields;
1026                 var id_field;
1027                 var selector;
1028                 angular.forEach(fields, function(fld) {
1029                     if (fld.datatype == 'id') {
1030                         id_field = fld.name;
1031                         selector = fld.selector ? fld.selector : id_field;
1032                         return;
1033                     }
1034                 });
1035                 angular.forEach(list, function(item) {
1036                     var rec = egCore.idl.toHash(item);
1037                     results.push({
1038                         id : rec[id_field],
1039                         name : rec[selector]
1040                     });
1041                 });
1042                 return results;
1043             }
1044
1045             var search = {};
1046             search[egCore.idl.classes[$scope.idlClass].pkey] = {'!=' : null};
1047             if ($scope.filter) {
1048                 angular.extend(search, $scope.filter);
1049             }
1050             egCore.pcrud.search(
1051                 $scope.idlClass, search, {}, {atomic : true}
1052             ).then(function(list) {
1053                 $scope.linked_values = flatten_linked_values($scope.idlClass, list);
1054             });
1055
1056             $scope.handleChange = function(value) {
1057                 if ($scope.stickySetting) {
1058                     egCore.hatch.setLocalItem($scope.stickySetting, value);
1059                 }
1060             }
1061
1062         }],
1063         link : function(scope, element, attrs) {
1064             if (scope.stickySetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
1065                 var value = scope.hatch.getLocalItem(scope.stickySetting);
1066                 scope.ngModel = value;
1067             }
1068             if (scope.ouSetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
1069                 scope.org.settings([scope.ouSetting], scope.auth.user().ws_ou())
1070                 .then(function(set) {
1071                     var value = parseInt(set[scope.ouSetting]);
1072                     if (!isNaN(value))
1073                         scope.ngModel = value;
1074                 });
1075             }
1076         }
1077     }
1078 })
1079
1080 /*
1081  *  egShareDepthSelector - widget for selecting a share depth
1082  */
1083 .directive('egShareDepthSelector', function() {
1084     return {
1085         restrict : 'E',
1086         transclude : true,
1087         scope : {
1088             ngModel : '=',
1089         },
1090         require: 'ngModel',
1091         templateUrl : './share/t_share_depth_selector',
1092         controller : ['$scope','egCore', function($scope , egCore) {
1093             $scope.values = [];
1094             egCore.pcrud.search('aout',
1095                 { id : {'!=' : null} },
1096                 { order_by : {aout : ['depth', 'name']} },
1097                 { atomic : true }
1098             ).then(function(list) {
1099                 var scratch = [];
1100                 angular.forEach(list, function(aout) {
1101                     var depth = parseInt(aout.depth());
1102                     if (depth in scratch) {
1103                         scratch[depth].push(aout.name());
1104                     } else {
1105                         scratch[depth] = [ aout.name() ]
1106                     }
1107                 });
1108                 scratch.forEach(function(val, idx) {
1109                     $scope.values.push({ id : idx,  name : scratch[idx].join(' / ') });
1110                 });
1111             });
1112         }]
1113     }
1114 })
1115
1116 /*
1117  * egHelpPopover - a helpful widget
1118  */
1119 .directive('egHelpPopover', function() {
1120     return {
1121         restrict : 'E',
1122         transclude : true,
1123         scope : {
1124             helpText : '@',
1125             helpLink : '@'
1126         },
1127         templateUrl : './share/t_help_popover',
1128         controller : ['$scope','$sce', function($scope , $sce) {
1129             if ($scope.helpLink) {
1130                 $scope.helpHtml = $sce.trustAsHtml(
1131                     '<a target="_new" href="' + $scope.helpLink + '">' +
1132                     $scope.helpText + '</a>'
1133                 );
1134             }
1135         }]
1136     }
1137 })
1138
1139 .factory('egWorkLog', ['egCore', function(egCore) {
1140     var service = {};
1141
1142     service.retrieve_all = function() {
1143         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1144         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1145
1146         return { 'work_log' : workLog, 'patron_log' : patronLog };
1147     }
1148
1149     service.record = function(message,data) {
1150         var max_entries;
1151         var max_patrons;
1152         if (typeof egCore != 'undefined') {
1153             if (typeof egCore.env != 'undefined') {
1154                 if (typeof egCore.env.aous != 'undefined') {
1155                     max_entries = egCore.env.aous['ui.admin.work_log.max_entries'];
1156                     max_patrons = egCore.env.aous['ui.admin.patron_log.max_entries'];
1157                 } else {
1158                     console.log('worklog: missing egCore.env.aous');
1159                 }
1160             } else {
1161                 console.log('worklog: missing egCore.env');
1162             }
1163         } else {
1164             console.log('worklog: missing egCore');
1165         }
1166         if (!max_entries) {
1167             if (typeof egCore.org != 'undefined') {
1168                 if (typeof egCore.org.cachedSettings != 'undefined') {
1169                     max_entries = egCore.org.cachedSettings['ui.admin.work_log.max_entries'];
1170                 } else {
1171                     console.log('worklog: missing egCore.org.cachedSettings');
1172                 }
1173             } else {
1174                 console.log('worklog: missing egCore.org');
1175             }
1176         }
1177         if (!max_patrons) {
1178             if (typeof egCore.org != 'undefined') {
1179                 if (typeof egCore.org.cachedSettings != 'undefined') {
1180                     max_patrons = egCore.org.cachedSettings['ui.admin.patron_log.max_entries'];
1181                 } else {
1182                     console.log('worklog: missing egCore.org.cachedSettings');
1183                 }
1184             } else {
1185                 console.log('worklog: missing egCore.org');
1186             }
1187         }
1188         if (!max_entries) {
1189             max_entries = 20;
1190             console.log('worklog: defaulting to max_entries = ' + max_entries);
1191         }
1192         if (!max_patrons) {
1193             max_patrons = 10;
1194             console.log('worklog: defaulting to max_patrons = ' + max_patrons);
1195         }
1196
1197         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1198         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1199         var entry = {
1200             'when' : new Date(),
1201             'msg' : message,
1202             'action' : data.action,
1203             'actor' : egCore.auth.user().usrname()
1204         };
1205         if (data.action == 'checkin') {
1206             entry['item'] = data.response.params.copy_barcode;
1207             entry['item_id'] = data.response.data.acp.id();
1208             if (data.response.data.au) {
1209                 entry['user'] = data.response.data.au.family_name();
1210                 entry['patron_id'] = data.response.data.au.id();
1211             }
1212         }
1213         if (data.action == 'checkout') {
1214             entry['item'] = data.response.params.copy_barcode;
1215             entry['user'] = data.response.data.au.family_name();
1216             entry['item_id'] = data.response.data.acp.id();
1217             entry['patron_id'] = data.response.data.au.id();
1218         }
1219         if (data.action == 'noncat_checkout') {
1220             entry['user'] = data.response.data.au.family_name();
1221             entry['patron_id'] = data.response.data.au.id();
1222         }
1223         if (data.action == 'renew') {
1224             entry['item'] = data.response.params.copy_barcode;
1225             entry['user'] = data.response.data.au.family_name();
1226             entry['item_id'] = data.response.data.acp.id();
1227             entry['patron_id'] = data.response.data.au.id();
1228         }
1229         if (data.action == 'requested_hold'
1230             || data.action == 'edited_patron'
1231             || data.action == 'registered_patron'
1232             || data.action == 'paid_bill') {
1233             entry['patron_id'] = data.patron_id;
1234         }
1235         if (data.action == 'requested_hold') {
1236             entry['hold_id'] = data.hold_id;
1237         }
1238         if (data.action == 'paid_bill') {
1239             entry['amount'] = data.total_amount;
1240         }
1241
1242         workLog.push( entry );
1243         if (workLog.length > max_entries) workLog.shift();
1244         egCore.hatch.setLocalItem('eg.work_log',workLog); // hatch JSONifies the data, so should be okay re: memory leaks?
1245
1246         if (entry['patron_id']) {
1247             var temp = [];
1248             for (var i = 0; i < patronLog.length; i++) { // filter out any matching patron
1249                 if (patronLog[i]['patron_id'] != entry['patron_id']) temp.push(patronLog[i]);
1250             }
1251             temp.push( entry );
1252             if (temp.length > max_patrons) temp.shift();
1253             patronLog = temp;
1254             egCore.hatch.setLocalItem('eg.patron_log',patronLog);
1255         }
1256
1257         console.log('worklog',entry);
1258     }
1259
1260     return service;
1261 }]);