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