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