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