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