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