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