]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Acq: optionally mark POs as prepayment_required; show/confirm it where needed
[Evergreen.git] / Open-ILS / web / js / ui / default / acq / common / li_table.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.User');
10 dojo.require('openils.Util');
11 dojo.require('openils.acq.Lineitem');
12 dojo.require('openils.acq.PO');
13 dojo.require('openils.acq.Picklist');
14 dojo.require('openils.widget.AutoFieldWidget');
15 dojo.require('dojo.data.ItemFileReadStore');
16 dojo.require('openils.widget.ProgressDialog');
17 dojo.require('openils.PermaCrud');
18 dojo.require('openils.XUL');
19
20 dojo.requireLocalization('openils.acq', 'acq');
21 var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
23 var li_exportable_attrs = ["issn", "isbn", "upc"];
24
25 var fundLabelFormat = ['${0} (${1})', 'code', 'year'];
26 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
27
28 function nodeByName(name, context) {
29     return dojo.query('[name='+name+']', context)[0];
30 }
31
32
33 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
34 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
35
36 function AcqLiTable() {
37
38     var self = this;
39     this.liCache = {};
40     this.plCache = {};
41     this.poCache = {};
42     this.relCache = {};
43     this.realDfaCache = {};
44     this.virtDfaCounts = {};
45     this.virtDfaId = -1;
46     this.dfeOffset = 0;
47     this.toggleState = false;
48     this.tbody = dojo.byId('acq-lit-tbody');
49     this.selectors = [];
50     this.noteAcks = {};
51     this.authtoken = openils.User.authtoken;
52     this.pcrud = new openils.PermaCrud();
53     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
54     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
55     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
56     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
57     this.copyBatchWidgets = {};
58     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
59     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
60     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
61     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
62     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
63
64     dojo.connect(acqLitLiActionsSelector, 'onChange', 
65         function() { 
66             self.applySelectedLiAction(this.attr('value')) 
67             acqLitLiActionsSelector.attr('value', '_');
68         });
69
70     acqLitCreatePoSubmit.onClick = function() {
71         if (self._confirmPoPrepaySituation()) {
72             acqLitPoCreateDialog.hide();
73             self._createPO(acqLitPoCreateDialog.getValues());
74         } else {
75             return false;
76         }
77     }
78
79     acqLitSavePlButton.onClick = function() {
80         acqLitSavePlDialog.hide();
81         self._savePl(acqLitSavePlDialog.getValues());
82     }
83
84     acqLitCancelLiStateButton.onClick = function() {
85         acqLitChangeLiStateDialog.hide();
86     }
87     acqLitSaveLiStateButton.onClick = function() {
88         acqLitChangeLiStateDialog.hide();
89         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
90     }
91
92
93     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
94     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
95     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
96     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
97     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
98
99     this.reset = function() {
100         while(self.tbody.childNodes[0])
101             self.tbody.removeChild(self.tbody.childNodes[0]);
102         self.selectors = [];
103         self.noteAcks = {};
104         self.relCache = {};
105     };
106     
107     this.setNext = function(handler) {
108         var link = dojo.byId('acq-lit-next');
109         if(handler) {
110             dojo.style(link, 'visibility', 'visible');
111             link.onclick = handler;
112         } else {
113             dojo.style(link, 'visibility', 'hidden');
114         }
115     };
116
117     this.setPrev = function(handler) {
118         var link = dojo.byId('acq-lit-prev');
119         if(handler) {
120             dojo.style(link, 'visibility', 'visible'); 
121             link.onclick = handler; 
122         } else {
123             dojo.style(link, 'visibility', 'hidden');
124         }
125     };
126
127     this.show = function(div) {
128         openils.Util.hide('acq-lit-table-div');
129         openils.Util.hide('acq-lit-info-div');
130         openils.Util.hide('acq-lit-li-details');
131         openils.Util.hide('acq-lit-notes-div');
132         openils.Util.hide('acq-lit-real-copies-div');
133         switch(div) {
134             case 'list':
135                 openils.Util.show('acq-lit-table-div');
136                 break;
137             case 'info':
138                 openils.Util.show('acq-lit-info-div');
139                 break;
140             case 'copies':
141                 openils.Util.show('acq-lit-li-details');
142                 break;
143             case 'real-copies':
144                 openils.Util.show('acq-lit-real-copies-div');
145                 break;
146             case 'notes':
147                 openils.Util.show('acq-lit-notes-div');
148                 break;
149             default:
150                 if(div) 
151                     openils.Util.show(div);
152         }
153     }
154
155     this.hide = function() {
156         this.show(null);
157     }
158
159     this.toggleSelect = function() {
160         if(self.toggleState) 
161             dojo.forEach(self.selectors, function(i){i.checked = false});
162         else 
163             dojo.forEach(self.selectors, function(i){i.checked = true});
164         self.toggleState = !self.toggleState;
165     };
166
167
168     /** @param all If true, assume all are selected */
169     this.getSelected = function(all) {
170         var selected = [];
171         dojo.forEach(self.selectors, 
172             function(i) { 
173                 if(i.checked || all)
174                     selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
175             }
176         );
177         return selected;
178     };
179
180     this.setRowAttr = function(td, liWrapper, field, type) {
181         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
182         td.appendChild(document.createTextNode(val));
183     };
184
185     /**
186      * Inserts a single lineitem into the growing table of lineitems
187      * @param {Object} li The lineitem object to insert
188      */
189     this.addLineitem = function(li, skip_final_placement) {
190         this.liCache[li.id()] = li;
191
192         // sort the lineitem notes on edit_time
193         if(!li.lineitem_notes()) li.lineitem_notes([]);
194
195         var liWrapper = new openils.acq.Lineitem({lineitem:li});
196         var row = self.rowTemplate.cloneNode(true);
197         row.setAttribute('li', li.id());
198         var tds = dojo.query('[attr]', row);
199         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
200         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
201
202         var isbn = liWrapper.findAttr('isbn', 'lineitem_marc_attr_definition');
203         if(isbn) {
204             // XXX media prefix for added content
205             dojo.query('[name=jacket]', row)[0].setAttribute('src', '/opac/extras/ac/jacket/small/' + isbn);
206         }
207
208         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
209         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
210         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
211
212         this.updateLiNotesCount(li, row);
213
214         // show which PO this lineitem is a member of
215         if(li.purchase_order() && !this.isPO) {
216             var po = 
217                 this.poCache[li.purchase_order()] =
218                 this.poCache[li.purchase_order()] ||
219                 fieldmapper.standardRequest(
220                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
221                     {params: [
222                         this.authtoken, li.purchase_order(), {
223                             "flesh_price_summary": true,
224                             "flesh_lineitem_count": true
225                         }
226                     ]});
227             if(po && !this.isMeta) {
228                 openils.Util.show(nodeByName('po', row), 'inline');
229                 var link = nodeByName('po_link', row);
230                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
231                 link.innerHTML = 'PO: ' + po.name(); // TODO i18n
232             }
233         }
234
235         // show which picklist this lineitem is a member of
236         if(li.picklist() && (this.isPO || this.isMeta)) {
237             var pl = 
238                 this.plCache[li.picklist()] = 
239                 this.plCache[li.picklist()] || 
240                 fieldmapper.standardRequest(
241                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve'],
242                     {params: [this.authtoken, li.picklist()]});
243             if(pl) {
244                 openils.Util.show(nodeByName('pl', row), 'inline');
245                 var link = nodeByName('pl_link', row);
246                 link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
247                 link.innerHTML = 'PL: '+pl.name(); // TODO i18n
248             }
249         }
250
251         var countNode = nodeByName('count', row);
252         var count = li.item_count() || 0;
253         if (typeof(this._copy_count_cb) == "function") {
254             this._copy_count_cb(li.id(), count);
255         }
256         countNode.innerHTML = count;
257         countNode.id = 'acq-lit-copy-count-label-' + li.id();
258
259         // lineitem price
260         var priceInput = dojo.query('[name=price]', row)[0];
261         priceInput.value = li.estimated_unit_price() || '';
262         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
263
264         // show either "mark received" or "unreceive" as appropriate
265         this.updateLiState(li, row);
266
267         if (!skip_final_placement) {
268             self.tbody.appendChild(row);
269             self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
270         } else {
271             return row;
272         }
273     };
274
275     this.updateLiNotesCount = function(li, row) {
276         if (typeof(row) == "undefined")
277             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
278
279         var has_notes = (li.lineitem_notes().filter(
280                 function(o) { return Boolean (o.alert_text()); }
281             ).length > 0);
282
283         /* U+2691 is the code point for a filled-in flag character */
284         nodeByName("notes_alert_flag", row).innerHTML =
285              has_notes ? "⚑" : "";
286         nodeByName("noteslink", row).style.fontStyle =
287             has_notes ? "italic" : "normal";
288         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
289     };
290
291     /* XXX NOT related to _updateLiState(). rethink */
292     this.updateLiState = function(li, row) {
293         if (typeof(row) == "undefined")
294             row = dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
295
296         var recv_link = nodeByName("receive_link", row);
297         var unrecv_link = nodeByName("unreceive_link", row);
298         var real_copies_link = nodeByName("real_copies_link", row);
299         var holdings_maintenance_link = nodeByName("holdings_maintenance_link", row);
300         var state_cell = nodeByName("li_state", row);
301
302         if (li.state() == "cancelled") {
303             if (typeof li.cancel_reason() == "object") {
304                 var holds_state = dojo.create(
305                     "span", {
306                         "style": "border-bottom: 1px dashed #000;",
307                         "innerHTML": li.state()
308                     }, state_cell, "only"
309                 );
310                 new dijit.Tooltip(
311                     {
312                         "label": "<em>" + li.cancel_reason().label() +
313                             "</em><br />" + li.cancel_reason().description(),
314                         "connectId": [holds_state]
315                     }, dojo.create("span", null, state_cell, "last")
316                 );
317             } else {
318                 state_cell.innerHTML = li.state(); // TODO i18n state labels
319             }
320         } else {
321             state_cell.innerHTML = li.state(); // TODO i18n state labels
322         }
323
324
325         /* handle row coloring for based on LI state */
326         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
327         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
328
329         /* handle links that appear/disappear based on whether LI is received */
330         if (this.isPO) {
331             var self = this;
332             switch(li.state()) {
333                 case "on-order":
334                     openils.Util.hide(real_copies_link);
335                     openils.Util.hide(unrecv_link);
336                     openils.Util.show(recv_link, "inline");
337                     recv_link.onclick = function() {
338                         if (self.checkLiAlerts(li.id()))
339                             self.issueReceive(li);
340                     };
341                     return;
342                 case "received":
343                     openils.Util.hide(recv_link);
344                     openils.Util.show(unrecv_link, "inline");
345                     unrecv_link.onclick = function() {
346                         if (confirm(localeStrings.UNRECEIVE_LI))
347                             self.issueReceive(li, /* rollback */ true);
348                     };
349                     // TODO we should allow editing before receipt, in which case the
350                     // test should be "if 1 or more real (acp) copies exist
351                     openils.Util.show(real_copies_link, "inline");
352                     real_copies_link.onclick = function() {
353                         self.showRealCopyEditUI(li);
354                     }
355                     openils.Util.show(holdings_maintenance_link, "inline");
356                     holdings_maintenance_link.onclick = self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser' );
357                     return;
358             }
359         }
360
361         openils.Util.hide(recv_link);
362         openils.Util.hide(unrecv_link);
363         openils.Util.hide(real_copies_link);
364     };
365
366
367     this._setAlertStore = function() {
368         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
369             {
370                 "data": acqliat.toStoreData(
371                     this.pcrud.search(
372                         "acqliat", {"id": {"!=": null}}
373                     )
374                 )
375             }
376         );
377         acqLitAlertAlertText.setValue(); /* make the store "live" */
378         acqLitAlertAlertText._store_ready = true;
379     };
380
381     /**
382      * Draws and shows the lineitem notes pane
383      */
384     this.drawLiNotes = function(li) {
385         var self = this;
386
387         if (!acqLitAlertAlertText._store_ready)
388             this._setAlertStore();
389
390         li.lineitem_notes(
391             li.lineitem_notes().sort(
392                 function(a, b) { 
393                     if(a.edit_time() < b.edit_time()) return 1;
394                     return -1;
395                 }
396             )
397         );
398
399         while(this.liNotesTbody.childNodes[0])
400             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
401         this.show('notes');
402
403         acqLitCreateNoteSubmit.onClick = function() {
404             var value = acqLitCreateNoteText.attr('value');
405             if(!value) return;
406             var note = new fieldmapper.acqlin();
407             note.isnew(true);
408             note.vendor_public(
409                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
410             );
411             note.value(value);
412             note.lineitem(li.id());
413
414             self.updateLiNotes(li, note);
415             acqLitCreateNoteVendorPublic.attr("checked", false);
416             acqLitCreateNoteText.attr("value", "");
417         }
418
419         acqLitCreateAlertSubmit.onClick = function() {
420             if (!acqLitAlertAlertText.item) {
421                 alert(localeStrings.ALERT_UNSELECTED);
422                 return;
423             }
424
425             var alert_text = new fieldmapper.acqliat().fromStoreItem(
426                 acqLitAlertAlertText.item
427             );
428             var value = acqLitAlertNoteValue.attr("value") || "";
429
430             var note = new fieldmapper.acqlin();
431             note.isnew(true);
432             note.lineitem(li.id());
433             note.value(value);
434             note.alert_text(alert_text);
435
436             self.updateLiNotes(li, note);
437         }
438
439         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
440     }
441
442     /**
443      * Draws a single lineitem note in the notes pane
444      */
445     this.addLiNote = function(li, note) {
446         if(note.isdeleted()) return;
447         var self = this;
448         var row = self.liNotesRow.cloneNode(true);
449         nodeByName("value", row).innerHTML = note.value();
450         var alert_node = nodeByName("alert_code", row);
451         if (note.alert_text()) {
452             alert_node.innerHTML = note.alert_text().code();
453             if (note.alert_text().description()) {
454                 new dijit.Tooltip(
455                     {
456                         "connectId": [alert_node],
457                         "label": note.alert_text().description()
458                     }, dojo.create("span", null, alert_node, "after")
459                 );
460             }
461         }
462
463         if (openils.Util.isTrue(note.vendor_public()))
464             nodeByName("vendor_public", row).innerHTML =
465                 localeStrings.VENDOR_PUBLIC;
466
467         nodeByName("delete", row).onclick = function() {
468             note.isdeleted(true);
469             self.liNotesTbody.removeChild(row);
470             self.updateLiNotes(li);
471         };
472
473         if(note.edit_time()) {
474             nodeByName("edit_time", row).innerHTML =
475                 dojo.date.locale.format(
476                     dojo.date.stamp.fromISOString(note.edit_time()), 
477                     {formatLength:'short'});
478         }
479
480         self.liNotesTbody.appendChild(row);
481     }
482
483     /**
484      * Updates any new/changed/deleted notes on the server
485      */
486     this.updateLiNotes = function(li, newNote) {
487
488         var notes;
489         if(newNote) {
490             notes = [newNote];
491         } else {
492             notes = li.lineitem_notes().filter(
493                 function(note) {
494                     if(note.ischanged() || note.isnew() || note.isdeleted())
495                         return note;
496                 }
497             );
498         }
499
500         if(notes.length == 0) return;
501         progressDialog.show();
502
503         fieldmapper.standardRequest(
504             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
505             {   async : true,
506                 params : [this.authtoken, notes],
507                 onresponse : function(r) {
508                     var resp = openils.Util.readResponse(r);
509
510                     if(resp.complete) {
511
512                         if(!newNote) {
513                             // remove the old changed notes
514                             var list = [];
515                             dojo.forEach(li.lineitem_notes(), 
516                                 function(note) {
517                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
518                                         list.push(note);
519                                 }
520                             );
521                             li.lineitem_notes(list);
522                         }
523
524                         progressDialog.hide();
525                         self.updateLiNotesCount(li);
526                         self.drawLiNotes(li);
527                         return;
528                     }
529
530                     progressDialog.update(resp);
531                     var newnote = resp.note;
532
533                     if(!newnote.isdeleted()) {
534                         newnote.isnew(false);
535                         newnote.ischanged(false);
536                         li.lineitem_notes().push(newnote);
537                     }
538                 },
539             }
540         );
541     }
542
543     this.updateLiPrice = function(input, li) {
544
545         var price = input.value;
546         if(Number(price) == Number(li.estimated_unit_price())) return;
547
548         fieldmapper.standardRequest(
549             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
550             {   async : true,
551                 params : [this.authtoken, li.id(), price],
552                 oncomplete : function(r) {
553                     openils.Util.readResponse(r);
554                 }
555             }
556         );
557     }
558
559     this.removeLineitem = function(liId) {
560         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
561         delete this.liCache[liId];
562         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
563     }
564
565     this.drawInfo = function(liId) {
566         if (!this._isRelatedViewer) {
567             var d = dojo.byId("acq-lit-info-related");
568             if (!this.relCache[liId]) {
569                 fieldmapper.standardRequest(
570                     [
571                         "open-ils.acq",
572                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
573                     ], {
574                         "async": true,
575                         "params": [openils.User.authtoken, liId],
576                         "onresponse": function(r) {
577                             self.relCache[liId] = openils.Util.readResponse(r);
578                             nodeByName("related_number", d).innerHTML =
579                                 self.relCache[liId];
580                             openils.Util[
581                                 self.relCache[liId] >1 ? "show" : "hide"
582                             ](d);
583                         }
584                     }
585                 );
586             } else {
587                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
588                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
589             }
590         }
591
592         this.show('info');
593         openils.acq.Lineitem.fetchAttrDefs(
594             function() { 
595                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
596             } 
597         );
598     };
599
600     this._fetchLineitem = function(liId, handler) {
601
602         var li = this.liCache[liId];
603         if(li && li.marc() && li.lineitem_details())
604             return handler(li);
605         
606         fieldmapper.standardRequest(
607             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve'],
608             {   async: true,
609
610                 params: [self.authtoken, liId, {
611                     flesh_attrs: true,
612                     flesh_cancel_reason: true,
613                     flesh_li_details: true,
614                     flesh_fund_debit: true }],
615
616                 oncomplete: function(r) {
617                     var li = openils.Util.readResponse(r);
618                     handler(li)
619                 }
620             }
621         );
622     };
623
624     this._drawInfo = function(li) {
625
626         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
627
628         if(li.eg_bib_id()) {
629             openils.Util.hide('acq-lit-marc-order-record-label');
630             openils.Util.hide(acqLitEditOrderMarc.domNode);
631             openils.Util.show('acq-lit-marc-real-record-label');
632         } else {
633             openils.Util.show('acq-lit-marc-order-record-label');
634             openils.Util.show(acqLitEditOrderMarc.domNode);
635             openils.Util.hide('acq-lit-marc-real-record-label');
636         }
637
638         this.drawMarcHTML(li);
639         this.infoTbody = dojo.byId('acq-lit-info-tbody');
640
641         if(!this.infoRow)
642             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
643         while(this.infoTbody.childNodes[0])
644             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
645
646         if (!this._isRelatedViewer) {
647             for(var i = 0; i < li.attributes().length; i++) {
648                 var attr = li.attributes()[i];
649                 var row = this.infoRow.cloneNode(true);
650
651                 var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
652                 var name = openils.acq.Lineitem.attrDefs[type].filter(
653                     function(a) {
654                         return (a.code() == attr.attr_name());
655                     }
656                 ).pop().description();
657
658                 dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
659                 dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
660                 this.infoTbody.appendChild(row);
661             }
662
663             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
664                 "/eg/acq/lineitem/related/" + li.id();
665         }
666
667         if(li.eg_bib_id()) {
668
669             openils.Util.show('acq-lit-info-cat-link');
670             var link = dojo.byId('acq-lit-info-cat-link').getElementsByTagName('a')[0];
671
672             if(openils.XUL.isXUL()) {
673
674                 link.setAttribute('href', 'javascript:void(0);');
675                 link.onclick = this.generateMakeRecTab( li.eg_bib_id() );
676
677             } else {
678                 var href = link.getAttribute('href');
679                 if(href.match(/=$/))
680                     link.setAttribute('href',  href + li.eg_bib_id());
681             }
682         } else {
683             openils.Util.hide('acq-lit-info-cat-link');
684         }
685     };
686
687     this.generateMakeRecTab = function(bib_id,default_view) {
688         return function() {
689             xulG.new_tab(
690                 XUL_OPAC_WRAPPER,
691                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
692                 {
693                     no_xulG : false, 
694                     show_nav_buttons : true, 
695                     show_print_button : true, 
696                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + '?r=' + bib_id),
697                     default_view : default_view
698                 }
699             );
700         }
701     };
702
703     this.drawMarcHTML = function(li) {
704         var params = [null, true, li.marc()];
705         if(li.eg_bib_id()) 
706             params = [li.eg_bib_id(), true];
707
708         fieldmapper.standardRequest(
709             ['open-ils.search', 'open-ils.search.biblio.record.html'],
710             {   async: true,
711                 params: params,
712                 oncomplete: function(r) {
713                     dojo.byId('acq-lit-marc-div').innerHTML = 
714                         openils.Util.readResponse(r);
715                 }
716             }
717         );
718     }
719
720     this.drawCopies = function(liId) {
721         this.show('copies');
722         var self = this;
723         this.copyCache = {};
724         this.copyWidgetCache = {};
725         this.oldCopyWidgetCache = {};
726         this.virtDfaCounts = {};
727         this.realDfaCache = {};
728         this.dfeOffset = 0;
729
730         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
731         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
732         acqLitCopyCountInput.attr('value', '0');
733
734         while(this.copyTbody.childNodes[0])
735             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
736
737         this._drawBatchCopyWidgets();
738
739         this._drawDistribApplied(liId);
740
741         this._fetchDistribFormulas(
742             function() {
743                 openils.acq.Lineitem.fetchAttrDefs(
744                     function() { 
745                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}); 
746                     } 
747                 );
748             }
749         );
750     };
751
752     this._saveDistribAppliedTemplates = function() {
753         if (!this._appliedDistribTemplate) {
754             this._appliedDistribTemplate =
755                 dojo.byId("acq-lit-distrib-applied-tbody").
756                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
757             dojo.attr(this._appliedDistribTemplate, "id");
758         }
759     };
760
761     this._drawDistribApplied = function(liId) {
762         /* Build this table while hidden to prevent rendering artifacts */
763         openils.Util.hide("acq-lit-distrib-applied-tbody");
764
765         this._saveDistribAppliedTemplates();
766
767         /* Remove any rows in the table from previous populations */
768         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
769             forEach(dojo.destroy);
770
771         /* Unregister all dijits previously created (for some reason this isn't
772          * covered by the above destroy calls). */
773         dijit.registry.forEach(
774             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
775         );
776
777         /* Populate the table with our liId */
778         var total = 0;
779         fieldmapper.standardRequest(
780             ["open-ils.acq",
781             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
782             {
783                 "async": true,
784                 "params": [self.authtoken, liId],
785                 "onresponse": function(r) {
786                     var dfa = openils.Util.readResponse(r);
787                     if (dfa) {
788                         total++;
789                         self.realDfaCache[dfa.id()] = dfa;
790                         self._drawDistribAppliedUnit(dfa);
791                     }
792                 },
793                 "oncomplete": function() {
794                     /* Reveal built table */
795                     if (total) {
796                         openils.Util.show(
797                             "acq-lit-distrib-applied-tbody", "table-row-group"
798                         );
799                     }
800                 }
801             }
802         );
803     };
804
805     this._drawDistribAppliedUnit = function(dfa) {
806         var new_row = false;
807         var row = dojo.query(
808             'tr[formula="' + dfa.formula().id() + '"]',
809             "acq-lit-distrib-applied-tbody"
810         )[0];
811
812         if (!row) {
813             new_row = true;
814             row = dojo.clone(this._appliedDistribTemplate);
815             dojo.attr(row, "formula", dfa.formula().id());
816             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
817         }
818
819         var td = dojo.query("td", row)[0];
820
821         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
822         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
823
824         if (new_row)
825             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
826
827         new dijit.form.Button(
828             {
829                 "onClick": function() {
830                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
831                         self.deleteDfa(dfa);
832                 },
833                 "label": "X",
834                 /* XXX I /cannot/ make the following work in as a CSS class
835                  * for some reason. So frustrating... */
836                 "style": function(id) {
837                      return (id > 0 ?
838                         "font-weight: bold; color: #c00;" :
839                         "color: #666;");
840                      }(dfa.id()) + "margin: 0 6px;display: inline;"
841             }, "dfa-button-" + dfa.id()
842         );
843         new dijit.Tooltip(
844             {
845                 "connectId": ["dfa-button-" + dfa.id()],
846                 "label": dojo.string.substitute(
847                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
848                         openils.User.formalName(dfa.creator()),
849                         dojo.date.locale.format(
850                             dojo.date.stamp.fromISOString(dfa.create_time()),
851                             {"formatLength":"short"}
852                         )
853                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
854                 )
855             }, "dfa-tip-" + dfa.id()
856         );
857     }
858
859     this.deleteDfa = function(dfa) {
860         if (dfa.id() > 0) { /* real */
861             this.pcrud.eliminate(
862                 dfa, {
863                     "async": true,
864                     "oncomplete": function() {
865                         self._removeDistribApplied(dfa.id());
866                         delete self.realDfaCache[dfa.id()];
867                     }
868                 }
869             );
870         } else { /* virtual */
871             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
872             this.virtDfaCounts[dfa.formula().id()] = 0;
873             /* hasn't been saved yet, so no need to do anything server side */
874             this._removeDistribApplied(dfa.id());
875         }
876
877     };
878
879     this._removeDistribApplied = function(dfaId) {
880         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
881         dijit.registry.forEach(
882             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
883         );
884         this._removeDistribAppliedEmptyRows();
885     };
886
887     this._removeAllDistribAppliedVirtual = function() {
888         /* Unregister dijits */
889         dijit.registry.forEach(
890             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
891         );
892         this._removeDistribAppliedEmptyRows();
893     };
894
895     this._removeDistribAppliedEmptyRows = function() {
896         /* Remove any rows with no DFA at all */
897         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
898             function(o) {
899                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
900             }
901         );
902     };
903
904     /**
905      * Insert a new row into the distribution formula selection form
906      */
907     this._addDistribFormulaRow = function() {
908         var self = this;
909
910         if (!self.distribForms) {
911             // no formulas, hide the form
912             openils.Util.hide('acq-lit-distrib-formula-tbody');
913             return;
914         }
915
916         if(!this.distribFormulaTemplate) 
917             this.distribFormulaTemplate = 
918                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
919
920         var row = this.distribFormulaTemplate.cloneNode(true);
921         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
922
923         this.dfSelector = new dijit.form.FilteringSelect(
924             {"labelAttr": "dynLabel", "labelType": "html"},
925             nodeByName("selector", row)
926         );
927         this._updateFormulaStore();
928         this.dfSelector.fetchProperties =
929             {"sort": [{"attribute": "use_count", "descending": true}]};
930
931         var apply = new dijit.form.Button(
932             {"label": localeStrings.APPLY},
933             nodeByName('set_button', row)
934         ); 
935
936         var reset = new dijit.form.Button(
937             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
938             nodeByName("reset_button", row)  
939         );
940
941         dojo.connect(apply, 'onClick', 
942             function() {
943                 var form_id = self.dfSelector.attr("value");
944                 if(!form_id) return;
945                 self._applyDistribFormula(form_id);
946                 reset.attr("disabled", false);
947             }
948         );
949
950         dojo.connect(reset, 'onClick', 
951             function() {
952                 self.restoreCopyFieldsBeforeDF();
953                 self.virtDfaCounts = {};
954                 self.virtDfaId = -1;
955                 self.dfeOffset = 0;
956                 self._updateFormulaStore();
957                 self._removeAllDistribAppliedVirtual();
958                 reset.attr("disabled", "true");
959             }
960         );
961
962     };
963
964     /**
965      * Applies a distrib formula to the current set of copies
966      */
967     this._applyDistribFormula = function(formula) {
968         if(!formula) return;
969
970         formula = this.distribForms.filter(
971             function(form) { return form.id() == formula; }
972         )[0];
973
974         var copyRows = dojo.query('tr', self.copyTbody);
975
976         if (this.dfeOffset >= copyRows.length) {
977             alert(localeStrings.OUT_OF_COPIES);
978             return;
979         }
980
981         var entries_applied = 0;
982         for(
983             var rowIndex = this.dfeOffset;
984             rowIndex < copyRows.length;
985             rowIndex++
986         ) {
987             
988             var row = copyRows[rowIndex];
989             var copy_id = row.getAttribute('copy_id');
990             var copyWidgets = this.copyWidgetCache[copy_id];
991             var entryIndex = this.dfeOffset;
992             var entry = null;
993
994             // find the correct entry for the current row
995             dojo.forEach(formula.entries(), 
996                 function(e) {
997                     if(!entry) {
998                         entryIndex += e.item_count();
999                         if(entryIndex > rowIndex)
1000                             entry = e;
1001                     }
1002                 }
1003             );
1004
1005             if(entry) {
1006                 
1007                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1008                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1009     
1010                 entries_applied++;
1011                 this.saveCopyFieldsBeforeDF(copy_id);
1012                 this._copy_fields_for_acqdf.forEach(
1013                     function(field) {
1014                         if(entry[field]()) {
1015                             copyWidgets[field].attr('value', (entry[field]()));
1016                         }
1017                     }
1018                 );
1019             }
1020         }
1021
1022         if (entries_applied) {
1023             this.virtDfaCounts[formula.id()] =
1024                 ++(this.virtDfaCounts[formula.id()]) || 1;
1025             this._updateFormulaStore();
1026             this._drawDistribAppliedUnit(
1027                 function(df) {
1028                     var dfa = new acqdfa();
1029                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1030                 }(formula)
1031             );
1032             this.dfeOffset += entries_applied;
1033         };
1034     };
1035
1036     /**
1037      * This function updates the DF store for the dropdown so that use_counts
1038      * can reflect DF applications from this session before they're saved
1039      * server-side.
1040      */
1041     this._updateFormulaStore = function() {
1042         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1043             {
1044                 "data": self._labelFormulasWithCounts(
1045                     acqdf.toStoreData(self.distribForms)
1046                 )
1047             }
1048         );
1049     };
1050
1051     this.saveCopyFieldsBeforeDF = function(copy_id) {
1052         var self = this;
1053         if (!this.oldCopyWidgetCache[copy_id]) {
1054             var copyWidgets = this.copyWidgetCache[copy_id];
1055
1056             this.oldCopyWidgetCache[copy_id] = {};
1057             this._copy_fields_for_acqdf.forEach(
1058                 function(f) {
1059                     self.oldCopyWidgetCache[copy_id][f] =
1060                         copyWidgets[f].attr("value");
1061                 }
1062             );
1063         }
1064     };
1065
1066     this.restoreCopyFieldsBeforeDF = function() {
1067         var self = this;
1068         for (var copy_id in this.oldCopyWidgetCache) {
1069             this._copy_fields_for_acqdf.forEach(
1070                 function(f) {
1071                     self.copyWidgetCache[copy_id][f].attr(
1072                         "value", self.oldCopyWidgetCache[copy_id][f]
1073                     );
1074                 }
1075             );
1076         }
1077     };
1078
1079     this._labelFormulasWithCounts = function(store_data) {
1080         for (var key in store_data.items) {
1081             var obj = store_data.items[key];
1082             obj.use_count = Number(obj.use_count); /* needed for sorting */
1083
1084             if (this.virtDfaCounts[obj.id])
1085                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1086
1087             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1088                 obj.use_count + "]</span>&nbsp; " + obj.name;
1089         }
1090         return store_data;
1091     };
1092
1093     /**
1094      * This method formerly would not refetch the DF formulas if they'd been
1095      * loaded already, but now it always re-fetches, since use_count changes.
1096      */
1097     this._fetchDistribFormulas = function(onload) {
1098         fieldmapper.standardRequest(
1099             ["open-ils.acq",
1100                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1101             {
1102                 "async": true,
1103                 "params": [openils.User.authtoken],
1104                 "oncomplete": function(r) {
1105                     self.distribForms = openils.Util.readResponse(r);
1106                     if(!self.distribForms || self.distribForms.length == 0) {
1107                         self.distribForms = [];
1108                     }
1109                     self._addDistribFormulaRow();
1110                     onload();
1111                 }
1112             }
1113         );
1114     }
1115
1116     this._drawBatchCopyWidgets = function() {
1117         var row = this.copyBatchRow;
1118         dojo.forEach(liDetailBatchFields, 
1119             function(field) {
1120                 if(self.copyBatchRowDrawn) {
1121                     self.copyBatchWidgets[field].attr('value', null);
1122                 } else {
1123                     var widget = new openils.widget.AutoFieldWidget({
1124                         fmField : field,
1125                         fmClass : 'acqlid',
1126                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1127                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1128                         parentNode : dojo.query('[name='+field+']', row)[0],
1129                         orgLimitPerms : ['CREATE_PICKLIST'],
1130                         dijitArgs : {required:false},
1131                         forceSync : true
1132                     });
1133                     widget.build(
1134                         function(w, ww) {
1135                             self.copyBatchWidgets[field] = w;
1136                         }
1137                     );
1138                 }
1139             }
1140         );
1141         this.copyBatchRowDrawn = true;
1142     };
1143
1144     this.batchCopyUpdate = function() {
1145         var self = this;
1146         for(var k in this.copyWidgetCache) {
1147             var cache = this.copyWidgetCache[k];
1148             dojo.forEach(liDetailBatchFields, function(f) {
1149                 var newval = self.copyBatchWidgets[f].attr('value');
1150                 if(newval) cache[f].attr('value', newval);
1151             });
1152         }
1153     };
1154
1155     this._drawCopies = function(li) {
1156         var self = this;
1157
1158         // this button sets the total number of copies for a given lineitem
1159         acqLitAddCopyCount.onClick = function() { 
1160             var count = acqLitCopyCountInput.attr('value');
1161
1162             // add new rows
1163             while(self.copyCount() < count)
1164                 self.addCopy(li); 
1165             
1166             // delete rows if necessary
1167             var diff = self.copyCount() - count;
1168             if(diff > 0) {
1169                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1170                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1171                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1172                 } else {
1173                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1174                 }
1175             }
1176         }
1177
1178
1179         if(li.lineitem_details().length > 0) {
1180             dojo.forEach(li.lineitem_details(),
1181                 function(copy) {
1182                     self.addCopy(li, copy);
1183                 }
1184             );
1185         } else {
1186             self.addCopy(li);
1187         }
1188     };
1189
1190     this.copyCount = function() {
1191         var count = 0;
1192         for(var id in this.copyCache) {
1193             if(!this.copyCache[id].isdeleted())
1194                 count++;
1195         }
1196         return count;
1197     }
1198
1199     this.virtCopyId = -1;
1200     this.addCopy = function(li, copy) {
1201         var row = this.copyRow.cloneNode(true);
1202         this.copyTbody.appendChild(row);
1203         var self = this;
1204
1205         if(!copy) {
1206             copy = new fieldmapper.acqlid();
1207             copy.isnew(true);
1208             copy.id(this.virtCopyId--);
1209             copy.lineitem(li.id());
1210         }
1211
1212         this.copyCache[copy.id()] = copy;
1213         row.setAttribute('copy_id', copy.id());
1214         self.copyWidgetCache[copy.id()] = {};
1215
1216         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1217
1218         dojo.forEach(liDetailFields,
1219             function(field) {
1220                 var widget = new openils.widget.AutoFieldWidget({
1221                     fmObject : copy,
1222                     fmField : field,
1223                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1224                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1225                     fmClass : 'acqlid',
1226                     parentNode : dojo.query('[name='+field+']', row)[0],
1227                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1228                     readOnly : Boolean(copy.eg_copy_id())
1229                 });
1230                 widget.build(
1231                     // make sure we capture the value from any async widgets
1232                     function(w, ww) { 
1233                         copy[field](ww.getFormattedValue()) 
1234                         self.copyWidgetCache[copy.id()][field] = w;
1235                     }
1236                 );
1237                 dojo.connect(widget.widget, 'onChange', 
1238                     function(val) { 
1239                         if(copy.isnew() || val != copy[field]()) {
1240                             // prevent setting ischanged() automatically on widget load for existing copies
1241                             copy[field](widget.getFormattedValue()) 
1242                             copy.ischanged(true);
1243                         }
1244                     }
1245                 );
1246             }
1247         );
1248
1249         this.updateLidState(copy, row);
1250     };
1251
1252     this.updateLidState = function(copy, row) {
1253         if (typeof(row) == "undefined") {
1254             row = dojo.query(
1255                 'tr[copy_id="' + copy.id() + '"]', this.copyTbody
1256             )[0];
1257         }
1258
1259         var self = this;
1260         var recv_link = nodeByName("receive", row);
1261         var unrecv_link = nodeByName("unreceive", row);
1262         var del_link = nodeByName("delete", row);
1263         var cxl_link = nodeByName("cancel", row);
1264         var cxl_reason_link = nodeByName("cancel_reason", row);
1265
1266         if (copy.cancel_reason()) {
1267             openils.Util.hide(del_link.parentNode);
1268             openils.Util.hide(recv_link);
1269             openils.Util.hide(unrecv_link);
1270             openils.Util.hide(cxl_link);
1271
1272             /* XXX the following may leak memory in a long lived table: dijits may not get destroyed... not positive. revisit. */
1273             var holds_reason = dojo.create(
1274                 "span", {
1275                     "style": "border-bottom: 1px dashed #000;",
1276                     "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1277                 }, cxl_reason_link, "only"
1278             );
1279             new dijit.Tooltip(
1280                 {
1281                     "label": "<em>" + copy.cancel_reason().label() +
1282                         "</em><br />" + copy.cancel_reason().description(),
1283                     "connectId": [holds_reason]
1284                 }, dojo.create("span", null, cxl_reason_link, "last")
1285             );
1286             openils.Util.show(cxl_reason_link, "inline");
1287         } else if (this.isPO) {
1288             openils.Util.hide(del_link.parentNode);
1289             openils.Util.hide(cxl_reason_link);
1290
1291             /* Avoid showing (un)receive links, cancel links, for virt copies */
1292             if (copy.id() > 0) {
1293                 if(copy.recv_time()) {
1294                     openils.Util.hide(cxl_link);
1295                     openils.Util.hide(recv_link);
1296                     openils.Util.show(unrecv_link, "inline");
1297                     unrecv_link.onclick = function() {
1298                         if (confirm(localeStrings.UNRECEIVE_LID))
1299                             self.issueReceive(copy, /* rollback */ true);
1300                     };
1301                 } else {
1302                     openils.Util.hide(unrecv_link);
1303                     openils.Util.show(recv_link, "inline");
1304                     openils.Util.show(cxl_link, "inline");
1305                     recv_link.onclick = function() {
1306                         if (self.checkLiAlerts(copy.lineitem()))
1307                             self.issueReceive(copy);
1308                     };
1309                     cxl_link.onclick = function() {
1310                         self.cancelLid(copy.id());
1311                     };
1312                 }
1313             } else {
1314                 openils.Util.hide(cxl_link);
1315                 openils.Util.hide(unrecv_link);
1316                 openils.Util.hide(recv_link);
1317             }
1318         } else {
1319             openils.Util.hide(unrecv_link);
1320             openils.Util.hide(recv_link);
1321             openils.Util.hide(cxl_reason_link);
1322
1323             del_link.onclick = function() { self.deleteCopy(row) };
1324             openils.Util.show(del_link.parentNode);
1325         }
1326     }
1327
1328     this.cancelLid = function(lid_id) {
1329         lidCancelDialog._lid_id = lid_id;
1330         openils.Util.show(lidCancelDialog.domNode.parentNode);
1331         lidCancelDialog.show();
1332         if (!lidCancelDialog._prepared) {
1333             var widget = new openils.widget.AutoFieldWidget({
1334                 "fmField": "cancel_reason",
1335                 "fmClass": "acqlid",
1336                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1337                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1338                 "forceSync": true
1339             });
1340             widget.build(
1341                 function(w, ww) {
1342                     acqLidCancelButton.onClick = function() {
1343                         if (w.attr("value")) {
1344                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1345                                 self._cancelLid(
1346                                     lidCancelDialog._lid_id,
1347                                     w.attr("value")
1348                                 );
1349                             }
1350                             lidCancelDialog.hide();
1351                         }
1352                     };
1353                     lidCancelDialog._prepared = true;
1354                 }
1355             );
1356         }
1357     };
1358
1359     this._cancelLid = function(lid_id, reason) {
1360         fieldmapper.standardRequest(
1361             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1362                 "params": [openils.User.authtoken, lid_id, reason],
1363                 "async": true,
1364                 "onresponse": function(r) {
1365                     if (r = openils.Util.readResponse(r)) {
1366                         if (r.lid) {
1367                             for (var id in r.lid) {
1368                                 /* actually this should only iterate once */
1369                                 self.copyCache[id].cancel_reason(
1370                                     r.lid[id].cancel_reason
1371                                 );
1372                                 self.updateLidState(self.copyCache[id]);
1373                             }
1374                         }
1375                     }
1376                 }
1377             }
1378         );
1379     };
1380
1381     this._confirmAlert = function(li, lin) {
1382         return confirm(
1383             dojo.string.substitute(
1384                 localeStrings.CONFIRM_LI_ALERT, [
1385                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1386                         "title", "lineitem_marc_attr_definition"
1387                     ),
1388                     lin.alert_text().code(),
1389                     lin.alert_text().description() || "",
1390                     lin.value()
1391                 ]
1392             )
1393         );
1394     };
1395
1396     this.checkLiAlerts = function(li_id) {
1397         var li = this.liCache[li_id];
1398
1399         var alert_notes = li.lineitem_notes().filter(
1400             function(o) { return Boolean(o.alert_text()); }
1401         );
1402
1403         /* this is _intentionally_ not done in a call to forEach() ... */
1404         for (var i = 0; i < alert_notes.length; i++) {
1405             if (this.noteAcks[alert_notes[i].id()])
1406                 continue;
1407             else if (!this._confirmAlert(li, alert_notes[i]))
1408                 return false;
1409             else
1410                 this.noteAcks[alert_notes[i].id()] = true;
1411         }
1412
1413         return true;
1414     };
1415
1416     this.deleteCopy = function(row) {
1417         var copy = this.copyCache[row.getAttribute('copy_id')];
1418         copy.isdeleted(true);
1419         if(copy.isnew())
1420             delete this.copyCache[copy.id()];
1421         this.copyTbody.removeChild(row);
1422     }
1423
1424     this._virtDfaCountsAsList = function() {
1425         var L = [];
1426         for (var key in this.virtDfaCounts) {
1427             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1428                 L.push(key);
1429         }
1430         return L;
1431     }
1432
1433     this.saveCopyChanges = function(liId) {
1434         var self = this;
1435         var copies = [];
1436
1437
1438         var total = 0;
1439         for(var id in this.copyCache) {
1440             var c = this.copyCache[id];
1441             if(!c.isdeleted()) total++;
1442             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1443                 if(c.id() < 0) c.id(null);
1444                 copies.push(c);
1445             }
1446         }
1447
1448         if (typeof(this._copy_count_cb) == "function") {
1449             this._copy_count_cb(liId, total);
1450         }
1451
1452         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1453
1454
1455         if (copies.length > 0) {
1456             openils.Util.show("acq-lit-update-copies-progress");
1457             fieldmapper.standardRequest(
1458                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1459                 {   async: true,
1460                     params: [openils.User.authtoken, copies],
1461                     onresponse: function(r) {
1462                         var res = openils.Util.readResponse(r);
1463                         litUpdateCopiesProgress.update(res);
1464                     },
1465                     oncomplete: function() {
1466                         self.drawCopies(liId);
1467                         openils.Util.hide("acq-lit-update-copies-progress");
1468                     }
1469                 }
1470             );
1471         }
1472
1473         var dfa_list = this._virtDfaCountsAsList();
1474         if (dfa_list.length > 0) {
1475             fieldmapper.standardRequest(
1476                 ["open-ils.acq",
1477                 "open-ils.acq.distribution_formula.record_application"],
1478                 {
1479                     "async": true,
1480                     "params": [openils.User.authtoken, dfa_list, liId],
1481                     "onresponse": function(r) {
1482                         var res = openils.Util.readResponse(r);
1483                         if (res && res.length < dfa_list.length)
1484                             alert(localeStrings.DFA_NOT_ALL);
1485                     }
1486                 }
1487             );
1488             this.virtDfaCounts = {};
1489         }
1490     }
1491
1492     this._updateCreatePoPrepayCheckbox = function(prepay) {
1493         var prepay = openils.Util.isTrue(prepay);
1494         this._prepayRequiredByVendor = prepay;
1495         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
1496     };
1497
1498     this._confirmPoPrepaySituation = function() {
1499         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
1500         if (want_prepay != this._prepayRequiredByVendor) {
1501             return confirm(
1502                 want_prepay ?
1503                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
1504                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
1505             );
1506         } else {
1507             return true;
1508         }
1509     };
1510
1511     this.applySelectedLiAction = function(action) {
1512         var self = this;
1513         switch(action) {
1514
1515             case 'delete_selected':
1516                 this._deleteLiList(self.getSelected());
1517                 break;
1518
1519             case 'create_order':
1520
1521                 if(!this.createPoProviderSelector) {
1522                     var widget = new openils.widget.AutoFieldWidget({
1523                         fmField : 'provider',
1524                         fmClass : 'acqpo',
1525                         searchFilter: {"active": "t"},
1526                         parentNode : dojo.byId('acq-lit-po-provider'),
1527                         dijitArgs : {
1528                             "onChange": function() {
1529                                 if (this.item) {
1530                                     self._updateCreatePoPrepayCheckbox(
1531                                         this.item.prepayment_required
1532                                     );
1533                                 }
1534                             }
1535                         }
1536                     });
1537                     widget.build(
1538                         function(w) { self.createPoProviderSelector = w; }
1539                     );
1540                 }
1541
1542                 if(!this.createPoAgencySelector) {
1543                     var widget = new openils.widget.AutoFieldWidget({
1544                         fmField : 'ordering_agency',
1545                         fmClass : 'acqpo',
1546                         parentNode : dojo.byId('acq-lit-po-agency'),
1547                         orgLimitPerms : ['CREATE_PURCHASE_ORDER'],
1548                     });
1549                     widget.build(
1550                         function(w) { self.createPoAgencySelector = w; }
1551                     );
1552                 }
1553
1554          
1555                 acqLitPoCreateDialog.show();
1556                 break;
1557
1558             case 'save_picklist':
1559                 this._loadPLSelect();
1560                 acqLitSavePlDialog.show();
1561                 break;
1562
1563             case 'selector_ready':
1564             case 'order_ready':
1565                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
1566                 acqLitChangeLiStateDialog.show();
1567                 break;
1568
1569             case 'print_po':
1570                 this.printPO();
1571                 break;
1572
1573             case 'receive_po':
1574                 this.receivePO();
1575                 break;
1576
1577             case 'rollback_receive_po':
1578                 this.rollbackPoReceive();
1579                 break;
1580
1581             case 'create_assets':
1582                 this.createAssets();
1583                 break;
1584
1585             case 'export_attr_list':
1586                 this.chooseExportAttr();
1587                 break;
1588
1589             case 'add_brief_record':
1590                 if(this.isPO)
1591                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
1592                 else
1593                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
1594
1595                 break;
1596
1597             case "cancel_lineitems":
1598                 this.maybeCancelLineitems();
1599                 break;
1600         }
1601     }
1602
1603     this.createAssets = function() {
1604         if(!this.isPO) return;
1605         if(!confirm(localeStrings.CREATE_PO_ASSETS_CONFIRM)) return;
1606         this.show('acq-lit-progress-numbers');
1607         var self = this;
1608         fieldmapper.standardRequest(
1609             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
1610             {   async: true,
1611                 params: [this.authtoken, this.isPO],
1612                 onresponse: function(r) {
1613                     var resp = openils.Util.readResponse(r);
1614                     self._updateProgressNumbers(resp, true);
1615                 }
1616             }
1617         );
1618     }
1619
1620     this.maybeCancelLineitems = function() {
1621         openils.Util.show("acq-lit-cancel-reason", "inline");
1622         if (!acqLitCancelLineitemsButton._prepared) {
1623             var widget = new openils.widget.AutoFieldWidget({
1624                 "fmField": "cancel_reason",
1625                 "fmClass": "jub",
1626                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
1627                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1628                 "forceSync": true
1629             });
1630             widget.build(
1631                 function(w, ww) {
1632                     acqLitCancelLineitemsButton.onClick = function() {
1633                         if (w.attr("value")) {
1634                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
1635                                 self._cancelLineitems(w.attr("value"));
1636                             }
1637                             openils.Util.hide("acq-lit-cancel-reason");
1638                         }
1639                     };
1640                     acqLitCancelLineitemsButton._prepared = true;
1641                 }
1642             );
1643         }
1644     };
1645
1646     this._cancelLineitems = function(reason) {
1647         var id_list = this.getSelected().map(function(o) { return o.id(); });
1648         fieldmapper.standardRequest(
1649             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
1650                 "params": [openils.User.authtoken, id_list, reason],
1651                 "async": true,
1652                 "onresponse": function(r) {
1653                     if (r = openils.Util.readResponse(r)) {
1654                         if (r.li) {
1655                             for (var id in r.li) {
1656                                 self.liCache[id].state(r.li[id].state);
1657                                 self.liCache[id].cancel_reason(
1658                                     r.li[id].cancel_reason
1659                                 );
1660                                 self.updateLiState(self.liCache[id]);
1661                             }
1662                         }
1663                         if (r.lid && self.copyCache) {
1664                             for (var id in r.lid) {
1665                                 if (self.copyCache[id]) {
1666                                     self.copyCache[id].cancel_reason(
1667                                         r.lid[id].cancel_reason
1668                                     );
1669                                     self.updateLidState(self.copyCache[id]);
1670                                 }
1671                             }
1672                         }
1673                     }
1674                 }
1675             }
1676         );
1677     };
1678
1679     this.chooseExportAttr = function() {
1680         if (!acqLitExportAttrSelector._li_setup) {
1681             var self = this;
1682             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
1683                 {
1684                     "data": acqliad.toStoreData(
1685                         this.pcrud.search(
1686                             "acqliad", {"code": li_exportable_attrs}
1687                         )
1688                     )
1689                 }
1690             );
1691             acqLitExportAttrSelector.setValue();
1692             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
1693             acqLitExportAttrSelector._li_setup = true;
1694         }
1695         openils.Util.show("acq-lit-export-attr-holder", "inline");
1696     };
1697
1698     this.exportAttrList = function() {
1699         var attr_def = acqLitExportAttrSelector.item;
1700         var li_list = this.getSelected();
1701         var value_list = li_list.map(
1702             function(li) {
1703                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1704                     attr_def.code, "lineitem_marc_attr_definition"
1705                 );
1706             }
1707         ).filter(function(attr) { return Boolean(attr); });
1708
1709         if (value_list.length > 0) {
1710             if (value_list.length < li_list.length) {
1711                 if (!confirm(
1712                     dojo.string.substitute(
1713                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
1714                     )
1715                 )) {
1716                     return;
1717                 }
1718             }
1719             try {
1720                 openils.XUL.contentToFileSaveDialog(
1721                     value_list.join("\n"),
1722                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
1723                 );
1724             } catch (E) {
1725                 alert(E);
1726             }
1727         } else {
1728             alert(dojo.string.substitute(
1729                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
1730             ));
1731         }
1732
1733         openils.Util.hide("acq-lit-export-attr-holder");
1734     };
1735
1736     this.printPO = function() {
1737         if(!this.isPO) return;
1738         progressDialog.show(true);
1739         fieldmapper.standardRequest(
1740             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
1741             {   async: true,
1742                 params: [this.authtoken, this.isPO, 'html'],
1743                 oncomplete: function(r) {
1744                     progressDialog.hide();
1745                     var evt = openils.Util.readResponse(r);
1746                     if(evt && evt.template_output()) {
1747                         win = window.open('','', 'resizable,width=800,height=600,scrollbars=1');
1748                         win.document.body.innerHTML = evt.template_output().data();
1749                     }
1750                 }
1751             }
1752         );
1753     }
1754
1755
1756     this.receivePO = function() {
1757         if (!this.isPO) return;
1758
1759         for (var id in this.liCache) {
1760             /* assumption: liCache reflects exactly the
1761              * set of LIs that belong to our PO */
1762             if (this.liCache[id].state() != "received" &&
1763                 !this.checkLiAlerts(id)) return;
1764         }
1765
1766         this.show('acq-lit-progress-numbers');
1767         var self = this;
1768         fieldmapper.standardRequest(
1769             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
1770             {   async: true,
1771                 params: [this.authtoken, this.isPO],
1772                 onresponse : function(r) {
1773                     var resp = openils.Util.readResponse(r);
1774                     self._updateProgressNumbers(resp, true);
1775                 },
1776             }
1777         );
1778     }
1779
1780     this.issueReceive = function(obj, rollback) {
1781         /* (For now) there shall be no marking LI or LIDs (un)received
1782          * except from the actual "view PO" interface. */
1783         if (!this.isPO) return;
1784
1785         var part =
1786             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
1787         var method =
1788             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
1789
1790         progressDialog.show(true);
1791         fieldmapper.standardRequest(
1792             ["open-ils.acq", method], {
1793                 "async": true,
1794                 "params": [this.authtoken, obj.id()],
1795                 "onresponse": function(r) {
1796                     self.handleReceive(openils.Util.readResponse(r));
1797                     progressDialog.hide();
1798                 }
1799             }
1800         );
1801     };
1802
1803     /**
1804      * Handles the responses from receive and rollback ML calls.
1805      */
1806     this.handleReceive = function(resp) {
1807         if (resp) {
1808             if (resp.li) {
1809                 for (var li_id in resp.li) {
1810                     for (var key in resp.li[li_id])
1811                         self.liCache[li_id][key](resp.li[li_id][key]);
1812                     self.updateLiState(self.liCache[li_id]);
1813                 }
1814             }
1815             if (resp.po) {
1816                 if (typeof(self.poUpdateCallback) == "function")
1817                     self.poUpdateCallback(resp.po);
1818             }
1819             if (resp.lid) {
1820                 for (var lid_id in resp.lid) {
1821                     for (var key in resp.lid[lid_id])
1822                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
1823                     self.updateLidState(self.copyCache[lid_id]);
1824                 }
1825             }
1826         }
1827     };
1828
1829     this.rollbackPoReceive = function() {
1830         if(!this.isPO) return;
1831         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
1832         this.show('acq-lit-progress-numbers');
1833         var self = this;
1834         fieldmapper.standardRequest(
1835             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
1836             {   async: true,
1837                 params: [this.authtoken, this.isPO],
1838                 onresponse : function(r) {
1839                     var resp = openils.Util.readResponse(r);
1840                     self._updateProgressNumbers(resp, true);
1841                 },
1842             }
1843         );
1844     }
1845
1846     this._updateProgressNumbers = function(resp, reloadOnComplete) {
1847         if(!resp) return;
1848         dojo.byId('acq-pl-lit-li-processed').innerHTML = resp.li;
1849         dojo.byId('acq-pl-lit-lid-processed').innerHTML = resp.lid;
1850         dojo.byId('acq-pl-lit-debits-processed').innerHTML = resp.debits_accrued;
1851         dojo.byId('acq-pl-lit-bibs-processed').innerHTML = resp.bibs;
1852         dojo.byId('acq-pl-lit-indexed-processed').innerHTML = resp.indexed;
1853         dojo.byId('acq-pl-lit-copies-processed').innerHTML = resp.copies;
1854         if(resp.complete && reloadOnComplete) 
1855             location.href = location.href;
1856     }
1857
1858
1859     this._createPO = function(fields) {
1860         this.show('acq-lit-progress-numbers');
1861         var po = new fieldmapper.acqpo();
1862         po.provider(this.createPoProviderSelector.attr('value'));
1863         po.ordering_agency(this.createPoAgencySelector.attr('value'));
1864         po.prepayment_required(fields.prepayment_required[0] ? true : false);
1865
1866         var selected = this.getSelected( (fields.create_from == 'all') );
1867         if(selected.length == 0) return;
1868
1869         var max = selected.length * 3;
1870
1871         var self = this;
1872         fieldmapper.standardRequest(
1873             ['open-ils.acq', 'open-ils.acq.purchase_order.create'],
1874             {   async: true,
1875                 params: [
1876                     openils.User.authtoken, 
1877                     po, 
1878                     {
1879                         lineitems : selected.map(function(li) { return li.id() }),
1880                         create_assets : fields.create_assets[0],
1881                     }
1882                 ],
1883
1884                 onresponse : function(r) {
1885                     var resp = openils.Util.readResponse(r);
1886                     self._updateProgressNumbers(resp);
1887                     if(resp.complete) 
1888                         location.href = oilsBasePath + '/eg/acq/po/view/' + resp.purchase_order.id();
1889                 }
1890             }
1891         );
1892     }
1893
1894     this._deleteLiList = function(list, idx) {
1895         if(idx == null) idx = 0;
1896         if(idx >= list.length) return;
1897         var liId = list[idx].id();
1898         fieldmapper.standardRequest(
1899             ['open-ils.acq', 'open-ils.acq.lineitem.delete'],
1900             {   async: true,
1901                 params: [openils.User.authtoken, liId],
1902                 oncomplete: function(r) {
1903                     self.removeLineitem(liId);
1904                     self._deleteLiList(list, ++idx);
1905                 }
1906             }
1907         );
1908     }
1909
1910     this.editOrderMarc = function(li) {
1911
1912         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
1913             to true in about:config */
1914
1915         if(!openils.XUL.enableXPConnect()) return;
1916
1917         if(openils.XUL.isXUL()) {
1918             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
1919         } else {
1920             win = window.open('/xul/server/cat/marcedit.xul'); 
1921         }
1922         var self = this;
1923         win.xulG = {
1924             record : {marc : li.marc()},
1925             save : {
1926                 label: 'Save Record', // XXX I18N
1927                 func: function(xmlString) {
1928                     li.marc(xmlString);
1929                     fieldmapper.standardRequest(
1930                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
1931                         {   async: true,
1932                             params: [openils.User.authtoken, li],
1933                             oncomplete: function(r) {
1934                                 openils.Util.readResponse(r);
1935                                 win.close();
1936                                 self.drawInfo(li.id())
1937                             }
1938                         }
1939                     );
1940                 },
1941             }
1942         };
1943     }
1944
1945     this._savePl = function(values) {
1946         var self = this;
1947         var selected = this.getSelected( (values.which == 'all') );
1948         openils.Util.show('acq-lit-generic-progress');
1949
1950         if(values.new_name) {
1951             openils.acq.Picklist.create(
1952                 {name: values.new_name}, 
1953                 function(id) {
1954                     self._updateLiList(id, selected, 0, 
1955                         function(){
1956                             location.href = oilsBasePath + '/eg/acq/picklist/view/' + id;
1957                         });
1958                 }
1959             );
1960         } else if(values.existing_pl) {
1961             // update lineitems to use an existing picklist
1962             self._updateLiList(values.existing_pl, selected, 0, 
1963                 function(){
1964                     location.href = oilsBasePath + '/eg/acq/picklist/view/' + values.existing_pl;
1965                 });
1966         }
1967     }
1968
1969     this._updateLiState = function(values, state) {
1970         var self = this;
1971         var selected = this.getSelected( (values.which == 'all') );
1972         if(!selected.length) return;
1973         dojo.forEach(selected, function(li) {li.state(state);});
1974         self._updateLiList(null, selected, 0, 
1975             // TODO consider inline updates for efficiency
1976             function() { location.href = location.href }
1977         );
1978     }
1979
1980     this._updateLiList = function(pl, list, idx, oncomplete) {
1981         if(idx >= list.length) return oncomplete();
1982         var li = list[idx];
1983         if(pl != null) li.picklist(pl);
1984         litGenericProgress.update({maximum: list.length, progress: idx});
1985         new openils.acq.Lineitem({lineitem:li}).update(
1986             function(r) {
1987                 self._updateLiList(pl, list, ++idx, oncomplete);
1988             }
1989         );
1990     }
1991
1992     this._loadPLSelect = function() {
1993         if(this._plSelectLoaded) return;
1994         var plList = [];
1995         function handleResponse(r) {
1996             plList.push(r.recv().content());
1997         }
1998         var method = 'open-ils.acq.picklist.user.retrieve';
1999         fieldmapper.standardRequest(
2000             ['open-ils.acq', method],
2001             {   async: true,
2002                 params: [this.authtoken],
2003                 onresponse: handleResponse,
2004                 oncomplete: function() {
2005                     self._plSelectLoaded = true;
2006                     acqLitAddExistingSelect.store = 
2007                         new dojo.data.ItemFileReadStore({data:acqpl.toStoreData(plList)});
2008                     acqLitAddExistingSelect.setValue();
2009                 }
2010             }
2011         );
2012     }
2013
2014     this.showRealCopyEditUI = function(li) {
2015         copyList = [];
2016         var self = this;
2017         this.volCache = {};
2018
2019         this._fetchLineitem(li.id(), 
2020             function(fullLi) {
2021                 li = self.liCache[li.id()] = fullLi;
2022
2023                 self.pcrud.search(
2024                     'acp', {
2025                         id : li.lineitem_details().map(
2026                             function(item) { return item.eg_copy_id() }
2027                         )
2028                     }, {
2029                         async : true,
2030                         oncomplete : function(r) {
2031                             try {
2032                                 var r_list = openils.Util.readResponse( r );
2033                                 for (var i = 0; i < r_list.length; i++) {
2034                                     var copy = r_list[i];
2035                                     var volId = copy.call_number();
2036                                     var volume = self.volCache[volId];
2037                                     if(!volume) {
2038                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2039                                     }
2040                                     copy.call_number(volume);
2041                                     copyList.push(copy);
2042                                 }
2043                                 if (xulG) {
2044                                     // If we need to, we can pass in an update_copy function to handle the update instead of volume_item_creator
2045                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2046                                 }
2047                             } catch(E) {
2048                                 alert('error in oncomplete: ' + E);
2049                             }
2050                         }
2051                     }
2052                 );
2053             }
2054         );
2055     }
2056
2057     
2058     /*
2059     this.saveRealCopies = function() {
2060         progressDialog.show(true);
2061         var list = this.realCopyList.filter(function(copy) { return copy.ischanged(); });
2062         this.pcrud.update(list, {oncomplete: function() { 
2063             progressDialog.hide();
2064             self.show('list');
2065         }});
2066     }
2067
2068     // grab the li-details for this lineitem, grab the linked copies and volumes, add them to the table
2069     this.showRealCopies = function(li) {
2070         while(this.realCopiesTbody.childNodes[0])
2071             this.realCopiesTbody.removeChild(this.realCopiesTbody.childNodes[0]);
2072         this.show('real-copies');
2073
2074         this.realCopyList = [];
2075         this.volCache = {};
2076         var tabIndex = 1000;
2077         var self = this;
2078
2079         acqLitSaveRealCopies.onClick = function() {
2080             self.saveRealCopies();
2081         }
2082
2083         this._fetchLineitem(li.id(), 
2084             function(fullLi) {
2085                 li = self.liCache[li.id()] = fullLi;
2086
2087                 self.pcrud.search(
2088                     'acp', {
2089                         id : li.lineitem_details().map(
2090                             function(item) { return item.eg_copy_id() }
2091                         )
2092                     }, {
2093                         async : true,
2094                         streaming : true,
2095                         onresponse : function(r) {
2096                             var copy = openils.Util.readResponse(r);
2097                             var volId = copy.call_number();
2098                             var volume = self.volCache[volId];
2099                             if(!volume) {
2100                                 volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2101                             }
2102                             self.addRealCopy(volume, copy, tabIndex++);
2103                         }
2104                     }
2105                 );
2106             }
2107         );
2108     }
2109
2110     this.addRealCopy = function(volume, copy, tabIndex) {
2111         var row = this.realCopiesRow.cloneNode(true);
2112         this.realCopyList.push(copy);
2113
2114         var selectNode;
2115         dojo.forEach(
2116             ['owning_lib', 'location', 'circ_modifier', 'label', 'barcode'],
2117
2118             function(field) {
2119                 var isvol = (field == 'owning_lib' || field == 'label');
2120                 var widget = new openils.widget.AutoFieldWidget({
2121                     fmField : field,
2122                     fmObject : isvol ? volume : copy,
2123                     parentNode : nodeByName(field, row),
2124                     readOnly : (field != 'barcode'),
2125                 });
2126
2127                 var widgetDrawn = null;
2128
2129                 if(field == 'barcode') {
2130
2131                     widgetDrawn = function(w, ww) {
2132                         var node = w.domNode;
2133                         node.setAttribute('tabindex', ''+tabIndex);
2134
2135                         // on enter, select the next barcode input
2136                         dojo.connect(w, 'onKeyDown',
2137                             function(e) {
2138                                 if(e.keyCode == dojo.keys.ENTER) {
2139                                     var ti = node.getAttribute('tabindex');
2140                                     var nextNode = dojo.query('[tabindex=' + String(Number(ti) + 1) + ']', self.realCopiesTbody)[0];
2141                                     if(nextNode) nextNode.select();
2142                                 }
2143                             }
2144                         );
2145
2146                         dojo.connect(w, 'onChange', 
2147                             function(val) { 
2148                                 if(!val || val == copy.barcode()) return;
2149                                 copy.ischanged(true);
2150                                 copy.barcode(val);
2151                             }
2152                         );
2153
2154
2155                         if(self.realCopiesTbody.getElementsByTagName('TR').length == 0)
2156                             selectNode = node;
2157                     }
2158                 }
2159
2160                 widget.build(widgetDrawn);
2161             }
2162         );
2163
2164         this.realCopiesTbody.appendChild(row);
2165         if(selectNode) selectNode.select();
2166     };
2167     */
2168
2169 }