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