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