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