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