f798f4c4a4ae88028ef991f1729965aa03349899
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / cat / printlabels / app.js
1 /**
2  * Vol/Copy Editor
3  */
4
5 angular.module('egPrintLabels',
6     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod', 'egGridMod'])
7
8 .config(function ($routeProvider, $locationProvider, $compileProvider) {
9     $locationProvider.html5Mode(true);
10     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
11
12     var resolver = {
13         delay: ['egStartup', function (egStartup) { return egStartup.go(); }]
14     };
15
16     $routeProvider.when('/cat/printlabels/:dataKey', {
17         templateUrl: './cat/printlabels/t_view',
18         controller: 'LabelCtrl',
19         resolve: resolver
20     });
21
22 })
23
24 .factory('itemSvc',
25        ['egCore',
26 function (egCore) {
27
28     var service = {
29         copies: [], // copy barcode search results
30         index: 0 // search grid index
31     };
32
33     service.flesh = {
34         flesh: 3,
35         flesh_fields: {
36             acp: ['call_number', 'location', 'status', 'location', 'floating', 'circ_modifier', 'age_protect'],
37             acn: ['record', 'prefix', 'suffix'],
38             bre: ['simple_record', 'creator', 'editor']
39         },
40         select: {
41             // avoid fleshing MARC on the bre
42             // note: don't add simple_record.. not sure why
43             bre: ['id', 'tcn_value', 'creator', 'editor'],
44         }
45     }
46
47     // resolved with the last received copy
48     service.fetch = function (barcode, id, noListDupes) {
49         var promise;
50
51         if (barcode) {
52             promise = egCore.pcrud.search('acp',
53                 { barcode: barcode, deleted: 'f' }, service.flesh);
54         } else {
55             promise = egCore.pcrud.retrieve('acp', id, service.flesh);
56         }
57
58         var lastRes;
59         return promise.then(
60             function () { return lastRes },
61             null, // error
62
63             // notify reads the stream of copies, one at a time.
64             function (copy) {
65
66                 var flatCopy;
67                 if (noListDupes) {
68                     // use the existing copy if possible
69                     flatCopy = service.copies.filter(
70                         function (c) { return c.id == copy.id() })[0];
71                 }
72
73                 if (!flatCopy) {
74                     flatCopy = egCore.idl.toHash(copy, true);
75                     flatCopy.index = service.index++;
76                     service.copies.unshift(flatCopy);
77                 }
78
79                 return lastRes = {
80                     copy: copy,
81                     index: flatCopy.index
82                 }
83             }
84         );
85     }
86
87     return service;
88 }])
89
90 /**
91  * Label controller!
92  */
93 .controller('LabelCtrl',
94        ['$scope', '$q', '$window', '$routeParams', '$location', '$timeout', 'egCore', 'egNet', 'ngToast', 'itemSvc', 'labelOutputRowsFilter',
95 function ($scope, $q, $window, $routeParams, $location, $timeout, egCore, egNet, ngToast, itemSvc, labelOutputRowsFilter) {
96
97     var dataKey = $routeParams.dataKey;
98     console.debug('dataKey: ' + dataKey);
99
100     $scope.print = {
101         template_name: 'item_label',
102         template_output: '',
103         template_context: 'default'
104     };
105
106     var toolbox_settings = {
107         feed_option: {
108             options: [
109                 { label: "Continuous", value: "continuous" },
110                 { label: "Sheet", value: "sheet" },
111             ],
112             selected: "continuous"
113         },
114         label_set: {
115             margin_between: 0,
116             size: 1
117         },
118         mode: {
119             options: [
120                 { label: "Label 1 Only", value: "spine-only" },
121                 { label: "Labels 1 & 2", value: "spine-pocket" }
122             ],
123             selected: "spine-pocket"
124         },
125         page: {
126             column_class: ["spine"],
127             dimensions: {
128                 columns: 2,
129                 rows: 1
130             },
131             label: {
132                 gap: {
133                     size: 0
134                 },
135                 set: {
136                     size: 2
137                 }
138             },
139             margins: {
140                 top: { size: 0, label: "Top" },
141                 left: { size: 0, label: "Left" },
142             },
143             space_between_labels: {
144                 horizontal: { size: 0, label: "Horizontal" },
145                 vertical: { size: 0, label: "Vertical" }
146             },
147             start_position: {
148                 column: 1,
149                 row: 1
150             }
151         }
152     };
153
154     if (dataKey && dataKey.length > 0) {
155
156         egNet.request(
157             'open-ils.actor',
158             'open-ils.actor.anon_cache.get_value',
159             dataKey, 'print-labels-these-copies'
160         ).then(function (data) {
161
162             if (data) {
163
164                 $scope.preview_scope = {
165                     'copies': []
166                     , 'settings': {}
167                     , 'toolbox_settings': toolbox_settings
168                     , 'get_cn_for': function (copy) {
169                         var key = $scope.rendered_cn_key_by_copy_id[copy.id];
170                         if (key) {
171                             var manual_cn = $scope.rendered_call_number_set[key];
172                             if (manual_cn && manual_cn.value) {
173                                 return manual_cn.value;
174                             } else {
175                                 return '..';
176                             }
177                         } else {
178                             return '...';
179                         }
180                     }
181                     , 'get_bib_for': function (copy) {
182                         return $scope.record_details[copy['call_number.record.id']];
183                     }
184                     , 'get_cn_prefix': function (copy) {
185                         return copy['call_number.prefix.label'];
186                     }
187                     , 'get_cn_suffix': function (copy) {
188                         return copy['call_number.suffix.label'];
189                     }
190                     , 'get_location_prefix': function (copy) {
191                         return copy['location.label_prefix'];
192                     }
193                     , 'get_location_suffix': function (copy) {
194                         return copy['location.label_suffix'];
195                     }
196                     , 'get_cn_and_location_prefix': function (copy, separator) {
197                         var acpl_prefix = copy['location.label_prefix'] || '';
198                         var cn_prefix = copy['call_number.prefix.label'] || '';
199                         var prefix = acpl_prefix + ' ' + cn_prefix;
200                         prefix = prefix.trim();
201                         if (separator && prefix != '') { prefix += separator; }
202                         return prefix;
203                     }
204                     , 'get_cn_and_location_suffix': function (copy, separator) {
205                         var acpl_suffix = copy['location.label_suffix'] || '';
206                         var cn_suffix = copy['call_number.suffix.label'] || '';
207                         var suffix = cn_suffix + ' ' + acpl_suffix;
208                         suffix = suffix.trim();
209                         if (separator && suffix != '') { suffix = separator + suffix; }
210                         return suffix;
211                     }
212                     , 'valid_print_label_start_column': function () {
213                         return !angular.isNumber(toolbox_settings.page.dimensions.columns) || !angular.isNumber(toolbox_settings.page.start_position.column) ? false : (toolbox_settings.page.start_position.column <= toolbox_settings.page.dimensions.columns);
214                     }
215                     , 'valid_print_label_start_row': function () {
216                         return !angular.isNumber(toolbox_settings.page.dimensions.rows) || !angular.isNumber(toolbox_settings.page.start_position.row) ? false : (toolbox_settings.page.start_position.row <= toolbox_settings.page.dimensions.rows);
217                     }
218                 };
219                 $scope.record_details = {};
220                 $scope.org_unit_settings = {};
221
222                 var promises = [];
223                 $scope.org_unit_setting_list = [
224                      'webstaff.cat.label.font.family'
225                     , 'webstaff.cat.label.font.size'
226                     , 'webstaff.cat.label.font.weight'
227                     , 'webstaff.cat.label.inline_css'
228                     , 'webstaff.cat.label.left_label.height'
229                     , 'webstaff.cat.label.left_label.left_margin'
230                     , 'webstaff.cat.label.left_label.width'
231                     , 'webstaff.cat.label.right_label.height'
232                     , 'webstaff.cat.label.right_label.left_margin'
233                     , 'webstaff.cat.label.right_label.width'
234                     , 'webstaff.cat.label.call_number_wrap_filter_height'
235                     , 'webstaff.cat.label.call_number_wrap_filter_width'
236                 ];
237
238                 promises.push(
239                     egCore.pcrud.search('coust', { name: $scope.org_unit_setting_list }).then(
240                          null
241                         , null
242                         , function (yaous) {
243                             $scope.org_unit_settings[yaous.name()] = egCore.idl.toHash(yaous, true);
244                         }
245                     )
246                 );
247
248                 promises.push(
249                     egCore.org.settings($scope.org_unit_setting_list).then(function (res) {
250                         $scope.preview_scope.settings = res;
251                         egCore.hatch.getItem('cat.printlabels.last_settings').then(function (last_settings) {
252                             if (last_settings) {
253                                 for (s in last_settings) {
254                                     $scope.preview_scope.settings[s] = last_settings[s];
255                                 }
256                             }
257                         });
258                     })
259                 );
260
261                 angular.forEach(data.copies, function (copy) {
262                     promises.push(
263                         itemSvc.fetch(null, copy).then(function (res) {
264                             var flat_copy = egCore.idl.toHash(res.copy, true);
265                             $scope.preview_scope.copies.push(flat_copy);
266                             $scope.record_details[flat_copy['call_number.record.id']] = 1;
267                         })
268                     )
269                 });
270
271                 $q.all(promises).then(function () {
272
273                     var promises2 = [];
274                     angular.forEach($scope.record_details, function (el, k, obj) {
275                         promises2.push(
276                             egNet.request(
277                                 'open-ils.search',
278                                 'open-ils.search.biblio.record.mods_slim.retrieve.authoritative',
279                                 k
280                             ).then(function (data) {
281                                 obj[k] = egCore.idl.toHash(data, true);
282                             })
283                         );
284                     });
285
286                     $q.all(promises2).then(function () {
287                         // today, staff, current_location, etc.
288                         egCore.print.fleshPrintScope($scope.preview_scope);
289                         $scope.template_changed(); // load the default
290                         $scope.rebuild_cn_set();
291                         if ($scope.preview_scope.toolbox_settings && $scope.template_name && $scope.print.template_content) {
292                             var re = /eg\_plt/i;
293                             if (re.test($scope.print.template_content)) {
294                                 $scope.applyTemplate($scope.template_name);
295                                 $scope.redraw_label_table();
296                             }
297                         }
298                     });
299
300                 });
301             } else {
302                 ngToast.danger(egCore.strings.KEY_EXPIRED);
303             }
304
305         });
306
307     }
308
309     $scope.fetchTemplates = function (set_default) {
310         return egCore.hatch.getItem('cat.printlabels.templates').then(function (t) {
311             if (t) {
312                 $scope.templates = t;
313                 $scope.template_name_list = Object.keys(t);
314                 if (set_default) {
315                     egCore.hatch.getItem('cat.printlabels.default_template').then(function (d) {
316                         if ($scope.template_name_list.indexOf(d, 0) > -1) {
317                             $scope.template_name = d;
318                         }
319                     });
320                 }
321             }
322         });
323     }
324     $scope.fetchTemplates(true);
325
326     $scope.applyTemplate = function (n) {
327         $scope.print.cn_template_content = $scope.templates[n].cn_content;
328         $scope.print.template_content = $scope.templates[n].content;
329         $scope.print.template_context = $scope.templates[n].context;
330         for (var s in $scope.templates[n].settings) {
331             $scope.preview_scope.settings[s] = $scope.templates[n].settings[s];
332         }
333         if ($scope.templates[n].toolbox_settings) {
334             $scope.preview_scope.toolbox_settings = $scope.templates[n].toolbox_settings;
335             $scope.create_print_label_table();
336         }
337         egCore.hatch.setItem('cat.printlabels.default_template', n);
338         $scope.save_locally();
339     }
340
341     $scope.deleteTemplate = function (n) {
342         if (n) {
343             delete $scope.templates[n]
344             $scope.template_name_list = Object.keys($scope.templates);
345             $scope.template_name = '';
346             egCore.hatch.setItem('cat.printlabels.templates', $scope.templates);
347             $scope.fetchTemplates();
348             ngToast.create(egCore.strings.PRINT_LABEL_TEMPLATE_SUCCESS_DELETE);
349             egCore.hatch.getItem('cat.printlabels.default_template').then(function (d) {
350                 if (d && d == n) {
351                     egCore.hatch.removeItem('cat.printlabels.default_template');
352                 }
353             });
354         }
355     }
356
357     $scope.saveTemplate = function (n) {
358         if (n) {
359
360             $scope.templates[n] = {
361                 content: $scope.print.template_content
362                 , context: $scope.print.template_context
363                 , cn_content: $scope.print.cn_template_content
364                 , settings: $scope.preview_scope.settings
365                 , toolbox_settings: $scope.preview_scope.toolbox_settings
366             };
367             $scope.template_name_list = Object.keys($scope.templates);
368
369             egCore.hatch.setItem('cat.printlabels.templates', $scope.templates);
370             $scope.fetchTemplates();
371
372             $scope.dirty = false;
373         } else {
374             // save all templates, as we might do after an import
375             egCore.hatch.setItem('cat.printlabels.templates', $scope.templates);
376             $scope.fetchTemplates();
377         }
378         ngToast.create(egCore.strings.PRINT_LABEL_TEMPLATE_SUCCESS_SAVE);
379     }
380
381     $scope.templates = {};
382     $scope.imported_templates = { data: '' };
383     $scope.template_name = '';
384     $scope.template_name_list = [];
385
386     $scope.print_labels = function () {
387         return egCore.print.print({
388             context: $scope.print.template_context,
389             template: $scope.print.template_name,
390             scope: $scope.preview_scope,
391         });
392     }
393
394     $scope.template_changed = function () {
395         $scope.print.load_failed = false;
396         egCore.print.getPrintTemplate('item_label')
397         .then(
398             function (html) {
399                 $scope.print.template_content = html;
400             },
401             function () {
402                 $scope.print.template_content = '';
403                 $scope.print.load_failed = true;
404             }
405         );
406         egCore.print.getPrintTemplateContext('item_label')
407         .then(function (template_context) {
408             $scope.print.template_context = template_context;
409         });
410         egCore.print.getPrintTemplate('item_label_cn')
411         .then(
412             function (html) {
413                 $scope.print.cn_template_content = html;
414             },
415             function () {
416                 $scope.print.cn_template_content = '';
417                 $scope.print.load_failed = true;
418             }
419         );
420         egCore.hatch.getItem('cat.printlabels.last_settings').then(function (s) {
421             if (s) {
422                 $scope.preview_scope.settings = s;
423             }
424         });
425     }
426
427     $scope.reset_to_default = function () {
428         egCore.print.removePrintTemplate(
429             'item_label'
430         );
431         egCore.print.removePrintTemplateContext(
432             'item_label'
433         );
434         egCore.print.removePrintTemplate(
435             'item_label_cn'
436         );
437         egCore.hatch.removeItem('cat.printlabels.last_settings');
438         for (s in $scope.preview_scope.settings) {
439             $scope.preview_scope.settings[s] = undefined;
440         }
441         $scope.preview_scope.settings = {};
442         egCore.org.settings($scope.org_unit_setting_list).then(function (res) {
443             $scope.preview_scope.settings = res;
444         });
445
446         $scope.template_changed();
447     }
448
449     $scope.save_locally = function () {
450         egCore.print.storePrintTemplate(
451             'item_label',
452             $scope.print.template_content
453         );
454         egCore.print.storePrintTemplateContext(
455             'item_label',
456             $scope.print.template_context
457         );
458         egCore.print.storePrintTemplate(
459             'item_label_cn',
460             $scope.print.cn_template_content
461         );
462         egCore.hatch.setItem('cat.printlabels.last_settings', $scope.preview_scope.settings);
463     }
464
465     $scope.imported_print_templates = { data: '' };
466     $scope.$watch('imported_templates.data', function (newVal, oldVal) {
467         if (newVal && newVal != oldVal) {
468             try {
469                 var data = JSON.parse(newVal);
470                 angular.forEach(data, function (el, k) {
471                     $scope.templates[k] = {
472                         content: el.content
473                         , context: el.context
474                         , cn_content: el.cn_content
475                         , settings: el.settings
476                         , toolbox_settings: el.toolbox_settings
477                     };
478                 });
479                 $scope.saveTemplate();
480                 $scope.template_changed(); // refresh
481                 ngToast.create(egCore.strings.PRINT_TEMPLATES_SUCCESS_IMPORT);
482             } catch (E) {
483                 ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_IMPORT);
484             }
485         }
486     });
487
488     $scope.rendered_call_number_set = {};
489     $scope.rendered_cn_key_by_copy_id = {};
490     $scope.rebuild_cn_set = function () {
491         $timeout(function () {
492             $scope.rendered_call_number_set = {};
493             $scope.rendered_cn_key_by_copy_id = {};
494             for (var i = 0; i < $scope.preview_scope.copies.length; i++) {
495                 var copy = $scope.preview_scope.copies[i];
496                 var rendered_cn = document.getElementById('cn_for_copy_' + copy.id);
497                 if (rendered_cn && rendered_cn.textContent) {
498                     var key = rendered_cn.textContent;
499                     if (typeof $scope.rendered_call_number_set[key] == 'undefined') {
500                         $scope.rendered_call_number_set[key] = {
501                             value: key
502                         };
503                     }
504                     $scope.rendered_cn_key_by_copy_id[copy.id] = key;
505                 }
506             }
507             $scope.preview_scope.tickle = Date() + ' ' + Math.random();
508         });
509     }
510
511     $scope.create_print_label_table = function () {
512         if ($scope.print_label_form.$valid && $scope.print.template_content && $scope.preview_scope) {
513             $scope.preview_scope.label_output_copies = labelOutputRowsFilter($scope.preview_scope.copies, $scope.preview_scope.toolbox_settings);
514             var html = $scope.print.template_content;
515             var d = new Date(); //Added to table ID with 'eg_plt_' to cause $complie on $scope.print.template_content to fire due to template content change.
516             var table = "<table id=\"eg_plt_" + d.getTime().toString() + "_{{$index}}\" eg-print-label-table style=\"border-collapse: collapse; border: 0 solid transparent; border-spacing: 0; margin: {{$index === 0 ?toolbox_settings.page.margins.top.size : 0}} 0 0 0;\" class=\"custom-label-table{{$index % toolbox_settings.page.dimensions.rows === 0 && $index > 0 && toolbox_settings.feed_option.selected === 'sheet' ? ' page-break' : ''}}\" ng-init=\"parentIndex = $index\" ng-repeat=\"row in label_output_copies\">\n";
517             table += "<tr>\n";
518             table += "<td style=\"border: 0 solid transparent; padding: {{parentIndex % toolbox_settings.page.dimensions.rows === 0 && toolbox_settings.feed_option.selected === 'sheet' && parentIndex > 0 ? toolbox_settings.page.space_between_labels.vertical.size : parentIndex > 0 ? toolbox_settings.page.space_between_labels.vertical.size : 0}} 0 0 {{$index === 0 ? toolbox_settings.page.margins.left.size : col.styl ? col.styl : toolbox_settings.page.space_between_labels.horizontal.size}};\" ng-repeat=\"col in row.columns\">\n";
519             table += "<pre class=\"{{col.cls}}\" style=\"border: none; margin-bottom: 0; margin-top: 0; overflow: hidden;\" ng-if=\"col.cls === 'spine'\">\n";
520             table += "{{col.c ? get_cn_for(col.c) : ''}}";
521             table += "</pre>\n";
522             table += "<pre class=\"{{col.cls}}{{parentIndex % toolbox_settings.page.dimensions.rows === 0 && parentIndex > 0 && toolbox_settings.feed_option.selected === 'sheet' ? ' page-break' : ''}}\" style=\"border: none;  margin-bottom: 0; margin-top: 0; overflow: hidden;\" ng-if=\"col.cls === 'pocket'\">\n";
523             table += "{{col.c ? col.c.barcode : ''}}\n";
524             table += "{{col.c ? col.c['call_number.label'] : ''}}\n";
525             table += "{{col.c ? get_bib_for(col.c).author : ''}}\n";
526             table += "{{col.c ? (get_bib_for(col.c).title | wrap:28:'once':'  ') : ''}}\n";
527             table += "</pre>\n";
528             table += "</td>\n"
529             table += "</tr>\n";
530             table += "</table>";
531             var comments = html.match(/\<\!\-\-(?:(?!\-\-\>)(?:.|\s))*\-\-\>\s*/g);
532             html = html.replace(/\<\!\-\-(?:(?!\-\-\>)(?:.|\s))*\-\-\>\s*/g, "");
533             var style = html.match(/\<style[^\>]*\>(?:(?!\<\/style\>)(?:.|\s))*\<\/style\>\s*/gi);
534             var output = (style ? style.join("\n") : "") + (comments ? comments.join("\n") : "") + table;
535             output = output.replace(/\n+/, "\n");
536             $scope.print.template_content = output;
537             $scope.save_locally();
538         }
539     }
540
541     $scope.redraw_label_table = function () {
542         var d = new Date(); //Added to table ID with 'eg_plt_' to cause $complie on $scope.print.template_content to fire due to template content change.
543         var table = "<table id=\"eg_plt_" + d.getTime().toString() + "\"\></table>\n";
544         $scope.print.template_content += table;
545         $scope.create_print_label_table();
546     }
547
548     $scope.$watch('preview_scope.toolbox_settings.page.dimensions.columns',
549         function (newVal, oldVal) {
550             if (newVal && newVal != oldVal && $scope.preview_scope) {
551                 $scope.redraw_label_table();
552             }
553         }
554     );
555
556     $scope.$watch('print.cn_template_content', function (newVal, oldVal) {
557         if (newVal && newVal != oldVal) {
558             $scope.rebuild_cn_set();
559         }
560     });
561
562     $scope.$watch("preview_scope.settings['webstaff.cat.label.call_number_wrap_filter_height']", function (newVal, oldVal) {
563         if (newVal && newVal != oldVal) {
564             $scope.rebuild_cn_set();
565         }
566     });
567
568     $scope.$watch("preview_scope.settings['webstaff.cat.label.call_number_wrap_filter_width']", function (newVal, oldVal) {
569         if (newVal && newVal != oldVal) {
570             $scope.rebuild_cn_set();
571         }
572     });
573
574     $scope.$watchGroup(['preview_scope.toolbox_settings.page.margins.top.size', 'preview_scope.toolbox_settings.page.margins.left.size', 'preview_scope.toolbox_settings.page.dimensions.rows', 'preview_scope.toolbox_settings.page.space_between_labels.horizontal.size', 'preview_scope.toolbox_settings.page.space_between_labels.vertical.size', 'preview_scope.toolbox_settings.page.start_position.row', 'preview_scope.toolbox_settings.page.start_position.column', 'preview_scope.toolbox_settings.page.label.gap.size'], function (newVal, oldVal) {
575         if (newVal && newVal != oldVal && $scope.preview_scope.label_output_copies) {
576             $scope.redraw_label_table();
577         }
578     });
579
580     $scope.$watch("preview_scope.toolbox_settings.mode.selected", function (newVal, oldVal) {
581         if (newVal && newVal != oldVal) {
582             var ts_p = $scope.preview_scope.toolbox_settings.page;
583             if (ts_p.label.set.size === 1) {
584                 if (newVal === "spine-pocket") {
585                     ts_p.column_class = ["spine", "pocket"];
586                     ts_p.label.set.size = 2;
587                 } else {
588                     ts_p.column_class = ["spine"];
589                 }
590             } else {
591                 if (newVal === "spine-only") {
592                     for (var i = 0; i < ts_p.label.set.size; i++) {
593                         ts_p.column_class[i] = "spine";
594                     }
595                 } else {
596                     ts_p.label.set.size === 2 ? ts_p.column_class = ["spine", "pocket"] : false;
597                 }
598             }
599             $scope.redraw_label_table();
600         }
601     });
602
603     $scope.$watch("preview_scope.toolbox_settings.page.label.set.size", function (newVal, oldVal) {
604         if (newVal && newVal != oldVal) {
605             var ts_p = $scope.preview_scope.toolbox_settings.page;
606             if (angular.isNumber(newVal)) {
607                 while (ts_p.column_class.length > ts_p.label.set.size) {
608                     ts_p.column_class.splice((ts_p.column_class.length - 1), 1);
609                 }
610                 while (ts_p.column_class.length < ts_p.label.set.size) {
611                     ts_p.column_class.push("spine");
612                 }
613             }
614             $scope.redraw_label_table();
615         }
616     });
617
618     $scope.current_tab = 'call_numbers';
619     $scope.set_tab = function (tab) {
620         $scope.current_tab = tab;
621     }
622
623 }])
624
625 .directive("egPrintLabelColumnBounds", function () {
626     return {
627         link: function (scope, element, attr, ctrl) {
628             function withinBounds(v) {
629                 scope.$watch("preview_scope.toolbox_settings.page.dimensions.columns", function (newVal, oldVal) {
630                     ctrl.$setValidity("egWithinPrintColumnBounds", scope.preview_scope.valid_print_label_start_column())
631                 });
632                 return v;
633             }
634             ctrl.$parsers.push(withinBounds);
635             ctrl.$formatters.push(withinBounds);
636         },
637         require: "ngModel"
638     }
639 })
640
641 .directive("egPrintLabelRowBounds", function () {
642     return {
643         link: function (scope, element, attr, ctrl) {
644             function withinBounds(v) {
645                 scope.$watch("preview_scope.toolbox_settings.page.dimensions.rows", function (newVal, oldVal) {
646                     ctrl.$setValidity("egWithinPrintRowBounds", scope.preview_scope.valid_print_label_start_row());
647                 });
648                 return v;
649             }
650             ctrl.$parsers.push(withinBounds);
651             ctrl.$formatters.push(withinBounds);
652         },
653         require: "ngModel"
654     }
655 })
656
657 .directive("egPrintLabelValidCss", function () {
658     return {
659         require: "ngModel",
660         link: function (scope, element, attr, ctrl) {
661             function floatValidation(v) {
662                 ctrl.$setValidity("isFloat", v.toString().match(/^\-*(?:^0$|(?:\d+)(?:\.\d{1,})*([a-z]{2}))$/) ? true : false);
663                 return v;
664             }
665             ctrl.$parsers.push(floatValidation);
666         }
667     }
668 })
669
670 .directive("egPrintLabelValidInt", function () {
671     return {
672         require: "ngModel",
673         link: function (scope, element, attr, ctrl) {
674             function intValidation(v) {
675                 ctrl.$setValidity("isInteger", v.toString().match(/^\d+$/));
676                 return v;
677             }
678             ctrl.$parsers.push(intValidation);
679         }
680     }
681 })
682
683 .directive('egPrintTemplateOutput', ['$compile', function ($compile) {
684     return function (scope, element, attrs) {
685         scope.$watch(
686             function (scope) {
687                 return scope.$eval(attrs.content);
688             },
689             function (value) {
690                 // create an isolate scope and copy the print context
691                 // data into the new scope.
692                 // TODO: see also print security concerns in egHatch
693                 var result = element.html(value);
694                 var context = scope.$eval(attrs.context);
695                 var print_scope = scope.$new(true);
696                 angular.forEach(context, function (val, key) {
697                     print_scope[key] = val;
698                 })
699                 $compile(element.contents())(print_scope);
700             }
701         );
702     };
703 }])
704
705 .filter('cn_wrap', function () {
706     return function (input, w, h, wrap_type) {
707         var names;
708         var prefix = input[0];
709         var callnum = input[1];
710         var suffix = input[2];
711
712         if (!w) { w = 8; }
713         if (!h) { h = 9; }
714
715         /* handle spine labels differently if using LC */
716         if (wrap_type == 'lc' || wrap_type == 3) {
717             /* Establish a pattern where every return value should be isolated on its own line 
718                on the spine label: subclass letters, subclass numbers, cutter numbers, trailing stuff (date) */
719             var patt1 = /^([A-Z]{1,3})\s*(\d+(?:\.\d+)?)\s*(\.[A-Z]\d*)\s*([A-Z]\d*)?\s*(\d\d\d\d(?:-\d\d\d\d)?)?\s*(.*)$/i;
720             var result = callnum.match(patt1);
721             if (result) {
722                 callnum = result.slice(1).join('\t');
723             } else {
724                 callnum = callnum.split(/\s+/).join('\t');
725             }
726
727             /* If result is null, leave callnum alone. Can't parse this malformed call num */
728         } else {
729             callnum = callnum.split(/\s+/).join('\t');
730         }
731
732         if (prefix) {
733             callnum = prefix + '\t' + callnum;
734         }
735         if (suffix) {
736             callnum += '\t' + suffix;
737         }
738
739         /* At this point, the call number pieces are separated by tab characters.  This allows
740         *  some space-containing constructs like "v. 1" to appear on one line
741         */
742         callnum = callnum.replace(/\t\t/g, '\t');  /* Squeeze out empties */
743         names = callnum.split('\t');
744         var j = 0; var tb = [];
745         while (j < h) {
746
747             /* spine */
748             if (j < w) {
749
750                 var name = names.shift();
751                 if (name) {
752                     name = String(name);
753
754                     /* if the name is greater than the label width... */
755                     if (name.length > w) {
756                         /* then try to split it on periods */
757                         var sname = name.split(/\./);
758                         if (sname.length > 1) {
759                             /* if we can, then put the periods back in on each splitted element */
760                             if (name.match(/^\./)) sname[0] = '.' + sname[0];
761                             for (var k = 1; k < sname.length; k++) sname[k] = '.' + sname[k];
762                             /* and put all but the first one back into the names array */
763                             names = sname.slice(1).concat(names);
764                             /* if the name fragment is still greater than the label width... */
765                             if (sname[0].length > w) {
766                                 /* then just truncate and throw the rest back into the names array */
767                                 tb[j] = sname[0].substr(0, w);
768                                 names = [sname[0].substr(w)].concat(names);
769                             } else {
770                                 /* otherwise we're set */
771                                 tb[j] = sname[0];
772                             }
773                         } else {
774                             /* if we can't split on periods, then just truncate and throw the rest back into the names array */
775                             tb[j] = name.substr(0, w);
776                             names = [name.substr(w)].concat(names);
777                         }
778                     } else {
779                         /* otherwise we're set */
780                         tb[j] = name;
781                     }
782                 }
783             }
784             j++;
785         }
786         return tb.join('\n');
787     }
788 })
789
790 .filter("columnRowRange", function () {
791     return function (i) {
792         var res = [];
793         for (var j = 0; j < i; j++) {
794             res.push(j);
795         }
796         return res;
797     }
798 })
799
800 //Accepts $scope.preview_scope.copies and $scope.preview_scope.toolbox_settings as its parameters.
801 .filter("labelOutputRows", function () {
802     return function (copies, settings) {
803         var cols = [], rows = [];
804         for (var j = 0; j < (settings.page.start_position.row - 1) ; j++) {
805             cols = [];
806             for (var k = 0; k < settings.page.dimensions.columns; k++) {
807                 cols.push({ c: null, index: k, cls: getPrintLabelOutputClass(k, settings), styl: getPrintLabelStyle(k, settings) });
808             }
809             rows.push({ columns: cols });
810         }
811         cols = [];
812         for (var j = 0; j < (settings.page.start_position.column - 1) ; j++) {
813             cols.push({ c: null, index: j, cls: getPrintLabelOutputClass(j, settings), styl: getPrintLabelStyle(j, settings) });
814         }
815         var m = cols.length;
816         for (var j = 0; j < copies.length; j++) {
817             for (var n = 0; n < settings.page.label.set.size; n++) {
818                 if (m < settings.page.dimensions.columns) {
819                     cols.push({ c: copies[j], index: cols.length, cls: getPrintLabelOutputClass(m, settings), styl: getPrintLabelStyle(m, settings) });
820                     m += 1;
821                 }
822                 if (m === settings.page.dimensions.columns) {
823                     m = 0;
824                     rows.push({ columns: cols });
825                     cols = [];
826                     n = settings.page.label.set.size;
827                 }
828             }
829         }
830         cols.length > 0 ? rows.push({ columns: cols }) : false;
831         if (rows.length > 0) {
832             while ((rows[(rows.length - 1)].columns.length) < settings.page.dimensions.columns) {
833                 rows[(rows.length - 1)].columns.push({ c: null, index: rows[(rows.length - 1)].columns.length, cls: getPrintLabelOutputClass(rows[(rows.length - 1)].columns.length, settings), styl: getPrintLabelStyle(rows[(rows.length - 1)].columns.length, settings) });
834             }
835         }
836         return rows;
837     }
838 })
839
840 .filter('wrap', function () {
841     return function (input, w, wrap_type, indent) {
842         var output;
843
844         if (!w) return input;
845         if (!indent) indent = '';
846
847         function wrap_on_space(
848                 text,
849                 length,
850                 wrap_just_once,
851                 if_cant_wrap_then_truncate,
852                 idx
853         ) {
854             if (idx > 10) {
855                 console.log('possible infinite recursion, aborting');
856                 return '';
857             }
858             if (String(text).length <= length) {
859                 return text;
860             } else {
861                 var truncated_text = String(text).substr(0, length);
862                 var pivot_pos = truncated_text.lastIndexOf(' ');
863                 var left_chunk = text.substr(0, pivot_pos).replace(/\s*$/, '');
864                 var right_chunk = String(text).substr(pivot_pos + 1);
865
866                 var wrapped_line;
867                 if (left_chunk.length == 0) {
868                     if (if_cant_wrap_then_truncate) {
869                         wrapped_line = truncated_text;
870                     } else {
871                         wrapped_line = text;
872                     }
873                 } else {
874                     wrapped_line =
875                         left_chunk + '\n'
876                         + indent + (
877                             wrap_just_once
878                             ? right_chunk
879                             : (
880                                 right_chunk.length > length
881                                 ? wrap_on_space(
882                                     right_chunk,
883                                     length,
884                                     false,
885                                     if_cant_wrap_then_truncate,
886                                     idx + 1)
887                                 : right_chunk
888                             )
889                         )
890                     ;
891                 }
892                 return wrapped_line;
893             }
894         }
895
896         switch (wrap_type) {
897             case 'once':
898                 output = wrap_on_space(input, w, true, false, 0);
899                 break;
900             default:
901                 output = wrap_on_space(input, w, false, false, 0);
902                 break;
903         }
904
905         return output;
906     }
907 });
908
909 function getPrintLabelOutputClass(index, settings) {
910     return settings.page.column_class[index % settings.page.label.set.size];
911 }
912
913 function getPrintLabelStyle(index, settings) {
914     return index > 0 && (index % settings.page.label.set.size === 0) ? settings.page.label.gap.size : "";
915 }