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