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