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