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