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