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