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