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