Window.open fixes
[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() + '?focus_li=' + li.id());
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() + '?focus_li=' + li.id());
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('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         if (document.referrer.match(/invoice/)) {
1125             // got here from the invoice page, show the 'return-to-invoice' button
1126             var cgi = new openils.CGI({url : document.referrer});
1127             cgi.param('focus_li', liId);
1128             openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1129             var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1130             button.onclick = function() { location.href = cgi.url() };
1131         }
1132
1133         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1134             function(li, html) {
1135                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1136             }
1137         );
1138
1139         this.show('copies');
1140         var self = this;
1141         this.copyCache = {};
1142         this.copyWidgetCache = {};
1143         this.oldCopyWidgetCache = {};
1144         this.virtDfaCounts = {};
1145         this.realDfaCache = {};
1146         this.dfeOffset = 0;
1147
1148         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1149         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1150         acqLitCopyCountInput.attr('value', '0');
1151
1152         while(this.copyTbody.childNodes[0])
1153             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1154
1155         this._drawBatchCopyWidgets();
1156
1157         this._drawDistribApplied(liId);
1158
1159         this._fetchDistribFormulas(
1160             function() {
1161                 openils.acq.Lineitem.fetchAttrDefs(
1162                     function() { 
1163                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1164                     } 
1165                 );
1166             }
1167         );
1168     };
1169
1170     this._saveDistribAppliedTemplates = function() {
1171         if (!this._appliedDistribTemplate) {
1172             this._appliedDistribTemplate =
1173                 dojo.byId("acq-lit-distrib-applied-tbody").
1174                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1175             dojo.attr(this._appliedDistribTemplate, "id");
1176         }
1177     };
1178
1179     this._drawDistribApplied = function(liId) {
1180         /* Build this table while hidden to prevent rendering artifacts */
1181         openils.Util.hide("acq-lit-distrib-applied-tbody");
1182
1183         this._saveDistribAppliedTemplates();
1184
1185         /* Remove any rows in the table from previous populations */
1186         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1187             forEach(dojo.destroy);
1188
1189         /* Unregister all dijits previously created (for some reason this isn't
1190          * covered by the above destroy calls). */
1191         dijit.registry.forEach(
1192             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1193         );
1194
1195         /* Populate the table with our liId */
1196         var total = 0;
1197         fieldmapper.standardRequest(
1198             ["open-ils.acq",
1199             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1200             {
1201                 "async": true,
1202                 "params": [self.authtoken, liId],
1203                 "onresponse": function(r) {
1204                     var dfa = openils.Util.readResponse(r);
1205                     if (dfa) {
1206                         total++;
1207                         self.realDfaCache[dfa.id()] = dfa;
1208                         self._drawDistribAppliedUnit(dfa);
1209                     }
1210                 },
1211                 "oncomplete": function() {
1212                     /* Reveal built table */
1213                     if (total) {
1214                         openils.Util.show(
1215                             "acq-lit-distrib-applied-tbody", "table-row-group"
1216                         );
1217                     }
1218                 }
1219             }
1220         );
1221     };
1222
1223     this._drawDistribAppliedUnit = function(dfa) {
1224         var new_row = false;
1225         var row = dojo.query(
1226             'tr[formula="' + dfa.formula().id() + '"]',
1227             "acq-lit-distrib-applied-tbody"
1228         )[0];
1229
1230         if (!row) {
1231             new_row = true;
1232             row = dojo.clone(this._appliedDistribTemplate);
1233             dojo.attr(row, "formula", dfa.formula().id());
1234             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1235         }
1236
1237         var td = dojo.query("td", row)[0];
1238
1239         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1240         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1241
1242         if (new_row)
1243             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1244
1245         new dijit.form.Button(
1246             {
1247                 "onClick": function() {
1248                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1249                         self.deleteDfa(dfa);
1250                 },
1251                 "label": "X",
1252                 /* XXX I /cannot/ make the following work in as a CSS class
1253                  * for some reason. So frustrating... */
1254                 "style": function(id) {
1255                      return (id > 0 ?
1256                         "font-weight: bold; color: #c00;" :
1257                         "color: #666;");
1258                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1259             }, "dfa-button-" + dfa.id()
1260         );
1261         new dijit.Tooltip(
1262             {
1263                 "connectId": ["dfa-button-" + dfa.id()],
1264                 "label": dojo.string.substitute(
1265                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1266                         openils.User.formalName(dfa.creator()),
1267                         dojo.date.locale.format(
1268                             dojo.date.stamp.fromISOString(dfa.create_time()),
1269                             {"formatLength":"short"}
1270                         )
1271                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1272                 )
1273             }, "dfa-tip-" + dfa.id()
1274         );
1275     }
1276
1277     this.deleteDfa = function(dfa) {
1278         if (dfa.id() > 0) { /* real */
1279             this.pcrud.eliminate(
1280                 dfa, {
1281                     "async": true,
1282                     "oncomplete": function() {
1283                         self._removeDistribApplied(dfa.id());
1284                         delete self.realDfaCache[dfa.id()];
1285                     }
1286                 }
1287             );
1288         } else { /* virtual */
1289             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1290             this.virtDfaCounts[dfa.formula().id()] = 0;
1291             /* hasn't been saved yet, so no need to do anything server side */
1292             this._removeDistribApplied(dfa.id());
1293         }
1294
1295     };
1296
1297     this._removeDistribApplied = function(dfaId) {
1298         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1299         dijit.registry.forEach(
1300             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1301         );
1302         this._removeDistribAppliedEmptyRows();
1303     };
1304
1305     this._removeAllDistribAppliedVirtual = function() {
1306         /* Unregister dijits */
1307         dijit.registry.forEach(
1308             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1309         );
1310         this._removeDistribAppliedEmptyRows();
1311     };
1312
1313     this._removeDistribAppliedEmptyRows = function() {
1314         /* Remove any rows with no DFA at all */
1315         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1316             function(o) {
1317                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1318             }
1319         );
1320     };
1321
1322     /**
1323      * Insert a new row into the distribution formula selection form
1324      */
1325     this._addDistribFormulaRow = function() {
1326         var self = this;
1327
1328         if (!self.distribForms) {
1329             // no formulas, hide the form
1330             openils.Util.hide('acq-lit-distrib-formula-table');
1331             return;
1332         }
1333
1334         if(!this.distribFormulaTemplate) 
1335             this.distribFormulaTemplate = 
1336                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1337
1338         var row = this.distribFormulaTemplate.cloneNode(true);
1339         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1340
1341         this.dfSelector = new dijit.form.FilteringSelect(
1342             {"labelAttr": "dynLabel", "labelType": "html"},
1343             nodeByName("selector", row)
1344         );
1345         this._updateFormulaStore();
1346         this.dfSelector.fetchProperties =
1347             {"sort": [{"attribute": "use_count", "descending": true}]};
1348
1349         var apply = new dijit.form.Button(
1350             {"label": localeStrings.APPLY},
1351             nodeByName('set_button', row)
1352         ); 
1353
1354         var reset = new dijit.form.Button(
1355             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1356             nodeByName("reset_button", row)  
1357         );
1358
1359         dojo.connect(apply, 'onClick', 
1360             function() {
1361                 var form_id = self.dfSelector.attr("value");
1362                 if(!form_id) return;
1363                 self._applyDistribFormula(form_id);
1364                 reset.attr("disabled", false);
1365             }
1366         );
1367
1368         dojo.connect(reset, 'onClick', 
1369             function() {
1370                 self.restoreCopyFieldsBeforeDF();
1371                 self.virtDfaCounts = {};
1372                 self.virtDfaId = -1;
1373                 self.dfeOffset = 0;
1374                 self._updateFormulaStore();
1375                 self._removeAllDistribAppliedVirtual();
1376                 reset.attr("disabled", "true");
1377             }
1378         );
1379
1380     };
1381
1382     /**
1383      * Applies a distrib formula to the current set of copies
1384      */
1385     this._applyDistribFormula = function(formula) {
1386         if(!formula) return;
1387
1388         formula = this.distribForms.filter(
1389             function(form) { return form.id() == formula; }
1390         )[0];
1391
1392         var copyRows = dojo.query('tr', self.copyTbody);
1393
1394         if (this.dfeOffset >= copyRows.length) {
1395             alert(localeStrings.OUT_OF_COPIES);
1396             return;
1397         }
1398
1399         var entries_applied = 0;
1400         for(
1401             var rowIndex = this.dfeOffset;
1402             rowIndex < copyRows.length;
1403             rowIndex++
1404         ) {
1405             
1406             var row = copyRows[rowIndex];
1407             var copy_id = row.getAttribute('copy_id');
1408             var copyWidgets = this.copyWidgetCache[copy_id];
1409             var entryIndex = this.dfeOffset;
1410             var entry = null;
1411
1412             // find the correct entry for the current row
1413             dojo.forEach(formula.entries(), 
1414                 function(e) {
1415                     if(!entry) {
1416                         entryIndex += e.item_count();
1417                         if(entryIndex > rowIndex)
1418                             entry = e;
1419                     }
1420                 }
1421             );
1422
1423             if(entry) {
1424                 
1425                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1426                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1427     
1428                 entries_applied++;
1429                 this.saveCopyFieldsBeforeDF(copy_id);
1430                 this._copy_fields_for_acqdf.forEach(
1431                     function(field) {
1432                         if(entry[field]()) {
1433                             copyWidgets[field].attr('value', (entry[field]()));
1434                         }
1435                     }
1436                 );
1437             }
1438         }
1439
1440         if (entries_applied) {
1441             this.virtDfaCounts[formula.id()] =
1442                 ++(this.virtDfaCounts[formula.id()]) || 1;
1443             this._updateFormulaStore();
1444             this._drawDistribAppliedUnit(
1445                 function(df) {
1446                     var dfa = new acqdfa();
1447                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1448                 }(formula)
1449             );
1450             this.dfeOffset += entries_applied;
1451         };
1452     };
1453
1454     /**
1455      * This function updates the DF store for the dropdown so that use_counts
1456      * can reflect DF applications from this session before they're saved
1457      * server-side.
1458      */
1459     this._updateFormulaStore = function() {
1460         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1461             {
1462                 "data": self._labelFormulasWithCounts(
1463                     acqdf.toStoreData(self.distribForms)
1464                 )
1465             }
1466         );
1467     };
1468
1469     this.saveCopyFieldsBeforeDF = function(copy_id) {
1470         var self = this;
1471         if (!this.oldCopyWidgetCache[copy_id]) {
1472             var copyWidgets = this.copyWidgetCache[copy_id];
1473
1474             this.oldCopyWidgetCache[copy_id] = {};
1475             this._copy_fields_for_acqdf.forEach(
1476                 function(f) {
1477                     self.oldCopyWidgetCache[copy_id][f] =
1478                         copyWidgets[f].attr("value");
1479                 }
1480             );
1481         }
1482     };
1483
1484     this.restoreCopyFieldsBeforeDF = function() {
1485         var self = this;
1486         for (var copy_id in this.oldCopyWidgetCache) {
1487             this._copy_fields_for_acqdf.forEach(
1488                 function(f) {
1489                     self.copyWidgetCache[copy_id][f].attr(
1490                         "value", self.oldCopyWidgetCache[copy_id][f]
1491                     );
1492                 }
1493             );
1494         }
1495     };
1496
1497     this._labelFormulasWithCounts = function(store_data) {
1498         for (var key in store_data.items) {
1499             var obj = store_data.items[key];
1500             obj.use_count = Number(obj.use_count); /* needed for sorting */
1501
1502             if (this.virtDfaCounts[obj.id])
1503                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1504
1505             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1506                 obj.use_count + "]</span>&nbsp; " + obj.name;
1507         }
1508         return store_data;
1509     };
1510
1511     /**
1512      * This method formerly would not refetch the DF formulas if they'd been
1513      * loaded already, but now it always re-fetches, since use_count changes.
1514      */
1515     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1516     this._fetchDistribFormulas = function(onload) {
1517         fieldmapper.standardRequest(
1518             ["open-ils.acq",
1519                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1520             {
1521                 "async": true,
1522                 "params": [openils.User.authtoken, 0, 500],
1523                 "oncomplete": function(r) {
1524                     self.distribForms = openils.Util.readResponse(r);
1525                     if(!self.distribForms || self.distribForms.length == 0) {
1526                         self.distribForms = [];
1527                     }
1528                     self._addDistribFormulaRow();
1529                     onload();
1530                 }
1531             }
1532         );
1533     }
1534
1535     this._drawBatchCopyWidgets = function() {
1536         var row = this.copyBatchRow;
1537         dojo.forEach(liDetailBatchFields, 
1538             function(field) {
1539                 if(self.copyBatchRowDrawn) {
1540                     self.copyBatchWidgets[field].attr('value', null);
1541                 } else {
1542                     var widget = new openils.widget.AutoFieldWidget({
1543                         fmField : field,
1544                         fmClass : 'acqlid',
1545                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1546                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1547                         searchFilter : (field == 'fund') ? {"active": "t"} : null,
1548                         parentNode : dojo.query('[name='+field+']', row)[0],
1549                         orgLimitPerms : ['CREATE_PICKLIST'],
1550                         dijitArgs : {
1551                             "required": false,
1552                             "labelType": (field == "fund") ? "html" : null
1553                         },
1554                         noCache: (field == "fund"),
1555                         forceSync : true
1556                     });
1557                     widget.build(
1558                         function(w, ww) {
1559                             if (field == "fund" && w.store)
1560                                 self._ensureCSSFundClasses(w.store);
1561                             self.copyBatchWidgets[field] = w;
1562                         }
1563                     );
1564                     if (field == "fund") {
1565                         dojo.connect(
1566                             widget.widget, "onChange", function(val) {
1567                                 self._updateFundSelectorStyle(widget, val);
1568                             }
1569                         );
1570                     }
1571                 }
1572             }
1573         );
1574         this.copyBatchRowDrawn = true;
1575     };
1576
1577     this.batchCopyUpdate = function() {
1578         var self = this;
1579         for(var k in this.copyWidgetCache) {
1580             var cache = this.copyWidgetCache[k];
1581             dojo.forEach(liDetailBatchFields, function(f) {
1582                 var newval = self.copyBatchWidgets[f].attr('value');
1583                 if(newval) cache[f].attr('value', newval);
1584             });
1585         }
1586     };
1587
1588     this._drawCopies = function(li) {
1589         var self = this;
1590
1591         // this button sets the total number of copies for a given lineitem
1592         acqLitAddCopyCount.onClick = function() { 
1593             var count = acqLitCopyCountInput.attr('value');
1594
1595             // add new rows
1596             while(self.copyCount() < count)
1597                 self.addCopy(li); 
1598             
1599             // delete rows if necessary
1600             var diff = self.copyCount() - count;
1601             if(diff > 0) {
1602                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1603                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1604                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1605                 } else {
1606                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1607                 }
1608             }
1609         }
1610
1611
1612         if(li.lineitem_details().length > 0) {
1613             dojo.forEach(li.lineitem_details(),
1614                 function(copy) {
1615                     self.addCopy(li, copy);
1616                 }
1617             );
1618         } else {
1619             self.addCopy(li);
1620         }
1621     };
1622
1623     this.copyCount = function() {
1624         var count = 0;
1625         for(var id in this.copyCache) {
1626             if(!this.copyCache[id].isdeleted())
1627                 count++;
1628         }
1629         return count;
1630     }
1631
1632     this.virtCopyId = -1;
1633     this.addCopy = function(li, copy) {
1634         var row = this.copyRow.cloneNode(true);
1635         this.copyTbody.appendChild(row);
1636         var self = this;
1637
1638         if(!copy) {
1639             copy = new fieldmapper.acqlid();
1640             copy.isnew(true);
1641             copy.id(this.virtCopyId--);
1642             copy.lineitem(li.id());
1643         }
1644
1645         this.copyCache[copy.id()] = copy;
1646         row.setAttribute('copy_id', copy.id());
1647         self.copyWidgetCache[copy.id()] = {};
1648
1649         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1650
1651         var rcvr = copy.receiver();
1652         if (rcvr) {
1653             if (!userCache[rcvr]) {
1654                 if(rcvr == openils.User.user.id()) {
1655                     userCache[rcvr] = openils.User.user;
1656                 } else {
1657                     userCache[rcvr] = fieldmapper.standardRequest(
1658                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1659                         {params: [openils.User.authtoken, rcvr]}
1660                     );
1661                 }
1662             }
1663             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
1664         }
1665
1666         dojo.forEach(liDetailFields,
1667             function(field) {
1668                 var searchFilter;
1669                 if (field == "fund") {
1670                     searchFilter = (copy.fund() ?
1671                         {"-or": {"active": "t", "id": copy.fund()}} :
1672                         {"active" : "t"});
1673                 } else {
1674                     searchFilter = null;
1675                 }
1676
1677                 var readOnly = false;
1678                 
1679                 // TODO: Add support for changing the owning_lib after real copies have been made.  
1680                 // owning_lib is order data as much as its item data
1681                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1682                     readOnly = true;
1683                 }
1684
1685                 // TODO: add support for changing the fund after debits have been created
1686                 // Note: invoicing allows the change
1687                 if(copy.fund_debit() && field == 'fund') {
1688                     readOnly = true;
1689                 }
1690
1691
1692                 var widget = new openils.widget.AutoFieldWidget({
1693                     fmObject : copy,
1694                     fmField : field,
1695                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1696                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1697                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1698                     searchFilter : searchFilter,
1699                     noCache: (field == "fund"),
1700                     fmClass : 'acqlid',
1701                     parentNode : dojo.query('[name='+field+']', row)[0],
1702                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1703                     readOnly : readOnly,
1704                     orgDefaultsToWs : true
1705                 });
1706
1707                 widget.build(
1708                     // make sure we capture the value from any async widgets
1709                     function(w, ww) { 
1710
1711                         if (field == "fund" && w.store)
1712                             self._ensureCSSFundClasses(w.store);
1713
1714                         if(!readOnly) 
1715                             copy[field](ww.getFormattedValue()) 
1716
1717                         self.copyWidgetCache[copy.id()][field] = w;
1718
1719                         dojo.connect(w, 'onChange', 
1720                             function(val) { 
1721                                 if (field == "fund")
1722                                     self._updateFundSelectorStyle(widget, val);
1723
1724                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1725                                     // prevent setting ischanged() automatically on widget load for existing copies
1726                                     copy[field](widget.getFormattedValue()) 
1727                                     copy.ischanged(true);
1728                                 }
1729                             }
1730                         );
1731                     }
1732                 );
1733             }
1734         );
1735
1736         this.updateLidState(copy, row);
1737     };
1738
1739     this._ensureCSSFundClass = function(id) {
1740         if (!this.fundStyleSheet) {
1741             dojo.create(
1742                 "style", {"type": "text/css"},
1743                 document.getElementsByTagName("head")[0], "last"
1744             );
1745             this.fundStyleSheet = document.styleSheets[
1746                 document.styleSheets.length - 1
1747             ];
1748         }
1749
1750         var cn = "fund_" + id;
1751         if (!this.haveFundClass[cn]) {
1752             fieldmapper.standardRequest(
1753                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1754                 {
1755                     "params": [openils.User.authtoken, id],
1756                     "async": true,
1757                     "oncomplete": function(r) {
1758                         r = openils.Util.readResponse(r);
1759                         self.fundBalanceState[id] = r;
1760                         var style = "";
1761                         if (r[0] /* stop */)
1762                             style = fundStyles.stop;
1763                         else if (r[1] /* warning */)
1764                             style = fundStyles.warning;
1765                         self.fundStyleSheet.insertRule(
1766                             "." + cn + " { " + style + " }",
1767                             self.fundStyleSheet.cssRules.length
1768                         );
1769                         self.haveFundClass[cn] = true;
1770                     }
1771                 }
1772             );
1773         }
1774     };
1775
1776     this._ensureCSSFundClasses = function(store) {
1777         store.fetch({
1778             "query": {"id": "*"},
1779             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1780         });
1781     };
1782
1783     this._updateFundSelectorStyle = function(widget, fund_id) {
1784         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1785         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1786     };
1787
1788     this.updateLidState = function(copy, row) {
1789         var self = this;
1790
1791         if (typeof(row) == "undefined") {
1792             row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1793         }
1794
1795         // action links
1796         var recv_link = nodeByName("receive", row);
1797         var unrecv_link = nodeByName("unreceive", row);
1798         var del_link = nodeByName("delete", row);
1799         var cxl_link = nodeByName("cancel", row);
1800         var claim_link = nodeByName("claim", row);
1801         var cxl_reason_link = nodeByName("cancel_reason", row);
1802
1803         // by default, hide all the actions
1804         openils.Util.hide(del_link.parentNode);
1805         openils.Util.hide(recv_link);
1806         openils.Util.hide(unrecv_link);
1807         openils.Util.hide(cxl_link);
1808         openils.Util.hide(claim_link);
1809         openils.Util.hide(cxl_reason_link);
1810
1811         if (copy.id() > 0) { // real copies (LIDs)
1812
1813             if (copy.cancel_reason()) { 
1814
1815                 /* --------- cancelled -------------------------- */
1816
1817                 /* XXX the following may leak memory in a long lived table: 
1818                  * dijits may not get destroyed... not positive. revisit. */
1819                 var holds_reason = dojo.create(
1820                     "span", {
1821                         "style": "border-bottom: 1px dashed #000;",
1822                         "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1823                     }, cxl_reason_link, "only"
1824                 );
1825                 new dijit.Tooltip(
1826                     {
1827                         "label": "<em>" + copy.cancel_reason().label() +
1828                             "</em><br />" + copy.cancel_reason().description(),
1829                         "connectId": [holds_reason]
1830                     }, dojo.create("span", null, cxl_reason_link, "last")
1831                 );
1832                 openils.Util.show(cxl_reason_link, "inline");
1833
1834             } else if (copy.recv_time()) { 
1835
1836                 /* --------- received -------------------------- */
1837
1838                 openils.Util.show(unrecv_link, "inline");
1839                 unrecv_link.onclick = function() {
1840                     if (confirm(localeStrings.UNRECEIVE_LID))
1841                         self.issueReceive(copy, /* rollback */ true);
1842                 };
1843
1844             } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1845                 
1846                 /* --------- on order -------------------------- */
1847
1848                 openils.Util.show(recv_link, 'inline');
1849                 openils.Util.show(cxl_link, "inline");
1850
1851                 recv_link.onclick = function() {
1852                     if (self.checkLiAlerts(copy.lineitem()))
1853                         self.issueReceive(copy);
1854                 };
1855
1856                 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1857
1858             } else {
1859
1860                 /* --------- pre-order copies  -------------------------- */
1861
1862                 del_link.onclick = function() { self.deleteCopy(row) };
1863                 openils.Util.show(del_link.parentNode);
1864
1865             }
1866
1867         } else { 
1868
1869             /* --------- virtual copies  -------------------------- */
1870
1871             del_link.onclick = function() { self.deleteCopy(row) };
1872             openils.Util.show(del_link.parentNode);
1873         }
1874     };
1875
1876     this.cancelLid = function(lid_id) {
1877         lidCancelDialog._lid_id = lid_id;
1878         openils.Util.show(lidCancelDialog.domNode.parentNode);
1879         lidCancelDialog.show();
1880         if (!lidCancelDialog._prepared) {
1881             var widget = new openils.widget.AutoFieldWidget({
1882                 "fmField": "cancel_reason",
1883                 "fmClass": "acqlid",
1884                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1885                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1886                 "forceSync": true
1887             });
1888             widget.build(
1889                 function(w, ww) {
1890                     acqLidCancelButton.onClick = function() {
1891                         if (w.attr("value")) {
1892                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1893                                 self._cancelLid(
1894                                     lidCancelDialog._lid_id,
1895                                     w.attr("value")
1896                                 );
1897                             }
1898                             lidCancelDialog.hide();
1899                         }
1900                     };
1901                     lidCancelDialog._prepared = true;
1902                 }
1903             );
1904         }
1905     };
1906
1907     this._cancelLid = function(lid_id, reason) {
1908         fieldmapper.standardRequest(
1909             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1910                 "params": [openils.User.authtoken, lid_id, reason],
1911                 "async": true,
1912                 "onresponse": function(r) {
1913                     if (r = openils.Util.readResponse(r)) {
1914                         if (r.lid) {
1915                             for (var id in r.lid) {
1916                                 /* actually this should only iterate once */
1917                                 self.copyCache[id].cancel_reason(
1918                                     r.lid[id].cancel_reason
1919                                 );
1920                                 self.updateLidState(self.copyCache[id]);
1921                             }
1922                         }
1923                     }
1924                 }
1925             }
1926         );
1927     };
1928
1929     this._confirmAlert = function(li, lin) {
1930         return confirm(
1931             dojo.string.substitute(
1932                 localeStrings.CONFIRM_LI_ALERT, [
1933                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1934                         "title", "lineitem_marc_attr_definition"
1935                     ), (
1936                         /* XXX it's really better add a parameter and to adjust
1937                          * the format string rather than do this concatenation
1938                          * here, but if someone wants this for 2.2 in a hurry,
1939                          * we can sidestep the problem of updating the strings
1940                          * while the translators are working. */
1941                         "[" +
1942                         aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
1943                         "] " +
1944                         lin.alert_text().code()
1945                     ),
1946                     lin.alert_text().description() || "",
1947                     lin.value()
1948                 ]
1949             )
1950         );
1951     };
1952
1953     this.checkLiAlerts = function(li_id) {
1954         var li = this.liCache[li_id];
1955
1956         var alert_notes = li.lineitem_notes().filter(
1957             function(o) { return Boolean(o.alert_text()); }
1958         );
1959
1960         /* this is _intentionally_ not done in a call to forEach() ... */
1961         for (var i = 0; i < alert_notes.length; i++) {
1962             if (this.noteAcks[alert_notes[i].id()])
1963                 continue;
1964             else if (!this._confirmAlert(li, alert_notes[i]))
1965                 return false;
1966             else
1967                 this.noteAcks[alert_notes[i].id()] = true;
1968         }
1969
1970         return true;
1971     };
1972
1973     this.deleteCopy = function(row) {
1974         var copy = this.copyCache[row.getAttribute('copy_id')];
1975         copy.isdeleted(true);
1976         if(copy.isnew())
1977             delete this.copyCache[copy.id()];
1978         this.copyTbody.removeChild(row);
1979     }
1980
1981     this._virtDfaCountsAsList = function() {
1982         var L = [];
1983         for (var key in this.virtDfaCounts) {
1984             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1985                 L.push(key);
1986         }
1987         return L;
1988     }
1989
1990     this.confirmBreachedCopyFunds = function(copies) {
1991         var stop = 0, warning = 0;
1992         copies.forEach(
1993             function(o) {
1994                 if (o.fund()) {
1995                     var state = self.fundBalanceState[o.fund()];
1996                     if (state[0] /* stop */)
1997                         stop++;
1998                     else if (state[1] /* warning */)
1999                         warning++;
2000                 }
2001             }
2002         );
2003
2004         if (stop) {
2005             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2006         } else if (warning) {
2007             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2008         }
2009         return true;
2010     };
2011
2012     this.saveCopyChanges = function(liId) {
2013         var self = this;
2014         var copies = [];
2015
2016
2017         var total = 0;
2018         for(var id in this.copyCache) {
2019             var c = this.copyCache[id];
2020             if(!c.isdeleted()) total++;
2021             if(c.isnew() || c.ischanged() || c.isdeleted()) {
2022                 if(c.id() < 0) c.id(null);
2023                 copies.push(c);
2024             }
2025         }
2026
2027
2028         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2029
2030
2031         if (copies.length > 0) {
2032             if (!this.confirmBreachedCopyFunds(copies))
2033                 return;
2034
2035             if (typeof(this._copy_count_cb) == "function")
2036                 this._copy_count_cb(liId, total);
2037
2038             openils.Util.show("acq-lit-update-copies-progress");
2039             fieldmapper.standardRequest(
2040                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2041                 {   async: true,
2042                     params: [openils.User.authtoken, copies],
2043                     onresponse: function(r) {
2044                         var res = openils.Util.readResponse(r);
2045                         litUpdateCopiesProgress.update(res);
2046                     },
2047                     oncomplete: function() {
2048                         self.drawCopies(liId, true /* force_fetch */);
2049                         openils.Util.hide("acq-lit-update-copies-progress");
2050                     }
2051                 }
2052             );
2053         }
2054
2055         var dfa_list = this._virtDfaCountsAsList();
2056         if (dfa_list.length > 0) {
2057             fieldmapper.standardRequest(
2058                 ["open-ils.acq",
2059                 "open-ils.acq.distribution_formula.record_application"],
2060                 {
2061                     "async": true,
2062                     "params": [openils.User.authtoken, dfa_list, liId],
2063                     "onresponse": function(r) {
2064                         var res = openils.Util.readResponse(r);
2065                         if (res && res.length < dfa_list.length)
2066                             alert(localeStrings.DFA_NOT_ALL);
2067                     }
2068                 }
2069             );
2070             this.virtDfaCounts = {};
2071         }
2072     }
2073
2074     this._updateCreatePoPrepayCheckbox = function(prepay) {
2075         var prepay = openils.Util.isTrue(prepay);
2076         this._prepayRequiredByVendor = prepay;
2077         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2078     };
2079
2080     this._confirmPoPrepaySituation = function() {
2081         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2082         if (want_prepay != this._prepayRequiredByVendor) {
2083             return confirm(
2084                 want_prepay ?
2085                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2086                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2087             );
2088         } else {
2089             return true;
2090         }
2091     };
2092
2093     this.applySelectedLiAction = function(action) {
2094         var self = this;
2095         switch(action) {
2096
2097             case 'delete_selected':
2098                 this._deleteLiList(self.getSelected());
2099                 break;
2100
2101             case 'create_order':
2102                 this._loadPOSelect();
2103                 acqLitPoCreateDialog.show();
2104                 break;
2105
2106             case 'save_picklist':
2107                 acqLitSavePlDialog.show();
2108                 break;
2109
2110             case 'selector_ready':
2111             case 'order_ready':
2112                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2113                 acqLitChangeLiStateDialog.show();
2114                 break;
2115
2116             case 'print_po':
2117                 this.printPO();
2118                 break;
2119
2120             case 'po_history':
2121                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2122                 break;
2123
2124             case 'batch_create_invoice':
2125                 this.batchCreateInvoice();
2126                 break;
2127
2128             case 'batch_link_invoice':
2129                 this.batchLinkInvoice();
2130                 break;
2131
2132             case 'receive_po':
2133                 this.receivePO();
2134                 break;
2135
2136             case 'rollback_receive_po':
2137                 this.rollbackPoReceive();
2138                 break;
2139
2140             case 'create_assets':
2141                 this.showAssetCreator();
2142                 break;
2143
2144             case 'export_attr_list':
2145                 this.chooseExportAttr();
2146                 break;
2147
2148             case 'batch_apply_funds':
2149                 this.applyBatchLiFunds();
2150                 break;
2151
2152             case 'add_brief_record':
2153                 if(this.isPO)
2154                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2155                 else
2156                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2157
2158                 break;
2159
2160             case "cancel_lineitems":
2161                 this.maybeCancelLineitems();
2162                 break;
2163
2164             case "change_claim_policy":
2165                 var li_list = this.getSelected();
2166                 this.claimPolicyPicker.attr("value", null);
2167                 liClaimPolicyDialog.show();
2168                 liClaimPolicySave.onClick = function() {
2169                     self.changeClaimPolicy(
2170                         li_list,
2171                         self.claimPolicyPicker.attr("value"),
2172                         function() {
2173                             li_list.forEach(
2174                                 function(li) {
2175                                     self.setClaimPolicyControl(li);
2176                                     self.reconsiderClaimControl(li);
2177                                 }
2178                             );
2179                             liClaimPolicyDialog.hide();
2180                         }
2181                     )
2182                 };
2183                 break;
2184         }
2185     };
2186
2187     this.changeClaimPolicy = function(li_list, value, callback) {
2188         li_list.forEach(
2189             function(li) { li.claim_policy(value); }
2190         );
2191         fieldmapper.standardRequest(
2192             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2193                 "params": [openils.User.authtoken, li_list],
2194                 "async": true,
2195                 "oncomplete": function(r) {
2196                     r = openils.Util.readResponse(r);
2197                     if (callback) callback(r);
2198                 }
2199             }
2200         );
2201     };
2202
2203     this.showAssetCreator = function(onAssetsCreated) {
2204         if(!this.isPO) return;
2205         var self = this;
2206     
2207         // first, let's see if this PO has any LI's that need to be merged/imported
2208         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2209             id_list : true,
2210             oncomplete : function(r) {
2211                 var resp = openils.Util.readResponse(r);
2212                 if (resp && resp.length) {
2213                     // PO has some non-linked jubs.  
2214                     
2215                     self.show('asset-creator');
2216                     if(!self.vlAgent.loaded)
2217                         self.vlAgent.init();
2218
2219                     dojo.connect(assetCreatorButton, 'onClick', 
2220                         function() { self.createAssets(onAssetsCreated) });
2221
2222                 } else {
2223
2224                     // all jubs linked, move on to asset creation
2225                     self.createAssets(onAssetsCreated, true); 
2226                 }
2227             }
2228         });
2229     }
2230
2231     this.createAssets = function(onAssetsCreated, noVl) {
2232         this.show('acq-lit-progress-numbers');
2233         var self = this;
2234         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2235         fieldmapper.standardRequest(
2236             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2237             {   async: true,
2238                 params: [this.authtoken, this.isPO, vlArgs],
2239                 onresponse: function(r) {
2240                     var resp = openils.Util.readResponse(r);
2241                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2242                 }
2243             }
2244         );
2245     }
2246
2247     this.maybeCancelLineitems = function() {
2248         openils.Util.show("acq-lit-cancel-reason", "inline");
2249         if (!acqLitCancelLineitemsButton._prepared) {
2250             var widget = new openils.widget.AutoFieldWidget({
2251                 "fmField": "cancel_reason",
2252                 "fmClass": "jub",
2253                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2254                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2255                 "forceSync": true
2256             });
2257             widget.build(
2258                 function(w, ww) {
2259                     acqLitCancelLineitemsButton.onClick = function() {
2260                         if (w.attr("value")) {
2261                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2262                                 self._cancelLineitems(w.attr("value"));
2263                             }
2264                             openils.Util.hide("acq-lit-cancel-reason");
2265                         }
2266                     };
2267                     acqLitCancelLineitemsButton._prepared = true;
2268                 }
2269             );
2270         }
2271     };
2272
2273     this._cancelLineitems = function(reason) {
2274         var id_list = this.getSelected().map(function(o) { return o.id(); });
2275         fieldmapper.standardRequest(
2276             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2277                 "params": [openils.User.authtoken, id_list, reason],
2278                 "async": true,
2279                 "onresponse": function(r) {
2280                     if (r = openils.Util.readResponse(r)) {
2281                         if (r.li) {
2282                             for (var id in r.li) {
2283                                 self.liCache[id].state(r.li[id].state);
2284                                 self.liCache[id].cancel_reason(
2285                                     r.li[id].cancel_reason
2286                                 );
2287                                 self.updateLiState(self.liCache[id]);
2288                             }
2289                         }
2290                         if (r.lid && self.copyCache) {
2291                             for (var id in r.lid) {
2292                                 if (self.copyCache[id]) {
2293                                     self.copyCache[id].cancel_reason(
2294                                         r.lid[id].cancel_reason
2295                                     );
2296                                     self.updateLidState(self.copyCache[id]);
2297                                 }
2298                             }
2299                         }
2300                     }
2301                 }
2302             }
2303         );
2304     };
2305
2306     this.chooseExportAttr = function() {
2307         if (!acqLitExportAttrSelector._li_setup) {
2308             var self = this;
2309             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2310                 {
2311                     "data": acqlimad.toStoreData(
2312                         this.pcrud.search(
2313                             "acqlimad", {"code": li_exportable_attrs}
2314                         )
2315                     )
2316                 }
2317             );
2318             acqLitExportAttrSelector.setValue();
2319             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2320             acqLitExportAttrSelector._li_setup = true;
2321         }
2322         openils.Util.show("acq-lit-export-attr-holder", "inline");
2323     };
2324
2325     this.exportAttrList = function() {
2326         var attr_def = acqLitExportAttrSelector.item;
2327         var li_list = this.getSelected();
2328         var value_list = li_list.map(
2329             function(li) {
2330                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2331                     attr_def.code, "lineitem_marc_attr_definition"
2332                 );
2333             }
2334         ).filter(function(attr) { return Boolean(attr); });
2335
2336         if (value_list.length > 0) {
2337             if (value_list.length < li_list.length) {
2338                 if (!confirm(
2339                     dojo.string.substitute(
2340                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2341                     )
2342                 )) {
2343                     return;
2344                 }
2345             }
2346             try {
2347                 openils.XUL.contentToFileSaveDialog(
2348                     value_list.join("\n"),
2349                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2350                 );
2351             } catch (E) {
2352                 alert(E);
2353             }
2354         } else {
2355             alert(dojo.string.substitute(
2356                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2357             ));
2358         }
2359
2360         openils.Util.hide("acq-lit-export-attr-holder");
2361     };
2362
2363     this.printPO = function() {
2364         if(!this.isPO) return;
2365         progressDialog.show(true);
2366         fieldmapper.standardRequest(
2367             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2368             {   async: true,
2369                 params: [this.authtoken, this.isPO, 'html'],
2370                 oncomplete: function(r) {
2371                     progressDialog.hide();
2372                     var evt = openils.Util.readResponse(r);
2373                     if(evt && evt.template_output()) {
2374                         openils.Util.printHtmlString(evt.template_output().data());
2375                     }
2376                 }
2377             }
2378         );
2379     };
2380
2381     this.batchCreateInvoice = function() {
2382         var liIds = this.getSelected(false, null, true /* id_list */)
2383         if (!liIds.length) return;
2384         var path = oilsBasePath + '/acq/invoice/view?create=1';
2385         dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
2386         location.href = path;
2387     };
2388
2389     this.batchLinkInvoice = function(create) {
2390         var liIds = this.getSelected(false, null, true /* id_list */)
2391         if (!liIds.length) return;
2392         if (!self.invoiceLinkDialogManager) {
2393             self.invoiceLinkDialogManager =
2394                 new InvoiceLinkDialogManager("li");
2395         }
2396         self.invoiceLinkDialogManager.target = liIds;
2397         acqLitLinkInvoiceDialog.show();
2398     };
2399
2400     this.receivePO = function() {
2401         if (!this.isPO) return;
2402
2403         for (var id in this.liCache) {
2404             /* assumption: liCache reflects exactly the
2405              * set of LIs that belong to our PO */
2406             if (this.liCache[id].state() != "received" &&
2407                 !this.checkLiAlerts(id)) return;
2408         }
2409
2410         this.show('acq-lit-progress-numbers');
2411         var self = this;
2412         fieldmapper.standardRequest(
2413             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2414             {   async: true,
2415                 params: [this.authtoken, this.isPO],
2416                 onresponse : function(r) {
2417                     var resp = openils.Util.readResponse(r);
2418                     self._updateProgressNumbers(resp, true);
2419                 },
2420             }
2421         );
2422     }
2423
2424     this.issueReceive = function(obj, rollback) {
2425         var part =
2426             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2427         var method =
2428             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2429
2430         progressDialog.show(true);
2431         fieldmapper.standardRequest(
2432             ["open-ils.acq", method], {
2433                 "async": true,
2434                 "params": [this.authtoken, obj.id()],
2435                 "onresponse": function(r) {
2436                     if (r = openils.Util.readResponse(r)) {
2437                         self.fetchClaimInfo(
2438                             part == "lineitem" ? obj.id() : obj.lineitem(),
2439                             /* force */ true,
2440                             function() { self.handleReceive(r); }
2441                         );
2442                         progressDialog.hide();
2443                     }
2444                 }
2445             }
2446         );
2447     };
2448
2449     /**
2450      * Handles the responses from receive and rollback ML calls.
2451      */
2452     this.handleReceive = function(resp) {
2453         if (resp) {
2454             if (resp.li) {
2455                 for (var li_id in resp.li) {
2456                     for (var key in resp.li[li_id])
2457                         self.liCache[li_id][key](resp.li[li_id][key]);
2458                     self.updateLiState(self.liCache[li_id]);
2459                 }
2460             }
2461             if (resp.po) {
2462                 if (typeof(self.poUpdateCallback) == "function")
2463                     self.poUpdateCallback(resp.po);
2464             }
2465             if (resp.lid) {
2466                 for (var lid_id in resp.lid) {
2467                     for (var key in resp.lid[lid_id])
2468                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2469                     self.updateLidState(self.copyCache[lid_id]);
2470                 }
2471             }
2472         }
2473     };
2474
2475     this.rollbackPoReceive = function() {
2476         if(!this.isPO) return;
2477         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2478         this.show('acq-lit-progress-numbers');
2479         var self = this;
2480         fieldmapper.standardRequest(
2481             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2482             {   async: true,
2483                 params: [this.authtoken, this.isPO],
2484                 onresponse : function(r) {
2485                     var resp = openils.Util.readResponse(r);
2486                     self._updateProgressNumbers(resp, true);
2487                 },
2488             }
2489         );
2490     }
2491
2492     this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2493         this.vlAgent.handleResponse(resp,
2494             function(resp, res) {
2495                 if(reloadOnComplete)
2496                      location.href = location.href;
2497                 if (onComplete)
2498                     onComplete(resp, res);
2499             }
2500         );
2501     }
2502
2503
2504     this._createPO = function(fields) {
2505         var wantall = (fields.create_from == "all");
2506
2507         /* If we're a picklist or purchase order already and the user wants
2508          * all lineitems, we might have pages' worth of lineitems haven't all
2509          * been loaded yet, so getSelected() won't find them.  The server,
2510          * however, should know about all our lineitems, so let's ask the
2511          * server for a complete list.
2512          */
2513
2514         if (wantall) {
2515             this.getSelected(
2516                 true, function(list) {
2517                     self._createPOFromLineitems(fields, list);
2518                 }, /* id_list */ true
2519             );
2520         } else {
2521             this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2522         }
2523     };
2524
2525     this._createPOFromLineitems = function(fields, selected) {
2526         if (selected.length == 0) return;
2527         var self = this;
2528
2529         var po = new fieldmapper.acqpo();
2530         po.provider(this.createPoProviderSelector.attr("value"));
2531         po.ordering_agency(this.createPoAgencySelector.attr("value"));
2532         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2533
2534         // if we're creating assets, delay the asset creation 
2535         // until after the PO is created.  This will allow us to 
2536         // use showAssetCreator() directly.
2537
2538         fieldmapper.standardRequest(
2539             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2540             {   async: true,
2541                 params: [
2542                     openils.User.authtoken, 
2543                     po, {lineitems : selected}
2544                 ],
2545                 onresponse : function(r) {
2546                     var resp = openils.Util.readResponse(r);
2547                     if (resp.complete) {
2548                         // self.isPO is needed for showAssetCreator();
2549                         self.isPO = resp.purchase_order.id(); 
2550                         var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2551                         if (fields.create_assets[0]) {
2552                             self.showAssetCreator(
2553                                 function() {location.href = redir}
2554                             );
2555                         } else {
2556                            location.href = redir;
2557                         }
2558                     }
2559                 }
2560             }
2561         );
2562     };
2563
2564
2565     this.batchFundWidget = null;
2566
2567     this.applyBatchLiFunds = function() {
2568
2569         var liIds = this.getSelected().map(function(li) { return li.id(); });
2570         if(liIds.length == 0) return; // warn?
2571
2572         var self = this;
2573         batchFundUpdateDialog.show();
2574
2575         if(!this.batchFundWidget) {
2576             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2577                 fmClass : 'acqf',
2578                 selfReference : true,
2579                 labelFormat : fundLabelFormat,
2580                 searchFormat : fundSearchFormat,
2581                 searchFilter : {"active": "t"},
2582                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2583                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2584                 dijitArgs : { "required": true, "labelType": "html" },
2585                 forceSync : true
2586             });
2587             this.batchFundWidget.build();
2588         }
2589
2590         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2591         dojo.connect(batchFundUpdateSubmit, 'onClick', 
2592             function() { 
2593
2594                 // TODO: call .dry_run first to test thresholds
2595                 fieldmapper.standardRequest(
2596                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2597                     {
2598                         params : [
2599                             openils.User.authtoken, 
2600                             liIds,
2601                             self.batchFundWidget.widget.attr('value')
2602                         ],
2603                         oncomplete : function(r) {
2604                             var resp = openils.Util.readResponse(r);
2605                             if(resp) {
2606                                 location.href = location.href;
2607                             }
2608                         }
2609                     }
2610                 )
2611             }
2612         );
2613     }
2614
2615     this._deleteLiList = function(list, idx) {
2616         if(idx == null) idx = 0;
2617         if(idx >= list.length) return;
2618
2619         var li = list[idx];
2620         var liId = li.id();
2621
2622         if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2623             /* It makes little sense to delete a lineitem from a PO that has
2624              * already been marked 'on-order'.  Especially if EDI is in use,
2625              * such a purchase order will probably have already been shipped
2626              * off to a vendor, and mucking with it at this point could leave
2627              * your data in a bad state that doesn't jive with reality.
2628              *
2629              * I could see making this restriction even firmer.
2630              *
2631              * I could also see adjusting the li state comparisons, extending
2632              * the comparison to the PO's state, and/or providing functions
2633              * that house the logic for comparing states in a single location.
2634              *
2635              * Yes, this will be really annoying if you have selected a lot
2636              * of lineitems to cancel that have been ordered. You'll get a
2637              * confirm dialog for each one.
2638              */
2639
2640             if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2641                 self._deleteLiList(list, ++idx); /* move on to next in list */
2642                 return;
2643             }
2644         }
2645
2646         fieldmapper.standardRequest(
2647             ['open-ils.acq',
2648              this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2649             {   async: true,
2650                 params: [openils.User.authtoken, liId],
2651                 oncomplete: function(r) {
2652                     self.removeLineitem(liId);
2653                     self._deleteLiList(list, ++idx);
2654                 }
2655             }
2656         );
2657     }
2658
2659     this.editOrderMarc = function(li) {
2660
2661         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
2662             to true in about:config */
2663
2664         if(openils.XUL.isXUL()) {
2665             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
2666         } else {
2667             win = window.open('/xul/server/cat/marcedit.xul','','chrome'); 
2668         }
2669         var self = this;
2670         win.xulG = {
2671             record : {marc : li.marc(), "rtype": "bre"},
2672             save : {
2673                 label: 'Save Record', // XXX I18N
2674                 func: function(xmlString) {
2675                     li.marc(xmlString);
2676                     fieldmapper.standardRequest(
2677                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2678                         {   async: true,
2679                             params: [openils.User.authtoken, li],
2680                             oncomplete: function(r) {
2681                                 openils.Util.readResponse(r);
2682                                 win.close();
2683                                 self.drawInfo(li.id())
2684                             }
2685                         }
2686                     );
2687                 },
2688             },
2689             'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2690             'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2691         };
2692     }
2693
2694     this._savePl = function(values) {
2695         this.getSelected(
2696             (values.which == 'all'),
2697             function(list) { self._savePlFromLineitems(values, list); }
2698         );
2699     };
2700
2701     this._savePlFromLineitems = function(values, selected) {
2702         openils.Util.show("acq-lit-generic-progress");
2703
2704         if(values.new_name) {
2705             openils.acq.Picklist.create(
2706                 {name: values.new_name},
2707                 function(id) {
2708                     self._updateLiList(
2709                         id, selected, 0,
2710                         function() {
2711                             location.href =
2712                                 oilsBasePath + "/acq/picklist/view/" + id;
2713                         }
2714                     );
2715                 }
2716             );
2717         } else if(values.existing_pl) {
2718             // update lineitems to use an existing picklist
2719             self._updateLiList(
2720                 values.existing_pl, selected, 0,
2721                 function(){
2722                     location.href =
2723                         oilsBasePath + "/acq/picklist/view/" +
2724                         values.existing_pl;
2725                 }
2726             );
2727         }
2728     };
2729
2730     this._updateLiState = function(values, state) {
2731         progressDialog.show(true);
2732         this.getSelected(
2733             (values.which == 'all'),
2734             function(list) {
2735                 self._updateLiStateFromLineitems(values, state, list);
2736             }
2737         );
2738     };
2739
2740     this._updateLiStateFromLineitems = function(values, state, selected) {
2741         if(!selected.length) return;
2742         dojo.forEach(selected, function(li) {li.state(state);});
2743         self._updateLiList(null, selected, 0,
2744             // TODO consider inline updates for efficiency
2745             function() { location.href = location.href }
2746         );
2747     };
2748
2749     this._updateLiList = function(pl, list, idx, oncomplete) {
2750         if(idx >= list.length) return oncomplete();
2751         var li = list[idx];
2752         if(pl != null) li.picklist(pl);
2753         litGenericProgress.update({maximum: list.length, progress: idx});
2754         new openils.acq.Lineitem({lineitem:li}).update(
2755             function(r) {
2756                 self._updateLiList(pl, list, ++idx, oncomplete);
2757             }
2758         );
2759     }
2760
2761     this._loadPOSelect = function() {
2762         if (!this.createPoProviderSelector) {
2763             var widget = new openils.widget.AutoFieldWidget({
2764                 "fmField": "provider",
2765                 "fmClass": "acqpo",
2766                 "searchFilter": {"active": "t"},
2767                 "parentNode": dojo.byId("acq-lit-po-provider"),
2768                 "dijitArgs": {
2769                     "onChange": function() {
2770                         if (this.item) {
2771                             self._updateCreatePoPrepayCheckbox(
2772                                 this.item.prepayment_required()
2773                             );
2774                         }
2775                     }
2776                 }
2777             });
2778             widget.build(function(w) { self.createPoProviderSelector = w; });
2779         }
2780
2781         if (!this.createPoAgencySelector) {
2782             var widget = new openils.widget.AutoFieldWidget({
2783                 "fmField": "ordering_agency",
2784                 "fmClass": "acqpo",
2785                 "parentNode": dojo.byId("acq-lit-po-agency"),
2786                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2787             });
2788             widget.build(function(w) { self.createPoAgencySelector = w; });
2789         }
2790     };
2791
2792     this.showRealCopyEditUI = function(li) {
2793         copyList = [];
2794         var self = this;
2795         this.volCache = {};
2796
2797         this._fetchLineitem(li.id(), 
2798             function(fullLi) {
2799                 li = self.liCache[li.id()] = fullLi;
2800
2801                 self.pcrud.search(
2802                     'acp', {
2803                         id : li.lineitem_details().map(
2804                             function(item) { return item.eg_copy_id() }
2805                         )
2806                     }, {
2807                         async : true,
2808                         oncomplete : function(r) {
2809                             try {
2810                                 var r_list = openils.Util.readResponse( r );
2811                                 for (var i = 0; i < r_list.length; i++) {
2812                                     var copy = r_list[i];
2813                                     var volId = copy.call_number();
2814                                     var volume = self.volCache[volId];
2815                                     if(!volume) {
2816                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2817                                     }
2818                                     copy.call_number(volume);
2819                                     copyList.push(copy);
2820                                 }
2821                                 if (xulG) {
2822                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2823                                 }
2824                             } catch(E) {
2825                                 alert('error in oncomplete: ' + E);
2826                             }
2827                         }
2828                     }
2829                 );
2830             }
2831         );
2832     },
2833
2834     this.drawBibFinder = function(li) {
2835
2836         var query = '';
2837         var liWrapper = new openils.acq.Lineitem({lineitem:li});
2838
2839         dojo.forEach(
2840             ['isbn', 'upc', 'issn', 'title', 'author'],
2841             function(field) {
2842                 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2843                 if(val) {
2844                     if(field == 'title' || field == 'author') {
2845                         query += field +':' + val + ' ';
2846                     } else {
2847                         query += 'identifier|' + field + ':' + val + ' ';
2848                     }
2849                 }
2850             }
2851         );
2852
2853         win = window.open(
2854             oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2855             '', 'resizable,scrollbars=1,chrome');
2856
2857         win.window.recordFound = function(bibId) { 
2858             win.close();
2859
2860             var attrs = li.attributes();
2861             li.attributes(null);
2862             li.eg_bib_id(bibId);
2863
2864             fieldmapper.standardRequest(
2865                 ["open-ils.acq", "open-ils.acq.lineitem.update"], 
2866                 {
2867                     "params": [openils.User.authtoken, li],
2868                     "async": true,
2869                     "oncomplete": function(r) {
2870                         if(openils.Util.readResponse(r)) {
2871                             location.href = location.href;
2872                         }
2873                     }
2874                 }
2875             );
2876         }
2877     }
2878 }
2879