]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
Merge remote branch 'working/user/dbwells/shared_siss_editor'
[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", {"id": {"!=": null}}
695                     )
696                 )
697             }
698         );
699         acqLitAlertAlertText.setValue(); /* make the store "live" */
700         acqLitAlertAlertText._store_ready = true;
701     };
702
703     /**
704      * Draws and shows the lineitem notes pane
705      */
706     this.drawLiNotes = function(li) {
707         var self = this;
708
709         if (!acqLitAlertAlertText._store_ready)
710             this._setAlertStore();
711
712         li.lineitem_notes(
713             li.lineitem_notes().sort(
714                 function(a, b) { 
715                     if(a.edit_time() < b.edit_time()) return 1;
716                     return -1;
717                 }
718             )
719         );
720
721         while(this.liNotesTbody.childNodes[0])
722             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
723         this.show('notes');
724
725         acqLitCreateNoteSubmit.onClick = function() {
726             var value = acqLitCreateNoteText.attr('value');
727             if(!value) return;
728             var note = new fieldmapper.acqlin();
729             note.isnew(true);
730             note.vendor_public(
731                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
732             );
733             note.value(value);
734             note.lineitem(li.id());
735
736             self.updateLiNotes(li, note);
737             acqLitCreateNoteVendorPublic.attr("checked", false);
738             acqLitCreateNoteText.attr("value", "");
739         }
740
741         acqLitCreateAlertSubmit.onClick = function() {
742             if (!acqLitAlertAlertText.item) {
743                 alert(localeStrings.ALERT_UNSELECTED);
744                 return;
745             }
746
747             var alert_text = new fieldmapper.acqliat().fromStoreItem(
748                 acqLitAlertAlertText.item
749             );
750             var value = acqLitAlertNoteValue.attr("value") || "";
751
752             var note = new fieldmapper.acqlin();
753             note.isnew(true);
754             note.lineitem(li.id());
755             note.value(value);
756             note.alert_text(alert_text);
757
758             self.updateLiNotes(li, note);
759         }
760
761         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
762     }
763
764     /**
765      * Draws a single lineitem note in the notes pane
766      */
767     this.addLiNote = function(li, note) {
768         if(note.isdeleted()) return;
769         var self = this;
770         var row = self.liNotesRow.cloneNode(true);
771         nodeByName("value", row).innerHTML = note.value();
772         var alert_node = nodeByName("alert_code", row);
773         if (note.alert_text()) {
774             alert_node.innerHTML = note.alert_text().code();
775             if (note.alert_text().description()) {
776                 new dijit.Tooltip(
777                     {
778                         "connectId": [alert_node],
779                         "label": note.alert_text().description()
780                     }, dojo.create("span", null, alert_node, "after")
781                 );
782             }
783         }
784
785         if (openils.Util.isTrue(note.vendor_public()))
786             nodeByName("vendor_public", row).innerHTML =
787                 localeStrings.VENDOR_PUBLIC;
788
789         nodeByName("delete", row).onclick = function() {
790             note.isdeleted(true);
791             self.liNotesTbody.removeChild(row);
792             self.updateLiNotes(li);
793         };
794
795         if(note.edit_time()) {
796             nodeByName("edit_time", row).innerHTML =
797                 dojo.date.locale.format(
798                     dojo.date.stamp.fromISOString(note.edit_time()), 
799                     {formatLength:'short'});
800         }
801
802         self.liNotesTbody.appendChild(row);
803     }
804
805     /**
806      * Updates any new/changed/deleted notes on the server
807      */
808     this.updateLiNotes = function(li, newNote) {
809
810         var notes;
811         if(newNote) {
812             notes = [newNote];
813         } else {
814             notes = li.lineitem_notes().filter(
815                 function(note) {
816                     if(note.ischanged() || note.isnew() || note.isdeleted())
817                         return note;
818                 }
819             );
820         }
821
822         if(notes.length == 0) return;
823         progressDialog.show();
824
825         fieldmapper.standardRequest(
826             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
827             {   async : true,
828                 params : [this.authtoken, notes],
829                 onresponse : function(r) {
830                     var resp = openils.Util.readResponse(r);
831
832                     if(resp.complete) {
833
834                         if(!newNote) {
835                             // remove the old changed notes
836                             var list = [];
837                             dojo.forEach(li.lineitem_notes(), 
838                                 function(note) {
839                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
840                                         list.push(note);
841                                 }
842                             );
843                             li.lineitem_notes(list);
844                         }
845
846                         progressDialog.hide();
847                         self.updateLiNotesCount(li);
848                         self.drawLiNotes(li);
849                         return;
850                     }
851
852                     progressDialog.update(resp);
853                     var newnote = resp.note;
854
855                     if(!newnote.isdeleted()) {
856                         newnote.isnew(false);
857                         newnote.ischanged(false);
858                         li.lineitem_notes().push(newnote);
859                     }
860                 },
861             }
862         );
863     }
864
865     this.updateLiPrice = function(input, li) {
866         var self = this;
867         var price = input.value;
868         if(Number(price) == Number(li.estimated_unit_price())) return;
869
870         fieldmapper.standardRequest(
871             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
872             {   async : false, // redundant w/ timeout
873                 timeout : 10,
874                 params : [this.authtoken, li.id(), price],
875                 oncomplete : function(r) {
876                     openils.Util.readResponse(r);
877                     li.estimated_unit_price(price); // update local copy
878
879                     /*
880                      * If this is a PO and every visible lineitem has a price,
881                      * check again to see if this PO can be activated.  Note that 
882                      * every visible lineitem having a price does not guarantee it can
883                      * be activated, which is why we still make the call.  Having a price
884                      * set for every visiable lineitem is just the lowest barrier to entry.
885                      */
886                     if (self.isPO) {
887                         var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
888                         var allSet = true;
889                         dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
890                         if (allSet) checkCouldActivatePo();
891                     }
892                 }
893             }
894         );
895     }
896
897     this.removeLineitem = function(liId) {
898         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
899         delete this.liCache[liId];
900         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
901     }
902
903     this.drawInfo = function(liId) {
904         if (!this._isRelatedViewer) {
905             var d = dojo.byId("acq-lit-info-related");
906             if (!this.relCache[liId]) {
907                 fieldmapper.standardRequest(
908                     [
909                         "open-ils.acq",
910                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
911                     ], {
912                         "async": true,
913                         "params": [openils.User.authtoken, liId],
914                         "onresponse": function(r) {
915                             self.relCache[liId] = openils.Util.readResponse(r);
916                             nodeByName("related_number", d).innerHTML =
917                                 self.relCache[liId];
918                             openils.Util[
919                                 self.relCache[liId] >1 ? "show" : "hide"
920                             ](d);
921                         }
922                     }
923                 );
924             } else {
925                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
926                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
927             }
928         }
929
930         this.show('info');
931         openils.acq.Lineitem.fetchAttrDefs(
932             function() { 
933                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
934             } 
935         );
936     };
937
938     /* For a given list of lineitem ids, build a list of full lineitems
939      * re-using the fetching logic that is otherwise typical to use in this
940      * module.
941      *
942      * If we've already got a lineitem in the cache, just use that.
943      *
944      * Once we've built a list of lineitems, call callback(thatlist).
945      */
946     this.fetchLineitemsById = function(id_list, callback) {
947         var total = id_list.length;
948         var result_list = [];
949
950         var inner = function(li) {
951             result_list.push(li)
952             if (--total <= 0)
953                 callback(result_list);
954         };
955
956         id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
957     };
958
959     this._fetchLineitem = function(liId, handler, force) {
960
961         var li = this.liCache[liId];
962         if(li && li.marc() && li.lineitem_details() && !force)
963             return handler(li);
964         
965         fieldmapper.standardRequest(
966             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
967             {   async: true,
968
969                 params: [self.authtoken, liId, {
970                     flesh_attrs: true,
971                     flesh_cancel_reason: true,
972                     flesh_li_details: true,
973                     flesh_notes: true,
974                     flesh_fund_debit: true }],
975
976                 oncomplete: function(r) {
977                     var li = openils.Util.readResponse(r);
978                     self.liCache[liId] = li;
979                     handler(li)
980                 }
981             }
982         );
983     };
984
985     this._drawInfo = function(li) {
986
987         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
988
989         if(li.eg_bib_id()) {
990             openils.Util.hide('acq-lit-marc-order-record-label');
991             openils.Util.hide(acqLitEditOrderMarc.domNode);
992             openils.Util.show('acq-lit-marc-real-record-label');
993         } else {
994             openils.Util.show('acq-lit-marc-order-record-label');
995             openils.Util.show(acqLitEditOrderMarc.domNode);
996             openils.Util.hide('acq-lit-marc-real-record-label');
997         }
998
999         this.drawMarcHTML(li);
1000         this.infoTbody = dojo.byId('acq-lit-info-tbody');
1001
1002         if(!this.infoRow)
1003             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1004         while(this.infoTbody.childNodes[0])
1005             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1006
1007         for(var i = 0; i < li.attributes().length; i++) {
1008             var attr = li.attributes()[i];
1009             var row = this.infoRow.cloneNode(true);
1010
1011             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1012             var name = openils.acq.Lineitem.attrDefs[type].filter(
1013                 function(a) {
1014                     return (a.code() == attr.attr_name());
1015                 }
1016             ).pop().description();
1017
1018             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1019             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1020             this.infoTbody.appendChild(row);
1021         }
1022
1023         if (!this._isRelatedViewer) {
1024             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1025                 oilsBasePath + "/acq/lineitem/related/" + li.id();
1026         }
1027
1028     };
1029
1030     this.generateMakeRecTab = function(bib_id,default_view, row) {
1031         return function() {
1032             xulG.new_tab(
1033                 XUL_OPAC_WRAPPER,
1034                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1035                 {
1036                     no_xulG : false, 
1037                     show_nav_buttons : true, 
1038                     show_print_button : true, 
1039                     opac_url : xulG.url_prefix(xulG.urls.opac_rdetail + bib_id),
1040                     default_view : default_view
1041                 }
1042             );
1043
1044             if(row) nodeByName("action_none", row).selected = true;
1045         }
1046     };
1047
1048     this.drawMarcHTML = function(li) {
1049         var params = [null, true, li.marc()];
1050         if(li.eg_bib_id()) 
1051             params = [li.eg_bib_id(), true];
1052
1053         fieldmapper.standardRequest(
1054             ['open-ils.search', 'open-ils.search.biblio.record.html'],
1055             {   async: true,
1056                 params: params,
1057                 oncomplete: function(r) {
1058                     dojo.byId('acq-lit-marc-div').innerHTML = 
1059                         openils.Util.readResponse(r);
1060                 }
1061             }
1062         );
1063     }
1064
1065     this.drawCopies = function(liId, force_fetch) {
1066         if (typeof force_fetch == "undefined")
1067             force_fetch = false;
1068
1069         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1070             function(li, html) {
1071                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1072             }
1073         );
1074
1075         this.show('copies');
1076         var self = this;
1077         this.copyCache = {};
1078         this.copyWidgetCache = {};
1079         this.oldCopyWidgetCache = {};
1080         this.virtDfaCounts = {};
1081         this.realDfaCache = {};
1082         this.dfeOffset = 0;
1083
1084         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1085         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1086         acqLitCopyCountInput.attr('value', '0');
1087
1088         while(this.copyTbody.childNodes[0])
1089             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1090
1091         this._drawBatchCopyWidgets();
1092
1093         this._drawDistribApplied(liId);
1094
1095         this._fetchDistribFormulas(
1096             function() {
1097                 openils.acq.Lineitem.fetchAttrDefs(
1098                     function() { 
1099                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1100                     } 
1101                 );
1102             }
1103         );
1104     };
1105
1106     this._saveDistribAppliedTemplates = function() {
1107         if (!this._appliedDistribTemplate) {
1108             this._appliedDistribTemplate =
1109                 dojo.byId("acq-lit-distrib-applied-tbody").
1110                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1111             dojo.attr(this._appliedDistribTemplate, "id");
1112         }
1113     };
1114
1115     this._drawDistribApplied = function(liId) {
1116         /* Build this table while hidden to prevent rendering artifacts */
1117         openils.Util.hide("acq-lit-distrib-applied-tbody");
1118
1119         this._saveDistribAppliedTemplates();
1120
1121         /* Remove any rows in the table from previous populations */
1122         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1123             forEach(dojo.destroy);
1124
1125         /* Unregister all dijits previously created (for some reason this isn't
1126          * covered by the above destroy calls). */
1127         dijit.registry.forEach(
1128             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1129         );
1130
1131         /* Populate the table with our liId */
1132         var total = 0;
1133         fieldmapper.standardRequest(
1134             ["open-ils.acq",
1135             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1136             {
1137                 "async": true,
1138                 "params": [self.authtoken, liId],
1139                 "onresponse": function(r) {
1140                     var dfa = openils.Util.readResponse(r);
1141                     if (dfa) {
1142                         total++;
1143                         self.realDfaCache[dfa.id()] = dfa;
1144                         self._drawDistribAppliedUnit(dfa);
1145                     }
1146                 },
1147                 "oncomplete": function() {
1148                     /* Reveal built table */
1149                     if (total) {
1150                         openils.Util.show(
1151                             "acq-lit-distrib-applied-tbody", "table-row-group"
1152                         );
1153                     }
1154                 }
1155             }
1156         );
1157     };
1158
1159     this._drawDistribAppliedUnit = function(dfa) {
1160         var new_row = false;
1161         var row = dojo.query(
1162             'tr[formula="' + dfa.formula().id() + '"]',
1163             "acq-lit-distrib-applied-tbody"
1164         )[0];
1165
1166         if (!row) {
1167             new_row = true;
1168             row = dojo.clone(this._appliedDistribTemplate);
1169             dojo.attr(row, "formula", dfa.formula().id());
1170             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1171         }
1172
1173         var td = dojo.query("td", row)[0];
1174
1175         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1176         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1177
1178         if (new_row)
1179             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1180
1181         new dijit.form.Button(
1182             {
1183                 "onClick": function() {
1184                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1185                         self.deleteDfa(dfa);
1186                 },
1187                 "label": "X",
1188                 /* XXX I /cannot/ make the following work in as a CSS class
1189                  * for some reason. So frustrating... */
1190                 "style": function(id) {
1191                      return (id > 0 ?
1192                         "font-weight: bold; color: #c00;" :
1193                         "color: #666;");
1194                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1195             }, "dfa-button-" + dfa.id()
1196         );
1197         new dijit.Tooltip(
1198             {
1199                 "connectId": ["dfa-button-" + dfa.id()],
1200                 "label": dojo.string.substitute(
1201                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1202                         openils.User.formalName(dfa.creator()),
1203                         dojo.date.locale.format(
1204                             dojo.date.stamp.fromISOString(dfa.create_time()),
1205                             {"formatLength":"short"}
1206                         )
1207                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1208                 )
1209             }, "dfa-tip-" + dfa.id()
1210         );
1211     }
1212
1213     this.deleteDfa = function(dfa) {
1214         if (dfa.id() > 0) { /* real */
1215             this.pcrud.eliminate(
1216                 dfa, {
1217                     "async": true,
1218                     "oncomplete": function() {
1219                         self._removeDistribApplied(dfa.id());
1220                         delete self.realDfaCache[dfa.id()];
1221                     }
1222                 }
1223             );
1224         } else { /* virtual */
1225             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1226             this.virtDfaCounts[dfa.formula().id()] = 0;
1227             /* hasn't been saved yet, so no need to do anything server side */
1228             this._removeDistribApplied(dfa.id());
1229         }
1230
1231     };
1232
1233     this._removeDistribApplied = function(dfaId) {
1234         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1235         dijit.registry.forEach(
1236             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1237         );
1238         this._removeDistribAppliedEmptyRows();
1239     };
1240
1241     this._removeAllDistribAppliedVirtual = function() {
1242         /* Unregister dijits */
1243         dijit.registry.forEach(
1244             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1245         );
1246         this._removeDistribAppliedEmptyRows();
1247     };
1248
1249     this._removeDistribAppliedEmptyRows = function() {
1250         /* Remove any rows with no DFA at all */
1251         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1252             function(o) {
1253                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1254             }
1255         );
1256     };
1257
1258     /**
1259      * Insert a new row into the distribution formula selection form
1260      */
1261     this._addDistribFormulaRow = function() {
1262         var self = this;
1263
1264         if (!self.distribForms) {
1265             // no formulas, hide the form
1266             openils.Util.hide('acq-lit-distrib-formula-table');
1267             return;
1268         }
1269
1270         if(!this.distribFormulaTemplate) 
1271             this.distribFormulaTemplate = 
1272                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1273
1274         var row = this.distribFormulaTemplate.cloneNode(true);
1275         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
1276
1277         this.dfSelector = new dijit.form.FilteringSelect(
1278             {"labelAttr": "dynLabel", "labelType": "html"},
1279             nodeByName("selector", row)
1280         );
1281         this._updateFormulaStore();
1282         this.dfSelector.fetchProperties =
1283             {"sort": [{"attribute": "use_count", "descending": true}]};
1284
1285         var apply = new dijit.form.Button(
1286             {"label": localeStrings.APPLY},
1287             nodeByName('set_button', row)
1288         ); 
1289
1290         var reset = new dijit.form.Button(
1291             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
1292             nodeByName("reset_button", row)  
1293         );
1294
1295         dojo.connect(apply, 'onClick', 
1296             function() {
1297                 var form_id = self.dfSelector.attr("value");
1298                 if(!form_id) return;
1299                 self._applyDistribFormula(form_id);
1300                 reset.attr("disabled", false);
1301             }
1302         );
1303
1304         dojo.connect(reset, 'onClick', 
1305             function() {
1306                 self.restoreCopyFieldsBeforeDF();
1307                 self.virtDfaCounts = {};
1308                 self.virtDfaId = -1;
1309                 self.dfeOffset = 0;
1310                 self._updateFormulaStore();
1311                 self._removeAllDistribAppliedVirtual();
1312                 reset.attr("disabled", "true");
1313             }
1314         );
1315
1316     };
1317
1318     /**
1319      * Applies a distrib formula to the current set of copies
1320      */
1321     this._applyDistribFormula = function(formula) {
1322         if(!formula) return;
1323
1324         formula = this.distribForms.filter(
1325             function(form) { return form.id() == formula; }
1326         )[0];
1327
1328         var copyRows = dojo.query('tr', self.copyTbody);
1329
1330         if (this.dfeOffset >= copyRows.length) {
1331             alert(localeStrings.OUT_OF_COPIES);
1332             return;
1333         }
1334
1335         var entries_applied = 0;
1336         for(
1337             var rowIndex = this.dfeOffset;
1338             rowIndex < copyRows.length;
1339             rowIndex++
1340         ) {
1341             
1342             var row = copyRows[rowIndex];
1343             var copy_id = row.getAttribute('copy_id');
1344             var copyWidgets = this.copyWidgetCache[copy_id];
1345             var entryIndex = this.dfeOffset;
1346             var entry = null;
1347
1348             // find the correct entry for the current row
1349             dojo.forEach(formula.entries(), 
1350                 function(e) {
1351                     if(!entry) {
1352                         entryIndex += e.item_count();
1353                         if(entryIndex > rowIndex)
1354                             entry = e;
1355                     }
1356                 }
1357             );
1358
1359             if(entry) {
1360                 
1361                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
1362                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
1363     
1364                 entries_applied++;
1365                 this.saveCopyFieldsBeforeDF(copy_id);
1366                 this._copy_fields_for_acqdf.forEach(
1367                     function(field) {
1368                         if(entry[field]()) {
1369                             copyWidgets[field].attr('value', (entry[field]()));
1370                         }
1371                     }
1372                 );
1373             }
1374         }
1375
1376         if (entries_applied) {
1377             this.virtDfaCounts[formula.id()] =
1378                 ++(this.virtDfaCounts[formula.id()]) || 1;
1379             this._updateFormulaStore();
1380             this._drawDistribAppliedUnit(
1381                 function(df) {
1382                     var dfa = new acqdfa();
1383                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
1384                 }(formula)
1385             );
1386             this.dfeOffset += entries_applied;
1387         };
1388     };
1389
1390     /**
1391      * This function updates the DF store for the dropdown so that use_counts
1392      * can reflect DF applications from this session before they're saved
1393      * server-side.
1394      */
1395     this._updateFormulaStore = function() {
1396         this.dfSelector.store = new dojo.data.ItemFileReadStore(
1397             {
1398                 "data": self._labelFormulasWithCounts(
1399                     acqdf.toStoreData(self.distribForms)
1400                 )
1401             }
1402         );
1403     };
1404
1405     this.saveCopyFieldsBeforeDF = function(copy_id) {
1406         var self = this;
1407         if (!this.oldCopyWidgetCache[copy_id]) {
1408             var copyWidgets = this.copyWidgetCache[copy_id];
1409
1410             this.oldCopyWidgetCache[copy_id] = {};
1411             this._copy_fields_for_acqdf.forEach(
1412                 function(f) {
1413                     self.oldCopyWidgetCache[copy_id][f] =
1414                         copyWidgets[f].attr("value");
1415                 }
1416             );
1417         }
1418     };
1419
1420     this.restoreCopyFieldsBeforeDF = function() {
1421         var self = this;
1422         for (var copy_id in this.oldCopyWidgetCache) {
1423             this._copy_fields_for_acqdf.forEach(
1424                 function(f) {
1425                     self.copyWidgetCache[copy_id][f].attr(
1426                         "value", self.oldCopyWidgetCache[copy_id][f]
1427                     );
1428                 }
1429             );
1430         }
1431     };
1432
1433     this._labelFormulasWithCounts = function(store_data) {
1434         for (var key in store_data.items) {
1435             var obj = store_data.items[key];
1436             obj.use_count = Number(obj.use_count); /* needed for sorting */
1437
1438             if (this.virtDfaCounts[obj.id])
1439                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
1440
1441             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
1442                 obj.use_count + "]</span>&nbsp; " + obj.name;
1443         }
1444         return store_data;
1445     };
1446
1447     /**
1448      * This method formerly would not refetch the DF formulas if they'd been
1449      * loaded already, but now it always re-fetches, since use_count changes.
1450      */
1451     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
1452     this._fetchDistribFormulas = function(onload) {
1453         fieldmapper.standardRequest(
1454             ["open-ils.acq",
1455                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
1456             {
1457                 "async": true,
1458                 "params": [openils.User.authtoken, 0, 500],
1459                 "oncomplete": function(r) {
1460                     self.distribForms = openils.Util.readResponse(r);
1461                     if(!self.distribForms || self.distribForms.length == 0) {
1462                         self.distribForms = [];
1463                     }
1464                     self._addDistribFormulaRow();
1465                     onload();
1466                 }
1467             }
1468         );
1469     }
1470
1471     this._drawBatchCopyWidgets = function() {
1472         var row = this.copyBatchRow;
1473         dojo.forEach(liDetailBatchFields, 
1474             function(field) {
1475                 if(self.copyBatchRowDrawn) {
1476                     self.copyBatchWidgets[field].attr('value', null);
1477                 } else {
1478                     var widget = new openils.widget.AutoFieldWidget({
1479                         fmField : field,
1480                         fmClass : 'acqlid',
1481                         labelFormat : (field == 'fund') ? fundLabelFormat : null,
1482                         searchFormat : (field == 'fund') ? fundSearchFormat : null,
1483                         searchFilter : (field == 'fund') ? {"active": "t"} : null,
1484                         parentNode : dojo.query('[name='+field+']', row)[0],
1485                         orgLimitPerms : ['CREATE_PICKLIST'],
1486                         dijitArgs : {
1487                             "required": false,
1488                             "labelType": (field == "fund") ? "html" : null
1489                         },
1490                         noCache: (field == "fund"),
1491                         forceSync : true
1492                     });
1493                     widget.build(
1494                         function(w, ww) {
1495                             if (field == "fund" && w.store)
1496                                 self._ensureCSSFundClasses(w.store);
1497                             self.copyBatchWidgets[field] = w;
1498                         }
1499                     );
1500                     if (field == "fund") {
1501                         dojo.connect(
1502                             widget.widget, "onChange", function(val) {
1503                                 self._updateFundSelectorStyle(widget, val);
1504                             }
1505                         );
1506                     }
1507                 }
1508             }
1509         );
1510         this.copyBatchRowDrawn = true;
1511     };
1512
1513     this.batchCopyUpdate = function() {
1514         var self = this;
1515         for(var k in this.copyWidgetCache) {
1516             var cache = this.copyWidgetCache[k];
1517             dojo.forEach(liDetailBatchFields, function(f) {
1518                 var newval = self.copyBatchWidgets[f].attr('value');
1519                 if(newval) cache[f].attr('value', newval);
1520             });
1521         }
1522     };
1523
1524     this._drawCopies = function(li) {
1525         var self = this;
1526
1527         // this button sets the total number of copies for a given lineitem
1528         acqLitAddCopyCount.onClick = function() { 
1529             var count = acqLitCopyCountInput.attr('value');
1530
1531             // add new rows
1532             while(self.copyCount() < count)
1533                 self.addCopy(li); 
1534             
1535             // delete rows if necessary
1536             var diff = self.copyCount() - count;
1537             if(diff > 0) {
1538                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
1539                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
1540                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
1541                 } else {
1542                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
1543                 }
1544             }
1545         }
1546
1547
1548         if(li.lineitem_details().length > 0) {
1549             dojo.forEach(li.lineitem_details(),
1550                 function(copy) {
1551                     self.addCopy(li, copy);
1552                 }
1553             );
1554         } else {
1555             self.addCopy(li);
1556         }
1557     };
1558
1559     this.copyCount = function() {
1560         var count = 0;
1561         for(var id in this.copyCache) {
1562             if(!this.copyCache[id].isdeleted())
1563                 count++;
1564         }
1565         return count;
1566     }
1567
1568     this.virtCopyId = -1;
1569     this.addCopy = function(li, copy) {
1570         var row = this.copyRow.cloneNode(true);
1571         this.copyTbody.appendChild(row);
1572         var self = this;
1573
1574         if(!copy) {
1575             copy = new fieldmapper.acqlid();
1576             copy.isnew(true);
1577             copy.id(this.virtCopyId--);
1578             copy.lineitem(li.id());
1579         }
1580
1581         this.copyCache[copy.id()] = copy;
1582         row.setAttribute('copy_id', copy.id());
1583         self.copyWidgetCache[copy.id()] = {};
1584
1585         acqLitCopyCountInput.attr('value', self.copyCount()+'');
1586
1587         var rcvr = copy.receiver();
1588         if (rcvr) {
1589             if (!userCache[rcvr]) {
1590                 if(rcvr == openils.User.user.id()) {
1591                     userCache[rcvr] = openils.User.user;
1592                 } else {
1593                     userCache[rcvr] = fieldmapper.standardRequest(
1594                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
1595                         {params: [openils.User.authtoken, rcvr]}
1596                     );
1597                 }
1598             }
1599             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
1600         }
1601
1602         dojo.forEach(liDetailFields,
1603             function(field) {
1604                 var searchFilter;
1605                 if (field == "fund") {
1606                     searchFilter = (copy.fund() ?
1607                         {"-or": {"active": "t", "id": copy.fund()}} :
1608                         {"active" : "t"});
1609                 } else {
1610                     searchFilter = null;
1611                 }
1612
1613                 var readOnly = false;
1614                 
1615                 // TODO: Add support for changing the owning_lib after real copies have been made.  
1616                 // owning_lib is order data as much as its item data
1617                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
1618                     readOnly = true;
1619                 }
1620
1621                 // TODO: add support for changing the fund after debits have been created
1622                 // Note: invoicing allows the change
1623                 if(copy.fund_debit() && field == 'fund') {
1624                     readOnly = true;
1625                 }
1626
1627
1628                 var widget = new openils.widget.AutoFieldWidget({
1629                     fmObject : copy,
1630                     fmField : field,
1631                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1632                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1633                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1634                     searchFilter : searchFilter,
1635                     noCache: (field == "fund"),
1636                     fmClass : 'acqlid',
1637                     parentNode : dojo.query('[name='+field+']', row)[0],
1638                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
1639                     readOnly : readOnly,
1640                     orgDefaultsToWs : true
1641                 });
1642
1643                 widget.build(
1644                     // make sure we capture the value from any async widgets
1645                     function(w, ww) { 
1646
1647                         if (field == "fund" && w.store)
1648                             self._ensureCSSFundClasses(w.store);
1649
1650                         if(!readOnly) 
1651                             copy[field](ww.getFormattedValue()) 
1652
1653                         self.copyWidgetCache[copy.id()][field] = w;
1654
1655                         dojo.connect(w, 'onChange', 
1656                             function(val) { 
1657                                 if (field == "fund")
1658                                     self._updateFundSelectorStyle(widget, val);
1659
1660                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
1661                                     // prevent setting ischanged() automatically on widget load for existing copies
1662                                     copy[field](widget.getFormattedValue()) 
1663                                     copy.ischanged(true);
1664                                 }
1665                             }
1666                         );
1667                     }
1668                 );
1669             }
1670         );
1671
1672         this.updateLidState(copy, row);
1673     };
1674
1675     this._ensureCSSFundClass = function(id) {
1676         if (!this.fundStyleSheet) {
1677             dojo.create(
1678                 "style", {"type": "text/css"},
1679                 document.getElementsByTagName("head")[0], "last"
1680             );
1681             this.fundStyleSheet = document.styleSheets[
1682                 document.styleSheets.length - 1
1683             ];
1684         }
1685
1686         var cn = "fund_" + id;
1687         if (!this.haveFundClass[cn]) {
1688             fieldmapper.standardRequest(
1689                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
1690                 {
1691                     "params": [openils.User.authtoken, id],
1692                     "async": true,
1693                     "oncomplete": function(r) {
1694                         r = openils.Util.readResponse(r);
1695                         self.fundBalanceState[id] = r;
1696                         var style = "";
1697                         if (r[0] /* stop */)
1698                             style = fundStyles.stop;
1699                         else if (r[1] /* warning */)
1700                             style = fundStyles.warning;
1701                         self.fundStyleSheet.insertRule(
1702                             "." + cn + " { " + style + " }",
1703                             self.fundStyleSheet.cssRules.length
1704                         );
1705                         self.haveFundClass[cn] = true;
1706                     }
1707                 }
1708             );
1709         }
1710     };
1711
1712     this._ensureCSSFundClasses = function(store) {
1713         store.fetch({
1714             "query": {"id": "*"},
1715             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
1716         });
1717     };
1718
1719     this._updateFundSelectorStyle = function(widget, fund_id) {
1720         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
1721         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
1722     };
1723
1724     this.updateLidState = function(copy, row) {
1725         var self = this;
1726
1727         if (typeof(row) == "undefined") {
1728             row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
1729         }
1730
1731         // action links
1732         var recv_link = nodeByName("receive", row);
1733         var unrecv_link = nodeByName("unreceive", row);
1734         var del_link = nodeByName("delete", row);
1735         var cxl_link = nodeByName("cancel", row);
1736         var claim_link = nodeByName("claim", row);
1737         var cxl_reason_link = nodeByName("cancel_reason", row);
1738
1739         // by default, hide all the actions
1740         openils.Util.hide(del_link.parentNode);
1741         openils.Util.hide(recv_link);
1742         openils.Util.hide(unrecv_link);
1743         openils.Util.hide(cxl_link);
1744         openils.Util.hide(claim_link);
1745         openils.Util.hide(cxl_reason_link);
1746
1747         if (copy.id() > 0) { // real copies (LIDs)
1748
1749             if (copy.cancel_reason()) { 
1750
1751                 /* --------- cancelled -------------------------- */
1752
1753                 /* XXX the following may leak memory in a long lived table: 
1754                  * dijits may not get destroyed... not positive. revisit. */
1755                 var holds_reason = dojo.create(
1756                     "span", {
1757                         "style": "border-bottom: 1px dashed #000;",
1758                         "innerHTML": "Cancelled" /* XXX [sic] and i18n */
1759                     }, cxl_reason_link, "only"
1760                 );
1761                 new dijit.Tooltip(
1762                     {
1763                         "label": "<em>" + copy.cancel_reason().label() +
1764                             "</em><br />" + copy.cancel_reason().description(),
1765                         "connectId": [holds_reason]
1766                     }, dojo.create("span", null, cxl_reason_link, "last")
1767                 );
1768                 openils.Util.show(cxl_reason_link, "inline");
1769
1770             } else if (copy.recv_time()) { 
1771
1772                 /* --------- received -------------------------- */
1773
1774                 openils.Util.show(unrecv_link, "inline");
1775                 unrecv_link.onclick = function() {
1776                     if (confirm(localeStrings.UNRECEIVE_LID))
1777                         self.issueReceive(copy, /* rollback */ true);
1778                 };
1779
1780             } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
1781                 
1782                 /* --------- on order -------------------------- */
1783
1784                 openils.Util.show(recv_link, 'inline');
1785                 openils.Util.show(cxl_link, "inline");
1786
1787                 recv_link.onclick = function() {
1788                     if (self.checkLiAlerts(copy.lineitem()))
1789                         self.issueReceive(copy);
1790                 };
1791
1792                 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
1793
1794             } else {
1795
1796                 /* --------- pre-order copies  -------------------------- */
1797
1798                 del_link.onclick = function() { self.deleteCopy(row) };
1799                 openils.Util.show(del_link.parentNode);
1800
1801             }
1802
1803         } else { 
1804
1805             /* --------- virtual copies  -------------------------- */
1806
1807             del_link.onclick = function() { self.deleteCopy(row) };
1808             openils.Util.show(del_link.parentNode);
1809         }
1810     };
1811
1812     this.cancelLid = function(lid_id) {
1813         lidCancelDialog._lid_id = lid_id;
1814         openils.Util.show(lidCancelDialog.domNode.parentNode);
1815         lidCancelDialog.show();
1816         if (!lidCancelDialog._prepared) {
1817             var widget = new openils.widget.AutoFieldWidget({
1818                 "fmField": "cancel_reason",
1819                 "fmClass": "acqlid",
1820                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
1821                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
1822                 "forceSync": true
1823             });
1824             widget.build(
1825                 function(w, ww) {
1826                     acqLidCancelButton.onClick = function() {
1827                         if (w.attr("value")) {
1828                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
1829                                 self._cancelLid(
1830                                     lidCancelDialog._lid_id,
1831                                     w.attr("value")
1832                                 );
1833                             }
1834                             lidCancelDialog.hide();
1835                         }
1836                     };
1837                     lidCancelDialog._prepared = true;
1838                 }
1839             );
1840         }
1841     };
1842
1843     this._cancelLid = function(lid_id, reason) {
1844         fieldmapper.standardRequest(
1845             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
1846                 "params": [openils.User.authtoken, lid_id, reason],
1847                 "async": true,
1848                 "onresponse": function(r) {
1849                     if (r = openils.Util.readResponse(r)) {
1850                         if (r.lid) {
1851                             for (var id in r.lid) {
1852                                 /* actually this should only iterate once */
1853                                 self.copyCache[id].cancel_reason(
1854                                     r.lid[id].cancel_reason
1855                                 );
1856                                 self.updateLidState(self.copyCache[id]);
1857                             }
1858                         }
1859                     }
1860                 }
1861             }
1862         );
1863     };
1864
1865     this._confirmAlert = function(li, lin) {
1866         return confirm(
1867             dojo.string.substitute(
1868                 localeStrings.CONFIRM_LI_ALERT, [
1869                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
1870                         "title", "lineitem_marc_attr_definition"
1871                     ),
1872                     lin.alert_text().code(),
1873                     lin.alert_text().description() || "",
1874                     lin.value()
1875                 ]
1876             )
1877         );
1878     };
1879
1880     this.checkLiAlerts = function(li_id) {
1881         var li = this.liCache[li_id];
1882
1883         var alert_notes = li.lineitem_notes().filter(
1884             function(o) { return Boolean(o.alert_text()); }
1885         );
1886
1887         /* this is _intentionally_ not done in a call to forEach() ... */
1888         for (var i = 0; i < alert_notes.length; i++) {
1889             if (this.noteAcks[alert_notes[i].id()])
1890                 continue;
1891             else if (!this._confirmAlert(li, alert_notes[i]))
1892                 return false;
1893             else
1894                 this.noteAcks[alert_notes[i].id()] = true;
1895         }
1896
1897         return true;
1898     };
1899
1900     this.deleteCopy = function(row) {
1901         var copy = this.copyCache[row.getAttribute('copy_id')];
1902         copy.isdeleted(true);
1903         if(copy.isnew())
1904             delete this.copyCache[copy.id()];
1905         this.copyTbody.removeChild(row);
1906     }
1907
1908     this._virtDfaCountsAsList = function() {
1909         var L = [];
1910         for (var key in this.virtDfaCounts) {
1911             for (var i = 0; i < this.virtDfaCounts[key]; i++)
1912                 L.push(key);
1913         }
1914         return L;
1915     }
1916
1917     this.confirmBreachedCopyFunds = function(copies) {
1918         var stop = 0, warning = 0;
1919         copies.forEach(
1920             function(o) {
1921                 if (o.fund()) {
1922                     var state = self.fundBalanceState[o.fund()];
1923                     if (state[0] /* stop */)
1924                         stop++;
1925                     else if (state[1] /* warning */)
1926                         warning++;
1927                 }
1928             }
1929         );
1930
1931         if (stop) {
1932             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
1933         } else if (warning) {
1934             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
1935         }
1936         return true;
1937     };
1938
1939     this.saveCopyChanges = function(liId) {
1940         var self = this;
1941         var copies = [];
1942
1943
1944         var total = 0;
1945         for(var id in this.copyCache) {
1946             var c = this.copyCache[id];
1947             if(!c.isdeleted()) total++;
1948             if(c.isnew() || c.ischanged() || c.isdeleted()) {
1949                 if(c.id() < 0) c.id(null);
1950                 copies.push(c);
1951             }
1952         }
1953
1954
1955         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
1956
1957
1958         if (copies.length > 0) {
1959             if (!this.confirmBreachedCopyFunds(copies))
1960                 return;
1961
1962             if (typeof(this._copy_count_cb) == "function")
1963                 this._copy_count_cb(liId, total);
1964
1965             openils.Util.show("acq-lit-update-copies-progress");
1966             fieldmapper.standardRequest(
1967                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
1968                 {   async: true,
1969                     params: [openils.User.authtoken, copies],
1970                     onresponse: function(r) {
1971                         var res = openils.Util.readResponse(r);
1972                         litUpdateCopiesProgress.update(res);
1973                     },
1974                     oncomplete: function() {
1975                         self.drawCopies(liId, true /* force_fetch */);
1976                         openils.Util.hide("acq-lit-update-copies-progress");
1977                     }
1978                 }
1979             );
1980         }
1981
1982         var dfa_list = this._virtDfaCountsAsList();
1983         if (dfa_list.length > 0) {
1984             fieldmapper.standardRequest(
1985                 ["open-ils.acq",
1986                 "open-ils.acq.distribution_formula.record_application"],
1987                 {
1988                     "async": true,
1989                     "params": [openils.User.authtoken, dfa_list, liId],
1990                     "onresponse": function(r) {
1991                         var res = openils.Util.readResponse(r);
1992                         if (res && res.length < dfa_list.length)
1993                             alert(localeStrings.DFA_NOT_ALL);
1994                     }
1995                 }
1996             );
1997             this.virtDfaCounts = {};
1998         }
1999     }
2000
2001     this._updateCreatePoPrepayCheckbox = function(prepay) {
2002         var prepay = openils.Util.isTrue(prepay);
2003         this._prepayRequiredByVendor = prepay;
2004         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2005     };
2006
2007     this._confirmPoPrepaySituation = function() {
2008         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2009         if (want_prepay != this._prepayRequiredByVendor) {
2010             return confirm(
2011                 want_prepay ?
2012                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2013                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2014             );
2015         } else {
2016             return true;
2017         }
2018     };
2019
2020     this.applySelectedLiAction = function(action) {
2021         var self = this;
2022         switch(action) {
2023
2024             case 'delete_selected':
2025                 this._deleteLiList(self.getSelected());
2026                 break;
2027
2028             case 'create_order':
2029                 this._loadPOSelect();
2030                 acqLitPoCreateDialog.show();
2031                 break;
2032
2033             case 'save_picklist':
2034                 acqLitSavePlDialog.show();
2035                 break;
2036
2037             case 'selector_ready':
2038             case 'order_ready':
2039                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2040                 acqLitChangeLiStateDialog.show();
2041                 break;
2042
2043             case 'print_po':
2044                 this.printPO();
2045                 break;
2046
2047             case 'po_history':
2048                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2049                 break;
2050
2051             case 'receive_po':
2052                 this.receivePO();
2053                 break;
2054
2055             case 'rollback_receive_po':
2056                 this.rollbackPoReceive();
2057                 break;
2058
2059             case 'create_assets':
2060                 this.showAssetCreator();
2061                 break;
2062
2063             case 'export_attr_list':
2064                 this.chooseExportAttr();
2065                 break;
2066
2067             case 'batch_apply_funds':
2068                 this.applyBatchLiFunds();
2069                 break;
2070
2071             case 'add_brief_record':
2072                 if(this.isPO)
2073                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2074                 else
2075                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2076
2077                 break;
2078
2079             case "cancel_lineitems":
2080                 this.maybeCancelLineitems();
2081                 break;
2082
2083             case "change_claim_policy":
2084                 var li_list = this.getSelected();
2085                 this.claimPolicyPicker.attr("value", null);
2086                 liClaimPolicyDialog.show();
2087                 liClaimPolicySave.onClick = function() {
2088                     self.changeClaimPolicy(
2089                         li_list,
2090                         self.claimPolicyPicker.attr("value"),
2091                         function() {
2092                             li_list.forEach(
2093                                 function(li) {
2094                                     self.setClaimPolicyControl(li);
2095                                     self.reconsiderClaimControl(li);
2096                                 }
2097                             );
2098                             liClaimPolicyDialog.hide();
2099                         }
2100                     )
2101                 };
2102                 break;
2103         }
2104     };
2105
2106     this.changeClaimPolicy = function(li_list, value, callback) {
2107         li_list.forEach(
2108             function(li) { li.claim_policy(value); }
2109         );
2110         fieldmapper.standardRequest(
2111             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2112                 "params": [openils.User.authtoken, li_list],
2113                 "async": true,
2114                 "oncomplete": function(r) {
2115                     r = openils.Util.readResponse(r);
2116                     if (callback) callback(r);
2117                 }
2118             }
2119         );
2120     };
2121
2122     this.showAssetCreator = function(onAssetsCreated) {
2123         if(!this.isPO) return;
2124         var self = this;
2125     
2126         // first, let's see if this PO has any LI's that need to be merged/imported
2127         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2128             id_list : true,
2129             oncomplete : function(r) {
2130                 var resp = openils.Util.readResponse(r);
2131                 if (resp && resp.length) {
2132                     // PO has some non-linked jubs.  
2133                     
2134                     self.show('asset-creator');
2135                     if(!self.vlAgent.loaded)
2136                         self.vlAgent.init();
2137
2138                     dojo.connect(assetCreatorButton, 'onClick', 
2139                         function() { self.createAssets(onAssetsCreated) });
2140
2141                 } else {
2142
2143                     // all jubs linked, move on to asset creation
2144                     self.createAssets(onAssetsCreated, true); 
2145                 }
2146             }
2147         });
2148     }
2149
2150     this.createAssets = function(onAssetsCreated, noVl) {
2151         this.show('acq-lit-progress-numbers');
2152         var self = this;
2153         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2154         fieldmapper.standardRequest(
2155             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2156             {   async: true,
2157                 params: [this.authtoken, this.isPO, vlArgs],
2158                 onresponse: function(r) {
2159                     var resp = openils.Util.readResponse(r);
2160                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2161                 }
2162             }
2163         );
2164     }
2165
2166     this.maybeCancelLineitems = function() {
2167         openils.Util.show("acq-lit-cancel-reason", "inline");
2168         if (!acqLitCancelLineitemsButton._prepared) {
2169             var widget = new openils.widget.AutoFieldWidget({
2170                 "fmField": "cancel_reason",
2171                 "fmClass": "jub",
2172                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2173                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2174                 "forceSync": true
2175             });
2176             widget.build(
2177                 function(w, ww) {
2178                     acqLitCancelLineitemsButton.onClick = function() {
2179                         if (w.attr("value")) {
2180                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2181                                 self._cancelLineitems(w.attr("value"));
2182                             }
2183                             openils.Util.hide("acq-lit-cancel-reason");
2184                         }
2185                     };
2186                     acqLitCancelLineitemsButton._prepared = true;
2187                 }
2188             );
2189         }
2190     };
2191
2192     this._cancelLineitems = function(reason) {
2193         var id_list = this.getSelected().map(function(o) { return o.id(); });
2194         fieldmapper.standardRequest(
2195             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2196                 "params": [openils.User.authtoken, id_list, reason],
2197                 "async": true,
2198                 "onresponse": function(r) {
2199                     if (r = openils.Util.readResponse(r)) {
2200                         if (r.li) {
2201                             for (var id in r.li) {
2202                                 self.liCache[id].state(r.li[id].state);
2203                                 self.liCache[id].cancel_reason(
2204                                     r.li[id].cancel_reason
2205                                 );
2206                                 self.updateLiState(self.liCache[id]);
2207                             }
2208                         }
2209                         if (r.lid && self.copyCache) {
2210                             for (var id in r.lid) {
2211                                 if (self.copyCache[id]) {
2212                                     self.copyCache[id].cancel_reason(
2213                                         r.lid[id].cancel_reason
2214                                     );
2215                                     self.updateLidState(self.copyCache[id]);
2216                                 }
2217                             }
2218                         }
2219                     }
2220                 }
2221             }
2222         );
2223     };
2224
2225     this.chooseExportAttr = function() {
2226         if (!acqLitExportAttrSelector._li_setup) {
2227             var self = this;
2228             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2229                 {
2230                     "data": acqlimad.toStoreData(
2231                         this.pcrud.search(
2232                             "acqlimad", {"code": li_exportable_attrs}
2233                         )
2234                     )
2235                 }
2236             );
2237             acqLitExportAttrSelector.setValue();
2238             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2239             acqLitExportAttrSelector._li_setup = true;
2240         }
2241         openils.Util.show("acq-lit-export-attr-holder", "inline");
2242     };
2243
2244     this.exportAttrList = function() {
2245         var attr_def = acqLitExportAttrSelector.item;
2246         var li_list = this.getSelected();
2247         var value_list = li_list.map(
2248             function(li) {
2249                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2250                     attr_def.code, "lineitem_marc_attr_definition"
2251                 );
2252             }
2253         ).filter(function(attr) { return Boolean(attr); });
2254
2255         if (value_list.length > 0) {
2256             if (value_list.length < li_list.length) {
2257                 if (!confirm(
2258                     dojo.string.substitute(
2259                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
2260                     )
2261                 )) {
2262                     return;
2263                 }
2264             }
2265             try {
2266                 openils.XUL.contentToFileSaveDialog(
2267                     value_list.join("\n"),
2268                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
2269                 );
2270             } catch (E) {
2271                 alert(E);
2272             }
2273         } else {
2274             alert(dojo.string.substitute(
2275                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
2276             ));
2277         }
2278
2279         openils.Util.hide("acq-lit-export-attr-holder");
2280     };
2281
2282     this.printPO = function() {
2283         if(!this.isPO) return;
2284         progressDialog.show(true);
2285         fieldmapper.standardRequest(
2286             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
2287             {   async: true,
2288                 params: [this.authtoken, this.isPO, 'html'],
2289                 oncomplete: function(r) {
2290                     progressDialog.hide();
2291                     var evt = openils.Util.readResponse(r);
2292                     if(evt && evt.template_output()) {
2293                         openils.Util.printHtmlString(evt.template_output().data());
2294                     }
2295                 }
2296             }
2297         );
2298     }
2299
2300
2301     this.receivePO = function() {
2302         if (!this.isPO) return;
2303
2304         for (var id in this.liCache) {
2305             /* assumption: liCache reflects exactly the
2306              * set of LIs that belong to our PO */
2307             if (this.liCache[id].state() != "received" &&
2308                 !this.checkLiAlerts(id)) return;
2309         }
2310
2311         this.show('acq-lit-progress-numbers');
2312         var self = this;
2313         fieldmapper.standardRequest(
2314             ['open-ils.acq', 'open-ils.acq.purchase_order.receive'],
2315             {   async: true,
2316                 params: [this.authtoken, this.isPO],
2317                 onresponse : function(r) {
2318                     var resp = openils.Util.readResponse(r);
2319                     self._updateProgressNumbers(resp, true);
2320                 },
2321             }
2322         );
2323     }
2324
2325     this.issueReceive = function(obj, rollback) {
2326         var part =
2327             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
2328         var method =
2329             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
2330
2331         progressDialog.show(true);
2332         fieldmapper.standardRequest(
2333             ["open-ils.acq", method], {
2334                 "async": true,
2335                 "params": [this.authtoken, obj.id()],
2336                 "onresponse": function(r) {
2337                     if (r = openils.Util.readResponse(r)) {
2338                         self.fetchClaimInfo(
2339                             part == "lineitem" ? obj.id() : obj.lineitem(),
2340                             /* force */ true,
2341                             function() { self.handleReceive(r); }
2342                         );
2343                         progressDialog.hide();
2344                     }
2345                 }
2346             }
2347         );
2348     };
2349
2350     /**
2351      * Handles the responses from receive and rollback ML calls.
2352      */
2353     this.handleReceive = function(resp) {
2354         if (resp) {
2355             if (resp.li) {
2356                 for (var li_id in resp.li) {
2357                     for (var key in resp.li[li_id])
2358                         self.liCache[li_id][key](resp.li[li_id][key]);
2359                     self.updateLiState(self.liCache[li_id]);
2360                 }
2361             }
2362             if (resp.po) {
2363                 if (typeof(self.poUpdateCallback) == "function")
2364                     self.poUpdateCallback(resp.po);
2365             }
2366             if (resp.lid) {
2367                 for (var lid_id in resp.lid) {
2368                     for (var key in resp.lid[lid_id])
2369                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
2370                     self.updateLidState(self.copyCache[lid_id]);
2371                 }
2372             }
2373         }
2374     };
2375
2376     this.rollbackPoReceive = function() {
2377         if(!this.isPO) return;
2378         if(!confirm(localeStrings.ROLLBACK_PO_RECEIVE_CONFIRM)) return;
2379         this.show('acq-lit-progress-numbers');
2380         var self = this;
2381         fieldmapper.standardRequest(
2382             ['open-ils.acq', 'open-ils.acq.purchase_order.receive.rollback'],
2383             {   async: true,
2384                 params: [this.authtoken, this.isPO],
2385                 onresponse : function(r) {
2386                     var resp = openils.Util.readResponse(r);
2387                     self._updateProgressNumbers(resp, true);
2388                 },
2389             }
2390         );
2391     }
2392
2393     this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
2394         this.vlAgent.handleResponse(resp,
2395             function(resp, res) {
2396                 if(reloadOnComplete)
2397                      location.href = location.href;
2398                 if (onComplete)
2399                     onComplete(resp, res);
2400             }
2401         );
2402     }
2403
2404
2405     this._createPO = function(fields) {
2406         var wantall = (fields.create_from == "all");
2407
2408         /* If we're a picklist or purchase order already and the user wants
2409          * all lineitems, we might have pages' worth of lineitems haven't all
2410          * been loaded yet, so getSelected() won't find them.  The server,
2411          * however, should know about all our lineitems, so let's ask the
2412          * server for a complete list.
2413          */
2414
2415         if (wantall) {
2416             this.getSelected(
2417                 true, function(list) {
2418                     self._createPOFromLineitems(fields, list);
2419                 }, /* id_list */ true
2420             );
2421         } else {
2422             this._createPOFromLineitems(fields, this.getSelected(false, null, true /* id_list */));
2423         }
2424     };
2425
2426     this._createPOFromLineitems = function(fields, selected) {
2427         if (selected.length == 0) return;
2428         var self = this;
2429
2430         var po = new fieldmapper.acqpo();
2431         po.provider(this.createPoProviderSelector.attr("value"));
2432         po.ordering_agency(this.createPoAgencySelector.attr("value"));
2433         po.prepayment_required(fields.prepayment_required[0] ? true : false);
2434
2435         // if we're creating assets, delay the asset creation 
2436         // until after the PO is created.  This will allow us to 
2437         // use showAssetCreator() directly.
2438
2439         fieldmapper.standardRequest(
2440             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
2441             {   async: true,
2442                 params: [
2443                     openils.User.authtoken, 
2444                     po, {lineitems : selected}
2445                 ],
2446                 onresponse : function(r) {
2447                     var resp = openils.Util.readResponse(r);
2448                     if (resp.complete) {
2449                         // self.isPO is needed for showAssetCreator();
2450                         self.isPO = resp.purchase_order.id(); 
2451                         var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
2452                         if (fields.create_assets[0]) {
2453                             self.showAssetCreator(
2454                                 function() {location.href = redir}
2455                             );
2456                         } else {
2457                            location.href = redir;
2458                         }
2459                     }
2460                 }
2461             }
2462         );
2463     };
2464
2465
2466     this.batchFundWidget = null;
2467
2468     this.applyBatchLiFunds = function() {
2469
2470         var liIds = this.getSelected().map(function(li) { return li.id(); });
2471         if(liIds.length == 0) return; // warn?
2472
2473         var self = this;
2474         batchFundUpdateDialog.show();
2475
2476         if(!this.batchFundWidget) {
2477             this.batchFundWidget = new openils.widget.AutoFieldWidget({
2478                 fmClass : 'acqf',
2479                 selfReference : true,
2480                 labelFormat : fundLabelFormat,
2481                 searchFormat : fundSearchFormat,
2482                 searchFilter : {"active": "t"},
2483                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
2484                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2485                 dijitArgs : { "required": true, "labelType": "html" },
2486                 forceSync : true
2487             });
2488             this.batchFundWidget.build();
2489         }
2490
2491         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
2492         dojo.connect(batchFundUpdateSubmit, 'onClick', 
2493             function() { 
2494
2495                 // TODO: call .dry_run first to test thresholds
2496                 fieldmapper.standardRequest(
2497                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
2498                     {
2499                         params : [
2500                             openils.User.authtoken, 
2501                             liIds,
2502                             self.batchFundWidget.widget.attr('value')
2503                         ],
2504                         oncomplete : function(r) {
2505                             var resp = openils.Util.readResponse(r);
2506                             if(resp) {
2507                                 location.href = location.href;
2508                             }
2509                         }
2510                     }
2511                 )
2512             }
2513         );
2514     }
2515
2516     this._deleteLiList = function(list, idx) {
2517         if(idx == null) idx = 0;
2518         if(idx >= list.length) return;
2519
2520         var li = list[idx];
2521         var liId = li.id();
2522
2523         if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
2524             /* It makes little sense to delete a lineitem from a PO that has
2525              * already been marked 'on-order'.  Especially if EDI is in use,
2526              * such a purchase order will probably have already been shipped
2527              * off to a vendor, and mucking with it at this point could leave
2528              * your data in a bad state that doesn't jive with reality.
2529              *
2530              * I could see making this restriction even firmer.
2531              *
2532              * I could also see adjusting the li state comparisons, extending
2533              * the comparison to the PO's state, and/or providing functions
2534              * that house the logic for comparing states in a single location.
2535              *
2536              * Yes, this will be really annoying if you have selected a lot
2537              * of lineitems to cancel that have been ordered. You'll get a
2538              * confirm dialog for each one.
2539              */
2540
2541             if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
2542                 self._deleteLiList(list, ++idx); /* move on to next in list */
2543                 return;
2544             }
2545         }
2546
2547         fieldmapper.standardRequest(
2548             ['open-ils.acq',
2549              this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
2550             {   async: true,
2551                 params: [openils.User.authtoken, liId],
2552                 oncomplete: function(r) {
2553                     self.removeLineitem(liId);
2554                     self._deleteLiList(list, ++idx);
2555                 }
2556             }
2557         );
2558     }
2559
2560     this.editOrderMarc = function(li) {
2561
2562         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
2563             to true in about:config */
2564
2565         if(!openils.XUL.enableXPConnect()) return;
2566
2567         if(openils.XUL.isXUL()) {
2568             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul');
2569         } else {
2570             win = window.open('/xul/server/cat/marcedit.xul'); 
2571         }
2572         var self = this;
2573         win.xulG = {
2574             record : {marc : li.marc(), "rtype": "bre"},
2575             save : {
2576                 label: 'Save Record', // XXX I18N
2577                 func: function(xmlString) {
2578                     li.marc(xmlString);
2579                     fieldmapper.standardRequest(
2580                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
2581                         {   async: true,
2582                             params: [openils.User.authtoken, li],
2583                             oncomplete: function(r) {
2584                                 openils.Util.readResponse(r);
2585                                 win.close();
2586                                 self.drawInfo(li.id())
2587                             }
2588                         }
2589                     );
2590                 },
2591             },
2592             'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
2593             'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
2594         };
2595     }
2596
2597     this._savePl = function(values) {
2598         this.getSelected(
2599             (values.which == 'all'),
2600             function(list) { self._savePlFromLineitems(values, list); }
2601         );
2602     };
2603
2604     this._savePlFromLineitems = function(values, selected) {
2605         openils.Util.show("acq-lit-generic-progress");
2606
2607         if(values.new_name) {
2608             openils.acq.Picklist.create(
2609                 {name: values.new_name},
2610                 function(id) {
2611                     self._updateLiList(
2612                         id, selected, 0,
2613                         function() {
2614                             location.href =
2615                                 oilsBasePath + "/acq/picklist/view/" + id;
2616                         }
2617                     );
2618                 }
2619             );
2620         } else if(values.existing_pl) {
2621             // update lineitems to use an existing picklist
2622             self._updateLiList(
2623                 values.existing_pl, selected, 0,
2624                 function(){
2625                     location.href =
2626                         oilsBasePath + "/acq/picklist/view/" +
2627                         values.existing_pl;
2628                 }
2629             );
2630         }
2631     };
2632
2633     this._updateLiState = function(values, state) {
2634         progressDialog.show(true);
2635         this.getSelected(
2636             (values.which == 'all'),
2637             function(list) {
2638                 self._updateLiStateFromLineitems(values, state, list);
2639             }
2640         );
2641     };
2642
2643     this._updateLiStateFromLineitems = function(values, state, selected) {
2644         if(!selected.length) return;
2645         dojo.forEach(selected, function(li) {li.state(state);});
2646         self._updateLiList(null, selected, 0,
2647             // TODO consider inline updates for efficiency
2648             function() { location.href = location.href }
2649         );
2650     };
2651
2652     this._updateLiList = function(pl, list, idx, oncomplete) {
2653         if(idx >= list.length) return oncomplete();
2654         var li = list[idx];
2655         if(pl != null) li.picklist(pl);
2656         litGenericProgress.update({maximum: list.length, progress: idx});
2657         new openils.acq.Lineitem({lineitem:li}).update(
2658             function(r) {
2659                 self._updateLiList(pl, list, ++idx, oncomplete);
2660             }
2661         );
2662     }
2663
2664     this._loadPOSelect = function() {
2665         if (!this.createPoProviderSelector) {
2666             var widget = new openils.widget.AutoFieldWidget({
2667                 "fmField": "provider",
2668                 "fmClass": "acqpo",
2669                 "searchFilter": {"active": "t"},
2670                 "parentNode": dojo.byId("acq-lit-po-provider"),
2671                 "dijitArgs": {
2672                     "onChange": function() {
2673                         if (this.item) {
2674                             self._updateCreatePoPrepayCheckbox(
2675                                 this.item.prepayment_required()
2676                             );
2677                         }
2678                     }
2679                 }
2680             });
2681             widget.build(function(w) { self.createPoProviderSelector = w; });
2682         }
2683
2684         if (!this.createPoAgencySelector) {
2685             var widget = new openils.widget.AutoFieldWidget({
2686                 "fmField": "ordering_agency",
2687                 "fmClass": "acqpo",
2688                 "parentNode": dojo.byId("acq-lit-po-agency"),
2689                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2690             });
2691             widget.build(function(w) { self.createPoAgencySelector = w; });
2692         }
2693     };
2694
2695     this.showRealCopyEditUI = function(li) {
2696         copyList = [];
2697         var self = this;
2698         this.volCache = {};
2699
2700         this._fetchLineitem(li.id(), 
2701             function(fullLi) {
2702                 li = self.liCache[li.id()] = fullLi;
2703
2704                 self.pcrud.search(
2705                     'acp', {
2706                         id : li.lineitem_details().map(
2707                             function(item) { return item.eg_copy_id() }
2708                         )
2709                     }, {
2710                         async : true,
2711                         oncomplete : function(r) {
2712                             try {
2713                                 var r_list = openils.Util.readResponse( r );
2714                                 for (var i = 0; i < r_list.length; i++) {
2715                                     var copy = r_list[i];
2716                                     var volId = copy.call_number();
2717                                     var volume = self.volCache[volId];
2718                                     if(!volume) {
2719                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
2720                                     }
2721                                     copy.call_number(volume);
2722                                     copyList.push(copy);
2723                                 }
2724                                 if (xulG) {
2725                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
2726                                 }
2727                             } catch(E) {
2728                                 alert('error in oncomplete: ' + E);
2729                             }
2730                         }
2731                     }
2732                 );
2733             }
2734         );
2735     },
2736
2737     this.drawBibFinder = function(li) {
2738
2739         var query = '';
2740         var liWrapper = new openils.acq.Lineitem({lineitem:li});
2741
2742         dojo.forEach(
2743             ['isbn', 'upc', 'issn', 'title', 'author'],
2744             function(field) {
2745                 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
2746                 if(val) {
2747                     if(field == 'title' || field == 'author') {
2748                         query += field +':' + val + ' ';
2749                     } else {
2750                         query += 'identifier|' + field + ':' + val + ' ';
2751                     }
2752                 }
2753             }
2754         );
2755
2756         win = window.open(
2757             oilsBasePath + '/acq/lineitem/findbib?query=' + escape(query),
2758             '', 'resizable,scrollbars=1');
2759
2760         win.window.recordFound = function(bibId) { 
2761             win.close();
2762
2763             var attrs = li.attributes();
2764             li.attributes(null);
2765             li.eg_bib_id(bibId);
2766
2767             fieldmapper.standardRequest(
2768                 ["open-ils.acq", "open-ils.acq.lineitem.update"], 
2769                 {
2770                     "params": [openils.User.authtoken, li],
2771                     "async": true,
2772                     "oncomplete": function(r) {
2773                         if(openils.Util.readResponse(r)) {
2774                             location.href = location.href;
2775                         }
2776                     }
2777                 }
2778             );
2779         }
2780     }
2781 }
2782