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