]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
ACQ : Lineitem recovers focus after actions
[working/Evergreen.git] / Open-ILS / web / js / ui / default / acq / common / li_table.js
1 dojo.require('dojo.date.locale');
2 dojo.require('dojo.date.stamp');
3 dojo.require('dijit.form.Button');
4 dojo.require('dijit.form.TextBox');
5 dojo.require('dijit.form.FilteringSelect');
6 dojo.require('dijit.form.Textarea');
7 dojo.require('dijit.Tooltip');
8 dojo.require('dijit.ProgressBar');
9 dojo.require('openils.acq.Lineitem');
10 dojo.require('openils.acq.PO');
11 dojo.require('openils.acq.Picklist');
12 dojo.require('openils.widget.AutoFieldWidget');
13 dojo.require('dojo.data.ItemFileReadStore');
14 dojo.require('openils.widget.ProgressDialog');
15 dojo.require('openils.PermaCrud');
16 dojo.require("openils.widget.PCrudAutocompleteBox");
17 dojo.require('openils.CGI');
18
19 if (!localeStrings) {   /* we can do this because javascript doesn't have block scope */
20     dojo.requireLocalization('openils.acq', 'acq');
21     var localeStrings = dojo.i18n.getLocalization('openils.acq', 'acq');
22 }
23 const XUL_OPAC_WRAPPER = 'chrome://open_ils_staff_client/content/cat/opac.xul';
24 var li_exportable_attrs = ["issn", "isbn", "upc"];
25
26 var fundLabelFormat = [
27     '<span class="fund_${0}">${1} (${2})</span>', 'id', 'code', 'year'
28 ];
29 var fundSearchFormat = ['${0} (${1})', 'code', 'year'];
30
31 function nodeByName(name, context) {
32     return dojo.query('[name='+name+']', context)[0];
33 }
34
35 // for caching linked users.  e.g. lineitem_detail.receiver
36 var userCache = {};
37
38 var liDetailBatchFields = ['fund', 'owning_lib', 'location', 'collection_code', 'circ_modifier', 'cn_label'];
39 var liDetailFields = liDetailBatchFields.concat(['barcode', 'note']);
40 var fundStyles = {
41     "stop": "color: #c00; font-weight: bold;",
42     "warning": "color: #c93;"
43 };
44
45 function AcqLiTable() {
46
47     var self = this;
48     this.liCache = {};
49     this.plCache = {};
50     this.poCache = {};
51     this.relCache = {};
52     this.haveFundClass = {}
53     this.fundBalanceState = {};
54     this.realDfaCache = {};
55     this.virtDfaCounts = {};
56     this.virtDfaId = -1;
57     this.dfeOffset = 0;
58     this.claimEligibleLidByLi = {};
59     this.claimEligibleLid = {};
60     this.toggleState = false;
61     this.tbody = dojo.byId('acq-lit-tbody');
62     this.selectors = [];
63     this.noteAcks = {};
64     this.authtoken = openils.User.authtoken;
65     this.pcrud = new openils.PermaCrud();
66     this.rowTemplate = this.tbody.removeChild(dojo.byId('acq-lit-row'));
67     this.copyTbody = dojo.byId('acq-lit-li-details-tbody');
68     this.copyRow = this.copyTbody.removeChild(dojo.byId('acq-lit-li-details-row'));
69     this.copyBatchRow = dojo.byId('acq-lit-li-details-batch-row');
70     this.copyBatchWidgets = {};
71     this.liNotesTbody = dojo.byId('acq-lit-notes-tbody');
72     this.liNotesRow = this.liNotesTbody.removeChild(dojo.byId('acq-lit-notes-row'));
73     this.realCopiesTbody = dojo.byId('acq-lit-real-copies-tbody');
74     this.realCopiesRow = this.realCopiesTbody.removeChild(dojo.byId('acq-lit-real-copies-row'));
75     this._copy_fields_for_acqdf = ['owning_lib', 'location'];
76     this.skipInitialEligibilityCheck = false;
77     this.claimDialog = new ClaimDialogManager(
78         liClaimDialog, finalClaimDialog, this.claimEligibleLidByLi,
79         function(li) {    /* callback that fires when claims are made */
80             self.fetchClaimInfo(li.id(), /* force update */ true);
81         }
82     );
83     this.vlAgent = new VLAgent();
84
85     this.focusLineitem = new openils.CGI().param('focus_li');
86
87     dojo.byId("acq-lit-li-actions-selector").onchange = function() { 
88         self.applySelectedLiAction(this.options[this.selectedIndex].value);
89         this.selectedIndex = 0;
90     };
91
92     acqLitCreatePoSubmit.onClick = function() {
93         if (!self.createPoProviderSelector.attr("value") ||
94                 !self.createPoAgencySelector.attr("value")) {
95             alert(localeStrings.CREATE_PO_INVALID);
96             return false;
97         } else if (self._confirmPoPrepaySituation()) {
98             acqLitPoCreateDialog.hide();
99             self._createPO(acqLitPoCreateDialog.getValues());
100         } else {
101             return false;
102         }
103     }
104
105     acqLitSavePlButton.onClick = function() {
106         acqLitSavePlDialog.hide();
107         self._savePl(acqLitSavePlDialog.getValues());
108     }
109
110     acqLitCancelLiStateButton.onClick = function() {
111         acqLitChangeLiStateDialog.hide();
112     }
113     acqLitSaveLiStateButton.onClick = function() {
114         acqLitChangeLiStateDialog.hide();
115         self._updateLiState(acqLitChangeLiStateDialog.getValues(), acqLitChangeLiStateDialog.attr('state'));
116     }
117
118
119     dojo.byId('acq-lit-select-toggle').onclick = function(){self.toggleSelect()};
120     dojo.byId('acq-lit-info-back-button').onclick = function(){self.show('list')};
121     dojo.byId('acq-lit-copies-back-button').onclick = function(){self.show('list')};
122     dojo.byId('acq-lit-notes-back-button').onclick = function(){self.show('list')};
123     dojo.byId('acq-lit-real-copies-back-button').onclick = function(){self.show('list')};
124
125     this.reset = function(keep_selectors) {
126         while(self.tbody.childNodes[0])
127             self.tbody.removeChild(self.tbody.childNodes[0]);
128         self.noteAcks = {};
129         self.relCache = {};
130
131         if (!keep_selectors)
132             self.selectors = [];
133     };
134     
135     this.setNext = function(handler) {
136         var link = dojo.byId('acq-lit-next');
137         if(handler) {
138             dojo.style(link, 'visibility', 'visible');
139             link.onclick = handler;
140         } else {
141             dojo.style(link, 'visibility', 'hidden');
142         }
143     };
144
145     this.setPrev = function(handler) {
146         var link = dojo.byId('acq-lit-prev');
147         if(handler) {
148             dojo.style(link, 'visibility', 'visible'); 
149             link.onclick = handler; 
150         } else {
151             dojo.style(link, 'visibility', 'hidden');
152         }
153     };
154
155     /*
156      * Ensures this.focusLineitem is in view and causes a brief 
157      * border around the lineitem to come to life then fade.
158      */
159     this.focusLi = function() {
160         if (!this.focusLineitem) return;
161
162         // set during addLineitem()
163         var node = dojo.byId('li-title-ref-' + this.focusLineitem);
164
165         // LI may not yet be rendered
166         if (!node) return; 
167
168         // prevent numerous re-focuses
169         this.focusLineitem = null; 
170         
171         // causes the full row to be visible
172         dijit.scrollIntoView(node);
173
174         // may as well..
175         dojo.query('[attr=title]', node)[0].focus();
176
177         dojo.require('dojox.fx');
178
179         setTimeout(
180             function() {
181                 dojox.fx.highlight({color : '#BB4433', node : node, duration : 2000}).play();
182             }, 
183         100);
184     };
185
186     this.show = function(div) {
187         openils.Util.hide('acq-lit-table-div');
188         openils.Util.hide('acq-lit-info-div');
189         openils.Util.hide('acq-lit-li-details');
190         openils.Util.hide('acq-lit-notes-div');
191         openils.Util.hide('acq-lit-real-copies-div');
192         openils.Util.hide('acq-lit-asset-creator');
193         switch(div) {
194             case 'list':
195                 openils.Util.show('acq-lit-table-div');
196                 this.focusLi();
197                 break;
198             case 'info':
199                 openils.Util.show('acq-lit-info-div');
200                 break;
201             case 'copies':
202                 openils.Util.show('acq-lit-li-details');
203                 break;
204             case 'real-copies':
205                 openils.Util.show('acq-lit-real-copies-div');
206                 break;
207             case 'notes':
208                 openils.Util.show('acq-lit-notes-div');
209                 break;
210             case 'asset-creator':
211                 openils.Util.show('acq-lit-asset-creator');
212                 break;
213             default:
214                 if(div) 
215                     openils.Util.show(div);
216         }
217     }
218
219     this.hide = function() {
220         this.show(null);
221     }
222
223     this.toggleSelect = function() {
224         if(self.toggleState) 
225             dojo.forEach(self.selectors, function(i){i.checked = false});
226         else 
227             dojo.forEach(self.selectors, function(i){i.checked = true});
228         self.toggleState = !self.toggleState;
229     };
230
231
232     this.getAll = function(callback, id_only) {
233         /* For some uses of the li table, we may not really know about "all"
234          * the lineitems that the user thinks we know about. If we're a paged
235          * picklist, for example, we only know about the lineitems we've
236          * displayed, but not necessarily all the lineitems on the picklist.
237          * So we reach out to pcrud to inform us.
238          */
239
240         var oncomplete = function(r) {
241             var id_list = openils.Util.readResponse(r);
242             if (id_only)
243                 callback(id_list);
244             else
245                 self.fetchLineitemsById(id_list, callback);
246         };
247
248         if (this.isPL) {
249             this.pcrud.search(
250                 "jub", {"picklist": this.isPL}, {
251                     "id_list": true,    /* sic, even if id_only */
252                     "async": true,
253                     "oncomplete": oncomplete
254                 }
255             );
256             return;
257         } else if (this.isPO) {
258             this.pcrud.search(
259                 "jub", {"purchase_order": this.isPO}, {
260                     "id_list": true,
261                     "async": true,
262                     "oncomplete": oncomplete
263                 }
264             );
265             return;
266         } else if (this.isUni && this.pager) {
267             this.pager.getAllLineitemIDs(oncomplete);
268             return;
269         }
270
271         /* If execution reaches this point, we don't need or can't perform
272          * any special tricks to find out the "real" list of "all" lineitems
273          * in this context, so we fall back to the old method.
274          */
275         callback(this.getSelected(true, null, id_only));
276     };
277
278     /** @param all If true, assume all are selected */
279     this.getSelected = function(
280         all,
281         callback /* If you want a "good" idea of "all" lineitems, you must
282         provide a callback that accepts an array parameter, rather than
283         relying on the return value of this method itself. */,
284         id_only
285     ) {
286         if (all && callback)
287             return this.getAll(callback, id_only);
288
289         var indices = {};   /* use to uniqify. needed in paging situations. */
290         dojo.forEach(this.selectors,
291             function(i) { 
292                 if(i.checked || all)
293                     indices[i.parentNode.parentNode.getAttribute('li')] = true;
294             }
295         );
296
297         var result = openils.Util.objectProperties(indices);
298
299         if (!id_only)
300             result = result.map(function(liId) { return self.liCache[liId]; });
301
302         if (callback)
303             callback(result);
304         else
305             return result;
306     };
307
308     this.setRowAttr = function(td, liWrapper, field, type) {
309         var val = liWrapper.findAttr(field, type || 'lineitem_marc_attr_definition') || '';
310         td.appendChild(document.createTextNode(val));
311     };
312
313     this.setClaimPolicyControl = function(li, row) {
314         if (!self.claimPolicyPicker) {
315             self.claimPolicyPicker = true; /* prevents a race condition */
316             new openils.widget.AutoFieldWidget({
317                 "parentNode": "acq-lit-li-claim-policy",
318                 "fmClass": "acqclp",
319                 "selfReference": true,
320                 "dijitArgs": {"required": true}
321             }).build(function(w) { self.claimPolicyPicker = w; });
322         }
323
324         if (!row) row = this._findLiRow(li);
325
326         var actViewPolicy = nodeByName("action_view_claim_policy", row);
327         if (li.claim_policy())
328             actViewPolicy.innerHTML = localeStrings.CHANGE_CLAIM_POLICY;
329
330         if (!actViewPolicy.onclick) {
331             actViewPolicy.onclick = function() {
332                 if (li.claim_policy())
333                     self.claimPolicyPicker.attr("value", li.claim_policy());
334                 liClaimPolicyDialog.show();
335                 liClaimPolicySave.onClick = function() {
336                     self.changeClaimPolicy(
337                         [li], self.claimPolicyPicker.attr("value"),
338                         function() {
339                             self.setClaimPolicyControl(li, row);
340                             self.reconsiderClaimControl(li, row);
341                             liClaimPolicyDialog.hide();
342                         }
343                     );
344                 }
345             };
346         }
347     };
348
349     this.fetchClaimInfo = function(liId, force, callback, row) {
350         this._fetchLineitem(
351             liId, function(full) {
352                 self.liCache[full.id()] = full;
353                 self.checkClaimEligibility(full, callback, row);
354             }, force
355         );
356     }
357
358     /**
359      * Inserts a single lineitem into the growing table of lineitems
360      * @param {Object} li The lineitem object to insert
361      */
362     this.addLineitem = function(li, skip_final_placement) {
363         this.liCache[li.id()] = li;
364
365         // insert the row right away so that final order isn't
366         // dependent on how long subsequent async request take
367         // for a given line item
368         var row = self.rowTemplate.cloneNode(true);
369         if (!skip_final_placement) {
370             self.tbody.appendChild(row);
371         }
372         self.selectors.push(dojo.query('[name=selectbox]', row)[0]);
373
374         // sort the lineitem notes on edit_time
375         if(!li.lineitem_notes()) li.lineitem_notes([]);
376
377         var liWrapper = new openils.acq.Lineitem({lineitem:li});
378         row.setAttribute('li', li.id());
379         var tds = dojo.query('[attr]', row);
380         dojo.forEach(tds, function(td) {self.setRowAttr(td, liWrapper, td.getAttribute('attr'), td.getAttribute('attr_type'));});
381         dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
382
383         // so we can scroll to it later
384         dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
385
386         var identifier =
387             liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
388             liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
389
390         // XXX media prefix for added content
391         if (identifier) {
392             nodeByName("jacket", row).setAttribute(
393                 "src", "/opac/extras/ac/jacket/small/" + identifier
394             );
395         }
396
397         nodeByName("liid", row).innerHTML += li.id();
398
399         if(li.eg_bib_id()) {
400             openils.Util.show(nodeByName('catalog', row), 'inline');
401             nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
402         } else {
403             openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
404             nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
405         }
406
407         if (li.queued_record()) {
408             this.pcrud.retrieve('vqbr', li.queued_record(),
409                 {   async : true, 
410                     oncomplete : function(r) {
411                         var qrec = openils.Util.readResponse(r);
412                         openils.Util.show(nodeByName('queue', row), 'inline');
413                         var link = nodeByName("queue_link", row);
414                         link.onclick = function() { 
415                             // open a new tab to the vandelay queue for this record
416                             openils.XUL.newTabEasy(
417                                 oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
418                             );
419                         }
420                     }
421                 }
422             );
423         }
424
425         nodeByName("worksheet_link", row).href =
426             oilsBasePath + "/acq/lineitem/worksheet/" + li.id();
427
428         nodeByName("show_requests_link", row).href =
429             oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id();
430
431         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
432         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
433         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
434
435         if (!this.skipInitialEligibilityCheck)
436             this.fetchClaimInfo(
437                 li.id(),
438                 false,
439                 function(full) { self.setClaimPolicyControl(full, row) },
440                 row
441             );
442
443         this.updateLiNotesCount(li, row);
444
445         // show which PO this lineitem is a member of
446         if(li.purchase_order() && !this.isPO) {
447             var po = 
448                 this.poCache[li.purchase_order()] =
449                 this.poCache[li.purchase_order()] ||
450                 fieldmapper.standardRequest(
451                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
452                     {params: [
453                         this.authtoken, li.purchase_order(), {
454                             "flesh_price_summary": true,
455                             "flesh_provider" : true,
456                             "flesh_lineitem_count": true
457                         }
458                     ]});
459             if(po && !this.isMeta) {
460                 openils.Util.show(nodeByName('po', row), 'inline');
461                 var link = nodeByName('po_link', row);
462                 link.setAttribute('href', oilsBasePath + '/acq/po/view/' + li.purchase_order());
463                 link.innerHTML += po.name();
464
465                 openils.Util.show(nodeByName('pro', row), 'inline');
466                 link = nodeByName('pro_link', row);
467                 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
468                 link.innerHTML += po.provider().code();
469             }
470         }
471
472         // show which picklist this lineitem is a member of
473         if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
474             var pl = 
475                 this.plCache[li.picklist()] = 
476                 this.plCache[li.picklist()] || 
477                 fieldmapper.standardRequest(
478                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
479                     {params: [this.authtoken, li.picklist()]});
480             if (pl) {
481                 if (pl.name() == "") {
482                     openils.Util.show(nodeByName("bib_origin", row), "inline");
483
484                 } else {
485
486                     openils.Util.show(nodeByName('pl', row), 'inline');
487                     var link = nodeByName('pl_link', row);
488                     link.setAttribute('href', oilsBasePath + '/acq/picklist/view/' + li.picklist());
489                     link.innerHTML += pl.name();
490                 }
491             }
492         }
493
494         var countNode = nodeByName('count', row);
495         var count = li.item_count() || 0;
496         if (typeof(this._copy_count_cb) == "function") {
497             this._copy_count_cb(li.id(), count);
498         }
499         countNode.innerHTML = count;
500         countNode.id = 'acq-lit-copy-count-label-' + li.id();
501
502         // lineitem price
503         var priceInput = dojo.query('[name=price]', row)[0];
504         priceInput.value = li.estimated_unit_price() || '';
505         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
506
507         // show either "mark received" or "unreceive" as appropriate
508         this.updateLiState(li, row);
509
510         if (skip_final_placement) {
511             return row;
512         }
513
514         // the last LI may be rendered after the call to show('list'),
515         // so make sure it's focused if necessary.
516         if (this.focusLineitem == li.id())
517             this.focusLi();
518     };
519
520     this._liCountClaims = function(li) {
521         var total = 0;
522         for (var i = 0; i < li.lineitem_details().length; i++)
523             total += li.lineitem_details()[i].claims().length;
524         return total;
525     };
526
527     this._findLiRow = function(li) {
528         return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
529     };
530
531     this.reconsiderClaimControl = function(li, row) {
532         if (!row) row = this._findLiRow(li);
533         var option = nodeByName("action_manage_claims", row);
534         var eligible = this.claimEligibleLidByLi[li.id()].length;
535         var count = this._liCountClaims(li);
536
537         option.disabled = !(count || eligible);
538         option.innerHTML =
539             dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
540         option.onclick = function() { self.claimDialog.show(li); };
541     };
542
543     this.clearEligibility = function(li) {
544         this.claimEligibleLidByLi[li.id()] = [];
545
546         if (li.lineitem_details()) {
547             li.lineitem_details().forEach(
548                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
549             );
550         }
551
552         if (this.copyCache) {
553             var to_del = [];
554             for (var k in this.copyCache) {
555                 if (this.copyCache[k].lineitem() == li.id())
556                     to_del.push(k);
557             }
558             to_del.forEach(
559                 function(k) { delete self.claimEligibleLid[k]; }
560             );
561         }
562     };
563
564     this.checkClaimEligibility = function(li, callback, row) {
565         /* Assume always eligible, i.e. from this interface we don't care about
566          * claim eligibility any more. this is where the user would force a
567          * claime. */
568         this.clearEligibility(li);
569         this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
570             function(lid) { return lid.id(); }
571         );
572         li.lineitem_details().forEach(
573             function(lid) { self.claimEligibleLid[lid.id()] = true; }
574         );
575         this.reconsiderClaimControl(li, row);
576         if (callback) callback(li);
577         /*
578         this.clearEligibility(li);
579         fieldmapper.standardRequest(
580             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
581                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
582                 "async": true,
583                 "onresponse": function(r) {
584                     if (r = openils.Util.readResponse(r)) {
585                         self.claimEligibleLidByLi[li.id()].push(
586                             r.lineitem_detail()
587                         );
588                         self.claimEligibleLid[r.lineitem_detail()] = true;
589                     }
590                 },
591                 "oncomplete": function() {
592                     self.reconsiderClaimControl(li, row);
593                     if (typeof(callback) == "function")
594                         callback();
595                 }
596             }
597         );
598         */
599     };
600
601     this.updateLiNotesCount = function(li, row) {
602         if (!row) row = this._findLiRow(li);
603
604         var has_notes = (li.lineitem_notes().filter(
605                 function(o) { return Boolean (o.alert_text()); }
606             ).length > 0);
607
608         /* U+2691 is the code point for a filled-in flag character */
609         nodeByName("notes_alert_flag", row).innerHTML =
610              has_notes ? "&#x2691;" : "";
611         nodeByName("noteslink", row).style.fontStyle =
612             has_notes ? "italic" : "normal";
613         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
614     };
615
616     /* XXX NOT related to _updateLiState(). rethink */
617     this.updateLiState = function(li, row) {
618         if (!row) row = this._findLiRow(li);
619
620         var actReceive = nodeByName("action_mark_recv", row);
621         var actUnRecv = nodeByName("action_mark_unrecv", row);
622         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
623         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
624         var actNewInvoice = nodeByName('action_new_invoice', row);
625         var actLinkInvoice = nodeByName('action_link_invoice', row);
626         var actViewInvoice = nodeByName('action_view_invoice', row);
627
628         // always allow access to LI history
629         nodeByName('action_view_history', row).onclick = 
630             function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
631
632         /* handle row coloring for based on LI state */
633         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
634         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
635
636         // Expose invoice actions for any lineitem that is linked to a PO 
637         if( li.purchase_order() ) {
638
639             actNewInvoice.disabled = false;
640             actLinkInvoice.disabled = false;
641             actViewInvoice.disabled = false;
642
643             actNewInvoice.onclick = function() {
644                 location.href = oilsBasePath + '/acq/invoice/view?create=1&attach_li=' + li.id();
645                 nodeByName("action_none", row).selected = true;
646             };
647
648             actLinkInvoice.onclick = function() {
649                 if (!self.invoiceLinkDialogManager) {
650                     self.invoiceLinkDialogManager =
651                         new InvoiceLinkDialogManager("li");
652                 }
653                 self.invoiceLinkDialogManager.target = li;
654                 acqLitLinkInvoiceDialog.show();
655                 nodeByName("action_none", row).selected = true;
656             };
657
658             actViewInvoice.onclick = function() {
659                 location.href = oilsBasePath +
660                     "/acq/search/unified?so=" +
661                     base64Encode({"jub":[{"id": li.id()}]}) +
662                     "&rt=invoice";
663                 nodeByName("action_none", row).selected = true;
664             };
665         }
666                 
667
668         /*
669          * If we haven't fleshed the lineitem_details, default to allowing access to the 
670          * holdings maintenence actions.  The alternative is to flesh LIDs on every lineitem, 
671          * but that will add to page render time.  Let's see if this will suffice...
672          */
673         var lids = li.lineitem_details();
674         if( !lids || 
675                 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
676
677             actUpdateBarcodes.disabled = false;
678             actUpdateBarcodes.onclick = function() {
679                 self.showRealCopyEditUI(li);
680                 nodeByName("action_none", row).selected = true;
681             }
682             actHoldingsMaint.disabled = false;
683             actHoldingsMaint.onclick = 
684                 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
685         }
686
687         var state_cell = nodeByName("li_state", row);
688
689         switch(li.state()) {
690
691             case 'cancelled':
692                 if(typeof li.cancel_reason() == "object") {
693                     var holds_state = dojo.create(
694                         "span", {
695                             "style": "border-bottom: 1px dashed #000;",
696                             "innerHTML": li.state()
697                         }, state_cell, "only"
698                     );
699                     new dijit.Tooltip(
700                         {
701                             "label": "<em>" + li.cancel_reason().label() +
702                                 "</em><br />" + li.cancel_reason().description(),
703                             "connectId": [holds_state]
704                         }, dojo.create("span", null, state_cell, "last")
705                     );
706                 }
707                 return; // all done
708
709             case "on-order":
710                 actReceive.disabled = false;
711                 actReceive.onclick = function() {
712                     if (self.checkLiAlerts(li.id()))
713                         self.issueReceive(li);
714                     nodeByName("action_none", row).selected = true;
715                 };
716                 break;
717
718             case "received":
719                 actUnRecv.disabled = false;
720                 actUnRecv.onclick = function() {
721                     if (confirm(localeStrings.UNRECEIVE_LI))
722                         self.issueReceive(li, /* rollback */ true);
723                     nodeByName("action_none", row).selected = true;
724                 };
725                 break;
726         }
727
728         state_cell.innerHTML = li.state(); // TODO i18n state labels
729     };
730
731
732     this._setAlertStore = function() {
733         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
734             {
735                 "data": acqliat.toStoreData(
736                     this.pcrud.search(
737                         "acqliat", {
738                             "owning_lib": aou.orgNodeTrail(
739                                 aou.findOrgUnit(openils.User.user.ws_ou())
740                             ).map(function(o) { return o.id(); })
741                         }
742                     )
743                 )
744             }
745         );
746         acqLitAlertAlertText.setValue(); /* make the store "live" */
747         acqLitAlertAlertText._store_ready = true;
748     };
749
750     /**
751      * Draws and shows the lineitem notes pane
752      */
753     this.drawLiNotes = function(li) {
754         var self = this;
755         this.focusLineitem = li.id();
756
757         if (!acqLitAlertAlertText._store_ready)
758             this._setAlertStore();
759
760         li.lineitem_notes(
761             li.lineitem_notes().sort(
762                 function(a, b) { 
763                     if(a.edit_time() < b.edit_time()) return 1;
764                     return -1;
765                 }
766             )
767         );
768
769         while(this.liNotesTbody.childNodes[0])
770             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
771         this.show('notes');
772
773         acqLitCreateNoteSubmit.onClick = function() {
774             var value = acqLitCreateNoteText.attr('value');
775             if(!value) return;
776             var note = new fieldmapper.acqlin();
777             note.isnew(true);
778             note.vendor_public(
779                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
780             );
781             note.value(value);
782             note.lineitem(li.id());
783
784             self.updateLiNotes(li, note);
785             acqLitCreateNoteVendorPublic.attr("checked", false);
786             acqLitCreateNoteText.attr("value", "");
787         }
788
789         acqLitCreateAlertSubmit.onClick = function() {
790             if (!acqLitAlertAlertText.item) {
791                 alert(localeStrings.ALERT_UNSELECTED);
792                 return;
793             }
794
795             var alert_text = new fieldmapper.acqliat().fromStoreItem(
796                 acqLitAlertAlertText.item
797             );
798             var value = acqLitAlertNoteValue.attr("value") || "";
799
800             var note = new fieldmapper.acqlin();
801             note.isnew(true);
802             note.lineitem(li.id());
803             note.value(value);
804             note.alert_text(alert_text);
805
806             self.updateLiNotes(li, note);
807         }
808
809         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
810     }
811
812     /**
813      * Draws a single lineitem note in the notes pane
814      */
815     this.addLiNote = function(li, note) {
816         if(note.isdeleted()) return;
817         var self = this;
818         var row = self.liNotesRow.cloneNode(true);
819         nodeByName("value", row).innerHTML = note.value();
820         var alert_node = nodeByName("alert_code", row);
821         if (note.alert_text()) {
822             alert_node.innerHTML = dojo.string.substitute(
823                 "[${0}] ${1}", [
824                     aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
825                     note.alert_text().code()
826                 ]
827             );
828             if (note.alert_text().description()) {
829                 new dijit.Tooltip(
830                     {
831                         "connectId": [alert_node],
832                         "label": note.alert_text().description()
833                     }, dojo.create("span", null, alert_node, "after")
834                 );
835             }
836         }
837
838         if (openils.Util.isTrue(note.vendor_public()))
839             nodeByName("vendor_public", row).innerHTML =
840                 localeStrings.VENDOR_PUBLIC;
841
842         nodeByName("delete", row).onclick = function() {
843             note.isdeleted(true);
844             self.liNotesTbody.removeChild(row);
845             self.updateLiNotes(li);
846         };
847
848         if(note.edit_time()) {
849             nodeByName("edit_time", row).innerHTML =
850                 dojo.date.locale.format(
851                     dojo.date.stamp.fromISOString(note.edit_time()), 
852                     {formatLength:'short'});
853         }
854
855         self.liNotesTbody.appendChild(row);
856     }
857
858     /**
859      * Updates any new/changed/deleted notes on the server
860      */
861     this.updateLiNotes = function(li, newNote) {
862
863         var notes;
864         if(newNote) {
865             notes = [newNote];
866         } else {
867             notes = li.lineitem_notes().filter(
868                 function(note) {
869                     if(note.ischanged() || note.isnew() || note.isdeleted())
870                         return note;
871                 }
872             );
873         }
874
875         if(notes.length == 0) return;
876         progressDialog.show();
877
878         fieldmapper.standardRequest(
879             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
880             {   async : true,
881                 params : [this.authtoken, notes],
882                 onresponse : function(r) {
883                     var resp = openils.Util.readResponse(r);
884
885                     if(resp.complete) {
886
887                         if(!newNote) {
888                             // remove the old changed notes
889                             var list = [];
890                             dojo.forEach(li.lineitem_notes(), 
891                                 function(note) {
892                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
893                                         list.push(note);
894                                 }
895                             );
896                             li.lineitem_notes(list);
897                         }
898
899                         progressDialog.hide();
900                         self.updateLiNotesCount(li);
901                         self.drawLiNotes(li);
902                         return;
903                     }
904
905                     progressDialog.update(resp);
906                     var newnote = resp.note;
907
908                     if(!newnote.isdeleted()) {
909                         newnote.isnew(false);
910                         newnote.ischanged(false);
911                         li.lineitem_notes().push(newnote);
912                     }
913                 },
914             }
915         );
916     }
917
918     this.updateLiPrice = function(input, li) {
919         var self = this;
920         var price = input.value;
921         if(Number(price) == Number(li.estimated_unit_price())) return;
922
923         fieldmapper.standardRequest(
924             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
925             {   async : false, // redundant w/ timeout
926                 timeout : 10,
927                 params : [this.authtoken, li.id(), price],
928                 oncomplete : function(r) {
929                     openils.Util.readResponse(r);
930                     li.estimated_unit_price(price); // update local copy
931
932                     /*
933                      * If this is a PO and every visible lineitem has a price,
934                      * check again to see if this PO can be activated.  Note that 
935                      * every visible lineitem having a price does not guarantee it can
936                      * be activated, which is why we still make the call.  Having a price
937                      * set for every visiable lineitem is just the lowest barrier to entry.
938                      */
939                     if (self.isPO) {
940                         var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
941                         var allSet = true;
942                         dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
943                         if (allSet) checkCouldActivatePo();
944                     }
945                 }
946             }
947         );
948     }
949
950     this.removeLineitem = function(liId) {
951         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
952         delete this.liCache[liId];
953         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
954     }
955
956     this.drawInfo = function(liId) {
957         this.focusLineitem = liId;
958         if (!this._isRelatedViewer) {
959             var d = dojo.byId("acq-lit-info-related");
960             if (!this.relCache[liId]) {
961                 fieldmapper.standardRequest(
962                     [
963                         "open-ils.acq",
964                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
965                     ], {
966                         "async": true,
967                         "params": [openils.User.authtoken, liId],
968                         "onresponse": function(r) {
969                             self.relCache[liId] = openils.Util.readResponse(r);
970                             nodeByName("related_number", d).innerHTML =
971                                 self.relCache[liId];
972                             openils.Util[
973                                 self.relCache[liId] >1 ? "show" : "hide"
974                             ](d);
975                         }
976                     }
977                 );
978             } else {
979                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
980                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
981             }
982         }
983
984         this.show('info');
985         openils.acq.Lineitem.fetchAttrDefs(
986             function() { 
987                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
988             } 
989         );
990     };
991
992     /* For a given list of lineitem ids, build a list of full lineitems
993      * re-using the fetching logic that is otherwise typical to use in this
994      * module.
995      *
996      * If we've already got a lineitem in the cache, just use that.
997      *
998      * Once we've built a list of lineitems, call callback(thatlist).
999      */
1000     this.fetchLineitemsById = function(id_list, callback) {
1001         var total = id_list.length;
1002         var result_list = [];
1003
1004         var inner = function(li) {
1005             result_list.push(li)
1006             if (--total <= 0)
1007                 callback(result_list);
1008         };
1009
1010         id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1011     };
1012
1013     this._fetchLineitem = function(liId, handler, force) {
1014
1015         var li = this.liCache[liId];
1016         if(li && li.marc() && li.lineitem_details() && !force)
1017             return handler(li);
1018         
1019         fieldmapper.standardRequest(
1020             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1021             {   async: true,
1022
1023                 params: [self.authtoken, liId, {
1024                     flesh_attrs: true,
1025                     flesh_cancel_reason: true,
1026                     flesh_li_details: true,
1027                     flesh_notes: true,
1028                     flesh_fund_debit: true }],
1029
1030                 oncomplete: function(r) {
1031                     var li = openils.Util.readResponse(r);
1032                     self.liCache[liId] = li;
1033                     handler(li)
1034                 }
1035             }
1036         );
1037     };
1038
1039     this._drawInfo = function(li) {
1040
1041         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1042
1043         if(li.eg_bib_id()) {
1044             openils.Util.hide('acq-lit-marc-order-record-label');
1045             openils.Util.hide(acqLitEditOrderMarc.domNode);
1046             openils.Util.show('acq-lit-marc-real-record-label');
1047         } else {
1048             openils.Util.show('acq-lit-marc-order-record-label');
1049             openils.Util.show(acqLitEditOrderMarc.domNode);
1050             openils.Util.hide('acq-lit-marc-real-record-label');
1051         }
1052
1053         this.drawMarcHTML(li);
1054         this.infoTbody = dojo.byId('acq-lit-info-tbody');
1055
1056         if(!this.infoRow)
1057             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1058         while(this.infoTbody.childNodes[0])
1059             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1060
1061         for(var i = 0; i < li.attributes().length; i++) {
1062             var attr = li.attributes()[i];
1063             var row = this.infoRow.cloneNode(true);
1064
1065             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1066             var name = openils.acq.Lineitem.attrDefs[type].filter(
1067                 function(a) {
1068                     return (a.code() == attr.attr_name());
1069                 }
1070             ).pop().description();
1071
1072             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1073             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1074             this.infoTbody.appendChild(row);
1075         }
1076
1077         if (!this._isRelatedViewer) {
1078             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1079                 oilsBasePath + "/acq/lineitem/related/" + li.id();
1080         }
1081
1082     };
1083
1084     this.generateMakeRecTab = function(bib_id,default_view, row) {
1085         return function() {
1086             xulG.new_tab(
1087                 XUL_OPAC_WRAPPER,
1088                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1089                 {
1090                     no_xulG : false, 
1091                     show_nav_buttons : true, 
1092                     show_print_button : true, 
1093                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + bib_id),
1094                     default_view : default_view
1095                 }
1096             );
1097
1098             if(row) nodeByName("action_none", row).selected = true;
1099         }
1100     };
1101
1102     this.drawMarcHTML = function(li) {
1103         var params = [null, true, li.marc()];
1104         if(li.eg_bib_id()) 
1105             params = [li.eg_bib_id(), true];
1106
1107         fieldmapper.standardRequest(
1108             ['open-ils.search', 'open-ils.search.biblio.record.html'],
1109             {   async: true,
1110                 params: params,
1111                 oncomplete: function(r) {
1112                     dojo.byId('acq-lit-marc-div').innerHTML = 
1113                         openils.Util.readResponse(r);
1114                 }
1115             }
1116         );
1117     }
1118
1119     this.drawCopies = function(liId, force_fetch) {
1120         this.focusLineitem = liId;
1121         if (typeof force_fetch == "undefined")
1122             force_fetch = false;
1123
1124         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1125             function(li, html) {
1126                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1127             }
1128         );
1129
1130         this.show('copies');
1131         var self = this;
1132         this.copyCache = {};
1133         this.copyWidgetCache = {};
1134         this.oldCopyWidgetCache = {};
1135         this.virtDfaCounts = {};
1136         this.realDfaCache = {};
1137         this.dfeOffset = 0;
1138
1139         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1140         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1141         acqLitCopyCountInput.attr('value', '0');
1142
1143         while(this.copyTbody.childNodes[0])
1144             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1145
1146         this._drawBatchCopyWidgets();
1147
1148         this._drawDistribApplied(liId);
1149
1150         this._fetchDistribFormulas(
1151             function() {
1152                 openils.acq.Lineitem.fetchAttrDefs(
1153                     function() { 
1154                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1155                     } 
1156                 );
1157             }
1158         );
1159     };
1160
1161     this._saveDistribAppliedTemplates = function() {
1162         if (!this._appliedDistribTemplate) {
1163             this._appliedDistribTemplate =
1164                 dojo.byId("acq-lit-distrib-applied-tbody").
1165                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1166             dojo.attr(this._appliedDistribTemplate, "id");
1167         }
1168     };
1169
1170     this._drawDistribApplied = function(liId) {
1171         /* Build this table while hidden to prevent rendering artifacts */
1172         openils.Util.hide("acq-lit-distrib-applied-tbody");
1173
1174         this._saveDistribAppliedTemplates();
1175
1176         /* Remove any rows in the table from previous populations */
1177         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1178             forEach(dojo.destroy);
1179
1180         /* Unregister all dijits previously created (for some reason this isn't
1181          * covered by the above destroy calls). */
1182         dijit.registry.forEach(
1183             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1184         );
1185
1186         /* Populate the table with our liId */
1187         var total = 0;
1188         fieldmapper.standardRequest(
1189             ["open-ils.acq",
1190             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1191             {
1192                 "async": true,
1193                 "params": [self.authtoken, liId],
1194                 "onresponse": function(r) {
1195                     var dfa = openils.Util.readResponse(r);
1196                     if (dfa) {
1197                         total++;
1198                         self.realDfaCache[dfa.id()] = dfa;
1199                         self._drawDistribAppliedUnit(dfa);
1200                     }
1201                 },
1202                 "oncomplete": function() {
1203                     /* Reveal built table */
1204                     if (total) {
1205                         openils.Util.show(
1206                             "acq-lit-distrib-applied-tbody", "table-row-group"
1207                         );
1208                     }
1209                 }
1210             }
1211         );
1212     };
1213
1214     this._drawDistribAppliedUnit = function(dfa) {
1215         var new_row = false;
1216         var row = dojo.query(
1217             'tr[formula="' + dfa.formula().id() + '"]',
1218             "acq-lit-distrib-applied-tbody"
1219         )[0];
1220
1221         if (!row) {
1222             new_row = true;
1223             row = dojo.clone(this._appliedDistribTemplate);
1224             dojo.attr(row, "formula", dfa.formula().id());
1225             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1226         }
1227
1228         var td = dojo.query("td", row)[0];
1229
1230         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1231         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1232
1233         if (new_row)
1234             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1235
1236         new dijit.form.Button(
1237             {
1238                 "onClick": function() {
1239                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1240                         self.deleteDfa(dfa);
1241                 },
1242                 "label": "X",
1243                 /* XXX I /cannot/ make the following work in as a CSS class
1244                  * for some reason. So frustrating... */
1245                 "style": function(id) {
1246                      return (id > 0 ?
1247                         "font-weight: bold; color: #c00;" :
1248                         "color: #666;");
1249                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1250             }, "dfa-button-" + dfa.id()
1251         );
1252         new dijit.Tooltip(
1253             {
1254                 "connectId": ["dfa-button-" + dfa.id()],
1255                 "label": dojo.string.substitute(
1256                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1257                         openils.User.formalName(dfa.creator()),
1258                         dojo.date.locale.format(
1259                             dojo.date.stamp.fromISOString(dfa.create_time()),
1260                             {"formatLength":"short"}
1261                         )
1262                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1263                 )
1264             }, "dfa-tip-" + dfa.id()
1265         );
1266     }
1267
1268     this.deleteDfa = function(dfa) {
1269         if (dfa.id() > 0) { /* real */
1270             this.pcrud.eliminate(
1271                 dfa, {
1272                     "async": true,
1273                     "oncomplete": function() {
1274                         self._removeDistribApplied(dfa.id());
1275                         delete self.realDfaCache[dfa.id()];
1276                     }
1277                 }
1278             );
1279         } else { /* virtual */
1280             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1281             this.virtDfaCounts[dfa.formula().id()] = 0;
1282             /* hasn't been saved yet, so no need to do anything server side */
1283             this._removeDistribApplied(dfa.id());
1284         }
1285
1286     };
1287
1288     this._removeDistribApplied = function(dfaId) {
1289         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1290         dijit.registry.forEach(
1291             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1292         );
1293         this._removeDistribAppliedEmptyRows();
1294     };
1295
1296     this._removeAllDistribAppliedVirtual = function() {
1297         /* Unregister dijits */
1298         dijit.registry.forEach(
1299             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1300         );
1301         this._removeDistribAppliedEmptyRows();
1302     };
1303
1304     this._removeDistribAppliedEmptyRows = function() {
1305         /* Remove any rows with no DFA at all */
1306         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1307             function(o) {
1308                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1309             }
1310         );
1311     };
1312
1313     /**
1314      * Insert a new row into the distribution formula selection form
1315      */
1316     this._addDistribFormulaRow = function() {
1317         var self = this;
1318
1319         if (!self.distribForms) {
1320             // no formulas, hide the form
1321             openils.Util.hide('acq-lit-distrib-formula-table');
1322             return;
1323         }
1324
1325         if(!this.distribFormulaTemplate) 
1326             this.distribFormulaTemplate = 
1327                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1328
1329         var row = this.distribFormulaTemplate.cloneNode(true);
1330         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1331
1332         this.dfSelector = new dijit.form.FilteringSelect(
1333             {"labelAttr": "dynLabel", "labelType": "html"},
1334             nodeByName("selector", row)
1335         );
1336         this._updateFormulaStore();
1337         this.dfSelector.fetchProperties =
1338             {"sort": [{"attribute": "use_count", "descending": true}]};
1339
1340         var apply = new dijit.form.Button(
1341             {"label": localeStrings.APPLY},
1342             nodeByName('set_button', row)
1343         ); 
1344
1345         var reset = new dijit.form.Button(
1346             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1347             nodeByName("reset_button", row)  
1348         );
1349
1350         dojo.connect(apply, 'onClick', 
1351             function() {
1352                 var form_id = self.dfSelector.attr("value");
1353                 if(!form_id) return;
1354                 self._applyDistribFormula(form_id);
1355                 reset.attr("disabled", false);
1356             }
1357         );
1358
1359         dojo.connect(reset, 'onClick', 
1360             function() {
1361                 self.restoreCopyFieldsBeforeDF();
1362                 self.virtDfaCounts = {};
1363                 self.virtDfaId = -1;
1364                 self.dfeOffset = 0;
1365                 self._updateFormulaStore();
1366                 self._removeAllDistribAppliedVirtual();
1367                 reset.attr("disabled", "true");
1368             }
1369         );
1370
1371     };
1372
1373     /**
1374      * Applies a distrib formula to the current set of copies
1375      */
1376     this._applyDistribFormula = function(formula) {
1377         if(!formula) return;
1378
1379         formula = this.distribForms.filter(
1380             function(form) { return form.id() == formula; }
1381         )[0];
1382
1383         var copyRows = dojo.query('tr', self.copyTbody);
1384
1385         if (this.dfeOffset >= copyRows.length) {
1386             alert(localeStrings.OUT_OF_COPIES);
1387             return;
1388         }
1389
1390         var entries_applied = 0;
1391         for(
1392             var rowIndex = this.dfeOffset;
1393             rowIndex < copyRows.length;
1394             rowIndex++
1395         ) {
1396             
1397             var row = copyRows[rowIndex];
1398             var copy_id = row.getAttribute('copy_id');
1399             var copyWidgets = this.copyWidgetCache[copy_id];
1400             var entryIndex = this.dfeOffset;
1401             var entry = null;
1402
1403             // find the correct entry for the current row
1404             dojo.forEach(formula.entries(), 
1405                 function(e) {
1406                     if(!entry) {
1407                         entryIndex += e.item_count();
1408                         if(entryIndex > rowIndex)
1409                             entry = e;
1410                     }
1411                 }
1412             );
1413
1414             if(entry) {
1415                 
1416                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1417                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1418     
1419                 entries_applied++;
1420                 this.saveCopyFieldsBeforeDF(copy_id);
1421                 this._copy_fields_for_acqdf.forEach(
1422                     function(field) {
1423                         if(entry[field]()) {
1424                             copyWidgets[field].attr('value', (entry[field]()));
1425                         }
1426                     }
1427                 );
1428             }
1429         }
1430
1431         if (entries_applied) {
1432             this.virtDfaCounts[formula.id()] =
1433                 ++(this.virtDfaCounts[formula.id()]) || 1;
1434             this._updateFormulaStore();
1435             this._drawDistribAppliedUnit(
1436                 function(df) {
1437                     var dfa = new acqdfa();
1438                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1439                 }(formula)
1440             );
1441             this.dfeOffset += entries_applied;
1442         };
1443     };
1444
1445     /**
1446      * This function updates the DF store for the dropdown so that use_counts
1447      * can reflect DF applications from this session before they're saved
1448      * server-side.
1449      */
1450     this._updateFormulaStore = function() {
1451         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1452             {
1453                 "data": self._labelFormulasWithCounts(
1454                     acqdf.toStoreData(self.distribForms)
1455                 )
1456             }
1457         );
1458     };
1459
1460     this.saveCopyFieldsBeforeDF = function(copy_id) {
1461         var self = this;
1462         if (!this.oldCopyWidgetCache[copy_id]) {
1463             var copyWidgets = this.copyWidgetCache[copy_id];
1464
1465             this.oldCopyWidgetCache[copy_id] = {};
1466             this._copy_fields_for_acqdf.forEach(
1467                 function(f) {
1468                     self.oldCopyWidgetCache[copy_id][f] =
1469                         copyWidgets[f].attr("value");
1470                 }
1471             );
1472         }
1473     };
1474
1475     this.restoreCopyFieldsBeforeDF = function() {
1476         var self = this;
1477         for (var copy_id in this.oldCopyWidgetCache) {
1478             this._copy_fields_for_acqdf.forEach(
1479                 function(f) {
1480                     self.copyWidgetCache[copy_id][f].attr(
1481                         "value", self.oldCopyWidgetCache[copy_id][f]
1482                     );
1483                 }
1484             );
1485         }
1486     };
1487
1488     this._labelFormulasWithCounts = function(store_data) {
1489         for (var key in store_data.items) {
1490             var obj = store_data.items[key];
1491             obj.use_count = Number(obj.use_count); /* needed for sorting */
1492
1493             if (this.virtDfaCounts[obj.id])
1494                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1495
1496             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1497                 obj.use_count + "]</span>&nbsp; " + obj.name;
1498         }
1499         return store_data;
1500     };
1501
1502     /**
1503      * This method formerly would not refetch the DF formulas if they'd been
1504      * loaded already, but now it always re-fetches, since use_count changes.
1505      */
1506     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1507     this._fetchDistribFormulas = function(onload) {
1508         fieldmapper.standardRequest(
1509             ["open-ils.acq",
1510                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1511             {
1512                 "async": true,
1513                 "params": [openils.User.authtoken, 0, 500],
1514                 "oncomplete": function(r) {
1515                     self.distribForms = openils.Util.readResponse(r);
1516                     if(!self.distribForms || self.distribForms.length == 0) {
1517                         self.distribForms = [];
1518                     }
1519                     self._addDistribFormulaRow();
1520                     onload();
1521                 }
1522             }
1523         );
1524     }
1525
1526     this._drawBatchCopyWidgets = function() {
1527         var row = this.copyBatchRow;
1528         dojo.forEach(liDetailBatchFields, 
1529             function(field) {
1530                 if(self.copyBatchRowDrawn) {
1531                     self.copyBatchWidgets[field].attr('value', null);
1532                 } else {
1533                     var widget = new openils.widget.AutoFieldWidget({
1534                         fmField : field,
1535                         fmClass : 'acqlid',
1536                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1537                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1538                         searchFilter : (field == 'fund') ? {"active": "t"} : null,
1539                         parentNode : dojo.query('[name='+field+']', row)[0],
1540                         orgLimitPerms : ['CREATE_PICKLIST'],
1541                         dijitArgs : {
1542                             "required": false,
1543                             "labelType": (field == "fund") ? "html" : null
1544                         },
1545                         noCache: (field == "fund"),
1546                         forceSync : true
1547                     });
1548                     widget.build(
1549                         function(w, ww) {
1550                             if (field == "fund" && w.store)
1551                                 self._ensureCSSFundClasses(w.store);
1552                             self.copyBatchWidgets[field] = w;
1553                         }
1554                     );
1555                     if (field == "fund") {
1556                         dojo.connect(
1557                             widget.widget, "onChange", function(val) {
1558                                 self._updateFundSelectorStyle(widget, val);
1559                             }
1560                         );
1561                     }
1562                 }
1563             }
1564         );
1565         this.copyBatchRowDrawn = true;
1566     };
1567
1568     this.batchCopyUpdate = function() {
1569         var self = this;
1570         for(var k in this.copyWidgetCache) {
1571             var cache = this.copyWidgetCache[k];
1572             dojo.forEach(liDetailBatchFields, function(f) {
1573                 var newval = self.copyBatchWidgets[f].attr('value');
1574                 if(newval) cache[f].attr('value', newval);
1575             });
1576         }
1577     };
1578
1579     this._drawCopies = function(li) {
1580         var self = this;
1581
1582         // this button sets the total number of copies for a given lineitem
1583         acqLitAddCopyCount.onClick = function() { 
1584             var count = acqLitCopyCountInput.attr('value');
1585
1586             // add new rows
1587             while(self.copyCount() < count)
1588                 self.addCopy(li); 
1589             
1590             // delete rows if necessary
1591             var diff = self.copyCount() - count;
1592             if(diff > 0) {
1593                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1594                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1595                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1596                 } else {
1597                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1598                 }
1599             }
1600         }
1601
1602
1603         if(li.lineitem_details().length > 0) {
1604             dojo.forEach(li.lineitem_details(),
1605                 function(copy) {
1606                     self.addCopy(li, copy);
1607                 }
1608             );
1609         } else {
1610             self.addCopy(li);
1611         }
1612     };
1613
1614     this.copyCount = function() {
1615         var count = 0;
1616         for(var id in this.copyCache) {
1617             if(!this.copyCache[id].isdeleted())
1618                 count++;
1619         }
1620         return count;
1621     }
1622
1623     this.virtCopyId = -1;
1624     this.addCopy = function(li, copy) {
1625         var row = this.copyRow.cloneNode(true);
1626         this.copyTbody.appendChild(row);
1627         var self = this;
1628
1629         if(!copy) {
1630             copy = new fieldmapper.acqlid();
1631             copy.isnew(true);
1632             copy.id(this.virtCopyId--);
1633             copy.lineitem(li.id());
1634         }
1635
1636         this.copyCache[copy.id()] = copy;
1637         row.setAttribute('copy_id', copy.id());
1638         self.copyWidgetCache[copy.id()] = {};
1639
1640         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1641
1642         var rcvr = copy.receiver();
1643         if (rcvr) {
1644             if (!userCache[rcvr]) {
1645                 if(rcvr == openils.User.user.id()) {
1646                     userCache[rcvr] = openils.User.user;
1647                 } else {
1648                     userCache[rcvr] = fieldmapper.standardRequest(
1649                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1650                         {params: [openils.User.authtoken, rcvr]}
1651                     );
1652                 }
1653             }
1654             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
1655         }
1656
1657         dojo.forEach(liDetailFields,
1658             function(field) {
1659                 var searchFilter;
1660                 if (field == "fund") {
1661                     searchFilter = (copy.fund() ?
1662                         {"-or": {"active": "t", "id": copy.fund()}} :
1663                         {"active" : "t"});
1664                 } else {
1665                     searchFilter = null;
1666                 }
1667
1668                 var readOnly = false;
1669                 
1670                 // TODO: Add support for changing the owning_lib after real copies have been made.  
1671                 // owning_lib is order data as much as its item data
1672                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1673                     readOnly = true;
1674                 }
1675
1676                 // TODO: add support for changing the fund after debits have been created
1677                 // Note: invoicing allows the change
1678                 if(copy.fund_debit() && field == 'fund') {
1679                     readOnly = true;
1680                 }
1681
1682
1683                 var widget = new openils.widget.AutoFieldWidget({
1684                     fmObject : copy,
1685                     fmField : field,
1686                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1687                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1688                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1689                     searchFilter : searchFilter,
1690                     noCache: (field == "fund"),
1691                     fmClass : 'acqlid',
1692                     parentNode : dojo.query('[name='+field+']', row)[0],
1693                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1694                     readOnly : readOnly,
1695                     orgDefaultsToWs : true
1696                 });
1697
1698                 widget.build(
1699                     // make sure we capture the value from any async widgets
1700                     function(w, ww) { 
1701
1702                         if (field == "fund" && w.store)
1703                             self._ensureCSSFundClasses(w.store);
1704
1705                         if(!readOnly) 
1706                             copy[field](ww.getFormattedValue()) 
1707
1708                         self.copyWidgetCache[copy.id()][field] = w;
1709
1710                         dojo.connect(w, 'onChange', 
1711                             function(val) { 
1712                                 if (field == "fund")
1713                                     self._updateFundSelectorStyle(widget, val);
1714
1715                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1716                                     // prevent setting ischanged() automatically on widget load for existing copies
1717                                     copy[field](widget.getFormattedValue()) 
1718                                     copy.ischanged(true);
1719                                 }
1720                             }
1721                         );
1722                     }
1723                 );
1724             }
1725         );
1726
1727         this.updateLidState(copy, row);
1728     };
1729
1730     this._ensureCSSFundClass = function(id) {
1731         if (!this.fundStyleSheet) {
1732             dojo.create(
1733                 "style", {"type": "text/css"},
1734                 document.getElementsByTagName("head")[0], "last"
1735             );
1736             this.fundStyleSheet = document.styleSheets[
1737                 document.styleSheets.length - 1
1738             ];
1739         }
1740
1741         var cn = "fund_" + id;
1742         if (!this.haveFundClass[cn]) {
1743             fieldmapper.standardRequest(
1744                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1745                 {
1746                     "params": [openils.User.authtoken, id],
1747                     "async": true,
1748                     "oncomplete": function(r) {
1749                         r = openils.Util.readResponse(r);
1750                         self.fundBalanceState[id] = r;
1751                         var style = "";
1752                         if (r[0] /* stop */)
1753                             style = fundStyles.stop;
1754                         else if (r[1] /* warning */)
1755                             style = fundStyles.warning;
1756                         self.fundStyleSheet.insertRule(
1757                             "." + cn + " { " + style + " }",
1758                             self.fundStyleSheet.cssRules.length
1759                         );
1760                         self.haveFundClass[cn] = true;
1761                     }
1762                 }
1763             );
1764         }
1765     };
1766
1767     this._ensureCSSFundClasses = function(store) {
1768         store.fetch({
1769             "query": {"id": "*"},
1770             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1771         });
1772     };
1773
1774     this._updateFundSelectorStyle = function(widget, fund_id) {
1775         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1776         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1777     };
1778
1779     this.updateLidState = function(copy, row) {
1780         var self = this;
1781
1782         if (typeof(row) == "undefined") {
1783             row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1784         }
1785
1786         // action links
1787         var recv_link = nodeByName("receive", row);
1788         var unrecv_link = nodeByName("unreceive", row);
1789         var del_link = nodeByName("delete", row);
1790         var cxl_link = nodeByName("cancel", row);
1791         var claim_link = nodeByName("claim", row);
1792         var cxl_reason_link = nodeByName("cancel_reason", row);
1793
1794         // by default, hide all the actions
1795         openils.Util.hide(del_link.parentNode);
1796         openils.Util.hide(recv_link);
1797         openils.Util.hide(unrecv_link);
1798         openils.Util.hide(cxl_link);
1799         openils.Util.hide(claim_link);
1800         openils.Util.hide(cxl_reason_link);
1801
1802         if (copy.id() > 0) { // real copies (LIDs)
1803
1804             if (copy.cancel_reason()) { 
1805
1806                 /* --------- cancelled -------------------------- */
1807
1808                 /* XXX the following may leak memory in a long lived table: 
1809                  * dijits may not get destroyed... not positive. revisit. */
1810                 var holds_reason = dojo.create(
1811                     "span", {
1812                         "style": "border-bottom: 1px dashed #000;",
1813                         "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1814                     }, cxl_reason_link, "only"
1815                 );
1816                 new dijit.Tooltip(
1817                     {
1818                         "label": "<em>" + copy.cancel_reason().label() +
1819                             "</em><br />" + copy.cancel_reason().description(),
1820                         "connectId": [holds_reason]
1821                     }, dojo.create("span", null, cxl_reason_link, "last")
1822                 );
1823                 openils.Util.show(cxl_reason_link, "inline");
1824
1825             } else if (copy.recv_time()) { 
1826
1827                 /* --------- received -------------------------- */
1828
1829                 openils.Util.show(unrecv_link, "inline");
1830                 unrecv_link.onclick = function() {
1831                     if (confirm(localeStrings.UNRECEIVE_LID))
1832                         self.issueReceive(copy, /* rollback */ true);
1833                 };
1834
1835             } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1836                 
1837                 /* --------- on order -------------------------- */
1838
1839                 openils.Util.show(recv_link, 'inline');
1840                 openils.Util.show(cxl_link, "inline");
1841
1842                 recv_link.onclick = function() {
1843                     if (self.checkLiAlerts(copy.lineitem()))
1844                         self.issueReceive(copy);
1845                 };
1846
1847                 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1848
1849             } else {
1850
1851                 /* --------- pre-order copies  -------------------------- */
1852
1853                 del_link.onclick = function() { self.deleteCopy(row) };
1854                 openils.Util.show(del_link.parentNode);
1855
1856             }
1857
1858         } else { 
1859
1860             /* --------- virtual copies  -------------------------- */
1861
1862             del_link.onclick = function() { self.deleteCopy(row) };
1863             openils.Util.show(del_link.parentNode);
1864         }
1865     };
1866
1867     this.cancelLid = function(lid_id) {
1868         lidCancelDialog._lid_id = lid_id;
1869         openils.Util.show(lidCancelDialog.domNode.parentNode);
1870         lidCancelDialog.show();
1871         if (!lidCancelDialog._prepared) {
1872             var widget = new openils.widget.AutoFieldWidget({
1873                 "fmField": "cancel_reason",
1874                 "fmClass": "acqlid",
1875                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1876                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1877                 "forceSync": true
1878             });
1879             widget.build(
1880                 function(w, ww) {
1881                     acqLidCancelButton.onClick = function() {
1882                         if (w.attr("value")) {
1883                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1884                                 self._cancelLid(
1885                                     lidCancelDialog._lid_id,
1886                                     w.attr("value")
1887                                 );
1888                             }
1889                             lidCancelDialog.hide();
1890                         }
1891                     };
1892                     lidCancelDialog._prepared = true;
1893                 }
1894             );
1895         }
1896     };
1897
1898     this._cancelLid = function(lid_id, reason) {
1899         fieldmapper.standardRequest(
1900             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1901                 "params": [openils.User.authtoken, lid_id, reason],
1902                 "async": true,
1903                 "onresponse": function(r) {
1904                     if (r = openils.Util.readResponse(r)) {
1905                         if (r.lid) {
1906                             for (var id in r.lid) {
1907                                 /* actually this should only iterate once */
1908                                 self.copyCache[id].cancel_reason(
1909                                     r.lid[id].cancel_reason
1910                                 );
1911                                 self.updateLidState(self.copyCache[id]);
1912                             }
1913                         }
1914                     }
1915                 }
1916             }
1917         );
1918     };
1919
1920     this._confirmAlert = function(li, lin) {
1921         return confirm(
1922             dojo.string.substitute(
1923                 localeStrings.CONFIRM_LI_ALERT, [
1924                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1925                         "title", "lineitem_marc_attr_definition"
1926                     ), (
1927                         /* XXX it's really better add a parameter and to adjust
1928                          * the format string rather than do this concatenation
1929                          * here, but if someone wants this for 2.2 in a hurry,
1930                          * we can sidestep the problem of updating the strings
1931                          * while the translators are working. */
1932                         "[" +
1933                         aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
1934                         "] " +
1935                         lin.alert_text().code()
1936                     ),
1937                     lin.alert_text().description() || "",
1938                     lin.value()
1939                 ]
1940             )
1941         );
1942     };
1943
1944     this.checkLiAlerts = function(li_id) {
1945         var li = this.liCache[li_id];
1946
1947         var alert_notes = li.lineitem_notes().filter(
1948             function(o) { return Boolean(o.alert_text()); }
1949         );
1950
1951         /* this is _intentionally_ not done in a call to forEach() ... */
1952         for (var i = 0; i < alert_notes.length; i++) {
1953             if (this.noteAcks[alert_notes[i].id()])
1954                 continue;
1955             else if (!this._confirmAlert(li, alert_notes[i]))
1956                 return false;
1957             else
1958                 this.noteAcks[alert_notes[i].id()] = true;
1959         }
1960
1961         return true;
1962     };
1963
1964     this.deleteCopy = function(row) {
1965         var copy = this.copyCache[row.getAttribute('copy_id')];
1966         copy.isdeleted(true);
1967         if(copy.isnew())
1968             delete this.copyCache[copy.id()];
1969         this.copyTbody.removeChild(row);
1970     }
1971
1972     this._virtDfaCountsAsList = function() {
1973         var L = [];
1974         for (var key in this.virtDfaCounts) {
1975             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1976                 L.push(key);
1977         }
1978         return L;
1979     }
1980
1981     this.confirmBreachedCopyFunds = function(copies) {
1982         var stop = 0, warning = 0;
1983         copies.forEach(
1984             function(o) {
1985                 if (o.fund()) {
1986                     var state = self.fundBalanceState[o.fund()];
1987                     if (state[0] /* stop */)
1988                         stop++;
1989                     else if (state[1] /* warning */)
1990                         warning++;
1991                 }
1992             }
1993         );
1994
1995         if (stop) {
1996             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1997         } else if (warning) {
1998             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1999         }
2000         return true;
2001     };
2002
2003     this.saveCopyChanges = function(liId) {
2004         var self = this;
2005         var copies = [];
2006
2007
2008         var total = 0;
2009         for(var id in this.copyCache) {
2010             var c = this.copyCache[id];
2011             if(!c.isdeleted()) total++;
2012             if(c.isnew() || c.ischanged() || c.isdeleted()) {
2013                 if(c.id() < 0) c.id(null);
2014                 copies.push(c);
2015             }
2016         }
2017
2018
2019         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2020
2021
2022         if (copies.length > 0) {
2023             if (!this.confirmBreachedCopyFunds(copies))
2024                 return;
2025
2026             if (typeof(this._copy_count_cb) == "function")
2027                 this._copy_count_cb(liId, total);
2028
2029             openils.Util.show("acq-lit-update-copies-progress");
2030             fieldmapper.standardRequest(
2031                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2032                 {   async: true,
2033                     params: [openils.User.authtoken, copies],
2034                     onresponse: function(r) {
2035                         var res = openils.Util.readResponse(r);
2036                         litUpdateCopiesProgress.update(res);
2037                     },
2038                     oncomplete: function() {
2039                         self.drawCopies(liId, true /* force_fetch */);
2040                         openils.Util.hide("acq-lit-update-copies-progress");
2041                     }
2042                 }
2043             );
2044         }
2045
2046         var dfa_list = this._virtDfaCountsAsList();
2047         if (dfa_list.length > 0) {
2048             fieldmapper.standardRequest(
2049                 ["open-ils.acq",
2050                 "open-ils.acq.distribution_formula.record_application"],
2051                 {
2052                     "async": true,
2053                     "params": [openils.User.authtoken, dfa_list, liId],
2054                     "onresponse": function(r) {
2055                         var res = openils.Util.readResponse(r);
2056                         if (res && res.length < dfa_list.length)
2057                             alert(localeStrings.DFA_NOT_ALL);
2058                     }
2059                 }
2060             );
2061             this.virtDfaCounts = {};
2062         }
2063     }
2064
2065     this._updateCreatePoPrepayCheckbox = function(prepay) {
2066         var prepay = openils.Util.isTrue(prepay);
2067         this._prepayRequiredByVendor = prepay;
2068         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2069     };
2070
2071     this._confirmPoPrepaySituation = function() {
2072         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2073         if (want_prepay != this._prepayRequiredByVendor) {
2074             return confirm(
2075                 want_prepay ?
2076                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2077                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2078             );
2079         } else {
2080             return true;
2081         }
2082     };
2083
2084     this.applySelectedLiAction = function(action) {
2085         var self = this;
2086         switch(action) {
2087
2088             case 'delete_selected':
2089                 this._deleteLiList(self.getSelected());
2090                 break;
2091
2092             case 'create_order':
2093                 this._loadPOSelect();
2094                 acqLitPoCreateDialog.show();
2095                 break;
2096
2097             case 'save_picklist':
2098                 acqLitSavePlDialog.show();
2099                 break;
2100
2101             case 'selector_ready':
2102             case 'order_ready':
2103                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2104                 acqLitChangeLiStateDialog.show();
2105                 break;
2106
2107             case 'print_po':
2108                 this.printPO();
2109                 break;
2110
2111             case 'po_history':
2112                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2113                 break;
2114
2115             case 'receive_po':
2116                 this.receivePO();
2117                 break;
2118
2119             case 'rollback_receive_po':
2120                 this.rollbackPoReceive();
2121                 break;
2122
2123             case 'create_assets':
2124                 this.showAssetCreator();
2125                 break;
2126
2127             case 'export_attr_list':
2128                 this.chooseExportAttr();
2129                 break;
2130
2131             case 'batch_apply_funds':
2132                 this.applyBatchLiFunds();
2133                 break;
2134
2135             case 'add_brief_record':
2136                 if(this.isPO)
2137                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2138                 else
2139                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2140
2141                 break;
2142
2143             case "cancel_lineitems":
2144                 this.maybeCancelLineitems();
2145                 break;
2146
2147             case "change_claim_policy":
2148                 var li_list = this.getSelected();
2149                 this.claimPolicyPicker.attr("value", null);
2150                 liClaimPolicyDialog.show();
2151                 liClaimPolicySave.onClick = function() {
2152                     self.changeClaimPolicy(
2153                         li_list,
2154                         self.claimPolicyPicker.attr("value"),
2155                         function() {
2156                             li_list.forEach(
2157                                 function(li) {
2158                                     self.setClaimPolicyControl(li);
2159                                     self.reconsiderClaimControl(li);
2160                                 }
2161                             );
2162                             liClaimPolicyDialog.hide();
2163                         }
2164                     )
2165                 };
2166                 break;
2167         }
2168     };
2169
2170     this.changeClaimPolicy = function(li_list, value, callback) {
2171         li_list.forEach(
2172             function(li) { li.claim_policy(value); }
2173         );
2174         fieldmapper.standardRequest(
2175             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2176                 "params": [openils.User.authtoken, li_list],
2177                 "async": true,
2178                 "oncomplete": function(r) {
2179                     r = openils.Util.readResponse(r);
2180                     if (callback) callback(r);
2181                 }
2182             }
2183         );
2184     };
2185
2186     this.showAssetCreator = function(onAssetsCreated) {
2187         if(!this.isPO) return;
2188         var self = this;
2189     
2190         // first, let's see if this PO has any LI's that need to be merged/imported
2191         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2192             id_list : true,
2193             oncomplete : function(r) {
2194                 var resp = openils.Util.readResponse(r);
2195                 if (resp && resp.length) {
2196                     // PO has some non-linked jubs.  
2197                     
2198                     self.show('asset-creator');
2199                     if(!self.vlAgent.loaded)
2200                         self.vlAgent.init();
2201
2202                     dojo.connect(assetCreatorButton, 'onClick', 
2203                         function() { self.createAssets(onAssetsCreated) });
2204
2205                 } else {
2206
2207                     // all jubs linked, move on to asset creation
2208                     self.createAssets(onAssetsCreated, true); 
2209                 }
2210             }
2211         });
2212     }
2213
2214     this.createAssets = function(onAssetsCreated, noVl) {
2215         this.show('acq-lit-progress-numbers');
2216         var self = this;
2217         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2218         fieldmapper.standardRequest(
2219             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2220             {   async: true,
2221                 params: [this.authtoken, this.isPO, vlArgs],
2222                 onresponse: function(r) {
2223                     var resp = openils.Util.readResponse(r);
2224                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2225                 }
2226             }
2227         );
2228     }
2229
2230     this.maybeCancelLineitems = function() {
2231         openils.Util.show("acq-lit-cancel-reason", "inline");
2232         if (!acqLitCancelLineitemsButton._prepared) {
2233             var widget = new openils.widget.AutoFieldWidget({
2234                 "fmField": "cancel_reason",
2235                 "fmClass": "jub",
2236                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2237                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2238                 "forceSync": true
2239             });
2240             widget.build(
2241                 function(w, ww) {
2242                     acqLitCancelLineitemsButton.onClick = function() {
2243                         if (w.attr("value")) {
2244                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2245                                 self._cancelLineitems(w.attr("value"));
2246                             }
2247                             openils.Util.hide("acq-lit-cancel-reason");
2248                         }
2249                     };
2250                     acqLitCancelLineitemsButton._prepared = true;
2251                 }
2252             );
2253         }
2254     };
2255
2256     this._cancelLineitems = function(reason) {
2257         var id_list = this.getSelected().map(function(o) { return o.id(); });
2258         fieldmapper.standardRequest(
2259             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2260                 "params": [openils.User.authtoken, id_list, reason],
2261                 "async": true,
2262                 "onresponse": function(r) {
2263                     if (r = openils.Util.readResponse(r)) {
2264                         if (r.li) {
2265                             for (var id in r.li) {
2266                                 self.liCache[id].state(r.li[id].state);
2267                                 self.liCache[id].cancel_reason(
2268                                     r.li[id].cancel_reason
2269                                 );
2270                                 self.updateLiState(self.liCache[id]);
2271                             }
2272                         }
2273                         if (r.lid && self.copyCache) {
2274                             for (var id in r.lid) {
2275                                 if (self.copyCache[id]) {
2276                                     self.copyCache[id].cancel_reason(
2277                                         r.lid[id].cancel_reason
2278                                     );
2279                                     self.updateLidState(self.copyCache[id]);
2280                                 }
2281                             }
2282                         }
2283                     }
2284                 }
2285             }
2286         );
2287     };
2288
2289     this.chooseExportAttr = function() {
2290         if (!acqLitExportAttrSelector._li_setup) {
2291             var self = this;
2292             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2293                 {
2294                     "data": acqlimad.toStoreData(
2295                         this.pcrud.search(
2296                             "acqlimad", {"code": li_exportable_attrs}
2297                         )
2298                     )
2299                 }
2300             );
2301             acqLitExportAttrSelector.setValue();
2302             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2303             acqLitExportAttrSelector._li_setup = true;
2304         }
2305         openils.Util.show("acq-lit-export-attr-holder", "inline");
2306     };
2307
2308     this.exportAttrList = function() {
2309         var attr_def = acqLitExportAttrSelector.item;
2310         var li_list = this.getSelected();
2311         var value_list = li_list.map(
2312             function(li) {
2313                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2314                     attr_def.code, "lineitem_marc_attr_definition"
2315                 );
2316             }
2317         ).filter(function(attr) { return Boolean(attr); });
2318
2319         if (value_list.length > 0) {
2320             if (value_list.length < li_list.length) {
2321                 if (!confirm(
2322                     dojo.string.substitute(
2323                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2324                     )
2325                 )) {
2326                     return;
2327                 }
2328             }
2329             try {
2330                 openils.XUL.contentToFileSaveDialog(
2331                     value_list.join("\n"),
2332                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2333                 );
2334             } catch (E) {
2335                 alert(E);
2336             }
2337         } else {
2338             alert(dojo.string.substitute(
2339                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2340             ));
2341         }
2342
2343         openils.Util.hide("acq-lit-export-attr-holder");
2344     };
2345
2346     this.printPO = function() {
2347         if(!this.isPO) return;
2348         progressDialog.show(true);
2349         fieldmapper.standardRequest(
2350             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2351             {   async: true,
2352                 params: [this.authtoken, this.isPO, 'html'],
2353                 oncomplete: function(r) {
2354                     progressDialog.hide();
2355                     var evt = openils.Util.readResponse(r);
2356                     if(evt && evt.template_output()) {
2357                         openils.Util.printHtmlString(evt.template_output().data());
2358                     }
2359                 }
2360             }
2361         );
2362     }
2363
2364
2365     this.receivePO = function() {
2366         if (!this.isPO) return;
2367
2368         for (var id in this.liCache) {
2369             /* assumption: liCache reflects exactly the
2370              * set of LIs that belong to our PO */
2371             if (this.liCache[id].state() != "received" &&
2372                 !this.checkLiAlerts(id)) return;
2373         }
2374
2375         this.show('acq-lit-progress-numbers');
2376         var self = this;
2377         fieldmapper.standardRequest(
2378             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2379             {   async: true,
2380                 params: [this.authtoken, this.isPO],
2381                 onresponse : function(r) {
2382                     var resp = openils.Util.readResponse(r);
2383                     self._updateProgressNumbers(resp, true);
2384                 },
2385             }
2386         );
2387     }
2388
2389     this.issueReceive = function(obj, rollback) {
2390         var part =
2391             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2392         var method =
2393             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2394
2395         progressDialog.show(true);
2396         fieldmapper.standardRequest(
2397             ["open-ils.acq", method], {
2398                 "async": true,
2399                 "params": [this.authtoken, obj.id()],
2400                 "onresponse": function(r) {
2401                     if (r = openils.Util.readResponse(r)) {
2402                         self.fetchClaimInfo(
2403                             part == "lineitem" ? obj.id() : obj.lineitem(),
2404                             /* force */ true,
2405                             function() { self.handleReceive(r); }
2406                         );
2407                         progressDialog.hide();
2408                     }
2409                 }
2410             }
2411         );
2412     };
2413
2414     /**
2415      * Handles the responses from receive and rollback ML calls.
2416      */
2417     this.handleReceive = function(resp) {
2418         if (resp) {
2419             if (resp.li) {
2420                 for (var li_id in resp.li) {
2421                     for (var key in resp.li[li_id])
2422                         self.liCache[li_id][key](resp.li[li_id][key]);
2423                     self.updateLiState(self.liCache[li_id]);
2424                 }
2425             }
2426             if (resp.po) {
2427                 if (typeof(self.poUpdateCallback) == "function")
2428                     self.poUpdateCallback(resp.po);
2429             }
2430             if (resp.lid) {
2431                 for (var lid_id in resp.lid) {
2432                     for (var key in resp.lid[lid_id])
2433                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2434                     self.updateLidState(self.copyCache[lid_id]);
2435                 }
2436             }
2437         }
2438     };
2439
2440     this.rollbackPoReceive = function() {
2441         if(!this.isPO) return;
2442         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2443         this.show('acq-lit-progress-numbers');
2444         var self = this;
2445         fieldmapper.standardRequest(
2446             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2447             {   async: true,
2448                 params: [this.authtoken, this.isPO],
2449                 onresponse : function(r) {
2450                     var resp = openils.Util.readResponse(r);
2451                     self._updateProgressNumbers(resp, true);
2452                 },
2453             }
2454         );
2455     }
2456
2457     this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2458         this.vlAgent.handleResponse(resp,
2459             function(resp, res) {
2460                 if(reloadOnComplete)
2461                      location.href = location.href;
2462                 if (onComplete)
2463                     onComplete(resp, res);
2464             }
2465         );
2466     }
2467
2468
2469     this._createPO = function(fields) {
2470         var wantall = (fields.create_from == "all");
2471
2472         /* If we're a picklist or purchase order already and the user wants
2473          * all lineitems, we might have pages' worth of lineitems haven't all
2474          * been loaded yet, so getSelected() won't find them.  The server,
2475          * however, should know about all our lineitems, so let's ask the
2476          * server for a complete list.
2477          */
2478
2479         if (wantall) {
2480             this.getSelected(
2481                 true, function(list) {
2482                     self._createPOFromLineitems(fields, list);
2483                 }, /* id_list */ true
2484             );
2485         } else {
2486             this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2487         }
2488     };
2489
2490     this._createPOFromLineitems = function(fields, selected) {
2491         if (selected.length == 0) return;
2492         var self = this;
2493
2494         var po = new fieldmapper.acqpo();
2495         po.provider(this.createPoProviderSelector.attr("value"));
2496         po.ordering_agency(this.createPoAgencySelector.attr("value"));
2497         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2498
2499         // if we're creating assets, delay the asset creation 
2500         // until after the PO is created.  This will allow us to 
2501         // use showAssetCreator() directly.
2502
2503         fieldmapper.standardRequest(
2504             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2505             {   async: true,
2506                 params: [
2507                     openils.User.authtoken, 
2508                     po, {lineitems : selected}
2509                 ],
2510                 onresponse : function(r) {
2511                     var resp = openils.Util.readResponse(r);
2512                     if (resp.complete) {
2513                         // self.isPO is needed for showAssetCreator();
2514                         self.isPO = resp.purchase_order.id(); 
2515                         var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2516                         if (fields.create_assets[0]) {
2517                             self.showAssetCreator(
2518                                 function() {location.href = redir}
2519                             );
2520                         } else {
2521                            location.href = redir;
2522                         }
2523                     }
2524                 }
2525             }
2526         );
2527     };
2528
2529
2530     this.batchFundWidget = null;
2531
2532     this.applyBatchLiFunds = function() {
2533
2534         var liIds = this.getSelected().map(function(li) { return li.id(); });
2535         if(liIds.length == 0) return; // warn?
2536
2537         var self = this;
2538         batchFundUpdateDialog.show();
2539
2540         if(!this.batchFundWidget) {
2541             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2542                 fmClass : 'acqf',
2543                 selfReference : true,
2544                 labelFormat : fundLabelFormat,
2545                 searchFormat : fundSearchFormat,
2546                 searchFilter : {"active": "t"},
2547                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2548                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2549                 dijitArgs : { "required": true, "labelType": "html" },
2550                 forceSync : true
2551             });
2552             this.batchFundWidget.build();
2553         }
2554
2555         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2556         dojo.connect(batchFundUpdateSubmit, 'onClick', 
2557             function() { 
2558
2559                 // TODO: call .dry_run first to test thresholds
2560                 fieldmapper.standardRequest(
2561                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2562                     {
2563                         params : [
2564                             openils.User.authtoken, 
2565                             liIds,
2566                             self.batchFundWidget.widget.attr('value')
2567                         ],
2568                         oncomplete : function(r) {
2569                             var resp = openils.Util.readResponse(r);
2570                             if(resp) {
2571                                 location.href = location.href;
2572                             }
2573                         }
2574                     }
2575                 )
2576             }
2577         );
2578     }
2579
2580     this._deleteLiList = function(list, idx) {
2581         if(idx == null) idx = 0;
2582         if(idx >= list.length) return;
2583
2584         var li = list[idx];
2585         var liId = li.id();
2586
2587         if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2588             /* It makes little sense to delete a lineitem from a PO that has
2589              * already been marked 'on-order'.  Especially if EDI is in use,
2590              * such a purchase order will probably have already been shipped
2591              * off to a vendor, and mucking with it at this point could leave
2592              * your data in a bad state that doesn't jive with reality.
2593              *
2594              * I could see making this restriction even firmer.
2595              *
2596              * I could also see adjusting the li state comparisons, extending
2597              * the comparison to the PO's state, and/or providing functions
2598              * that house the logic for comparing states in a single location.
2599              *
2600              * Yes, this will be really annoying if you have selected a lot
2601              * of lineitems to cancel that have been ordered. You'll get a
2602              * confirm dialog for each one.
2603              */
2604
2605             if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2606                 self._deleteLiList(list, ++idx); /* move on to next in list */
2607                 return;
2608             }
2609         }
2610
2611         fieldmapper.standardRequest(
2612             ['open-ils.acq',
2613              this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2614             {   async: true,
2615                 params: [openils.User.authtoken, liId],
2616                 oncomplete: function(r) {
2617                     self.removeLineitem(liId);
2618                     self._deleteLiList(list, ++idx);
2619                 }
2620             }
2621         );
2622     }
2623
2624     this.editOrderMarc = function(li) {
2625
2626         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
2627             to true in about:config */
2628
2629         if(!openils.XUL.enableXPConnect()) return;
2630
2631         if(openils.XUL.isXUL()) {
2632             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2633         } else {
2634             win = window.open('/xul/server/cat/marcedit.xul'); 
2635         }
2636         var self = this;
2637         win.xulG = {
2638             record : {marc : li.marc(), "rtype": "bre"},
2639             save : {
2640                 label: 'Save Record', // XXX I18N
2641                 func: function(xmlString) {
2642                     li.marc(xmlString);
2643                     fieldmapper.standardRequest(
2644                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2645                         {   async: true,
2646                             params: [openils.User.authtoken, li],
2647                             oncomplete: function(r) {
2648                                 openils.Util.readResponse(r);
2649                                 win.close();
2650                                 self.drawInfo(li.id())
2651                             }
2652                         }
2653                     );
2654                 },
2655             },
2656             'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2657             'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2658         };
2659     }
2660
2661     this._savePl = function(values) {
2662         this.getSelected(
2663             (values.which == 'all'),
2664             function(list) { self._savePlFromLineitems(values, list); }
2665         );
2666     };
2667
2668     this._savePlFromLineitems = function(values, selected) {
2669         openils.Util.show("acq-lit-generic-progress");
2670
2671         if(values.new_name) {
2672             openils.acq.Picklist.create(
2673                 {name: values.new_name},
2674                 function(id) {
2675                     self._updateLiList(
2676                         id, selected, 0,
2677                         function() {
2678                             location.href =
2679                                 oilsBasePath + "/acq/picklist/view/" + id;
2680                         }
2681                     );
2682                 }
2683             );
2684         } else if(values.existing_pl) {
2685             // update lineitems to use an existing picklist
2686             self._updateLiList(
2687                 values.existing_pl, selected, 0,
2688                 function(){
2689                     location.href =
2690                         oilsBasePath + "/acq/picklist/view/" +
2691                         values.existing_pl;
2692                 }
2693             );
2694         }
2695     };
2696
2697     this._updateLiState = function(values, state) {
2698         progressDialog.show(true);
2699         this.getSelected(
2700             (values.which == 'all'),
2701             function(list) {
2702                 self._updateLiStateFromLineitems(values, state, list);
2703             }
2704         );
2705     };
2706
2707     this._updateLiStateFromLineitems = function(values, state, selected) {
2708         if(!selected.length) return;
2709         dojo.forEach(selected, function(li) {li.state(state);});
2710         self._updateLiList(null, selected, 0,
2711             // TODO consider inline updates for efficiency
2712             function() { location.href = location.href }
2713         );
2714     };
2715
2716     this._updateLiList = function(pl, list, idx, oncomplete) {
2717         if(idx >= list.length) return oncomplete();
2718         var li = list[idx];
2719         if(pl != null) li.picklist(pl);
2720         litGenericProgress.update({maximum: list.length, progress: idx});
2721         new openils.acq.Lineitem({lineitem:li}).update(
2722             function(r) {
2723                 self._updateLiList(pl, list, ++idx, oncomplete);
2724             }
2725         );
2726     }
2727
2728     this._loadPOSelect = function() {
2729         if (!this.createPoProviderSelector) {
2730             var widget = new openils.widget.AutoFieldWidget({
2731                 "fmField": "provider",
2732                 "fmClass": "acqpo",
2733                 "searchFilter": {"active": "t"},
2734                 "parentNode": dojo.byId("acq-lit-po-provider"),
2735                 "dijitArgs": {
2736                     "onChange": function() {
2737                         if (this.item) {
2738                             self._updateCreatePoPrepayCheckbox(
2739                                 this.item.prepayment_required()
2740                             );
2741                         }
2742                     }
2743                 }
2744             });
2745             widget.build(function(w) { self.createPoProviderSelector = w; });
2746         }
2747
2748         if (!this.createPoAgencySelector) {
2749             var widget = new openils.widget.AutoFieldWidget({
2750                 "fmField": "ordering_agency",
2751                 "fmClass": "acqpo",
2752                 "parentNode": dojo.byId("acq-lit-po-agency"),
2753                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2754             });
2755             widget.build(function(w) { self.createPoAgencySelector = w; });
2756         }
2757     };
2758
2759     this.showRealCopyEditUI = function(li) {
2760         copyList = [];
2761         var self = this;
2762         this.volCache = {};
2763
2764         this._fetchLineitem(li.id(), 
2765             function(fullLi) {
2766                 li = self.liCache[li.id()] = fullLi;
2767
2768                 self.pcrud.search(
2769                     'acp', {
2770                         id : li.lineitem_details().map(
2771                             function(item) { return item.eg_copy_id() }
2772                         )
2773                     }, {
2774                         async : true,
2775                         oncomplete : function(r) {
2776                             try {
2777                                 var r_list = openils.Util.readResponse( r );
2778                                 for (var i = 0; i < r_list.length; i++) {
2779                                     var copy = r_list[i];
2780                                     var volId = copy.call_number();
2781                                     var volume = self.volCache[volId];
2782                                     if(!volume) {
2783                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2784                                     }
2785                                     copy.call_number(volume);
2786                                     copyList.push(copy);
2787                                 }
2788                                 if (xulG) {
2789                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2790                                 }
2791                             } catch(E) {
2792                                 alert('error in oncomplete: ' + E);
2793                             }
2794                         }
2795                     }
2796                 );
2797             }
2798         );
2799     },
2800
2801     this.drawBibFinder = function(li) {
2802
2803         var query = '';
2804         var liWrapper = new openils.acq.Lineitem({lineitem:li});
2805
2806         dojo.forEach(
2807             ['isbn', 'upc', 'issn', 'title', 'author'],
2808             function(field) {
2809                 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2810                 if(val) {
2811                     if(field == 'title' || field == 'author') {
2812                         query += field +':' + val + ' ';
2813                     } else {
2814                         query += 'identifier|' + field + ':' + val + ' ';
2815                     }
2816                 }
2817             }
2818         );
2819
2820         win = window.open(
2821             oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2822             '', 'resizable,scrollbars=1');
2823
2824         win.window.recordFound = function(bibId) { 
2825             win.close();
2826
2827             var attrs = li.attributes();
2828             li.attributes(null);
2829             li.eg_bib_id(bibId);
2830
2831             fieldmapper.standardRequest(
2832                 ["open-ils.acq", "open-ils.acq.lineitem.update"], 
2833                 {
2834                     "params": [openils.User.authtoken, li],
2835                     "async": true,
2836                     "oncomplete": function(r) {
2837                         if(openils.Util.readResponse(r)) {
2838                             location.href = location.href;
2839                         }
2840                     }
2841                 }
2842             );
2843         }
2844     }
2845 }
2846