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