]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/acq/common/li_table.js
LP#1254918 limit ACQ batch update fund retrieval by perms
[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", row);
1211
1212         switch(li.state()) {
1213
1214             case 'cancelled':
1215                 if(typeof li.cancel_reason() == "object") {
1216                     var holds_state = dojo.create(
1217                         "span", {
1218                             "style": "border-bottom: 1px dashed #000;",
1219                             "innerHTML": li.state()
1220                         }, state_cell, "only"
1221                     );
1222                     new dijit.Tooltip(
1223                         {
1224                             "label": "<em>" + li.cancel_reason().label() +
1225                                 "</em><br />" + li.cancel_reason().description(),
1226                             "connectId": [holds_state]
1227                         }, dojo.create("span", null, state_cell, "last")
1228                     );
1229
1230                     if (li.cancel_reason().keep_debits() == 't') {
1231                         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1232                         openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1233                     }
1234                 }
1235                 return; // all done
1236
1237             case "on-order":
1238                 break;
1239
1240             case "received":
1241                 break;
1242         }
1243
1244         state_cell.innerHTML = li.state(); // TODO i18n state labels
1245     };
1246
1247
1248     this._setAlertStore = function() {
1249         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1250             {
1251                 "data": acqliat.toStoreData(
1252                     this.pcrud.search(
1253                         "acqliat", {
1254                             "owning_lib": aou.orgNodeTrail(
1255                                 aou.findOrgUnit(openils.User.user.ws_ou())
1256                             ).map(function(o) { return o.id(); })
1257                         }
1258                     )
1259                 )
1260             }
1261         );
1262         acqLitAlertAlertText.setValue(); /* make the store "live" */
1263         acqLitAlertAlertText._store_ready = true;
1264     };
1265
1266     /**
1267      * Draws and shows the lineitem notes pane
1268      */
1269     this.drawLiNotes = function(li) {
1270         var self = this;
1271         this.focusLineitem = li.id();
1272
1273         if (!acqLitAlertAlertText._store_ready)
1274             this._setAlertStore();
1275
1276         li.lineitem_notes(
1277             li.lineitem_notes().sort(
1278                 function(a, b) { 
1279                     if(a.edit_time() < b.edit_time()) return 1;
1280                     return -1;
1281                 }
1282             )
1283         );
1284
1285         while(this.liNotesTbody.childNodes[0])
1286             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1287         this.show('notes');
1288
1289         acqLitCreateNoteSubmit.onClick = function() {
1290             var value = acqLitCreateNoteText.attr('value');
1291             if(!value) return;
1292             var note = new fieldmapper.acqlin();
1293             note.isnew(true);
1294             note.vendor_public(
1295                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1296             );
1297             note.value(value);
1298             note.lineitem(li.id());
1299
1300             self.updateLiNotes(li, note);
1301             acqLitCreateNoteVendorPublic.attr("checked", false);
1302             acqLitCreateNoteText.attr("value", "");
1303         }
1304
1305         acqLitCreateAlertSubmit.onClick = function() {
1306             if (!acqLitAlertAlertText.item) {
1307                 alert(localeStrings.ALERT_UNSELECTED);
1308                 return;
1309             }
1310
1311             var alert_text = new fieldmapper.acqliat().fromStoreItem(
1312                 acqLitAlertAlertText.item
1313             );
1314             var value = acqLitAlertNoteValue.attr("value") || "";
1315
1316             var note = new fieldmapper.acqlin();
1317             note.isnew(true);
1318             note.lineitem(li.id());
1319             note.value(value);
1320             note.alert_text(alert_text);
1321
1322             self.updateLiNotes(li, note);
1323         }
1324
1325         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1326     }
1327
1328     /**
1329      * Draws a single lineitem note in the notes pane
1330      */
1331     this.addLiNote = function(li, note) {
1332         if(note.isdeleted()) return;
1333         var self = this;
1334         var row = self.liNotesRow.cloneNode(true);
1335         nodeByName("value", row).innerHTML = note.value();
1336         var alert_node = nodeByName("alert_code", row);
1337         if (note.alert_text()) {
1338             alert_node.innerHTML = dojo.string.substitute(
1339                 "[${0}] ${1}", [
1340                     aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1341                     note.alert_text().code()
1342                 ]
1343             );
1344             if (note.alert_text().description()) {
1345                 new dijit.Tooltip(
1346                     {
1347                         "connectId": [alert_node],
1348                         "label": note.alert_text().description()
1349                     }, dojo.create("span", null, alert_node, "after")
1350                 );
1351             }
1352         }
1353
1354         if (openils.Util.isTrue(note.vendor_public()))
1355             nodeByName("vendor_public", row).innerHTML =
1356                 localeStrings.VENDOR_PUBLIC;
1357
1358         nodeByName("delete", row).onclick = function() {
1359             note.isdeleted(true);
1360             self.liNotesTbody.removeChild(row);
1361             self.updateLiNotes(li);
1362         };
1363
1364         if(note.edit_time()) {
1365             nodeByName("edit_time", row).innerHTML =
1366                 dojo.date.locale.format(
1367                     dojo.date.stamp.fromISOString(note.edit_time()), 
1368                     {formatLength:'short'});
1369         }
1370
1371         self.liNotesTbody.appendChild(row);
1372     }
1373
1374     /**
1375      * Updates any new/changed/deleted notes on the server
1376      */
1377     this.updateLiNotes = function(li, newNote) {
1378
1379         var notes;
1380         if(newNote) {
1381             notes = [newNote];
1382         } else {
1383             notes = li.lineitem_notes().filter(
1384                 function(note) {
1385                     if(note.ischanged() || note.isnew() || note.isdeleted())
1386                         return note;
1387                 }
1388             );
1389         }
1390
1391         if(notes.length == 0) return;
1392         progressDialog.show();
1393
1394         fieldmapper.standardRequest(
1395             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1396             {   async : true,
1397                 params : [this.authtoken, notes],
1398                 onresponse : function(r) {
1399                     var resp = openils.Util.readResponse(r);
1400
1401                     if(resp.complete) {
1402
1403                         if(!newNote) {
1404                             // remove the old changed notes
1405                             var list = [];
1406                             dojo.forEach(li.lineitem_notes(), 
1407                                 function(note) {
1408                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1409                                         list.push(note);
1410                                 }
1411                             );
1412                             li.lineitem_notes(list);
1413                         }
1414
1415                         progressDialog.hide();
1416                         self.updateLiNotesCount(li);
1417                         self.drawLiNotes(li);
1418                         return;
1419                     }
1420
1421                     progressDialog.update(resp);
1422                     var newnote = resp.note;
1423
1424                     if(!newnote.isdeleted()) {
1425                         newnote.isnew(false);
1426                         newnote.ischanged(false);
1427                         li.lineitem_notes().push(newnote);
1428                     }
1429                 },
1430             }
1431         );
1432     }
1433
1434     this.updateLiPrice = function(input, li) {
1435         var self = this;
1436         var price = input.value;
1437         if(Number(price) == Number(li.estimated_unit_price())) return;
1438
1439         fieldmapper.standardRequest(
1440             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1441             {   async : false, // redundant w/ timeout
1442                 timeout : 10,
1443                 params : [this.authtoken, li.id(), price],
1444                 oncomplete : function(r) {
1445                     openils.Util.readResponse(r);
1446                     li.estimated_unit_price(price); // update local copy
1447
1448                     /*
1449                      * If this is a PO and every visible lineitem has a price,
1450                      * check again to see if this PO can be activated.  Note that 
1451                      * every visible lineitem having a price does not guarantee it can
1452                      * be activated, which is why we still make the call.  Having a price
1453                      * set for every visiable lineitem is just the lowest barrier to entry.
1454                      */
1455                     if (self.isPO) {
1456                         var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1457                         var allSet = true;
1458                         dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1459                         if (allSet) checkCouldActivatePo();
1460                     }
1461                 }
1462             }
1463         );
1464     }
1465
1466     this.removeLineitem = function(liId) {
1467         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1468         delete this.liCache[liId];
1469         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1470     }
1471
1472     this.drawInfo = function(liId) {
1473         this.focusLineitem = liId;
1474         if (!this._isRelatedViewer) {
1475             var d = dojo.byId("acq-lit-info-related");
1476             if (!this.relCache[liId]) {
1477                 fieldmapper.standardRequest(
1478                     [
1479                         "open-ils.acq",
1480                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1481                     ], {
1482                         "async": true,
1483                         "params": [openils.User.authtoken, liId],
1484                         "onresponse": function(r) {
1485                             self.relCache[liId] = openils.Util.readResponse(r);
1486                             nodeByName("related_number", d).innerHTML =
1487                                 self.relCache[liId];
1488                             openils.Util[
1489                                 self.relCache[liId] >1 ? "show" : "hide"
1490                             ](d);
1491                         }
1492                     }
1493                 );
1494             } else {
1495                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1496                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1497             }
1498         }
1499
1500         this.show('info');
1501         openils.acq.Lineitem.fetchAttrDefs(
1502             function() { 
1503                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
1504             } 
1505         );
1506     };
1507
1508     this.toggleInlineCopies = function() {
1509         // if any inline copies are not displayed, 
1510         // display them all otherwise, hide them all.
1511
1512         var displayAll = false;
1513
1514         for (var liId in this.liCache) {
1515             if (!this.inlineCopiesVisible(liId)) {
1516                 displayAll = true;
1517                 break;
1518             }
1519         }
1520
1521         for (var liId in this.liCache) {
1522             var row = dojo.byId('acq-inline-copies-row-' + liId);
1523             if (displayAll) {
1524                 if (!row || row._hidden) {
1525                     this.drawInlineCopies(liId);
1526                 }
1527             } else { // hide all
1528                 if (row) {
1529                     // drawInlineCopies() on a visible row will hide it.
1530                     this.drawInlineCopies(liId);
1531                 }
1532             }
1533         }
1534
1535     };
1536
1537     this.inlineCopiesVisible = function(liId) {
1538         var row = dojo.byId('acq-inline-copies-row-' + liId); 
1539         return (row && !row._hidden);
1540     }
1541
1542     this.refreshInlineCopies = function(all, reFetch) {
1543         var self = this;
1544         var liIds = this.inlineCopiesNeedingRefresh;
1545         if (all) liIds = openils.Util.objectProperties(liCache);
1546         liIds.forEach(function(liId) {
1547             if (self.inlineCopiesVisible(liId)) {
1548                 self.drawInlineCopies(liId, reFetch); // hide
1549                 self.drawInlineCopies(liId, reFetch); // re-draw
1550             }
1551         });
1552     };
1553
1554     // draw inline copy table.  if the table is 
1555     // already visible, hide the table as-is
1556     // reFetch forces a retrieval of the lineitem and 
1557     // copies from the server.  otherwise the locally
1558     // cached version of each is used.
1559     this.drawInlineCopies = function(liId, reFetch) {
1560         var self = this;
1561             
1562         // find or create the row where the inline copies table will live
1563         var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1564         var liRow = dojo.query('[li=' + liId + ']')[0];
1565
1566         if (!containerRow) {
1567
1568             // build the inline copies container row and add it to 
1569             // the DOM directly after the primary lineitem row
1570
1571             containerRow = self.inlineCopyContainer.cloneNode(true);
1572             containerRow.id = 'acq-inline-copies-row-' + liId;
1573
1574             if (liRow.nextSibling) {
1575                 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1576             } else {
1577                 self.tbody.appendChild(containerRow);
1578             }
1579
1580         } else {
1581
1582             // toggle the visible state
1583             containerRow._hidden = !containerRow._hidden;
1584             openils.Util.toggle(containerRow, 'table-row');
1585
1586             if (containerRow._hidden) return; // hide only
1587         }
1588
1589         var handler = function(li) {
1590
1591             var tbody = dojo.query(
1592                 '[name=acq-li-inline-copies-tbody]', 
1593                 containerRow)[0];
1594
1595             // reset the table before adding copy rows
1596             while (tbody.childNodes[0])
1597                 tbody.removeChild(tbody.childNodes[0]);
1598
1599             if(li.lineitem_details().length == 0) {
1600                 tbody.appendChild(
1601                     self.inlineNoCopies.cloneNode(true));
1602                 return; // no copies to show
1603             }
1604
1605             // add a row to the inline copy table for each copy
1606             dojo.forEach(li.lineitem_details(),
1607                 function(copy) {
1608                     var row = self.inlineCopyTemplate.cloneNode(true);
1609                     tbody.appendChild(row);
1610                     self.addInlineCopy(li, copy, row);
1611                 }
1612             );
1613         };
1614
1615         this._fetchLineitem(liId, handler, reFetch);
1616     };
1617
1618     /** Draw read-only copy widgets for inline copies */
1619     this.addInlineCopy = function(li, copy, row) {
1620
1621         var self = this;
1622         dojo.forEach(liDetailFields,
1623             function(field) {
1624
1625                 var widget = new openils.widget.AutoFieldWidget({
1626                     fmObject : copy,
1627                     fmField : field,
1628                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1629                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1630                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1631                     fmClass : 'acqlid',
1632                     parentNode : dojo.query('[name=' + field + ']', row)[0],
1633                     readOnly : true,
1634                 });
1635
1636                 widget.build();
1637             }
1638         );
1639     };
1640
1641     /* For a given list of lineitem ids, build a list of full lineitems
1642      * re-using the fetching logic that is otherwise typical to use in this
1643      * module.
1644      *
1645      * If we've already got a lineitem in the cache, just use that.
1646      *
1647      * Once we've built a list of lineitems, call callback(thatlist).
1648      */
1649     this.fetchLineitemsById = function(id_list, callback) {
1650         var total = id_list.length;
1651         var result_list = [];
1652
1653         var inner = function(li) {
1654             result_list.push(li)
1655             if (--total <= 0)
1656                 callback(result_list);
1657         };
1658
1659         id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1660     };
1661
1662     this._fetchLineitem = function(liId, handler, force) {
1663
1664         var li = this.liCache[liId];
1665         if(li && li.marc() && li.lineitem_details() && !force)
1666             return handler(li);
1667         
1668         fieldmapper.standardRequest(
1669             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1670             {   async: true,
1671
1672                 params: [self.authtoken, liId, {
1673                     flesh_attrs: true,
1674                     flesh_cancel_reason: true,
1675                     flesh_li_details: true,
1676                     flesh_notes: true,
1677                     flesh_fund_debit: true }],
1678
1679                 oncomplete: function(r) {
1680                     var li = openils.Util.readResponse(r);
1681                     self.liCache[liId] = li;
1682                     handler(li)
1683                 }
1684             }
1685         );
1686     };
1687
1688     this._drawInfo = function(li) {
1689
1690         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1691
1692         if(li.eg_bib_id()) {
1693             openils.Util.hide('acq-lit-marc-order-record-label');
1694             openils.Util.hide(acqLitEditOrderMarc.domNode);
1695             openils.Util.show('acq-lit-marc-real-record-label');
1696         } else {
1697             openils.Util.show('acq-lit-marc-order-record-label');
1698             openils.Util.show(acqLitEditOrderMarc.domNode);
1699             openils.Util.hide('acq-lit-marc-real-record-label');
1700         }
1701
1702         this.drawMarcHTML(li);
1703         this.infoTbody = dojo.byId('acq-lit-info-tbody');
1704
1705         if(!this.infoRow)
1706             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1707         while(this.infoTbody.childNodes[0])
1708             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1709
1710         for(var i = 0; i < li.attributes().length; i++) {
1711             var attr = li.attributes()[i];
1712             var row = this.infoRow.cloneNode(true);
1713
1714             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1715             var name = openils.acq.Lineitem.attrDefs[type].filter(
1716                 function(a) {
1717                     return (a.code() == attr.attr_name());
1718                 }
1719             ).pop().description();
1720
1721             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1722             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1723             this.infoTbody.appendChild(row);
1724         }
1725
1726         if (!this._isRelatedViewer) {
1727             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1728                 oilsBasePath + "/acq/lineitem/related/" + li.id();
1729         }
1730
1731         // if a top scroll point is defined, jump up to it here
1732         var node = dojo.byId('oils-scroll-to-top');
1733         if (node) dijit.scrollIntoView(node);
1734     };
1735
1736     this.generateMakeRecTab = function(bib_id,default_view, row) {
1737         return function() {
1738             xulG.new_tab(
1739                 XUL_OPAC_WRAPPER,
1740                 {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1741                 {
1742                     no_xulG : false, 
1743                     show_nav_buttons : true, 
1744                     show_print_button : true, 
1745                     opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1746                     default_view : default_view
1747                 }
1748             );
1749
1750             if(row) nodeByName("action_none", row).selected = true;
1751         }
1752     };
1753
1754     this.drawMarcHTML = function(li) {
1755         var params = [null, true, li.marc()];
1756         if(li.eg_bib_id()) 
1757             params = [li.eg_bib_id(), true];
1758
1759         fieldmapper.standardRequest(
1760             ['open-ils.search', 'open-ils.search.biblio.record.html'],
1761             {   async: true,
1762                 params: params,
1763                 oncomplete: function(r) {
1764                     dojo.byId('acq-lit-marc-div').innerHTML = 
1765                         openils.Util.readResponse(r);
1766                 }
1767             }
1768         );
1769     }
1770
1771     this.drawCopies = function(liId, force_fetch) {
1772         this.focusLineitem = liId;
1773         if (typeof force_fetch == "undefined")
1774             force_fetch = false;
1775
1776         var cgi = new openils.CGI();
1777         var source = cgi.param('source');
1778         if (source && source.match(/invoice/)) {
1779             // got here from the invoice page, show the 'return-to-invoice' button
1780             var cgi = new openils.CGI({url : source});
1781             cgi.param('focus_li', liId);
1782             openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1783             var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1784             button.onclick = function() { location.href = cgi.url() };
1785         }
1786
1787         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1788             function(li, html) {
1789                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1790             }
1791         );
1792
1793         this.show('copies');
1794         var self = this;
1795         this.copyCache = {};
1796         this.copyWidgetCache = {};
1797         this.oldCopyWidgetCache = {};
1798         this.virtDfaCounts = {};
1799         this.realDfaCache = {};
1800         this.dfeOffset = 0;
1801
1802         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1803         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1804         acqLitCopyCountInput.attr('value', '0');
1805
1806         if (this.isPO && PO && PO.order_date()) {
1807             // prevent adding copies to activated POs
1808             acqLitCopyCountInput.attr('disabled', true);
1809             acqLitAddCopyCount.attr('disabled', true);
1810         }
1811
1812         while(this.copyTbody.childNodes[0])
1813             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1814
1815         this._drawBatchCopyWidgets();
1816
1817         this._drawDistribApplied(liId);
1818
1819         this._fetchDistribFormulas(
1820             function() {
1821                 openils.acq.Lineitem.fetchAttrDefs(
1822                     function() { 
1823                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1824                     } 
1825                 );
1826             }
1827         );
1828     };
1829
1830     this._saveDistribAppliedTemplates = function() {
1831         if (!this._appliedDistribTemplate) {
1832             this._appliedDistribTemplate =
1833                 dojo.byId("acq-lit-distrib-applied-tbody").
1834                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1835             dojo.attr(this._appliedDistribTemplate, "id");
1836         }
1837     };
1838
1839     this._drawDistribApplied = function(liId) {
1840         /* Build this table while hidden to prevent rendering artifacts */
1841         openils.Util.hide("acq-lit-distrib-applied-tbody");
1842
1843         this._saveDistribAppliedTemplates();
1844
1845         /* Remove any rows in the table from previous populations */
1846         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1847             forEach(dojo.destroy);
1848
1849         /* Unregister all dijits previously created (for some reason this isn't
1850          * covered by the above destroy calls). */
1851         dijit.registry.forEach(
1852             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1853         );
1854
1855         /* Populate the table with our liId */
1856         var total = 0;
1857         fieldmapper.standardRequest(
1858             ["open-ils.acq",
1859             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1860             {
1861                 "async": true,
1862                 "params": [self.authtoken, liId],
1863                 "onresponse": function(r) {
1864                     var dfa = openils.Util.readResponse(r);
1865                     if (dfa) {
1866                         total++;
1867                         self.realDfaCache[dfa.id()] = dfa;
1868                         self._drawDistribAppliedUnit(dfa);
1869                     }
1870                 },
1871                 "oncomplete": function() {
1872                     /* Reveal built table */
1873                     if (total) {
1874                         openils.Util.show(
1875                             "acq-lit-distrib-applied-tbody", "table-row-group"
1876                         );
1877                     }
1878                 }
1879             }
1880         );
1881     };
1882
1883     this._drawDistribAppliedUnit = function(dfa) {
1884         var new_row = false;
1885         var row = dojo.query(
1886             'tr[formula="' + dfa.formula().id() + '"]',
1887             "acq-lit-distrib-applied-tbody"
1888         )[0];
1889
1890         if (!row) {
1891             new_row = true;
1892             row = dojo.clone(this._appliedDistribTemplate);
1893             dojo.attr(row, "formula", dfa.formula().id());
1894             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1895         }
1896
1897         var td = dojo.query("td", row)[0];
1898
1899         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1900         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1901
1902         if (new_row)
1903             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1904
1905         new dijit.form.Button(
1906             {
1907                 "onClick": function() {
1908                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1909                         self.deleteDfa(dfa);
1910                 },
1911                 "label": "X",
1912                 /* XXX I /cannot/ make the following work in as a CSS class
1913                  * for some reason. So frustrating... */
1914                 "style": function(id) {
1915                      return (id > 0 ?
1916                         "font-weight: bold; color: #c00;" :
1917                         "color: #666;");
1918                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1919             }, "dfa-button-" + dfa.id()
1920         );
1921         new dijit.Tooltip(
1922             {
1923                 "connectId": ["dfa-button-" + dfa.id()],
1924                 "label": dojo.string.substitute(
1925                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
1926                         openils.User.formalName(dfa.creator()),
1927                         dojo.date.locale.format(
1928                             dojo.date.stamp.fromISOString(dfa.create_time()),
1929                             {"formatLength":"short"}
1930                         )
1931                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
1932                 )
1933             }, "dfa-tip-" + dfa.id()
1934         );
1935     }
1936
1937     this.deleteDfa = function(dfa) {
1938         if (dfa.id() > 0) { /* real */
1939             this.pcrud.eliminate(
1940                 dfa, {
1941                     "async": true,
1942                     "oncomplete": function() {
1943                         self._removeDistribApplied(dfa.id());
1944                         delete self.realDfaCache[dfa.id()];
1945                     }
1946                 }
1947             );
1948         } else { /* virtual */
1949             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
1950             this.virtDfaCounts[dfa.formula().id()] = 0;
1951             /* hasn't been saved yet, so no need to do anything server side */
1952             this._removeDistribApplied(dfa.id());
1953         }
1954
1955     };
1956
1957     this._removeDistribApplied = function(dfaId) {
1958         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
1959         dijit.registry.forEach(
1960             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
1961         );
1962         this._removeDistribAppliedEmptyRows();
1963     };
1964
1965     this._removeAllDistribAppliedVirtual = function() {
1966         /* Unregister dijits */
1967         dijit.registry.forEach(
1968             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
1969         );
1970         this._removeDistribAppliedEmptyRows();
1971     };
1972
1973     this._removeDistribAppliedEmptyRows = function() {
1974         /* Remove any rows with no DFA at all */
1975         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
1976             function(o) {
1977                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
1978             }
1979         );
1980     };
1981
1982     /**
1983      * Insert a new row into the distribution formula selection form
1984      */
1985     this._addDistribFormulaRow = function() {
1986         var self = this;
1987
1988         if (!self.distribForms) {
1989             // no formulas, hide the form
1990             openils.Util.hide('acq-lit-distrib-formula-table');
1991             return;
1992         }
1993
1994         if(!this.distribFormulaTemplate) 
1995             this.distribFormulaTemplate = 
1996                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
1997
1998         var row = this.distribFormulaTemplate.cloneNode(true);
1999         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2000
2001         this.dfSelector = new dijit.form.FilteringSelect(
2002             {"labelAttr": "dynLabel", "labelType": "html"},
2003             nodeByName("selector", row)
2004         );
2005         this._updateFormulaStore();
2006         this.dfSelector.fetchProperties =
2007             {"sort": [{"attribute": "use_count", "descending": true}]};
2008
2009         var apply = new dijit.form.Button(
2010             {"label": localeStrings.APPLY},
2011             nodeByName('set_button', row)
2012         ); 
2013
2014         var reset = new dijit.form.Button(
2015             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2016             nodeByName("reset_button", row)  
2017         );
2018
2019         dojo.connect(apply, 'onClick', 
2020             function() {
2021                 var form_id = self.dfSelector.attr("value");
2022                 if(!form_id) return;
2023                 self._applyDistribFormula(form_id);
2024                 reset.attr("disabled", false);
2025             }
2026         );
2027
2028         dojo.connect(reset, 'onClick', 
2029             function() {
2030                 self.restoreCopyFieldsBeforeDF();
2031                 self.virtDfaCounts = {};
2032                 self.virtDfaId = -1;
2033                 self.dfeOffset = 0;
2034                 self._updateFormulaStore();
2035                 self._removeAllDistribAppliedVirtual();
2036                 reset.attr("disabled", "true");
2037             }
2038         );
2039
2040     };
2041
2042     /**
2043      * Applies a distrib formula to the current set of copies
2044      */
2045     this._applyDistribFormula = function(formula) {
2046         if(!formula) return;
2047
2048         formula = this.distribForms.filter(
2049             function(form) { return form.id() == formula; }
2050         )[0];
2051
2052         var copyRows = dojo.query('tr', self.copyTbody);
2053
2054         if (this.dfeOffset >= copyRows.length) {
2055             alert(localeStrings.OUT_OF_COPIES);
2056             return;
2057         }
2058
2059         var entries_applied = 0;
2060         for(
2061             var rowIndex = this.dfeOffset;
2062             rowIndex < copyRows.length;
2063             rowIndex++
2064         ) {
2065             
2066             var row = copyRows[rowIndex];
2067             var copy_id = row.getAttribute('copy_id');
2068             var copyWidgets = this.copyWidgetCache[copy_id];
2069             var entryIndex = this.dfeOffset;
2070             var entry = null;
2071
2072             // find the correct entry for the current row
2073             dojo.forEach(formula.entries(), 
2074                 function(e) {
2075                     if(!entry) {
2076                         entryIndex += e.item_count();
2077                         if(entryIndex > rowIndex)
2078                             entry = e;
2079                     }
2080                 }
2081             );
2082
2083             if(entry) {
2084                 
2085                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
2086                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2087     
2088                 entries_applied++;
2089                 this.saveCopyFieldsBeforeDF(copy_id);
2090                 this._copy_fields_for_acqdf.forEach(
2091                     function(field) {
2092                         if(entry[field]()) {
2093                             copyWidgets[field].attr('value', (entry[field]()));
2094                         }
2095                     }
2096                 );
2097             }
2098         }
2099
2100         if (entries_applied) {
2101             this.virtDfaCounts[formula.id()] =
2102                 ++(this.virtDfaCounts[formula.id()]) || 1;
2103             this._updateFormulaStore();
2104             this._drawDistribAppliedUnit(
2105                 function(df) {
2106                     var dfa = new acqdfa();
2107                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2108                 }(formula)
2109             );
2110             this.dfeOffset += entries_applied;
2111         };
2112     };
2113
2114     /**
2115      * This function updates the DF store for the dropdown so that use_counts
2116      * can reflect DF applications from this session before they're saved
2117      * server-side.
2118      */
2119     this._updateFormulaStore = function() {
2120         this.dfSelector.store = new dojo.data.ItemFileReadStore(
2121             {
2122                 "data": self._labelFormulasWithCounts(
2123                     acqdf.toStoreData(self.distribForms)
2124                 )
2125             }
2126         );
2127     };
2128
2129     this.saveCopyFieldsBeforeDF = function(copy_id) {
2130         var self = this;
2131         if (!this.oldCopyWidgetCache[copy_id]) {
2132             var copyWidgets = this.copyWidgetCache[copy_id];
2133
2134             this.oldCopyWidgetCache[copy_id] = {};
2135             this._copy_fields_for_acqdf.forEach(
2136                 function(f) {
2137                     self.oldCopyWidgetCache[copy_id][f] =
2138                         copyWidgets[f].attr("value");
2139                 }
2140             );
2141         }
2142     };
2143
2144     this.restoreCopyFieldsBeforeDF = function() {
2145         var self = this;
2146         for (var copy_id in this.oldCopyWidgetCache) {
2147             this._copy_fields_for_acqdf.forEach(
2148                 function(f) {
2149                     self.copyWidgetCache[copy_id][f].attr(
2150                         "value", self.oldCopyWidgetCache[copy_id][f]
2151                     );
2152                 }
2153             );
2154         }
2155     };
2156
2157     this._labelFormulasWithCounts = function(store_data) {
2158         for (var key in store_data.items) {
2159             var obj = store_data.items[key];
2160             obj.use_count = Number(obj.use_count); /* needed for sorting */
2161
2162             if (this.virtDfaCounts[obj.id])
2163                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2164
2165             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2166                 obj.use_count + "]</span>&nbsp; " + obj.name;
2167         }
2168         return store_data;
2169     };
2170
2171     /**
2172      * This method formerly would not refetch the DF formulas if they'd been
2173      * loaded already, but now it always re-fetches, since use_count changes.
2174      */
2175     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2176     this._fetchDistribFormulas = function(onload) {
2177         fieldmapper.standardRequest(
2178             ["open-ils.acq",
2179                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2180             {
2181                 "async": true,
2182                 "params": [openils.User.authtoken, 0, 500],
2183                 "oncomplete": function(r) {
2184                     self.distribForms = openils.Util.readResponse(r);
2185                     if(!self.distribForms || self.distribForms.length == 0) {
2186                         self.distribForms = [];
2187                     }
2188                     self._addDistribFormulaRow();
2189                     onload();
2190                 }
2191             }
2192         );
2193     }
2194
2195     this._drawBatchCopyWidgets = function() {
2196         var row = this.copyBatchRow;
2197         dojo.forEach(liDetailBatchFields, 
2198             function(field) {
2199                 if(self.copyBatchRowDrawn) {
2200                     self.copyBatchWidgets[field].attr('value', null);
2201                 } else {
2202                     var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2203                     args.parentNode = dojo.query('[name='+field+']', row)[0];
2204
2205                     var widget = new openils.widget.AutoFieldWidget(args);
2206                     widget.build(
2207                         function(w, ww) {
2208                             if (field == "fund" && w.store)
2209                                 self._ensureCSSFundClasses(w.store);
2210                             self.copyBatchWidgets[field] = w;
2211                         }
2212                     );
2213                     if (field == "fund") {
2214                         dojo.connect(
2215                             widget.widget, "onChange", function(val) {
2216                                 self._updateFundSelectorStyle(widget, val);
2217                             }
2218                         );
2219                     }
2220                 }
2221             }
2222         );
2223         this.copyBatchRowDrawn = true;
2224     };
2225
2226     this.batchCopyUpdate = function() {
2227         var self = this;
2228         for(var k in this.copyWidgetCache) {
2229             var cache = this.copyWidgetCache[k];
2230             dojo.forEach(liDetailBatchFields, function(f) {
2231                 var newval = self.copyBatchWidgets[f].attr('value');
2232                 if(newval) cache[f].attr('value', newval);
2233             });
2234         }
2235     };
2236
2237     this._drawCopies = function(li) {
2238         var self = this;
2239
2240         // this button sets the total number of copies for a given lineitem
2241         acqLitAddCopyCount.onClick = function() { 
2242             var count = acqLitCopyCountInput.attr('value');
2243
2244             // add new rows
2245             while(self.copyCount() < count)
2246                 self.addCopy(li); 
2247             
2248             // delete rows if necessary
2249             var diff = self.copyCount() - count;
2250             if(diff > 0) {
2251                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2252                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2253                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2254                 } else {
2255                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
2256                 }
2257             }
2258         }
2259
2260
2261         if(li.lineitem_details().length > 0) {
2262             dojo.forEach(li.lineitem_details(),
2263                 function(copy) {
2264                     self.addCopy(li, copy);
2265                 }
2266             );
2267         } else {
2268             self.addCopy(li);
2269         }
2270     };
2271
2272     this.copyCount = function() {
2273         var count = 0;
2274         for(var id in this.copyCache) {
2275             if(!this.copyCache[id].isdeleted())
2276                 count++;
2277         }
2278         return count;
2279     }
2280
2281     this.virtCopyId = -1;
2282     this.addCopy = function(li, copy) {
2283         var row = this.copyRow.cloneNode(true);
2284         this.copyTbody.appendChild(row);
2285         var self = this;
2286
2287         if(!copy) {
2288             copy = new fieldmapper.acqlid();
2289             copy.isnew(true);
2290             copy.id(this.virtCopyId--);
2291             copy.lineitem(li.id());
2292         }
2293
2294         this.copyCache[copy.id()] = copy;
2295         row.setAttribute('copy_id', copy.id());
2296         self.copyWidgetCache[copy.id()] = {};
2297
2298         acqLitCopyCountInput.attr('value', self.copyCount()+'');
2299
2300         var rcvr = copy.receiver();
2301         if (rcvr) {
2302             if (!userCache[rcvr]) {
2303                 if(rcvr == openils.User.user.id()) {
2304                     userCache[rcvr] = openils.User.user;
2305                 } else {
2306                     userCache[rcvr] = fieldmapper.standardRequest(
2307                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2308                         {params: [openils.User.authtoken, rcvr]}
2309                     );
2310                 }
2311             }
2312             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
2313         }
2314
2315         dojo.forEach(liDetailFields,
2316             function(field) {
2317                 var searchFilter;
2318                 if (field == "fund") {
2319                     searchFilter = (copy.fund() ?
2320                         {"-or": {"active": "t", "id": copy.fund()}} :
2321                         {"active" : "t"});
2322                 } else {
2323                     searchFilter = null;
2324                 }
2325
2326                 var readOnly = false;
2327                 
2328                 // TODO: Add support for changing the owning_lib after real copies have been made.  
2329                 // owning_lib is order data as much as its item data
2330                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2331                     readOnly = true;
2332                 }
2333
2334                 // TODO: add support for changing the fund after debits have been created
2335                 // Note: invoicing allows the change
2336                 if(copy.fund_debit() && field == 'fund') {
2337                     readOnly = true;
2338                 }
2339
2340
2341                 var widget = new openils.widget.AutoFieldWidget({
2342                     fmObject : copy,
2343                     fmField : field,
2344                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
2345                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
2346                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2347                     searchFilter : searchFilter,
2348                     noCache: (field == "fund"),
2349                     fmClass : 'acqlid',
2350                     parentNode : dojo.query('[name='+field+']', row)[0],
2351                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2352                     readOnly : readOnly,
2353                     orgDefaultsToWs : true
2354                 });
2355
2356                 widget.build(
2357                     // make sure we capture the value from any async widgets
2358                     function(w, ww) { 
2359
2360                         if (field == "fund" && w.store)
2361                             self._ensureCSSFundClasses(w.store);
2362
2363                         if(!readOnly) 
2364                             copy[field](ww.getFormattedValue()) 
2365
2366                         self.copyWidgetCache[copy.id()][field] = w;
2367
2368                         dojo.connect(w, 'onChange', 
2369                             function(val) { 
2370                                 if (field == "fund")
2371                                     self._updateFundSelectorStyle(widget, val);
2372
2373                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2374                                     // prevent setting ischanged() automatically on widget load for existing copies
2375                                     copy[field](widget.getFormattedValue()) 
2376                                     copy.ischanged(true);
2377                                 }
2378                             }
2379                         );
2380                     }
2381                 );
2382             }
2383         );
2384
2385         this.updateLidState(copy, row);
2386     };
2387
2388     this._ensureCSSFundClass = function(id) {
2389         if (!this.fundStyleSheet) {
2390             dojo.create(
2391                 "style", {"type": "text/css"},
2392                 document.getElementsByTagName("head")[0], "last"
2393             );
2394             this.fundStyleSheet = document.styleSheets[
2395                 document.styleSheets.length - 1
2396             ];
2397         }
2398
2399         var cn = "fund_" + id;
2400         if (!this.haveFundClass[cn]) {
2401             fieldmapper.standardRequest(
2402                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2403                 {
2404                     "params": [openils.User.authtoken, id],
2405                     "async": true,
2406                     "oncomplete": function(r) {
2407                         r = openils.Util.readResponse(r);
2408                         self.fundBalanceState[id] = r;
2409                         var style = "";
2410                         if (r[0] /* stop */)
2411                             style = fundStyles.stop;
2412                         else if (r[1] /* warning */)
2413                             style = fundStyles.warning;
2414                         self.fundStyleSheet.insertRule(
2415                             "." + cn + " { " + style + " }",
2416                             self.fundStyleSheet.cssRules.length
2417                         );
2418                         self.haveFundClass[cn] = true;
2419                     }
2420                 }
2421             );
2422         }
2423     };
2424
2425     this._ensureCSSFundClasses = function(store) {
2426         store.fetch({
2427             "query": {"id": "*"},
2428             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2429         });
2430     };
2431
2432     this._updateFundSelectorStyle = function(widget, fund_id) {
2433         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2434         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2435     };
2436
2437     this.updateLidState = function(copy, row) {
2438         var self = this;
2439
2440         if (typeof(row) == "undefined") {
2441             row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2442         }
2443
2444         // action links
2445         var recv_link = nodeByName("receive", row);
2446         var unrecv_link = nodeByName("unreceive", row);
2447         var del_link = nodeByName("delete", row);
2448         var cxl_link = nodeByName("cancel", row);
2449         var claim_link = nodeByName("claim", row);
2450         var cxl_reason_link = nodeByName("cancel_reason", row);
2451
2452         // by default, hide all the actions
2453         openils.Util.hide(del_link.parentNode);
2454         openils.Util.hide(recv_link);
2455         openils.Util.hide(unrecv_link);
2456         openils.Util.hide(cxl_link);
2457         openils.Util.hide(claim_link);
2458         openils.Util.hide(cxl_reason_link);
2459
2460         if (copy.id() > 0) { // real copies (LIDs)
2461
2462             if (copy.cancel_reason()) { 
2463
2464                 /* --------- cancelled -------------------------- */
2465
2466                 /* XXX the following may leak memory in a long lived table: 
2467                  * dijits may not get destroyed... not positive. revisit. */
2468                 var holds_reason = dojo.create(
2469                     "span", {
2470                         "style": "border-bottom: 1px dashed #000;",
2471                         "innerHTML": "Cancelled" /* XXX [sic] and i18n */
2472                     }, cxl_reason_link, "only"
2473                 );
2474                 new dijit.Tooltip(
2475                     {
2476                         "label": "<em>" + copy.cancel_reason().label() +
2477                             "</em><br />" + copy.cancel_reason().description(),
2478                         "connectId": [holds_reason]
2479                     }, dojo.create("span", null, cxl_reason_link, "last")
2480                 );
2481                 openils.Util.show(cxl_reason_link, "inline");
2482
2483             } else if (copy.recv_time()) { 
2484
2485                 /* --------- received -------------------------- */
2486
2487                 openils.Util.show(unrecv_link, "inline");
2488                 unrecv_link.onclick = function() {
2489                     if (confirm(localeStrings.UNRECEIVE_LID))
2490                         self.issueReceive(copy, /* rollback */ true);
2491                 };
2492
2493             } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2494                 
2495                 /* --------- on order -------------------------- */
2496
2497                 openils.Util.show(recv_link, 'inline');
2498                 openils.Util.show(cxl_link, "inline");
2499
2500                 recv_link.onclick = function() {
2501                     if (self.checkLiAlerts(copy.lineitem()))
2502                         self.issueReceive(copy);
2503                 };
2504
2505                 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2506
2507             } else {
2508
2509                 /* --------- pre-order copies  -------------------------- */
2510
2511                 del_link.onclick = function() { self.deleteCopy(row) };
2512                 openils.Util.show(del_link.parentNode);
2513
2514             }
2515
2516         } else { 
2517
2518             /* --------- virtual copies  -------------------------- */
2519
2520             del_link.onclick = function() { self.deleteCopy(row) };
2521             openils.Util.show(del_link.parentNode);
2522         }
2523     };
2524
2525     this.cancelLid = function(lid_id) {
2526         lidCancelDialog._lid_id = lid_id;
2527         openils.Util.show(lidCancelDialog.domNode.parentNode);
2528         lidCancelDialog.show();
2529         if (!lidCancelDialog._prepared) {
2530             var widget = new openils.widget.AutoFieldWidget({
2531                 "fmField": "cancel_reason",
2532                 "fmClass": "acqlid",
2533                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2534                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2535                 "forceSync": true
2536             });
2537             widget.build(
2538                 function(w, ww) {
2539                     acqLidCancelButton.onClick = function() {
2540                         if (w.attr("value")) {
2541                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2542                                 self._cancelLid(
2543                                     lidCancelDialog._lid_id,
2544                                     w.attr("value")
2545                                 );
2546                             }
2547                             lidCancelDialog.hide();
2548                         }
2549                     };
2550                     lidCancelDialog._prepared = true;
2551                 }
2552             );
2553         }
2554     };
2555
2556     this._cancelLid = function(lid_id, reason) {
2557         fieldmapper.standardRequest(
2558             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2559                 "params": [openils.User.authtoken, lid_id, reason],
2560                 "async": true,
2561                 "onresponse": function(r) {
2562                     if (r = openils.Util.readResponse(r)) {
2563                         if (r.lid) {
2564                             for (var id in r.lid) {
2565                                 /* actually this should only iterate once */
2566                                 self.copyCache[id].cancel_reason(
2567                                     r.lid[id].cancel_reason
2568                                 );
2569                                 self.updateLidState(self.copyCache[id]);
2570                             }
2571                         }
2572                     }
2573                 }
2574             }
2575         );
2576     };
2577
2578     this._confirmAlert = function(li, lin) {
2579         return confirm(
2580             dojo.string.substitute(
2581                 localeStrings.CONFIRM_LI_ALERT, [
2582                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2583                         "title", "lineitem_marc_attr_definition"
2584                     ), (
2585                         /* XXX it's really better add a parameter and to adjust
2586                          * the format string rather than do this concatenation
2587                          * here, but if someone wants this for 2.2 in a hurry,
2588                          * we can sidestep the problem of updating the strings
2589                          * while the translators are working. */
2590                         "[" +
2591                         aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2592                         "] " +
2593                         lin.alert_text().code()
2594                     ),
2595                     lin.alert_text().description() || "",
2596                     lin.value()
2597                 ]
2598             )
2599         );
2600     };
2601
2602     this.checkLiAlerts = function(li_id) {
2603         var li = this.liCache[li_id];
2604
2605         var alert_notes = li.lineitem_notes().filter(
2606             function(o) { return Boolean(o.alert_text()); }
2607         );
2608
2609         /* this is _intentionally_ not done in a call to forEach() ... */
2610         for (var i = 0; i < alert_notes.length; i++) {
2611             if (this.noteAcks[alert_notes[i].id()])
2612                 continue;
2613             else if (!this._confirmAlert(li, alert_notes[i]))
2614                 return false;
2615             else
2616                 this.noteAcks[alert_notes[i].id()] = true;
2617         }
2618
2619         return true;
2620     };
2621
2622     this.deleteCopy = function(row) {
2623         var copy = this.copyCache[row.getAttribute('copy_id')];
2624         copy.isdeleted(true);
2625         if(copy.isnew())
2626             delete this.copyCache[copy.id()];
2627         this.copyTbody.removeChild(row);
2628     }
2629
2630     this._virtDfaCountsAsList = function() {
2631         var L = [];
2632         for (var key in this.virtDfaCounts) {
2633             for (var i = 0; i < this.virtDfaCounts[key]; i++)
2634                 L.push(key);
2635         }
2636         return L;
2637     }
2638
2639     this.confirmBreachedCopyFunds = function(copies) {
2640         var stop = 0, warning = 0;
2641         copies.forEach(
2642             function(o) {
2643                 if (o.fund()) {
2644                     var state = self.fundBalanceState[o.fund()];
2645                     if (state[0] /* stop */)
2646                         stop++;
2647                     else if (state[1] /* warning */)
2648                         warning++;
2649                 }
2650             }
2651         );
2652
2653         if (stop) {
2654             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2655         } else if (warning) {
2656             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2657         }
2658         return true;
2659     };
2660
2661     this.saveCopyChanges = function(liId) {
2662         var self = this;
2663         var copies = [];
2664
2665
2666         var total = 0;
2667         for(var id in this.copyCache) {
2668             var c = this.copyCache[id];
2669             if(!c.isdeleted()) total++;
2670             if(c.isnew() || c.ischanged() || c.isdeleted()) {
2671                 if(c.id() < 0) c.id(null);
2672                 copies.push(c);
2673             }
2674         }
2675
2676
2677         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2678
2679
2680         if (copies.length > 0) {
2681             if (!this.confirmBreachedCopyFunds(copies))
2682                 return;
2683
2684             if (typeof(this._copy_count_cb) == "function")
2685                 this._copy_count_cb(liId, total);
2686
2687             openils.Util.show("acq-lit-update-copies-progress");
2688             fieldmapper.standardRequest(
2689                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2690                 {   async: true,
2691                     params: [openils.User.authtoken, copies],
2692                     onresponse: function(r) {
2693                         var res = openils.Util.readResponse(r);
2694                         litUpdateCopiesProgress.update(res);
2695                     },
2696                     oncomplete: function() {
2697                         self.drawCopies(liId, true /* force_fetch */);
2698                         openils.Util.hide("acq-lit-update-copies-progress");
2699                     }
2700                 }
2701             );
2702         }
2703
2704         var dfa_list = this._virtDfaCountsAsList();
2705         if (dfa_list.length > 0) {
2706             fieldmapper.standardRequest(
2707                 ["open-ils.acq",
2708                 "open-ils.acq.distribution_formula.record_application"],
2709                 {
2710                     "async": true,
2711                     "params": [openils.User.authtoken, dfa_list, liId],
2712                     "onresponse": function(r) {
2713                         var res = openils.Util.readResponse(r);
2714                         if (res && res.length < dfa_list.length)
2715                             alert(localeStrings.DFA_NOT_ALL);
2716                     }
2717                 }
2718             );
2719             this.virtDfaCounts = {};
2720         }
2721
2722         if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2723             this.inlineCopiesNeedingRefresh.push(liId);
2724     };
2725
2726     this._updateCreatePoPrepayCheckbox = function(prepay) {
2727         var prepay = openils.Util.isTrue(prepay);
2728         this._prepayRequiredByVendor = prepay;
2729         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2730     };
2731
2732     this._confirmPoPrepaySituation = function() {
2733         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2734         if (want_prepay != this._prepayRequiredByVendor) {
2735             return confirm(
2736                 want_prepay ?
2737                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2738                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2739             );
2740         } else {
2741             return true;
2742         }
2743     };
2744
2745     this.applySelectedLiAction = function(action) {
2746         var self = this;
2747         switch(action) {
2748
2749             case 'delete_selected':
2750                 this._deleteLiList(self.getSelected());
2751                 break;
2752
2753             case 'add_to_order':
2754                 addToPoDialog._get_li = dojo.hitch(
2755                     this,
2756                     function() { 
2757                         return this.getSelected(
2758                             false, null, true, li_pre_po_states);
2759                     }
2760                 );
2761                 if (addToPoDialog._get_li().length == 0) {
2762                     alert(localeStrings.NO_LI_GENERAL);
2763                     return;
2764                 }
2765                 addToPoDialog.show();
2766                 break;
2767
2768             case 'create_order':
2769                 this._loadPOSelect();
2770                 acqLitPoCreateDialog.show();
2771                 break;
2772
2773             case 'save_picklist':
2774                 acqLitSavePlDialog.show();
2775                 break;
2776
2777             case 'selector_ready':
2778             case 'order_ready':
2779                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2780                 acqLitChangeLiStateDialog.show();
2781                 break;
2782
2783             case 'print_po':
2784                 this.printPO();
2785                 break;
2786
2787             case 'po_history':
2788                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2789                 break;
2790
2791             case 'batch_create_invoice':
2792                 this.batchCreateInvoice();
2793                 break;
2794
2795             case 'batch_link_invoice':
2796                 this.batchLinkInvoice();
2797                 break;
2798
2799             case 'receive_lineitems':
2800                 this.receiveSelectedLineitems();
2801                 break;
2802
2803             case 'rollback_receive_lineitems':
2804                 this.rollbackReceiveLineitems();
2805                 break;
2806
2807             case 'create_assets':
2808                 this.showAssetCreator();
2809                 break;
2810
2811             case 'export_attr_list':
2812                 this.chooseExportAttr();
2813                 break;
2814
2815             case 'batch_apply_funds':
2816                 this.applyBatchLiFunds();
2817                 break;
2818
2819             case 'add_brief_record':
2820                 if(this.isPO)
2821                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2822                 else
2823                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2824
2825                 break;
2826
2827             case "cancel_lineitems":
2828                 console.log('HERE');
2829                 this.maybeCancelLineitems();
2830                 break;
2831
2832             case "apply_claim_policy":
2833                 var li_list = this.getSelected();
2834                 this.claimPolicyPicker.attr("value", null);
2835                 liClaimPolicyDialog.show();
2836                 liClaimPolicySave.onClick = function() {
2837                     self.changeClaimPolicy(
2838                         li_list,
2839                         self.claimPolicyPicker.attr("value"),
2840                         function() {
2841                             li_list.forEach(
2842                                 function(li) {
2843                                     self.setClaimPolicyControl(li);
2844                                     self.reconsiderClaimControl(li);
2845                                 }
2846                             );
2847                             liClaimPolicyDialog.hide();
2848                         }
2849                     )
2850                 };
2851                 break;
2852         }
2853     };
2854
2855     this.changeClaimPolicy = function(li_list, value, callback) {
2856         li_list.forEach(
2857             function(li) { li.claim_policy(value); }
2858         );
2859         fieldmapper.standardRequest(
2860             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2861                 "params": [openils.User.authtoken, li_list],
2862                 "async": true,
2863                 "oncomplete": function(r) {
2864                     r = openils.Util.readResponse(r);
2865                     if (callback) callback(r);
2866                 }
2867             }
2868         );
2869     };
2870
2871     this.showAssetCreator = function(onAssetsCreated) {
2872         if(!this.isPO) return;
2873         var self = this;
2874     
2875         // first, let's see if this PO has any LI's that need to be merged/imported
2876         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2877             id_list : true,
2878             oncomplete : function(r) {
2879                 var resp = openils.Util.readResponse(r);
2880                 if (resp && resp.length) {
2881                     // PO has some non-linked jubs.  
2882                     
2883                     self.show('asset-creator');
2884                     if(!self.vlAgent.loaded)
2885                         self.vlAgent.init();
2886
2887                     dojo.connect(assetCreatorButton, 'onClick', 
2888                         function() { self.createAssets(onAssetsCreated) });
2889
2890                 } else {
2891
2892                     // all jubs linked, move on to asset creation
2893                     self.createAssets(onAssetsCreated, true); 
2894                 }
2895             }
2896         });
2897     }
2898
2899     this.createAssets = function(onAssetsCreated, noVl) {
2900         this.show('acq-lit-progress-numbers');
2901         var self = this;
2902         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2903         fieldmapper.standardRequest(
2904             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2905             {   async: true,
2906                 params: [this.authtoken, this.isPO, vlArgs],
2907                 onresponse: function(r) {
2908                     var resp = openils.Util.readResponse(r);
2909                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated);
2910                 }
2911             }
2912         );
2913     }
2914
2915     this.maybeCancelLineitems = function() {
2916         openils.Util.show("acq-lit-cancel-reason", "inline");
2917         if (!acqLitCancelLineitemsButton._prepared) {
2918             var widget = new openils.widget.AutoFieldWidget({
2919                 "fmField": "cancel_reason",
2920                 "fmClass": "jub",
2921                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
2922                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2923                 "forceSync": true
2924             });
2925             widget.build(
2926                 function(w, ww) {
2927                     acqLitCancelLineitemsButton.onClick = function() {
2928                         if (w.attr("value")) {
2929                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
2930                                 self._cancelLineitems(w.attr("value"));
2931                             }
2932                             openils.Util.hide("acq-lit-cancel-reason");
2933                         }
2934                     };
2935                     acqLitCancelLineitemsButton._prepared = true;
2936                 }
2937             );
2938         }
2939     };
2940
2941     this._cancelLineitems = function(reason) {
2942
2943         // ignore canceled lineitems during batch lineitem cancel
2944         var states = li_active_states.filter(
2945             function(s) { return s != 'cancelled' });
2946
2947         var id_list = this.getSelected(null, null, true, states);
2948
2949         if (!id_list.length) {
2950             alert(localeStrings.NO_LI_GENERAL);
2951             return;
2952         }
2953         fieldmapper.standardRequest(
2954             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
2955                 "params": [openils.User.authtoken, id_list, reason],
2956                 "async": true,
2957                 "onresponse": function(r) {
2958                     if (r = openils.Util.readResponse(r)) {
2959                         if (r.li) {
2960                             for (var id in r.li) {
2961                                 self.liCache[id].state(r.li[id].state);
2962                                 self.liCache[id].cancel_reason(
2963                                     r.li[id].cancel_reason
2964                                 );
2965                                 self.updateLiState(self.liCache[id]);
2966                             }
2967                         }
2968                         if (r.lid && self.copyCache) {
2969                             for (var id in r.lid) {
2970                                 if (self.copyCache[id]) {
2971                                     self.copyCache[id].cancel_reason(
2972                                         r.lid[id].cancel_reason
2973                                     );
2974                                     self.updateLidState(self.copyCache[id]);
2975                                 }
2976                             }
2977                         }
2978                     }
2979                 }
2980             }
2981         );
2982     };
2983
2984     this.chooseExportAttr = function() {
2985         if (!acqLitExportAttrSelector._li_setup) {
2986             var self = this;
2987             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
2988                 {
2989                     "data": acqlimad.toStoreData(
2990                         this.pcrud.search(
2991                             "acqlimad", {"code": li_exportable_attrs}
2992                         )
2993                     )
2994                 }
2995             );
2996             acqLitExportAttrSelector.setValue();
2997             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
2998             acqLitExportAttrSelector._li_setup = true;
2999         }
3000         openils.Util.show("acq-lit-export-attr-holder", "inline");
3001     };
3002
3003     this.exportAttrList = function() {
3004         var attr_def = acqLitExportAttrSelector.item;
3005         var li_list = this.getSelected();
3006         var value_list = li_list.map(
3007             function(li) {
3008                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3009                     attr_def.code, "lineitem_marc_attr_definition"
3010                 );
3011             }
3012         ).filter(function(attr) { return Boolean(attr); });
3013
3014         if (value_list.length > 0) {
3015             if (value_list.length < li_list.length) {
3016                 if (!confirm(
3017                     dojo.string.substitute(
3018                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3019                     )
3020                 )) {
3021                     return;
3022                 }
3023             }
3024             try {
3025                 openils.XUL.contentToFileSaveDialog(
3026                     value_list.join("\n"),
3027                     localeStrings.EXPORT_SAVE_DIALOG_TITLE
3028                 );
3029             } catch (E) {
3030                 alert(E);
3031             }
3032         } else {
3033             alert(dojo.string.substitute(
3034                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3035             ));
3036         }
3037
3038         openils.Util.hide("acq-lit-export-attr-holder");
3039     };
3040
3041     this.printPO = function() {
3042         if(!this.isPO) return;
3043         progressDialog.show(true);
3044         fieldmapper.standardRequest(
3045             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3046             {   async: true,
3047                 params: [this.authtoken, this.isPO, 'html'],
3048                 oncomplete: function(r) {
3049                     progressDialog.hide();
3050                     var evt = openils.Util.readResponse(r);
3051                     if(evt && evt.template_output()) {
3052                         openils.Util.printHtmlString(evt.template_output().data());
3053                     }
3054                 }
3055             }
3056         );
3057     };
3058
3059     this.batchCreateInvoice = function() {
3060         var liIds = this.getSelected(
3061             false, null, true /* id_list */, li_active_states)
3062         if (!liIds.length) {
3063             alert(localeStrings.NO_LI_GENERAL);
3064             return;
3065         }
3066         var path = oilsBasePath + '/acq/invoice/view?create=1';
3067         dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3068         if (openils.XUL.isXUL())
3069             openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3070         else
3071             location.href = path;
3072     };
3073
3074     this.batchLinkInvoice = function(create) {
3075         var liIds = this.getSelected(
3076             false, null, true /* id_list */, li_active_states)
3077         if (!liIds.length) {
3078             alert(localeStrings.NO_LI_GENERAL);
3079             return;
3080         }
3081         if (!self.invoiceLinkDialogManager) {
3082             self.invoiceLinkDialogManager =
3083                 new InvoiceLinkDialogManager("li");
3084         }
3085         self.invoiceLinkDialogManager.target = liIds;
3086         acqLitLinkInvoiceDialog.show();
3087     };
3088
3089     this.receiveSelectedLineitems = function() {
3090         var states = li_post_po_states.filter(
3091             function(s) { return s != 'received' });
3092         var li_list = this.getSelected(null, null, null, states);
3093
3094         if (!li_list.length) {
3095             alert(localeStrings.NO_LI_GENERAL);
3096             return;
3097         }
3098
3099         for (var i = 0; i < li_list.length; i++) {
3100             var li = li_list[i];
3101
3102             if (li.state() != "received" &&
3103                 !this.checkLiAlerts(li.id())) return;
3104         }
3105
3106         this.show('acq-lit-progress-numbers');
3107
3108         var self = this;
3109         fieldmapper.standardRequest(
3110             ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3111             {   async: true,
3112                 params: [
3113                     this.authtoken,
3114                     li_list.map(function(li) { return li.id(); })
3115                 ],
3116                 onresponse : function(r) {
3117                     var resp = openils.Util.readResponse(r);
3118                     self._updateProgressNumbers(resp, true);
3119                 },
3120             }
3121         );
3122     };
3123
3124     this.issueReceive = function(obj, rollback) {
3125         var part =
3126             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3127         var method =
3128             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3129
3130         progressDialog.show(true);
3131         fieldmapper.standardRequest(
3132             ["open-ils.acq", method], {
3133                 "async": true,
3134                 "params": [this.authtoken, obj.id()],
3135                 "onresponse": function(r) {
3136                     if (r = openils.Util.readResponse(r)) {
3137                         self.fetchClaimInfo(
3138                             part == "lineitem" ? obj.id() : obj.lineitem(),
3139                             /* force */ true,
3140                             function() { self.handleReceive(r); }
3141                         );
3142                         progressDialog.hide();
3143                     }
3144                 }
3145             }
3146         );
3147     };
3148
3149     /**
3150      * Handles the responses from receive and rollback ML calls.
3151      */
3152     this.handleReceive = function(resp) {
3153         if (resp) {
3154             if (resp.li) {
3155                 for (var li_id in resp.li) {
3156                     for (var key in resp.li[li_id])
3157                         self.liCache[li_id][key](resp.li[li_id][key]);
3158                     self.updateLiState(self.liCache[li_id]);
3159                 }
3160             }
3161             if (resp.po) {
3162                 if (typeof(self.poUpdateCallback) == "function")
3163                     self.poUpdateCallback(resp.po);
3164             }
3165             if (resp.lid) {
3166                 for (var lid_id in resp.lid) {
3167                     for (var key in resp.lid[lid_id])
3168                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3169                     self.updateLidState(self.copyCache[lid_id]);
3170                 }
3171             }
3172         }
3173     };
3174
3175     this.rollbackReceiveLineitems = function() {
3176         var li_id_list = this.getSelected(false, null, true);
3177         if (!li_id_list.length) {
3178             alert(localeStrings.NO_LI_GENERAL);
3179             return;
3180         }
3181
3182         if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3183
3184         this.show('acq-lit-progress-numbers');
3185         var self = this;
3186
3187         fieldmapper.standardRequest(
3188             ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3189             {   async: true,
3190                 params: [this.authtoken, li_id_list],
3191                 onresponse : function(r) {
3192                     var resp = openils.Util.readResponse(r);
3193                     self._updateProgressNumbers(resp, true);
3194                 },
3195             }
3196         );
3197     };
3198
3199     this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete) {
3200         this.vlAgent.handleResponse(resp,
3201             function(resp, res) {
3202                 if(reloadOnComplete)
3203                      location.href = location.href;
3204                 if (onComplete)
3205                     onComplete(resp, res);
3206             }
3207         );
3208     }
3209
3210
3211     this._createPO = function(fields) {
3212         var wantall = (fields.create_from == "all");
3213
3214         /* If we're a picklist or purchase order already and the user wants
3215          * all lineitems, we might have pages' worth of lineitems haven't all
3216          * been loaded yet, so getSelected() won't find them.  The server,
3217          * however, should know about all our lineitems, so let's ask the
3218          * server for a complete list.
3219          */
3220
3221         if (wantall) {
3222             this.getSelected(
3223                 true, function(list) {
3224                     self._createPOFromLineitems(fields, list);
3225                 }, /* id_list */ true, li_pre_po_states
3226             );
3227         } else {
3228             this._createPOFromLineitems(
3229                 fields, this.getSelected(
3230                     false, null, true /* id_list */, li_pre_po_states)
3231             );
3232         }
3233     };
3234
3235     this._createPOFromLineitems = function(fields, selected) {
3236         if (selected.length == 0) {
3237             alert(localeStrings.NO_LI_GENERAL);
3238             return;
3239         }
3240         var self = this;
3241
3242         var po = new fieldmapper.acqpo();
3243         po.provider(this.createPoProviderSelector.attr("value"));
3244         po.ordering_agency(this.createPoAgencySelector.attr("value"));
3245         po.prepayment_required(fields.prepayment_required[0] ? true : false);
3246
3247         // if we're creating assets, delay the asset creation 
3248         // until after the PO is created.  This will allow us to 
3249         // use showAssetCreator() directly.
3250
3251         fieldmapper.standardRequest(
3252             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3253             {   async: true,
3254                 params: [
3255                     openils.User.authtoken, 
3256                     po, {lineitems : selected}
3257                 ],
3258                 onresponse : function(r) {
3259                     var resp = openils.Util.readResponse(r);
3260                     if (resp.complete) {
3261                         // self.isPO is needed for showAssetCreator();
3262                         self.isPO = resp.purchase_order.id(); 
3263                         var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3264                         if (fields.create_assets[0]) {
3265                             self.showAssetCreator(
3266                                 function() {location.href = redir}
3267                             );
3268                         } else {
3269                            location.href = redir;
3270                         }
3271                     }
3272                 }
3273             }
3274         );
3275     };
3276
3277
3278     this.batchFundWidget = null;
3279
3280     this.applyBatchLiFunds = function() {
3281
3282         var liIds = this.getSelected().map(function(li) { return li.id(); });
3283         if(liIds.length == 0) return; // warn?
3284
3285         var self = this;
3286         batchFundUpdateDialog.show();
3287
3288         if(!this.batchFundWidget) {
3289             this.batchFundWidget = new openils.widget.AutoFieldWidget({
3290                 fmClass : 'acqf',
3291                 selfReference : true,
3292                 labelFormat : fundLabelFormat,
3293                 searchFormat : fundSearchFormat,
3294                 searchFilter : {"active": "t"},
3295                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3296                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3297                 dijitArgs : { "required": true, "labelType": "html" },
3298                 forceSync : true
3299             });
3300             this.batchFundWidget.build();
3301         }
3302
3303         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3304         dojo.connect(batchFundUpdateSubmit, 'onClick', 
3305             function() { 
3306
3307                 // TODO: call .dry_run first to test thresholds
3308                 fieldmapper.standardRequest(
3309                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3310                     {
3311                         params : [
3312                             openils.User.authtoken, 
3313                             liIds,
3314                             self.batchFundWidget.widget.attr('value')
3315                         ],
3316                         oncomplete : function(r) {
3317                             var resp = openils.Util.readResponse(r);
3318                             if(resp) {
3319                                 location.href = location.href;
3320                             }
3321                         }
3322                     }
3323                 )
3324             }
3325         );
3326     }
3327
3328     this._deleteLiList = function(list, idx) {
3329         if(idx == null) idx = 0;
3330         if(idx >= list.length) return;
3331
3332         var li = list[idx];
3333         var liId = li.id();
3334
3335         if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3336             /* It makes little sense to delete a lineitem from a PO that has
3337              * already been marked 'on-order'.  Especially if EDI is in use,
3338              * such a purchase order will probably have already been shipped
3339              * off to a vendor, and mucking with it at this point could leave
3340              * your data in a bad state that doesn't jive with reality.
3341              *
3342              * I could see making this restriction even firmer.
3343              *
3344              * I could also see adjusting the li state comparisons, extending
3345              * the comparison to the PO's state, and/or providing functions
3346              * that house the logic for comparing states in a single location.
3347              *
3348              * Yes, this will be really annoying if you have selected a lot
3349              * of lineitems to cancel that have been ordered. You'll get a
3350              * confirm dialog for each one.
3351              */
3352
3353             if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3354                 self._deleteLiList(list, ++idx); /* move on to next in list */
3355                 return;
3356             }
3357         }
3358
3359         fieldmapper.standardRequest(
3360             ['open-ils.acq',
3361              this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],
3362             {   async: true,
3363                 params: [openils.User.authtoken, liId],
3364                 oncomplete: function(r) {
3365                     self.removeLineitem(liId);
3366                     self._deleteLiList(list, ++idx);
3367                 }
3368             }
3369         );
3370     }
3371
3372     this.editOrderMarc = function(li) {
3373
3374         /*  To run in Firefox directly, must set signed.applets.codebase_principal_support
3375             to true in about:config */
3376
3377         if(openils.XUL.isXUL()) {
3378             win = window.open('/xul/' + openils.XUL.buildId() + '/server/cat/marcedit.xul','','chrome');
3379         } else {
3380             win = window.open('/xul/server/cat/marcedit.xul','','chrome'); 
3381         }
3382         var self = this;
3383         win.xulG = {
3384             record : {marc : li.marc(), "rtype": "bre"},
3385             save : {
3386                 label: 'Save Record', // XXX I18N
3387                 func: function(xmlString) {
3388                     li.marc(xmlString);
3389                     fieldmapper.standardRequest(
3390                         ['open-ils.acq', 'open-ils.acq.lineitem.update'],
3391                         {   async: true,
3392                             params: [openils.User.authtoken, li],
3393                             oncomplete: function(r) {
3394                                 openils.Util.readResponse(r);
3395                                 win.close();
3396                                 self.drawInfo(li.id())
3397                             }
3398                         }
3399                     );
3400                 },
3401             },
3402             'lock_tab' : typeof xulG != 'undefined' ? (typeof xulG['lock_tab'] != 'undefined' ? xulG.lock_tab : undefined) : undefined,
3403             'unlock_tab' : typeof xulG != 'undefined' ? (typeof xulG['unlock_tab'] != 'undefined' ? xulG.unlock_tab : undefined) : undefined
3404         };
3405     }
3406
3407     this._savePl = function(values) {
3408         this.getSelected(
3409             (values.which == 'all'),
3410             function(list) { self._savePlFromLineitems(values, list); }
3411         );
3412     };
3413
3414     this._savePlFromLineitems = function(values, selected) {
3415         openils.Util.show("acq-lit-generic-progress");
3416
3417         if(values.new_name) {
3418             openils.acq.Picklist.create(
3419                 {name: values.new_name},
3420                 function(id) {
3421                     self._updateLiList(
3422                         id, selected, 0,
3423                         function() {
3424                             location.href =
3425                                 oilsBasePath + "/acq/picklist/view/" + id;
3426                         }
3427                     );
3428                 }
3429             );
3430         } else if(values.existing_pl) {
3431             // update lineitems to use an existing picklist
3432             self._updateLiList(
3433                 values.existing_pl, selected, 0,
3434                 function(){
3435                     location.href =
3436                         oilsBasePath + "/acq/picklist/view/" +
3437                         values.existing_pl;
3438                 }
3439             );
3440         }
3441     };
3442
3443     this._updateLiState = function(values, state, state_filter) {
3444         progressDialog.show(true);
3445         this.getSelected(
3446             (values.which == 'all'),
3447             function(list) {
3448                 self._updateLiStateFromLineitems(values, state, list);
3449             }, false /* id_list */, state_filter
3450         );
3451     };
3452
3453     this._updateLiStateFromLineitems = function(values, state, selected) {
3454         if(!selected.length) {
3455             try { progressDialog.hide() } catch(E) {};
3456             alert(localeStrings.NO_LI_GENERAL);
3457             return;
3458         }
3459         dojo.forEach(selected, function(li) {li.state(state);});
3460         self._updateLiList(null, selected, 0,
3461             // TODO consider inline updates for efficiency
3462             function() { location.href = location.href }
3463         );
3464     };
3465
3466     this._updateLiList = function(pl, list, idx, oncomplete) {
3467         if(idx >= list.length) return oncomplete();
3468         var li = list[idx];
3469         if(pl != null) li.picklist(pl);
3470         litGenericProgress.update({maximum: list.length, progress: idx});
3471         new openils.acq.Lineitem({lineitem:li}).update(
3472             function(r) {
3473                 self._updateLiList(pl, list, ++idx, oncomplete);
3474             }
3475         );
3476     }
3477
3478     this._loadPOSelect = function() {
3479         if (!this.createPoProviderSelector) {
3480             var widget = new openils.widget.AutoFieldWidget({
3481                 "fmField": "provider",
3482                 "fmClass": "acqpo",
3483                 "searchFilter": {"active": "t"},
3484                 "parentNode": dojo.byId("acq-lit-po-provider"),
3485                 "dijitArgs": {
3486                     "onChange": function() {
3487                         if (this.item) {
3488                             self._updateCreatePoPrepayCheckbox(
3489                                 this.item.prepayment_required()
3490                             );
3491                         }
3492                     }
3493                 }
3494             });
3495             widget.build(function(w) { self.createPoProviderSelector = w; });
3496         }
3497
3498         if (!this.createPoAgencySelector) {
3499             var widget = new openils.widget.AutoFieldWidget({
3500                 "fmField": "ordering_agency",
3501                 "fmClass": "acqpo",
3502                 "parentNode": dojo.byId("acq-lit-po-agency"),
3503                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3504             });
3505             widget.build(function(w) { self.createPoAgencySelector = w; });
3506         }
3507     };
3508
3509     this.showRealCopyEditUI = function(li) {
3510         copyList = [];
3511         var self = this;
3512         this.volCache = {};
3513
3514         this._fetchLineitem(li.id(), 
3515             function(fullLi) {
3516                 li = self.liCache[li.id()] = fullLi;
3517
3518                 self.pcrud.search(
3519                     'acp', {
3520                         id : li.lineitem_details().map(
3521                             function(item) { return item.eg_copy_id() }
3522                         )
3523                     }, {
3524                         async : true,
3525                         oncomplete : function(r) {
3526                             try {
3527                                 var r_list = openils.Util.readResponse( r );
3528                                 for (var i = 0; i < r_list.length; i++) {
3529                                     var copy = r_list[i];
3530                                     var volId = copy.call_number();
3531                                     var volume = self.volCache[volId];
3532                                     if(!volume) {
3533                                         volume = self.volCache[volId] = self.pcrud.retrieve('acn', volId);
3534                                     }
3535                                     copy.call_number(volume);
3536                                     copyList.push(copy);
3537                                 }
3538                                 if (xulG) {
3539                                     xulG.volume_item_creator( { 'existing_copies' : copyList } );
3540                                 }
3541                             } catch(E) {
3542                                 alert('error in oncomplete: ' + E);
3543                             }
3544                         }
3545                     }
3546                 );
3547             }
3548         );
3549     },
3550
3551     this.drawBibFinder = function(li) {
3552
3553         var query = '';
3554         var liWrapper = new openils.acq.Lineitem({lineitem:li});
3555
3556         dojo.forEach(
3557             ['isbn', 'upc', 'issn', 'title', 'author'],
3558             function(field) {
3559                 var val = liWrapper.findAttr(field, 'lineitem_marc_attr_definition');
3560                 if(val) {
3561                     if(field == 'title' || field == 'author') {
3562                         query += field +':' + val + ' ';
3563                     } else {
3564                         query += 'identifier|' + field + ':' + val + ' ';
3565                     }
3566                 }
3567             }
3568         );
3569
3570         win = window.open(
3571             oilsBasePath + '/acq/lineitem/findbib?query=' + encodeURIComponent(query),
3572             '', 'resizable,scrollbars=1,chrome');
3573
3574         win.window.recordFound = function(bibId) { 
3575             win.close();
3576
3577             var attrs = li.attributes();
3578             li.attributes(null);
3579             li.eg_bib_id(bibId);
3580
3581             fieldmapper.standardRequest(
3582                 ["open-ils.acq", "open-ils.acq.lineitem.update"], 
3583                 {
3584                     "params": [openils.User.authtoken, li],
3585                     "async": true,
3586                     "oncomplete": function(r) {
3587                         if(openils.Util.readResponse(r)) {
3588                             location.href = location.href;
3589                         }
3590                     }
3591                 }
3592             );
3593         }
3594     }
3595 }
3596