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