]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/ui.js
LP#1717007 Improve egProgressDialog collision handling
[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         return $uibModal.open({
314             templateUrl: './share/t_progress_dialog',
315             controller: ['$scope','$uibModalInstance','egProgressData',
316                 function( $scope , $uibModalInstance , egProgressData) {
317                     // Once the new modal instance is available, force-
318                     // kill any other instances
319                     service.close(true); 
320
321                     // Reset to an indeterminate progress bar, 
322                     // overlay with caller values.
323                     egProgressData.reset();
324                     service.update(angular.extend({}, args));
325
326                     service.currentInstance = $uibModalInstance;
327                     $scope.data = egProgressData; // tiny service
328                 }
329             ]
330         });
331     };
332
333     service.close = function(warn) {
334         if (service.currentInstance) {
335             if (warn) {
336                 console.warn("egProgressDialog replacing existing instance. "
337                     + "Only one may be open at a time.");
338             }
339             service.currentInstance.close();
340             delete service.currentInstance;
341         }
342     }
343
344     // Set the current state of the progress bar.
345     service.update = function(args) {
346         if (args.max != undefined) 
347             egProgressData.max = args.max;
348         if (args.value != undefined) 
349             egProgressData.value = args.value;
350     }
351
352     // Increment the current value.  If no amount is specified,
353     // it increments by 1.  Calling increment() on an indetermite
354     // progress bar will force it to be a (semi-)determinate bar.
355     service.increment = function(amt) {
356         if (!Number.isInteger(amt)) amt = 1;
357
358         if (!egProgressData.hasvalue())
359             egProgressData.value = 0;
360
361         egProgressData.value += amt;
362     }
363
364     return service;
365 }])
366
367 /**
368  * egAlertDialog.open({message : 'hello {{name}}'}).result.then(
369  *     function() { console.log('alert closed') });
370  */
371 .factory('egAlertDialog', 
372
373         ['$uibModal','$interpolate',
374 function($uibModal , $interpolate) {
375     var service = {};
376
377     service.open = function(message, msg_scope) {
378         return $uibModal.open({
379             templateUrl: './share/t_alert_dialog',
380             controller: ['$scope', '$uibModalInstance',
381                 function($scope, $uibModalInstance) {
382                     $scope.message = $interpolate(message)(msg_scope);
383                     $scope.ok = function() {
384                         if (msg_scope && msg_scope.ok) msg_scope.ok();
385                         $uibModalInstance.close()
386                     }
387                 }
388             ]
389         });
390     }
391
392     return service;
393 }])
394
395 /**
396  * egConfirmDialog.open("some message goes {{here}}", {
397  *  here : 'foo', ok : function() {}, cancel : function() {}},
398  *  'OK', 'Cancel');
399  */
400 .factory('egConfirmDialog', 
401     
402        ['$uibModal','$interpolate',
403 function($uibModal, $interpolate) {
404     var service = {};
405
406     service.open = function(title, message, msg_scope, ok_button_label, cancel_button_label) {
407         msg_scope = msg_scope || {};
408         return $uibModal.open({
409             templateUrl: './share/t_confirm_dialog',
410             controller: ['$scope', '$uibModalInstance',
411                 function($scope, $uibModalInstance) {
412                     $scope.title = $interpolate(title)(msg_scope);
413                     $scope.message = $interpolate(message)(msg_scope);
414                     $scope.ok_button_label = $interpolate(ok_button_label || '')(msg_scope);
415                     $scope.cancel_button_label = $interpolate(cancel_button_label || '')(msg_scope);
416                     $scope.ok = function() {
417                         if (msg_scope.ok) msg_scope.ok();
418                         $uibModalInstance.close()
419                     }
420                     $scope.cancel = function() {
421                         if (msg_scope.cancel) msg_scope.cancel();
422                         $uibModalInstance.dismiss();
423                     }
424                 }
425             ]
426         })
427     }
428
429     return service;
430 }])
431
432 /**
433  * egPromptDialog.open(
434  *    "prompt message goes {{here}}", 
435  *    promptValue,  // optional
436  *    {
437  *      here : 'foo',  
438  *      ok : function(value) {console.log(value)}, 
439  *      cancel : function() {console.log('prompt denied')}
440  *    }
441  *  );
442  */
443 .factory('egPromptDialog', 
444     
445        ['$uibModal','$interpolate',
446 function($uibModal, $interpolate) {
447     var service = {};
448
449     service.open = function(message, promptValue, msg_scope) {
450         return $uibModal.open({
451             templateUrl: './share/t_prompt_dialog',
452             controller: ['$scope', '$uibModalInstance',
453                 function($scope, $uibModalInstance) {
454                     $scope.message = $interpolate(message)(msg_scope);
455                     $scope.args = {value : promptValue || ''};
456                     $scope.focus = true;
457                     $scope.ok = function() {
458                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
459                         $uibModalInstance.close()
460                     }
461                     $scope.cancel = function() {
462                         if (msg_scope.cancel) msg_scope.cancel();
463                         $uibModalInstance.dismiss();
464                     }
465                 }
466             ]
467         })
468     }
469
470     return service;
471 }])
472
473 /**
474  * egSelectDialog.open(
475  *    "message goes {{here}}", 
476  *    list,           // ['values','for','dropdown'],
477  *    selectedValue,  // optional
478  *    {
479  *      here : 'foo',
480  *      ok : function(value) {console.log(value)}, 
481  *      cancel : function() {console.log('prompt denied')}
482  *    }
483  *  );
484  */
485 .factory('egSelectDialog', 
486     
487        ['$uibModal','$interpolate',
488 function($uibModal, $interpolate) {
489     var service = {};
490
491     service.open = function(message, inputList, selectedValue, msg_scope) {
492         return $uibModal.open({
493             templateUrl: './share/t_select_dialog',
494             controller: ['$scope', '$uibModalInstance',
495                 function($scope, $uibModalInstance) {
496                     $scope.message = $interpolate(message)(msg_scope);
497                     $scope.args = {
498                         list  : inputList,
499                         value : selectedValue
500                     };
501                     $scope.focus = true;
502                     $scope.ok = function() {
503                         if (msg_scope.ok) msg_scope.ok($scope.args.value);
504                         $uibModalInstance.close()
505                     }
506                     $scope.cancel = function() {
507                         if (msg_scope.cancel) msg_scope.cancel();
508                         $uibModalInstance.dismiss();
509                     }
510                 }
511             ]
512         })
513     }
514
515     return service;
516 }])
517
518 /**
519  * Warn on page unload and give the user a chance to avoid navigating
520  * away from the current page.  
521  * Only one handler is supported per page.
522  * NOTE: we can't use an egUnloadDialog as the dialog builder, because
523  * it renders asynchronously, which allows the page to redirect before
524  * the dialog appears.
525  */
526 .factory('egUnloadPrompt', [
527         '$window','egStrings', 
528 function($window , egStrings) {
529     var service = {attached : false};
530
531     // attach a page/scope unload prompt
532     service.attach = function($scope, msg) {
533         if (service.attached) return;
534         service.attached = true;
535
536         // handle page change
537         $($window).on('beforeunload', function() { 
538             service.clear();
539             return msg || egStrings.EG_UNLOAD_PAGE_PROMPT_MSG;
540         });
541
542         if (!$scope) return;
543
544         // If a scope was provided, attach a scope-change handler,
545         // similar to the page-page prompt.
546         service.locChangeCancel = 
547             $scope.$on('$locationChangeStart', function(evt, next, current) {
548             if (confirm(msg || egStrings.EG_UNLOAD_CTRL_PROMPT_MSG)) {
549                 // user allowed the page to change.  
550                 // Clear the unload handler.
551                 service.clear();
552             } else {
553                 evt.preventDefault();
554             }
555         });
556     };
557
558     // remove the page unload prompt
559     service.clear = function() {
560         $($window).off('beforeunload');
561         if (service.locChangeCancel)
562             service.locChangeCancel();
563         service.attached = false;
564     }
565
566     return service;
567 }])
568
569 .directive('aDisabled', function() {
570     return {
571         restrict : 'A',
572         compile: function(tElement, tAttrs, transclude) {
573             //Disable ngClick
574             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
575
576             //Toggle "disabled" to class when aDisabled becomes true
577             return function (scope, iElement, iAttrs) {
578                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
579                     if (newValue !== undefined) {
580                         iElement.toggleClass("disabled", newValue);
581                     }
582                 });
583
584                 //Disable href on click
585                 iElement.on("click", function(e) {
586                     if (scope.$eval(iAttrs["aDisabled"])) {
587                         e.preventDefault();
588                     }
589                 });
590             };
591         }
592     };
593 })
594
595 .directive('egBasicComboBox', function() {
596     return {
597         restrict: 'E',
598         replace: true,
599         scope: {
600             list: "=", // list of strings
601             selected: "=",
602             onSelect: "=",
603             egDisabled: "=",
604             allowAll: "@",
605             placeholder: "@",
606             focusMe: "=?"
607         },
608         template:
609             '<div class="input-group">'+
610                 '<input placeholder="{{placeholder}}" type="text" ng-disabled="egDisabled" class="form-control" ng-model="selected" ng-change="makeOpen()" focus-me="focusMe">'+
611                 '<div class="input-group-btn" dropdown ng-class="{open:isopen}">'+
612                     '<button type="button" ng-click="showAll()" ng-disabled="egDisabled" class="btn btn-default dropdown-toggle"><span class="caret"></span></button>'+
613                     '<ul class="dropdown-menu dropdown-menu-right">'+
614                         '<li ng-repeat="item in list|filter:selected:compare"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
615                         '<li ng-if="complete_list" class="divider"><span></span></li>'+
616                         '<li ng-if="complete_list" ng-repeat="item in list"><a href ng-click="changeValue(item)">{{item}}</a></li>'+
617                     '</ul>'+
618                 '</div>'+
619             '</div>',
620         controller: ['$scope','$filter',
621             function( $scope , $filter) {
622
623                 $scope.complete_list = false;
624                 $scope.isopen = false;
625                 $scope.clickedopen = false;
626                 $scope.clickedclosed = null;
627
628                 $scope.compare = function (ex, act) {
629                     if (act === null || act === undefined) return true;
630                     if (act.toString) act = act.toString();
631                     return new RegExp(act.toLowerCase()).test(ex)
632                 }
633
634                 $scope.showAll = function () {
635
636                     $scope.clickedopen = !$scope.clickedopen;
637
638                     if ($scope.clickedclosed === null) {
639                         if (!$scope.clickedopen) {
640                             $scope.clickedclosed = true;
641                         }
642                     } else {
643                         $scope.clickedclosed = !$scope.clickedopen;
644                     }
645
646                     if ($scope.selected && $scope.selected.length > 0) $scope.complete_list = true;
647                     if (!$scope.selected || $scope.selected.length == 0) $scope.complete_list = false;
648                     $scope.makeOpen();
649                 }
650
651                 $scope.makeOpen = function () {
652                     $scope.isopen = $scope.clickedopen || ($filter('filter')(
653                         $scope.list,
654                         $scope.selected
655                     ).length > 0 && $scope.selected.length > 0);
656                     if ($scope.clickedclosed) {
657                         $scope.isopen = false;
658                         $scope.clickedclosed = null;
659                     }
660                 }
661
662                 $scope.changeValue = function (newVal) {
663                     $scope.selected = newVal;
664                     $scope.isopen = false;
665                     $scope.clickedclosed = null;
666                     $scope.clickedopen = false;
667                     if ($scope.selected.length == 0) $scope.complete_list = false;
668                     if ($scope.onSelect) $scope.onSelect();
669                 }
670
671             }
672         ]
673     };
674 })
675
676 /**
677  * Nested org unit selector modeled as a Bootstrap dropdown button.
678  */
679 .directive('egOrgSelector', function() {
680     return {
681         restrict : 'AE',
682         transclude : true,
683         replace : true, // makes styling easier
684         scope : {
685             selected : '=', // defaults to workstation or root org,
686                             // unless the nodefault attibute exists
687
688             // Each org unit is passed into this function and, for
689             // any org units where the response value is true, the
690             // org unit will not be added to the selector.
691             hiddenTest : '=',
692
693             // Each org unit is passed into this function and, for
694             // any org units where the response value is true, the
695             // org unit will not be available for selection.
696             disableTest : '=',
697
698             // if set to true, disable the UI element altogether
699             alldisabled : '@',
700
701             // Caller can either $watch(selected, ..) or register an
702             // onchange handler.
703             onchange : '=',
704
705             // optional primary drop-down button label
706             label : '@',
707
708             // optional name of settings key for persisting
709             // the last selected org unit
710             stickySetting : '@'
711         },
712
713         // any reason to move this into a TT2 template?
714         template : 
715             '<div class="btn-group eg-org-selector" uib-dropdown>'
716             + '<button type="button" class="btn btn-default" uib-dropdown-toggle ng-disabled="disable_button">'
717              + '<span style="padding-right: 5px;">{{getSelectedName()}}</span>'
718              + '<span class="caret"></span>'
719            + '</button>'
720            + '<ul uib-dropdown-menu class="scrollable-menu">'
721              + '<li ng-repeat="org in orgList" ng-hide="hiddenTest(org.id)">'
722                + '<a href ng-click="orgChanged(org)" a-disabled="disableTest(org.id)" '
723                  + 'style="padding-left: {{org.depth * 10 + 5}}px">'
724                  + '{{org.shortname}}'
725                + '</a>'
726              + '</li>'
727            + '</ul>'
728           + '</div>',
729
730         controller : ['$scope','$timeout','egCore','egStartup','egLovefield','$q',
731               function($scope , $timeout , egCore , egStartup , egLovefield , $q) {
732
733             if ($scope.alldisabled) {
734                 $scope.disable_button = $scope.alldisabled == 'true' ? true : false;
735             } else {
736                 $scope.disable_button = false;
737             }
738
739             // avoid linking the full fleshed tree to the scope by 
740             // tossing in a flattened list.
741             // --
742             // Run-time code referencing post-start data should be run
743             // from within a startup block, otherwise accessing this
744             // module before startup completes will lead to failure.
745             //
746             // controller() runs before link().
747             // This post-startup code runs after link().
748             egStartup.go(
749             ).then(
750                 function() {
751                     return egCore.env.classLoaders.aou();
752                 }
753             ).then(
754                 function() {
755
756                     $scope.orgList = egCore.org.list().map(function(org) {
757                         return {
758                             id : org.id(),
759                             shortname : org.shortname(), 
760                             depth : org.ou_type().depth()
761                         }
762                     });
763                     
764     
765                     // Apply default values
766     
767                     if ($scope.stickySetting) {
768                         var orgId = egCore.hatch.getLocalItem($scope.stickySetting);
769                         if (orgId) {
770                             $scope.selected = egCore.org.get(orgId);
771                         }
772                     }
773     
774                     if (!$scope.selected && !$scope.nodefault && egCore.auth.user()) {
775                         $scope.selected = 
776                             egCore.org.get(egCore.auth.user().ws_ou());
777                     }
778     
779                     fire_orgsel_onchange(); // no-op if nothing is selected
780                 }
781             );
782
783             /**
784              * Fire onchange handler after a timeout, so the
785              * $scope.selected value has a chance to propagate to
786              * the page controllers before the onchange fires.  This
787              * way, the caller does not have to manually capture the
788              * $scope.selected value during onchange.
789              */
790             function fire_orgsel_onchange() {
791                 if (!$scope.selected || !$scope.onchange) return;
792                 $timeout(function() {
793                     console.debug(
794                         'egOrgSelector onchange('+$scope.selected.id()+')');
795                     $scope.onchange($scope.selected)
796                 });
797             }
798
799             $scope.getSelectedName = function() {
800                 if ($scope.selected && $scope.selected.shortname)
801                     return $scope.selected.shortname();
802                 return $scope.label;
803             }
804
805             $scope.orgChanged = function(org) {
806                 $scope.selected = egCore.org.get(org.id);
807                 if ($scope.stickySetting) {
808                     egCore.hatch.setLocalItem($scope.stickySetting, org.id);
809                 }
810                 fire_orgsel_onchange();
811             }
812
813         }],
814         link : function(scope, element, attrs, egGridCtrl) {
815
816             // boolean fields are presented as value-less attributes
817             angular.forEach(
818                 ['nodefault'],
819                 function(field) {
820                     if (angular.isDefined(attrs[field]))
821                         scope[field] = true;
822                     else
823                         scope[field] = false;
824                 }
825             );
826         }
827     }
828 })
829
830 .directive('nextOnEnter', function () {
831     return function (scope, element, attrs) {
832         element.bind("keydown keypress", function (event) {
833             if(event.which === 13) {
834                 $('#'+attrs.nextOnEnter).focus();
835                 event.preventDefault();
836             }
837         });
838     };
839 })
840
841 /* http://eric.sau.pe/angularjs-detect-enter-key-ngenter/ */
842 .directive('egEnter', function () {
843     return function (scope, element, attrs) {
844         element.bind("keydown keypress", function (event) {
845             if(event.which === 13) {
846                 scope.$apply(function (){
847                     scope.$eval(attrs.egEnter);
848                 });
849  
850                 event.preventDefault();
851             }
852         });
853     };
854 })
855
856 /*
857 * Handy wrapper directive for uib-datapicker-popup
858 */
859 .directive(
860     'egDateInput', ['egStrings', 'egCore',
861     function(egStrings, egCore) {
862         return {
863             scope : {
864                 id : '@',
865                 closeText : '@',
866                 ngModel : '=',
867                 ngChange : '=',
868                 ngBlur : '=',
869                 minDate : '=?',
870                 maxDate : '=?',
871                 ngDisabled : '=',
872                 ngRequired : '=',
873                 hideDatePicker : '=',
874                 dateFormat : '=?',
875                 outOfRange : '=?',
876                 focusMe : '=?'
877             },
878             require: 'ngModel',
879             templateUrl: './share/t_datetime',
880             replace: true,
881             controller : ['$scope', function($scope) {
882                 $scope.options = {
883                     minDate : $scope.minDate,
884                     maxDate : $scope.maxDate
885                 };
886
887                 var maxDateObj = $scope.maxDate ? new Date($scope.maxDate) : null;
888                 var minDateObj = $scope.minDate ? new Date($scope.minDate) : null;
889
890                 if ($scope.outOfRange !== undefined && (maxDateObj || minDateObj)) {
891                     $scope.$watch('ngModel', function (n,o) {
892                         if (n && n != o) {
893                             var bad = false;
894                             var newdate = new Date(n);
895                             if (maxDateObj && newdate.getTime() > maxDateObj.getTime()) bad = true;
896                             if (minDateObj && newdate.getTime() < minDateObj.getTime()) bad = true;
897                             $scope.outOfRange = bad;
898                         }
899                     });
900                 }
901             }],
902             link : function(scope, elm, attrs) {
903                 if (!scope.closeText)
904                     scope.closeText = egStrings.EG_DATE_INPUT_CLOSE_TEXT;
905
906                 if ('showTimePicker' in attrs)
907                     scope.showTimePicker = true;
908
909                 var default_format = 'mediumDate';
910                 egCore.org.settings(['format.date']).then(function(set) {
911                     default_format = set['format.date'];
912                     scope.date_format = (scope.dateFormat) ?
913                         scope.dateFormat :
914                         default_format;
915                 });
916             }
917         };
918     }
919 ])
920
921 /*
922  *  egFmValueSelector - widget for selecting a value from list specified
923  *                      by IDL class
924  */
925 .directive('egFmValueSelector', function() {
926     return {
927         restrict : 'E',
928         transclude : true,
929         scope : {
930             idlClass : '@',
931             ngModel : '=',
932
933             // optional filter for refining the set of rows that
934             // get returned. Example:
935             //
936             // filter="{'column':{'=':null}}"
937             filter : '=',
938
939             // optional name of settings key for persisting
940             // the last selected value
941             stickySetting : '@',
942
943             // optional OU setting for fetching default value;
944             // used only if sticky setting not set
945             ouSetting : '@'
946         },
947         require: 'ngModel',
948         templateUrl : './share/t_fm_value_selector',
949         controller : ['$scope','egCore', function($scope , egCore) {
950
951             $scope.org = egCore.org; // for use in the link function
952             $scope.auth = egCore.auth; // for use in the link function
953             $scope.hatch = egCore.hatch // for use in the link function
954
955             function flatten_linked_values(cls, list) {
956                 var results = [];
957                 var fields = egCore.idl.classes[cls].fields;
958                 var id_field;
959                 var selector;
960                 angular.forEach(fields, function(fld) {
961                     if (fld.datatype == 'id') {
962                         id_field = fld.name;
963                         selector = fld.selector ? fld.selector : id_field;
964                         return;
965                     }
966                 });
967                 angular.forEach(list, function(item) {
968                     var rec = egCore.idl.toHash(item);
969                     results.push({
970                         id : rec[id_field],
971                         name : rec[selector]
972                     });
973                 });
974                 return results;
975             }
976
977             var search = {};
978             search[egCore.idl.classes[$scope.idlClass].pkey] = {'!=' : null};
979             if ($scope.filter) {
980                 angular.extend(search, $scope.filter);
981             }
982             egCore.pcrud.search(
983                 $scope.idlClass, search, {}, {atomic : true}
984             ).then(function(list) {
985                 $scope.linked_values = flatten_linked_values($scope.idlClass, list);
986             });
987
988             $scope.handleChange = function(value) {
989                 if ($scope.stickySetting) {
990                     egCore.hatch.setLocalItem($scope.stickySetting, value);
991                 }
992             }
993
994         }],
995         link : function(scope, element, attrs) {
996             if (scope.stickySetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
997                 var value = scope.hatch.getLocalItem(scope.stickySetting);
998                 scope.ngModel = value;
999             }
1000             if (scope.ouSetting && (angular.isUndefined(scope.ngModel) || (scope.ngModel === null))) {
1001                 scope.org.settings([scope.ouSetting], scope.auth.user().ws_ou())
1002                 .then(function(set) {
1003                     var value = parseInt(set[scope.ouSetting]);
1004                     if (!isNaN(value))
1005                         scope.ngModel = value;
1006                 });
1007             }
1008         }
1009     }
1010 })
1011
1012 /*
1013  *  egShareDepthSelector - widget for selecting a share depth
1014  */
1015 .directive('egShareDepthSelector', function() {
1016     return {
1017         restrict : 'E',
1018         transclude : true,
1019         scope : {
1020             ngModel : '=',
1021         },
1022         require: 'ngModel',
1023         templateUrl : './share/t_share_depth_selector',
1024         controller : ['$scope','egCore', function($scope , egCore) {
1025             $scope.values = [];
1026             egCore.pcrud.search('aout',
1027                 { id : {'!=' : null} },
1028                 { order_by : {aout : ['depth', 'name']} },
1029                 { atomic : true }
1030             ).then(function(list) {
1031                 var scratch = [];
1032                 angular.forEach(list, function(aout) {
1033                     var depth = parseInt(aout.depth());
1034                     if (depth in scratch) {
1035                         scratch[depth].push(aout.name());
1036                     } else {
1037                         scratch[depth] = [ aout.name() ]
1038                     }
1039                 });
1040                 scratch.forEach(function(val, idx) {
1041                     $scope.values.push({ id : idx,  name : scratch[idx].join(' / ') });
1042                 });
1043             });
1044         }]
1045     }
1046 })
1047
1048 /*
1049  * egHelpPopover - a helpful widget
1050  */
1051 .directive('egHelpPopover', function() {
1052     return {
1053         restrict : 'E',
1054         transclude : true,
1055         scope : {
1056             helpText : '@',
1057             helpLink : '@'
1058         },
1059         templateUrl : './share/t_help_popover',
1060         controller : ['$scope','$sce', function($scope , $sce) {
1061             if ($scope.helpLink) {
1062                 $scope.helpHtml = $sce.trustAsHtml(
1063                     '<a target="_new" href="' + $scope.helpLink + '">' +
1064                     $scope.helpText + '</a>'
1065                 );
1066             }
1067         }]
1068     }
1069 })
1070
1071 .factory('egWorkLog', ['egCore', function(egCore) {
1072     var service = {};
1073
1074     service.retrieve_all = function() {
1075         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1076         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1077
1078         return { 'work_log' : workLog, 'patron_log' : patronLog };
1079     }
1080
1081     service.record = function(message,data) {
1082         var max_entries;
1083         var max_patrons;
1084         if (typeof egCore != 'undefined') {
1085             if (typeof egCore.env != 'undefined') {
1086                 if (typeof egCore.env.aous != 'undefined') {
1087                     max_entries = egCore.env.aous['ui.admin.work_log.max_entries'];
1088                     max_patrons = egCore.env.aous['ui.admin.patron_log.max_entries'];
1089                 } else {
1090                     console.log('worklog: missing egCore.env.aous');
1091                 }
1092             } else {
1093                 console.log('worklog: missing egCore.env');
1094             }
1095         } else {
1096             console.log('worklog: missing egCore');
1097         }
1098         if (!max_entries) {
1099             if (typeof egCore.org != 'undefined') {
1100                 if (typeof egCore.org.cachedSettings != 'undefined') {
1101                     max_entries = egCore.org.cachedSettings['ui.admin.work_log.max_entries'];
1102                 } else {
1103                     console.log('worklog: missing egCore.org.cachedSettings');
1104                 }
1105             } else {
1106                 console.log('worklog: missing egCore.org');
1107             }
1108         }
1109         if (!max_patrons) {
1110             if (typeof egCore.org != 'undefined') {
1111                 if (typeof egCore.org.cachedSettings != 'undefined') {
1112                     max_patrons = egCore.org.cachedSettings['ui.admin.patron_log.max_entries'];
1113                 } else {
1114                     console.log('worklog: missing egCore.org.cachedSettings');
1115                 }
1116             } else {
1117                 console.log('worklog: missing egCore.org');
1118             }
1119         }
1120         if (!max_entries) {
1121             max_entries = 20;
1122             console.log('worklog: defaulting to max_entries = ' + max_entries);
1123         }
1124         if (!max_patrons) {
1125             max_patrons = 10;
1126             console.log('worklog: defaulting to max_patrons = ' + max_patrons);
1127         }
1128
1129         var workLog = egCore.hatch.getLocalItem('eg.work_log') || [];
1130         var patronLog = egCore.hatch.getLocalItem('eg.patron_log') || [];
1131         var entry = {
1132             'when' : new Date(),
1133             'msg' : message,
1134             'action' : data.action,
1135             'actor' : egCore.auth.user().usrname()
1136         };
1137         if (data.action == 'checkin') {
1138             entry['item'] = data.response.params.copy_barcode;
1139             entry['item_id'] = data.response.data.acp.id();
1140             if (data.response.data.au) {
1141                 entry['user'] = data.response.data.au.family_name();
1142                 entry['patron_id'] = data.response.data.au.id();
1143             }
1144         }
1145         if (data.action == 'checkout') {
1146             entry['item'] = data.response.params.copy_barcode;
1147             entry['user'] = data.response.data.au.family_name();
1148             entry['item_id'] = data.response.data.acp.id();
1149             entry['patron_id'] = data.response.data.au.id();
1150         }
1151         if (data.action == 'noncat_checkout') {
1152             entry['user'] = data.response.data.au.family_name();
1153             entry['patron_id'] = data.response.data.au.id();
1154         }
1155         if (data.action == 'renew') {
1156             entry['item'] = data.response.params.copy_barcode;
1157             entry['user'] = data.response.data.au.family_name();
1158             entry['item_id'] = data.response.data.acp.id();
1159             entry['patron_id'] = data.response.data.au.id();
1160         }
1161         if (data.action == 'requested_hold'
1162             || data.action == 'edited_patron'
1163             || data.action == 'registered_patron'
1164             || data.action == 'paid_bill') {
1165             entry['patron_id'] = data.patron_id;
1166         }
1167         if (data.action == 'requested_hold') {
1168             entry['hold_id'] = data.hold_id;
1169         }
1170         if (data.action == 'paid_bill') {
1171             entry['amount'] = data.total_amount;
1172         }
1173
1174         workLog.push( entry );
1175         if (workLog.length > max_entries) workLog.shift();
1176         egCore.hatch.setLocalItem('eg.work_log',workLog); // hatch JSONifies the data, so should be okay re: memory leaks?
1177
1178         if (entry['patron_id']) {
1179             var temp = [];
1180             for (var i = 0; i < patronLog.length; i++) { // filter out any matching patron
1181                 if (patronLog[i]['patron_id'] != entry['patron_id']) temp.push(patronLog[i]);
1182             }
1183             temp.push( entry );
1184             if (temp.length > max_patrons) temp.shift();
1185             patronLog = temp;
1186             egCore.hatch.setLocalItem('eg.patron_log',patronLog);
1187         }
1188
1189         console.log('worklog',entry);
1190     }
1191
1192     return service;
1193 }]);