7f34f552b1ceb375c8d5d573e179943f84d2ddf9
[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         if (li.source_label() !== null)
714             dojo.query('[name=source_label]', row)[0].appendChild(document.createTextNode(li.source_label()));
715
716         // so we can scroll to it later
717         dojo.query('[name=bib-info-cell]', row)[0].id = 'li-title-ref-' + li.id();
718
719         var identifier =
720             liWrapper.findAttr("isbn", "lineitem_marc_attr_definition") ||
721             liWrapper.findAttr("upc", "lineitem_marc_attr_definition");
722
723         // XXX media prefix for added content
724         if (identifier) {
725             nodeByName("jacket", row).setAttribute(
726                 "src", "/opac/extras/ac/jacket/small/" + identifier
727             );
728         }
729
730         nodeByName("liid", row).innerHTML += li.id();
731
732         var exist = nodeByName('li_existing_count', row);
733         fieldmapper.standardRequest(
734             ['open-ils.acq', 'open-ils.acq.lineitem.existing_copies.count'],
735             {
736                 params: [this.authtoken, li.id()],
737                 oncomplete : function(r) {
738                     var count = openils.Util.readResponse(r);
739                     exist.innerHTML = count;
740                     if (Number(count) > 0) {
741                         openils.Util.addCSSClass(
742                             exist, 'acq-existing-count-warn');
743                     }
744                     new dijit.Tooltip({
745                         connectId : [exist],
746                         label : dojo.string.substitute(
747                             localeStrings.LI_EXISTING_COPIES, [count])
748                     });
749                 }
750             }
751         );
752
753         if(li.eg_bib_id()) {
754             openils.Util.show(nodeByName('catalog', row), 'inline');
755             nodeByName("catalog_link", row).onclick = this.generateMakeRecTab(li.eg_bib_id());
756         } else {
757             openils.Util.show(nodeByName('link_to_catalog', row), 'inline');
758             nodeByName("link_to_catalog_link", row).onclick = function() { self.drawBibFinder(li) };
759         }
760
761         if (li.queued_record()) {
762             this.pcrud.retrieve('vqbr', li.queued_record(),
763                 {   async : true, 
764                     oncomplete : function(r) {
765                         var qrec = openils.Util.readResponse(r);
766                         openils.Util.show(nodeByName('queue', row), 'inline');
767                         var link = nodeByName("queue_link", row);
768                         link.onclick = function() { 
769                             var url = oilsBasePath + '/vandelay/vandelay?qtype=bib&qid=' + qrec.queue()
770                             // open a new tab to the vandelay queue for this record
771                             if (window.IAMBROWSER) {
772                                 xulG.relay_url(url);
773                             } else {
774                                 openils.XUL.newTabEasy(url);
775                             }
776                         }
777                     }
778                 }
779             );
780         }
781
782         nodeByName("worksheet_link", row).href =
783             oilsBasePath + "/acq/lineitem/worksheet/" + li.id() + 
784             '?source=' + encodeURIComponent(location.pathname + location.search)
785
786         nodeByName("show_requests_link", row).href =
787             oilsBasePath + "/acq/picklist/user_request?lineitem=" + li.id() + 
788             '?source=' + encodeURIComponent(location.pathname + location.search)
789
790         dojo.query('[attr=title]', row)[0].onclick = function() {self.drawInfo(li.id())};
791         dojo.query('[name=copieslink]', row)[0].onclick = function() {self.drawCopies(li.id())};
792         dojo.query('[name=noteslink]', row)[0].onclick = function() {self.drawLiNotes(li)};
793         dojo.query('[name=expand_inline_copies]', row)[0].onclick = 
794             function() {self.drawInlineCopies(li.id())};
795
796         var sum;
797         if (sum = li.order_summary()) { // assignment
798             // Only show the paid label if at least one copy is invoiced.
799             // In other words, a lineitem whose every copy is canceled
800             // is not "paid off"
801             if (sum.invoice_count() > 0) {
802                 if (sum.item_count() == (
803                     sum.invoice_count() + sum.cancel_count())) {
804                     // Lineitem is fully paid.  Display the paid-off label
805                     openils.Util.show(nodeByName('paid', row), 'inline');
806                 }
807             }
808         }
809
810         this.drawOrderIdentSelector(li, row);
811
812         if (!this.skipInitialEligibilityCheck)
813             this.fetchClaimInfo(
814                 li.id(),
815                 false,
816                 function(full) { self.setClaimPolicyControl(full, row) },
817                 row
818             );
819
820         this.updateLiNotesCount(li, row);
821
822         // show which PO this lineitem is a member of
823         if(li.purchase_order() && !this.isPO) {
824             var po = 
825                 this.poCache[li.purchase_order()] =
826                 this.poCache[li.purchase_order()] ||
827                 fieldmapper.standardRequest(
828                     ['open-ils.acq', 'open-ils.acq.purchase_order.retrieve'],
829                     {params: [
830                         this.authtoken, li.purchase_order(), {
831                             "flesh_price_summary": true,
832                             "flesh_provider" : true,
833                             "flesh_lineitem_count": true
834                         }
835                     ]});
836             if(po && !this.isMeta) {
837                 openils.Util.show(nodeByName('po', row), 'inline');
838                 var link = nodeByName('po_link', row);
839                 link.setAttribute('href', oilsBasePath +
840                     '/acq/po/view/' + li.purchase_order() +
841                     '?focus_li=' + li.id() +
842                     '&source=' + encodeURIComponent(location.pathname + location.search)
843                 );
844                 link.innerHTML += po.name();
845
846                 openils.Util.show(nodeByName('pro', row), 'inline');
847                 link = nodeByName('pro_link', row);
848                 link.setAttribute('href', oilsBasePath + '/conify/global/acq/provider/' + po.provider().id())
849                 link.innerHTML += po.provider().code();
850             }
851         }
852
853         // show which picklist this lineitem is a member of
854         if(li.picklist() && (this.isPO || this.isMeta || this.isUni)) {
855             var pl = 
856                 this.plCache[li.picklist()] = 
857                 this.plCache[li.picklist()] || 
858                 fieldmapper.standardRequest(
859                     ['open-ils.acq', 'open-ils.acq.picklist.retrieve.authoritative'],
860                     {params: [this.authtoken, li.picklist()]});
861             if (pl) {
862                 if (pl.name() == "") {
863                     openils.Util.show(nodeByName("bib_origin", row), "inline");
864
865                 } else {
866
867                     openils.Util.show(nodeByName('pl', row), 'inline');
868                     var link = nodeByName('pl_link', row);
869                     link.setAttribute('href', oilsBasePath +
870                         '/acq/picklist/view/' + li.picklist() +
871                         '?focus_li=' + li.id() +
872                         '&source=' + encodeURIComponent(location.pathname + location.search)
873                     );
874                     link.innerHTML += pl.name();
875                 }
876             }
877         }
878
879         var countNode = nodeByName('count', row);
880         var count = li.item_count() || 0;
881         if (typeof(this._copy_count_cb) == "function") {
882             this._copy_count_cb(li.id(), count);
883         }
884         countNode.innerHTML = count;
885         countNode.id = 'acq-lit-copy-count-label-' + li.id();
886
887         // lineitem price
888         var priceInput = dojo.query('[name=price]', row)[0];
889         priceInput.value = li.estimated_unit_price() || '';
890         priceInput.onchange = function() { self.updateLiPrice(priceInput, li) };
891
892         // show either "mark received" or "unreceive" as appropriate
893         this.updateLiState(li, row);
894
895         if (skip_final_placement) {
896             return row;
897         }
898
899         // the last LI may be rendered after the call to show('list'),
900         // so make sure it's focused if necessary.
901         if (this.focusLineitem == li.id())
902             this.focusLi();
903     };
904
905     this._liCountClaims = function(li) {
906         var total = 0;
907         for (var i = 0; i < li.lineitem_details().length; i++)
908             total += li.lineitem_details()[i].claims().length;
909         return total;
910     };
911
912     this._findLiRow = function(li) {
913         return dojo.query('tr[li="' + li.id() + '"]', "acq-lit-tbody")[0];
914     };
915
916     this.reconsiderClaimControl = function(li, row) {
917         if (!row) row = this._findLiRow(li);
918         var option = nodeByName("action_manage_claims", row);
919         var eligible = this.claimEligibleLidByLi[li.id()].length;
920         var count = this._liCountClaims(li);
921
922         option.disabled = !(count || eligible);
923         option.innerHTML =
924             dojo.string.substitute(localeStrings.NUM_CLAIMS_EXISTING, [count]);
925         option.onclick = function() { self.claimDialog.show(li); };
926     };
927
928     this.clearEligibility = function(li) {
929         this.claimEligibleLidByLi[li.id()] = [];
930
931         if (li.lineitem_details()) {
932             li.lineitem_details().forEach(
933                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
934             );
935         }
936
937         if (this.copyCache) {
938             var to_del = [];
939             for (var k in this.copyCache) {
940                 if (this.copyCache[k].lineitem() == li.id())
941                     to_del.push(k);
942             }
943             to_del.forEach(
944                 function(k) { delete self.claimEligibleLid[k]; }
945             );
946         }
947     };
948
949     this.applyOrderIdentValues = function() {
950         this._identValuesInFlight = 
951             openils.Util.objectProperties(this.liCache).length;
952         for (var liId in this.liCache) {
953             this._applyOrderIdentValue(this.liCache[liId]);
954         }
955     };
956
957     // returns true if request was sent
958     this._applyOrderIdentValue = function(li, oncomplete) {
959         var self = this;
960
961         console.log('applying ident value for lineitem ' + li.id());
962
963         // main row
964         var row = dojo.query('[li=' + li.id() + ']')[0];
965
966         // find the selected ident value
967         var typeSel = dojo.query('[name=order_ident_type]', row)[0];
968         var valueSel = dojo.query('[name=order_ident_value]', row)[0];
969         var name = typeSel.options[typeSel.selectedIndex].value;
970         var val = typeSel._cbox.attr('value');
971
972         console.log("selected ident is " + val);
973
974         // it differs from the existing ident value, update it
975         var oldIdent = self.getLiOrderIdent(li);
976         if (oldIdent && 
977             oldIdent.attr_name() == name &&
978             oldIdent.attr_value() == val) {
979                 console.log('selected ident attr matches existing attr');
980                 if (--this._identValuesInFlight == 0) {
981                     if (oncomplete) oncomplete(li);
982                     else location.href = location.href;
983                 }
984                 return false;
985         }
986
987         // see if the selected ident value is represented
988         // by an existing lineitem attr
989
990         var args = {};
991         typeSel._cbox.store.fetch({
992             query : {attr_value : val},
993             onItem : function(item) {                                                       
994                 console.log('found existing attr for ident value');
995                 args.source_attr_id = li.attributes().filter(
996                     function(attr) { return attr.id() == item.id[0] }
997                 )[0];
998             }                                                                      
999         }); 
1000
1001
1002         if (!args.source_attr_id) {
1003             // user entered new text in the combobox
1004             // so we need to create a new attr
1005             console.log('creating new ident attr');
1006             args.lineitem_id = li.id();
1007             args.attr_name = name;
1008             args.attr_value = val;
1009         }
1010
1011         fieldmapper.standardRequest(
1012             ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1013             {   async : true,
1014                 params : [openils.User.authtoken, args],
1015                 oncomplete : function() {
1016                     console.log('order_ident oncomplete');
1017                     if (--self._identValuesInFlight == 0) {
1018                         if (oncomplete) oncomplete(li);
1019                         else location.href = location.href;
1020                     }
1021                     console.log(self._identValuesInFlight + ' still in flight');
1022                 }
1023             }
1024         );
1025
1026         return true;
1027     };
1028
1029     this.getLiOrderIdent = function(li) {
1030         var attrs = li.attributes();
1031         if (!attrs) return null;
1032         return attrs.filter(
1033             function(attr) {
1034                 return (
1035                     attr.attr_type() == 'lineitem_local_attr_definition' &&
1036                     openils.Util.isTrue(attr.order_ident())
1037                 );
1038             }
1039         )[0];
1040     };
1041
1042     this.drawOrderIdentSelector = function(li, row) {
1043         var self = this;
1044         var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1045         var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1046
1047         var attrs = li.attributes();
1048
1049         // limit to MARC attr defs
1050         attrs = attrs.filter(
1051             function(attr) {
1052                 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1053             }
1054         );
1055
1056         var identAttr = this.getLiOrderIdent(li);
1057
1058
1059         // collect the values for each type of identifier
1060         // find a reasonable default identifier type to render
1061         
1062         var values = {};
1063         var typeSet = null;
1064         dojo.forEach(['isbn', 'upc', 'issn'],
1065             function(name) {
1066
1067                 // collect the values for this attr name
1068                 values[name] =  attrs.filter(
1069                     function(attr) {
1070                         return (attr.attr_name() == name)
1071                     }
1072                 );
1073
1074                 // select a reasonable default name in the type-selector
1075                 if (!typeSet) {
1076                     var useMe = false;
1077                     if (identAttr) {
1078                         if (identAttr.attr_name() == name)
1079                             useMe = true;
1080                     } else if (values[name].length) {
1081                         useMe = true;
1082                     }
1083
1084                     if (useMe) {
1085                         dojo.forEach(typeSel.options, function(opt) {
1086                             if (opt.value == name) {
1087                                 opt.selected = true;
1088                                 typeSet = name;
1089                             }
1090                         });
1091                     }
1092                 }
1093             }
1094         );
1095
1096         function updateOrderIdent(val) {
1097             self._identValuesInFlight = 1;
1098             self._applyOrderIdentValue(
1099                 this._lineitem,
1100                 function(li) {
1101                     self.refreshLineitem(li);
1102                 }
1103             );
1104         }
1105
1106         // replace the ident combobox with a new 
1107         // one for the selected ident type 
1108         function changeComboBox(sel) {
1109             var name = sel.options[sel.selectedIndex].value;
1110
1111             var td = dojo.query('[name=order_ident_value]', row)[0];
1112             if (td.childNodes[0]) 
1113                 dojo.destroy(td.childNodes[0]);
1114
1115             var store = new dojo.data.ItemFileWriteStore({
1116                 data : acqlia.toStoreData(values[name])
1117             });
1118
1119             var cbox = new dijit.form.ComboBox(
1120                 {   store : store,
1121                     labelAttr : 'attr_value',
1122                     searchAttr : 'attr_value'
1123                 }, 
1124                 dojo.create('div', {}, td)
1125             );
1126
1127             cbox.startup();
1128
1129             // set the value for the cbox
1130             if (values[name].length) {
1131                 var orderIdent = self.getLiOrderIdent(li);
1132
1133                 if (orderIdent && orderIdent.attr_name() == name) {
1134                     cbox.attr('value', orderIdent.attr_value());
1135                 } else  {
1136                     cbox.attr('value', values[name][0].attr_value());
1137                 }
1138             }
1139
1140             if (!self.orderIdentAllowed) 
1141                 cbox.attr('disabled', true);
1142
1143             sel._cbox = cbox;
1144             cbox._lineitem = li;
1145             dojo.connect(cbox, 'onChange', updateOrderIdent);
1146         }
1147
1148         changeComboBox(typeSel); // force the initial draw
1149         typeSel.onchange = function() {changeComboBox(typeSel)};
1150     };
1151
1152     this.testOrderIdentPerms = function(org, callback) {
1153         var self = this;
1154         new openils.User().getPermOrgList(
1155             'ACQ_SET_LINEITEM_IDENTIFIER',
1156             function(orgs) { 
1157                 console.log('found orgs = ' + orgs);
1158                 for (var i = 0; i < orgs.length; i++) {
1159                     if (Number(orgs[i]) == Number(org)) {
1160                         self.orderIdentAllowed = true;
1161                         if (callback) callback();
1162                         return;
1163                     }
1164                 }
1165                 if (callback) callback();
1166             }, 
1167             true, true
1168         );
1169     };
1170
1171     this.checkClaimEligibility = function(li, callback, row) {
1172         /* Assume always eligible, i.e. from this interface we don't care about
1173          * claim eligibility any more. this is where the user would force a
1174          * claime. */
1175         this.clearEligibility(li);
1176         this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1177             function(lid) { return lid.id(); }
1178         );
1179         li.lineitem_details().forEach(
1180             function(lid) { self.claimEligibleLid[lid.id()] = true; }
1181         );
1182         this.reconsiderClaimControl(li, row);
1183         if (callback) callback(li);
1184         /*
1185         this.clearEligibility(li);
1186         fieldmapper.standardRequest(
1187             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1188                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1189                 "async": true,
1190                 "onresponse": function(r) {
1191                     if (r = openils.Util.readResponse(r)) {
1192                         self.claimEligibleLidByLi[li.id()].push(
1193                             r.lineitem_detail()
1194                         );
1195                         self.claimEligibleLid[r.lineitem_detail()] = true;
1196                     }
1197                 },
1198                 "oncomplete": function() {
1199                     self.reconsiderClaimControl(li, row);
1200                     if (typeof(callback) == "function")
1201                         callback();
1202                 }
1203             }
1204         );
1205         */
1206     };
1207
1208     this.updateLiNotesCount = function(li, row) {
1209         if (!row) row = this._findLiRow(li);
1210
1211         var has_notes = (li.lineitem_notes().filter(
1212                 function(o) { return Boolean (o.alert_text()); }
1213             ).length > 0);
1214
1215         /* U+2691 is the code point for a filled-in flag character */
1216         nodeByName("notes_alert_flag", row).innerHTML =
1217              has_notes ? "&#x2691;" : "";
1218         nodeByName("noteslink", row).style.fontStyle =
1219             has_notes ? "italic" : "normal";
1220         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1221     };
1222
1223     /* XXX NOT related to _updateLiState(). rethink */
1224     this.updateLiState = function(li, row) {
1225         if (!row) row = this._findLiRow(li);
1226
1227         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1228         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1229
1230         // always allow access to LI history
1231         nodeByName('action_view_history', row).onclick = 
1232             function() { location.href = oilsBasePath + '/acq/lineitem/history/' + li.id(); };
1233
1234         /* handle row coloring for based on LI state */
1235         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1236         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1237
1238         // Expose invoice actions for any lineitem that is linked to a PO 
1239         if (li.purchase_order()) {
1240             openils.Util.show(nodeByName("invoices_span", row), "inline");
1241             var link = nodeByName("invoices_link", row);
1242             link.onclick = function() {
1243                 var url = oilsBasePath + "/acq/search/unified?so=" +
1244                           base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1245                 if (window.IAMBROWSER) {
1246                     xulG.relay_url(url);
1247                 } else {
1248                     openils.XUL.newTabEasy(url);
1249                 }
1250                 return false;
1251             };
1252         }
1253                 
1254
1255         /*
1256          * If we haven't fleshed the lineitem_details, default to allowing access to the 
1257          * holdings maintenence actions.  The alternative is to flesh LIDs on every lineitem, 
1258          * but that will add to page render time.  Let's see if this will suffice...
1259          */
1260         var lids = li.lineitem_details();
1261         if( !lids || 
1262                 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1263
1264             actUpdateBarcodes.disabled = false;
1265             actUpdateBarcodes.onclick = function() {
1266                 self.showRealCopyEditUI(li);
1267                 nodeByName("action_none", row).selected = true;
1268             }
1269             actHoldingsMaint.disabled = false;
1270             actHoldingsMaint.onclick = 
1271                 self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row );
1272         }
1273
1274         var state_cell = nodeByName("li_state_" + li.state(), row);
1275
1276         // re-hide any state label nodes which may have been un-hidden
1277         // through previous actions.
1278         dojo.query('[state-label]', row).forEach(function(node) {
1279             openils.Util.hide(node)
1280         });
1281
1282         if (li.state() == 'cancelled') {
1283             if(typeof li.cancel_reason() == "object") {
1284
1285                 // clear the stock "Canceled" label, since we have more
1286                 // information to replace it with.
1287                 state_cell.innerHTML = '';
1288
1289                 var holds_state = dojo.create(
1290                     "span", {
1291                         "style": "border-bottom: 1px dashed #000;",
1292                         "innerHTML": li.cancel_reason().label()
1293                     }, state_cell, "only"
1294                 );
1295                 new dijit.Tooltip(
1296                     {
1297                         "label": "<em>" + li.cancel_reason().label() +
1298                             "</em><br />" + li.cancel_reason().description(),
1299                         "connectId": [holds_state]
1300                     }, dojo.create("span", null, state_cell, "last")
1301                 );
1302
1303                 if (li.cancel_reason().keep_debits() == 't') {
1304                     openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1305                     openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1306                 }
1307             } else {
1308                 console.log('li cancel_reason is un-fleshed.  Please fix');
1309             }
1310         } 
1311
1312         openils.Util.show(state_cell);
1313     };
1314
1315
1316     this._setAlertStore = function() {
1317         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1318             {
1319                 "data": acqliat.toStoreData(
1320                     this.pcrud.search(
1321                         "acqliat", {
1322                             "owning_lib": aou.orgNodeTrail(
1323                                 aou.findOrgUnit(openils.User.user.ws_ou())
1324                             ).map(function(o) { return o.id(); })
1325                         }
1326                     )
1327                 )
1328             }
1329         );
1330         acqLitAlertAlertText.setValue(); /* make the store "live" */
1331         acqLitAlertAlertText._store_ready = true;
1332     };
1333
1334     /**
1335      * Draws and shows the lineitem notes pane
1336      */
1337     this.drawLiNotes = function(li) {
1338         var self = this;
1339         this.focusLineitem = li.id();
1340
1341         if (!acqLitAlertAlertText._store_ready)
1342             this._setAlertStore();
1343
1344         li.lineitem_notes(
1345             li.lineitem_notes().sort(
1346                 function(a, b) { 
1347                     if(a.edit_time() < b.edit_time()) return 1;
1348                     return -1;
1349                 }
1350             )
1351         );
1352
1353         while(this.liNotesTbody.childNodes[0])
1354             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1355         this.show('notes');
1356
1357         acqLitCreateNoteSubmit.onClick = function() {
1358             var value = acqLitCreateNoteText.attr('value');
1359             if(!value) return;
1360             var note = new fieldmapper.acqlin();
1361             note.isnew(true);
1362             note.vendor_public(
1363                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1364             );
1365             note.value(value);
1366             note.lineitem(li.id());
1367
1368             self.updateLiNotes(li, note);
1369             acqLitCreateNoteVendorPublic.attr("checked", false);
1370             acqLitCreateNoteText.attr("value", "");
1371         }
1372
1373         acqLitCreateAlertSubmit.onClick = function() {
1374             if (!acqLitAlertAlertText.item) {
1375                 alert(localeStrings.ALERT_UNSELECTED);
1376                 return;
1377             }
1378
1379             var alert_text = new fieldmapper.acqliat().fromStoreItem(
1380                 acqLitAlertAlertText.item
1381             );
1382             var value = acqLitAlertNoteValue.attr("value") || "";
1383
1384             var note = new fieldmapper.acqlin();
1385             note.isnew(true);
1386             note.lineitem(li.id());
1387             note.value(value);
1388             note.alert_text(alert_text);
1389
1390             self.updateLiNotes(li, note);
1391         }
1392
1393         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1394     }
1395
1396     /**
1397      * Draws a single lineitem note in the notes pane
1398      */
1399     this.addLiNote = function(li, note) {
1400         if(note.isdeleted()) return;
1401         var self = this;
1402         var row = self.liNotesRow.cloneNode(true);
1403         nodeByName("value", row).innerHTML = note.value();
1404         var alert_node = nodeByName("alert_code", row);
1405         if (note.alert_text()) {
1406             alert_node.innerHTML = dojo.string.substitute(
1407                 "[${0}] ${1}", [
1408                     aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1409                     note.alert_text().code()
1410                 ]
1411             );
1412             if (note.alert_text().description()) {
1413                 new dijit.Tooltip(
1414                     {
1415                         "connectId": [alert_node],
1416                         "label": note.alert_text().description()
1417                     }, dojo.create("span", null, alert_node, "after")
1418                 );
1419             }
1420         }
1421
1422         if (openils.Util.isTrue(note.vendor_public()))
1423             nodeByName("vendor_public", row).innerHTML =
1424                 localeStrings.VENDOR_PUBLIC;
1425
1426         nodeByName("delete", row).onclick = function() {
1427             note.isdeleted(true);
1428             self.liNotesTbody.removeChild(row);
1429             self.updateLiNotes(li);
1430         };
1431
1432         if(note.edit_time()) {
1433             nodeByName("edit_time", row).innerHTML =
1434                 dojo.date.locale.format(
1435                     dojo.date.stamp.fromISOString(note.edit_time()), 
1436                     {formatLength:'short'});
1437         }
1438
1439         self.liNotesTbody.appendChild(row);
1440     }
1441
1442     /**
1443      * Updates any new/changed/deleted notes on the server
1444      */
1445     this.updateLiNotes = function(li, newNote) {
1446
1447         var notes;
1448         if(newNote) {
1449             notes = [newNote];
1450         } else {
1451             notes = li.lineitem_notes().filter(
1452                 function(note) {
1453                     if(note.ischanged() || note.isnew() || note.isdeleted())
1454                         return note;
1455                 }
1456             );
1457         }
1458
1459         if(notes.length == 0) return;
1460         progressDialog.show();
1461
1462         fieldmapper.standardRequest(
1463             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1464             {   async : true,
1465                 params : [this.authtoken, notes],
1466                 onresponse : function(r) {
1467                     var resp = openils.Util.readResponse(r);
1468
1469                     if(resp.complete) {
1470
1471                         if(!newNote) {
1472                             // remove the old changed notes
1473                             var list = [];
1474                             dojo.forEach(li.lineitem_notes(), 
1475                                 function(note) {
1476                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1477                                         list.push(note);
1478                                 }
1479                             );
1480                             li.lineitem_notes(list);
1481                         }
1482
1483                         progressDialog.hide();
1484                         self.updateLiNotesCount(li);
1485                         self.drawLiNotes(li);
1486                         return;
1487                     }
1488
1489                     progressDialog.update(resp);
1490                     var newnote = resp.note;
1491
1492                     if(!newnote.isdeleted()) {
1493                         newnote.isnew(false);
1494                         newnote.ischanged(false);
1495                         li.lineitem_notes().push(newnote);
1496                     }
1497                 },
1498             }
1499         );
1500     }
1501
1502     this.updateLiPrice = function(input, li) {
1503         var self = this;
1504         var price = input.value;
1505         if(Number(price) == Number(li.estimated_unit_price())) return;
1506
1507         fieldmapper.standardRequest(
1508             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1509             {   async : false, // redundant w/ timeout
1510                 timeout : 10,
1511                 params : [this.authtoken, li.id(), price],
1512                 oncomplete : function(r) {
1513                     openils.Util.readResponse(r);
1514                     li.estimated_unit_price(price); // update local copy
1515
1516                     /*
1517                      * If this is a PO and every visible lineitem has a price,
1518                      * check again to see if this PO can be activated.  Note that 
1519                      * every visible lineitem having a price does not guarantee it can
1520                      * be activated, which is why we still make the call.  Having a price
1521                      * set for every visiable lineitem is just the lowest barrier to entry.
1522                      */
1523                     if (self.isPO) {
1524                         var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1525                         var allSet = true;
1526                         dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1527                         if (allSet) checkCouldActivatePo();
1528                         refreshPOSummaryAmounts();
1529                     }
1530                 }
1531             }
1532         );
1533     }
1534
1535     this.removeLineitem = function(liId) {
1536         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1537         delete this.liCache[liId];
1538         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1539     }
1540
1541     this.drawInfo = function(liId) {
1542         this.focusLineitem = liId;
1543         if (!this._isRelatedViewer) {
1544             var d = dojo.byId("acq-lit-info-related");
1545             if (!this.relCache[liId]) {
1546                 fieldmapper.standardRequest(
1547                     [
1548                         "open-ils.acq",
1549                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1550                     ], {
1551                         "async": true,
1552                         "params": [openils.User.authtoken, liId],
1553                         "onresponse": function(r) {
1554                             self.relCache[liId] = openils.Util.readResponse(r);
1555                             nodeByName("related_number", d).innerHTML =
1556                                 self.relCache[liId];
1557                             openils.Util[
1558                                 self.relCache[liId] >1 ? "show" : "hide"
1559                             ](d);
1560                         }
1561                     }
1562                 );
1563             } else {
1564                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1565                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1566             }
1567         }
1568
1569         this.show('info');
1570         openils.acq.Lineitem.fetchAttrDefs(
1571             function() { 
1572                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
1573             } 
1574         );
1575     };
1576
1577     this.toggleInlineCopies = function() {
1578         // if any inline copies are not displayed, 
1579         // display them all otherwise, hide them all.
1580
1581         var displayAll = false;
1582
1583         for (var liId in this.liCache) {
1584             if (!this.inlineCopiesVisible(liId)) {
1585                 displayAll = true;
1586                 break;
1587             }
1588         }
1589
1590         for (var liId in this.liCache) {
1591             var row = dojo.byId('acq-inline-copies-row-' + liId);
1592             if (displayAll) {
1593                 if (!row || row._hidden) {
1594                     this.drawInlineCopies(liId);
1595                 }
1596             } else { // hide all
1597                 if (row) {
1598                     // drawInlineCopies() on a visible row will hide it.
1599                     this.drawInlineCopies(liId);
1600                 }
1601             }
1602         }
1603
1604     };
1605
1606     this.inlineCopiesVisible = function(liId) {
1607         var row = dojo.byId('acq-inline-copies-row-' + liId); 
1608         return (row && !row._hidden);
1609     }
1610
1611     this.refreshInlineCopies = function(all, reFetch) {
1612         var self = this;
1613         var liIds = this.inlineCopiesNeedingRefresh;
1614         if (all) liIds = openils.Util.objectProperties(liCache);
1615         liIds.forEach(function(liId) {
1616             if (self.inlineCopiesVisible(liId)) {
1617                 self.drawInlineCopies(liId, reFetch); // hide
1618                 self.drawInlineCopies(liId, reFetch); // re-draw
1619             }
1620         });
1621     };
1622
1623     // draw inline copy table.  if the table is 
1624     // already visible, hide the table as-is
1625     // reFetch forces a retrieval of the lineitem and 
1626     // copies from the server.  otherwise the locally
1627     // cached version of each is used.
1628     this.drawInlineCopies = function(liId, reFetch) {
1629         var self = this;
1630             
1631         // find or create the row where the inline copies table will live
1632         var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1633         var liRow = dojo.query('[li=' + liId + ']')[0];
1634
1635         if (!containerRow) {
1636
1637             // build the inline copies container row and add it to 
1638             // the DOM directly after the primary lineitem row
1639
1640             containerRow = self.inlineCopyContainer.cloneNode(true);
1641             containerRow.id = 'acq-inline-copies-row-' + liId;
1642
1643             if (liRow.nextSibling) {
1644                 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1645             } else {
1646                 self.tbody.appendChild(containerRow);
1647             }
1648
1649         } else {
1650
1651             // toggle the visible state
1652             containerRow._hidden = !containerRow._hidden;
1653             openils.Util.toggle(containerRow, 'table-row');
1654
1655             if (containerRow._hidden) return; // hide only
1656         }
1657
1658         var handler = function(li) {
1659
1660             var tbody = dojo.query(
1661                 '[name=acq-li-inline-copies-tbody]', 
1662                 containerRow)[0];
1663
1664             // reset the table before adding copy rows
1665             while (tbody.childNodes[0])
1666                 tbody.removeChild(tbody.childNodes[0]);
1667
1668             if(li.lineitem_details().length == 0) {
1669                 tbody.appendChild(
1670                     self.inlineNoCopies.cloneNode(true));
1671                 return; // no copies to show
1672             }
1673
1674             // add a row to the inline copy table for each copy
1675             dojo.forEach(li.lineitem_details(),
1676                 function(copy) {
1677                     var row = self.inlineCopyTemplate.cloneNode(true);
1678                     tbody.appendChild(row);
1679                     self.addInlineCopy(li, copy, row);
1680                 }
1681             );
1682         };
1683
1684         this._fetchLineitem(liId, handler, reFetch);
1685     };
1686
1687     /** Draw read-only copy widgets for inline copies */
1688     this.addInlineCopy = function(li, copy, row) {
1689
1690         var self = this;
1691         dojo.forEach(liDetailFields,
1692             function(field) {
1693
1694                 var widget = new openils.widget.AutoFieldWidget({
1695                     fmObject : copy,
1696                     fmField : field,
1697                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1698                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1699                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1700                     fmClass : 'acqlid',
1701                     parentNode : dojo.query('[name=' + field + ']', row)[0],
1702                     readOnly : true,
1703                 });
1704
1705                 widget.build();
1706             }
1707         );
1708     };
1709
1710     /* For a given list of lineitem ids, build a list of full lineitems
1711      * re-using the fetching logic that is otherwise typical to use in this
1712      * module.
1713      *
1714      * If we've already got a lineitem in the cache, just use that.
1715      *
1716      * Once we've built a list of lineitems, call callback(thatlist).
1717      */
1718     this.fetchLineitemsById = function(id_list, callback) {
1719         var total = id_list.length;
1720         var result_list = [];
1721
1722         var inner = function(li) {
1723             result_list.push(li)
1724             if (--total <= 0)
1725                 callback(result_list);
1726         };
1727
1728         id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1729     };
1730
1731     this._fetchLineitem = function(liId, handler, force) {
1732
1733         var li = this.liCache[liId];
1734         if(li && li.marc() && li.lineitem_details() && !force)
1735             return handler(li);
1736         
1737         fieldmapper.standardRequest(
1738             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1739             {   async: true,
1740
1741                 params: [self.authtoken, liId, {
1742                     flesh_attrs: true,
1743                     flesh_cancel_reason: true,
1744                     flesh_li_details: true,
1745                     flesh_notes: true,
1746                     flesh_fund_debit: true }],
1747
1748                 oncomplete: function(r) {
1749                     var li = openils.Util.readResponse(r);
1750                     self.liCache[liId] = li;
1751                     handler(li)
1752                 }
1753             }
1754         );
1755     };
1756
1757     this._drawInfo = function(li) {
1758
1759         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1760
1761         if(li.eg_bib_id()) {
1762             openils.Util.hide('acq-lit-marc-order-record-label');
1763             openils.Util.hide(acqLitEditOrderMarc.domNode);
1764             openils.Util.show('acq-lit-marc-real-record-label');
1765         } else {
1766             openils.Util.show('acq-lit-marc-order-record-label');
1767             openils.Util.show(acqLitEditOrderMarc.domNode);
1768             openils.Util.hide('acq-lit-marc-real-record-label');
1769         }
1770
1771         this.drawMarcHTML(li);
1772         this.infoTbody = dojo.byId('acq-lit-info-tbody');
1773
1774         if(!this.infoRow)
1775             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1776         while(this.infoTbody.childNodes[0])
1777             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1778
1779         for(var i = 0; i < li.attributes().length; i++) {
1780             var attr = li.attributes()[i];
1781             var row = this.infoRow.cloneNode(true);
1782
1783             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1784             var name = openils.acq.Lineitem.attrDefs[type].filter(
1785                 function(a) {
1786                     return (a.code() == attr.attr_name());
1787                 }
1788             ).pop().description();
1789
1790             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1791             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1792             this.infoTbody.appendChild(row);
1793         }
1794
1795         if (!this._isRelatedViewer) {
1796             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1797                 oilsBasePath + "/acq/lineitem/related/" + li.id();
1798         }
1799
1800         // if a top scroll point is defined, jump up to it here
1801         var node = dojo.byId('oils-scroll-to-top');
1802         if (node) dijit.scrollIntoView(node);
1803     };
1804
1805     this.generateMakeRecTab = function(bib_id,default_view, row) {
1806         return function() {
1807             if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1808                 xulG.new_tab(
1809                     XUL_OPAC_WRAPPER,
1810                     {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1811                     {
1812                         no_xulG : false, 
1813                         show_nav_buttons : true, 
1814                         show_print_button : true, 
1815                         opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1816                         default_view : default_view
1817                     }
1818                 );
1819             } else {
1820                 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1821                 if (default_view == 'copy_browser') {
1822                     url += '/holdings';
1823                 }
1824                 window.open(url);
1825             }
1826
1827             if(row) nodeByName("action_none", row).selected = true;
1828         }
1829     };
1830
1831     this.drawMarcHTML = function(li) {
1832         var params = [null, true, li.marc()];
1833         if(li.eg_bib_id()) 
1834             params = [li.eg_bib_id(), true];
1835
1836         fieldmapper.standardRequest(
1837             ['open-ils.search', 'open-ils.search.biblio.record.html'],
1838             {   async: true,
1839                 params: params,
1840                 oncomplete: function(r) {
1841                     dojo.byId('acq-lit-marc-div').innerHTML = 
1842                         openils.Util.readResponse(r);
1843                 }
1844             }
1845         );
1846     }
1847
1848     this.drawCopies = function(liId, force_fetch) {
1849         this.focusLineitem = liId;
1850         if (typeof force_fetch == "undefined")
1851             force_fetch = false;
1852
1853         var cgi = new openils.CGI();
1854         var source = cgi.param('source');
1855         if (source && source.match(/invoice/)) {
1856             // got here from the invoice page, show the 'return-to-invoice' button
1857             var cgi = new openils.CGI({url : source});
1858             cgi.param('focus_li', liId);
1859             openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1860             var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1861             button.onclick = function() { location.href = cgi.url() };
1862         }
1863
1864         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1865             function(li, html) {
1866                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1867             }
1868         );
1869
1870         this.show('copies');
1871         var self = this;
1872         this.copyCache = {};
1873         this.copyWidgetCache = {};
1874         this.oldCopyWidgetCache = {};
1875         this.virtDfaCounts = {};
1876         this.realDfaCache = {};
1877         this.dfeOffset = 0;
1878
1879         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1880         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1881         acqLitCopyCountInput.attr('value', '0');
1882
1883         if (this.isPO && PO && PO.order_date()) {
1884             // prevent adding copies to activated POs
1885             acqLitCopyCountInput.attr('disabled', true);
1886             acqLitAddCopyCount.attr('disabled', true);
1887         }
1888
1889         while(this.copyTbody.childNodes[0])
1890             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1891
1892         this._drawBatchCopyWidgets();
1893
1894         this._drawDistribApplied(liId);
1895
1896         this._fetchDistribFormulas(
1897             function() {
1898                 openils.acq.Lineitem.fetchAttrDefs(
1899                     function() { 
1900                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1901                     } 
1902                 );
1903             }
1904         );
1905     };
1906
1907     this._saveDistribAppliedTemplates = function() {
1908         if (!this._appliedDistribTemplate) {
1909             this._appliedDistribTemplate =
1910                 dojo.byId("acq-lit-distrib-applied-tbody").
1911                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1912             dojo.attr(this._appliedDistribTemplate, "id");
1913         }
1914     };
1915
1916     this._drawDistribApplied = function(liId) {
1917         /* Build this table while hidden to prevent rendering artifacts */
1918         openils.Util.hide("acq-lit-distrib-applied-tbody");
1919
1920         this._saveDistribAppliedTemplates();
1921
1922         /* Remove any rows in the table from previous populations */
1923         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1924             forEach(dojo.destroy);
1925
1926         /* Unregister all dijits previously created (for some reason this isn't
1927          * covered by the above destroy calls). */
1928         dijit.registry.forEach(
1929             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1930         );
1931
1932         /* Populate the table with our liId */
1933         var total = 0;
1934         fieldmapper.standardRequest(
1935             ["open-ils.acq",
1936             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1937             {
1938                 "async": true,
1939                 "params": [self.authtoken, liId],
1940                 "onresponse": function(r) {
1941                     var dfa = openils.Util.readResponse(r);
1942                     if (dfa) {
1943                         total++;
1944                         self.realDfaCache[dfa.id()] = dfa;
1945                         self._drawDistribAppliedUnit(dfa);
1946                     }
1947                 },
1948                 "oncomplete": function() {
1949                     /* Reveal built table */
1950                     if (total) {
1951                         openils.Util.show(
1952                             "acq-lit-distrib-applied-tbody", "table-row-group"
1953                         );
1954                     }
1955                 }
1956             }
1957         );
1958     };
1959
1960     this._drawDistribAppliedUnit = function(dfa) {
1961         var new_row = false;
1962         var row = dojo.query(
1963             'tr[formula="' + dfa.formula().id() + '"]',
1964             "acq-lit-distrib-applied-tbody"
1965         )[0];
1966
1967         if (!row) {
1968             new_row = true;
1969             row = dojo.clone(this._appliedDistribTemplate);
1970             dojo.attr(row, "formula", dfa.formula().id());
1971             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1972         }
1973
1974         var td = dojo.query("td", row)[0];
1975
1976         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1977         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1978
1979         if (new_row)
1980             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1981
1982         new dijit.form.Button(
1983             {
1984                 "onClick": function() {
1985                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1986                         self.deleteDfa(dfa);
1987                 },
1988                 "label": "X",
1989                 /* XXX I /cannot/ make the following work in as a CSS class
1990                  * for some reason. So frustrating... */
1991                 "style": function(id) {
1992                      return (id > 0 ?
1993                         "font-weight: bold; color: #c00;" :
1994                         "color: #666;");
1995                      }(dfa.id()) + "margin: 0 6px;display: inline;"
1996             }, "dfa-button-" + dfa.id()
1997         );
1998         new dijit.Tooltip(
1999             {
2000                 "connectId": ["dfa-button-" + dfa.id()],
2001                 "label": dojo.string.substitute(
2002                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
2003                         openils.User.formalName(dfa.creator()),
2004                         dojo.date.locale.format(
2005                             dojo.date.stamp.fromISOString(dfa.create_time()),
2006                             {"formatLength":"short"}
2007                         )
2008                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2009                 )
2010             }, "dfa-tip-" + dfa.id()
2011         );
2012     }
2013
2014     this.deleteDfa = function(dfa) {
2015         if (dfa.id() > 0) { /* real */
2016             this.pcrud.eliminate(
2017                 dfa, {
2018                     "async": true,
2019                     "oncomplete": function() {
2020                         self._removeDistribApplied(dfa.id());
2021                         delete self.realDfaCache[dfa.id()];
2022                     }
2023                 }
2024             );
2025         } else { /* virtual */
2026             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2027             this.virtDfaCounts[dfa.formula().id()] = 0;
2028             /* hasn't been saved yet, so no need to do anything server side */
2029             this._removeDistribApplied(dfa.id());
2030         }
2031
2032     };
2033
2034     this._removeDistribApplied = function(dfaId) {
2035         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2036         dijit.registry.forEach(
2037             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2038         );
2039         this._removeDistribAppliedEmptyRows();
2040     };
2041
2042     this._removeAllDistribAppliedVirtual = function() {
2043         /* Unregister dijits */
2044         dijit.registry.forEach(
2045             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2046         );
2047         this._removeDistribAppliedEmptyRows();
2048     };
2049
2050     this._removeDistribAppliedEmptyRows = function() {
2051         /* Remove any rows with no DFA at all */
2052         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2053             function(o) {
2054                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2055             }
2056         );
2057     };
2058
2059     /**
2060      * Insert a new row into the distribution formula selection form
2061      */
2062     this._addDistribFormulaRow = function() {
2063         var self = this;
2064
2065         if (!self.distribForms) {
2066             // no formulas, hide the form
2067             openils.Util.hide('acq-lit-distrib-formula-table');
2068             return;
2069         }
2070
2071         if(!this.distribFormulaTemplate) 
2072             this.distribFormulaTemplate = 
2073                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2074
2075         var row = this.distribFormulaTemplate.cloneNode(true);
2076         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2077
2078         this.dfSelector = new dijit.form.FilteringSelect(
2079             {"labelAttr": "dynLabel", "labelType": "html"},
2080             nodeByName("selector", row)
2081         );
2082         this._updateFormulaStore();
2083         this.dfSelector.fetchProperties =
2084             {"sort": [{"attribute": "use_count", "descending": true}]};
2085
2086         var apply = new dijit.form.Button(
2087             {"label": localeStrings.APPLY},
2088             nodeByName('set_button', row)
2089         ); 
2090
2091         var reset = new dijit.form.Button(
2092             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2093             nodeByName("reset_button", row)  
2094         );
2095
2096         dojo.connect(apply, 'onClick', 
2097             function() {
2098                 var form_id = self.dfSelector.attr("value");
2099                 if(!form_id) return;
2100                 self._applyDistribFormula(form_id);
2101                 reset.attr("disabled", false);
2102             }
2103         );
2104
2105         dojo.connect(reset, 'onClick', 
2106             function() {
2107                 self.restoreCopyFieldsBeforeDF();
2108                 self.virtDfaCounts = {};
2109                 self.virtDfaId = -1;
2110                 self.dfeOffset = 0;
2111                 self._updateFormulaStore();
2112                 self._removeAllDistribAppliedVirtual();
2113                 reset.attr("disabled", "true");
2114             }
2115         );
2116
2117     };
2118
2119     /**
2120      * Applies a distrib formula to the current set of copies
2121      */
2122     this._applyDistribFormula = function(formula) {
2123         if(!formula) return;
2124
2125         formula = this.distribForms.filter(
2126             function(form) { return form.id() == formula; }
2127         )[0];
2128
2129         var copyRows = dojo.query('tr', self.copyTbody);
2130
2131         if (this.dfeOffset >= copyRows.length) {
2132             alert(localeStrings.OUT_OF_COPIES);
2133             return;
2134         }
2135
2136         var entries_applied = 0;
2137         for(
2138             var rowIndex = this.dfeOffset;
2139             rowIndex < copyRows.length;
2140             rowIndex++
2141         ) {
2142             
2143             var row = copyRows[rowIndex];
2144             var copy_id = row.getAttribute('copy_id');
2145             var copyWidgets = this.copyWidgetCache[copy_id];
2146             var entryIndex = this.dfeOffset;
2147             var entry = null;
2148
2149             // find the correct entry for the current row
2150             dojo.forEach(formula.entries(), 
2151                 function(e) {
2152                     if(!entry) {
2153                         entryIndex += e.item_count();
2154                         if(entryIndex > rowIndex)
2155                             entry = e;
2156                     }
2157                 }
2158             );
2159
2160             if(entry) {
2161                 
2162                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
2163                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2164     
2165                 entries_applied++;
2166                 this.saveCopyFieldsBeforeDF(copy_id);
2167                 this._copy_fields_for_acqdf.forEach(
2168                     function(field) {
2169                         if(entry[field]()) {
2170                             copyWidgets[field].attr('value', (entry[field]()));
2171                         }
2172                     }
2173                 );
2174             }
2175         }
2176
2177         if (entries_applied) {
2178             this.virtDfaCounts[formula.id()] =
2179                 ++(this.virtDfaCounts[formula.id()]) || 1;
2180             this._updateFormulaStore();
2181             this._drawDistribAppliedUnit(
2182                 function(df) {
2183                     var dfa = new acqdfa();
2184                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2185                 }(formula)
2186             );
2187             this.dfeOffset += entries_applied;
2188         };
2189     };
2190
2191     /**
2192      * This function updates the DF store for the dropdown so that use_counts
2193      * can reflect DF applications from this session before they're saved
2194      * server-side.
2195      */
2196     this._updateFormulaStore = function() {
2197         this.dfSelector.store = new dojo.data.ItemFileReadStore(
2198             {
2199                 "data": self._labelFormulasWithCounts(
2200                     acqdf.toStoreData(self.distribForms)
2201                 )
2202             }
2203         );
2204     };
2205
2206     this.saveCopyFieldsBeforeDF = function(copy_id) {
2207         var self = this;
2208         if (!this.oldCopyWidgetCache[copy_id]) {
2209             var copyWidgets = this.copyWidgetCache[copy_id];
2210
2211             this.oldCopyWidgetCache[copy_id] = {};
2212             this._copy_fields_for_acqdf.forEach(
2213                 function(f) {
2214                     self.oldCopyWidgetCache[copy_id][f] =
2215                         copyWidgets[f].attr("value");
2216                 }
2217             );
2218         }
2219     };
2220
2221     this.restoreCopyFieldsBeforeDF = function() {
2222         var self = this;
2223         for (var copy_id in this.oldCopyWidgetCache) {
2224             this._copy_fields_for_acqdf.forEach(
2225                 function(f) {
2226                     self.copyWidgetCache[copy_id][f].attr(
2227                         "value", self.oldCopyWidgetCache[copy_id][f]
2228                     );
2229                 }
2230             );
2231         }
2232     };
2233
2234     this._labelFormulasWithCounts = function(store_data) {
2235         for (var key in store_data.items) {
2236             var obj = store_data.items[key];
2237             obj.use_count = Number(obj.use_count); /* needed for sorting */
2238
2239             if (this.virtDfaCounts[obj.id])
2240                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2241
2242             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2243                 obj.use_count + "]</span>&nbsp; " + obj.name;
2244         }
2245         return store_data;
2246     };
2247
2248     /**
2249      * This method formerly would not refetch the DF formulas if they'd been
2250      * loaded already, but now it always re-fetches, since use_count changes.
2251      */
2252     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2253     this._fetchDistribFormulas = function(onload) {
2254         fieldmapper.standardRequest(
2255             ["open-ils.acq",
2256                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2257             {
2258                 "async": true,
2259                 "params": [openils.User.authtoken, 0, 500],
2260                 "oncomplete": function(r) {
2261                     self.distribForms = openils.Util.readResponse(r);
2262                     if(!self.distribForms || self.distribForms.length == 0) {
2263                         self.distribForms = [];
2264                     }
2265                     self._addDistribFormulaRow();
2266                     onload();
2267                 }
2268             }
2269         );
2270     }
2271
2272     this._drawBatchCopyWidgets = function() {
2273         var row = this.copyBatchRow;
2274         dojo.forEach(liDetailBatchFields, 
2275             function(field) {
2276                 if(self.copyBatchRowDrawn) {
2277                     self.copyBatchWidgets[field].attr('value', null);
2278                 } else {
2279                     var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2280                     args.parentNode = dojo.query('[name='+field+']', row)[0];
2281
2282                     var widget = new openils.widget.AutoFieldWidget(args);
2283                     widget.build(
2284                         function(w, ww) {
2285                             if (field == "fund" && w.store)
2286                                 self._ensureCSSFundClasses(w.store);
2287                             self.copyBatchWidgets[field] = w;
2288                         }
2289                     );
2290                     if (field == "fund") {
2291                         dojo.connect(
2292                             widget.widget, "onChange", function(val) {
2293                                 self._updateFundSelectorStyle(widget, val);
2294                             }
2295                         );
2296                     }
2297                 }
2298             }
2299         );
2300         this.copyBatchRowDrawn = true;
2301     };
2302
2303     this.batchCopyUpdate = function() {
2304         var self = this;
2305         for(var k in this.copyWidgetCache) {
2306             var cache = this.copyWidgetCache[k];
2307             dojo.forEach(liDetailBatchFields, function(f) {
2308                 var newval = self.copyBatchWidgets[f].attr('value');
2309                 if(newval) cache[f].attr('value', newval);
2310             });
2311         }
2312     };
2313
2314     this._drawCopies = function(li) {
2315         var self = this;
2316
2317         // this button sets the total number of copies for a given lineitem
2318         acqLitAddCopyCount.onClick = function() { 
2319             var count = acqLitCopyCountInput.attr('value');
2320
2321             // add new rows
2322             while(self.copyCount() < count)
2323                 self.addCopy(li); 
2324             
2325             // delete rows if necessary
2326             var diff = self.copyCount() - count;
2327             if(diff > 0) {
2328                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2329                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2330                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2331                 } else {
2332                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
2333                 }
2334             }
2335         }
2336
2337
2338         if(li.lineitem_details().length > 0) {
2339             dojo.forEach(li.lineitem_details(),
2340                 function(copy) {
2341                     self.addCopy(li, copy);
2342                 }
2343             );
2344         } else {
2345             self.addCopy(li);
2346         }
2347     };
2348
2349     this.copyCount = function() {
2350         var count = 0;
2351         for(var id in this.copyCache) {
2352             if(!this.copyCache[id].isdeleted())
2353                 count++;
2354         }
2355         return count;
2356     }
2357
2358     this.virtCopyId = -1;
2359     this.addCopy = function(li, copy) {
2360         var row = this.copyRow.cloneNode(true);
2361         this.copyTbody.appendChild(row);
2362         var self = this;
2363
2364         if(!copy) {
2365             copy = new fieldmapper.acqlid();
2366             copy.isnew(true);
2367             copy.id(this.virtCopyId--);
2368             copy.lineitem(li.id());
2369         }
2370
2371         this.copyCache[copy.id()] = copy;
2372         row.setAttribute('copy_id', copy.id());
2373         self.copyWidgetCache[copy.id()] = {};
2374
2375         acqLitCopyCountInput.attr('value', self.copyCount()+'');
2376
2377         var rcvr = copy.receiver();
2378         if (rcvr) {
2379             if (!userCache[rcvr]) {
2380                 if(rcvr == openils.User.user.id()) {
2381                     userCache[rcvr] = openils.User.user;
2382                 } else {
2383                     userCache[rcvr] = fieldmapper.standardRequest(
2384                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2385                         {params: [openils.User.authtoken, rcvr]}
2386                     );
2387                 }
2388             }
2389             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
2390         }
2391
2392         dojo.forEach(liDetailFields,
2393             function(field) {
2394                 var searchFilter;
2395                 if (field == "fund") {
2396                     searchFilter = (copy.fund() ?
2397                         {"-or": {"active": "t", "id": copy.fund()}} :
2398                         {"active" : "t"});
2399                     searchFilter.org = fundSearchFilter.org;
2400                 } else {
2401                     searchFilter = null;
2402                 }
2403
2404                 var readOnly = false;
2405                 
2406                 // TODO: Add support for changing the owning_lib after real copies have been made.  
2407                 // owning_lib is order data as much as its item data
2408                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2409                     readOnly = true;
2410                 }
2411
2412                 // TODO: add support for changing the fund after debits have been created
2413                 // Note: invoicing allows the change
2414                 if(copy.fund_debit() && field == 'fund') {
2415                     readOnly = true;
2416                 }
2417
2418
2419                 var widget = new openils.widget.AutoFieldWidget({
2420                     fmObject : copy,
2421                     fmField : field,
2422                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
2423                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
2424                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2425                     searchFilter : searchFilter,
2426                     noCache: (field == "fund"),
2427                     fmClass : 'acqlid',
2428                     parentNode : dojo.query('[name='+field+']', row)[0],
2429                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2430                     readOnly : readOnly,
2431                     orgDefaultsToWs : true
2432                 });
2433
2434                 widget.build(
2435                     // make sure we capture the value from any async widgets
2436                     function(w, ww) { 
2437
2438                         if (field == "fund" && w.store)
2439                             self._ensureCSSFundClasses(w.store);
2440
2441                         if(!readOnly) 
2442                             copy[field](ww.getFormattedValue()) 
2443
2444                         self.copyWidgetCache[copy.id()][field] = w;
2445
2446                         dojo.connect(w, 'onChange', 
2447                             function(val) { 
2448                                 if (field == "fund")
2449                                     self._updateFundSelectorStyle(widget, val);
2450
2451                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2452                                     // prevent setting ischanged() automatically on widget load for existing copies
2453                                     copy[field](widget.getFormattedValue()) 
2454                                     copy.ischanged(true);
2455                                 }
2456                             }
2457                         );
2458                     }
2459                 );
2460             }
2461         );
2462
2463         this.updateLidState(copy, row);
2464     };
2465
2466     this._ensureCSSFundClass = function(id) {
2467         if (!this.fundStyleSheet) {
2468             dojo.create(
2469                 "style", {"type": "text/css"},
2470                 document.getElementsByTagName("head")[0], "last"
2471             );
2472             this.fundStyleSheet = document.styleSheets[
2473                 document.styleSheets.length - 1
2474             ];
2475         }
2476
2477         var cn = "fund_" + id;
2478         if (!this.haveFundClass[cn]) {
2479             fieldmapper.standardRequest(
2480                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2481                 {
2482                     "params": [openils.User.authtoken, id],
2483                     "async": true,
2484                     "oncomplete": function(r) {
2485                         r = openils.Util.readResponse(r);
2486                         self.fundBalanceState[id] = r;
2487                         var style = "";
2488                         if (r[0] /* stop */)
2489                             style = fundStyles.stop;
2490                         else if (r[1] /* warning */)
2491                             style = fundStyles.warning;
2492                         self.fundStyleSheet.insertRule(
2493                             "." + cn + " { " + style + " }",
2494                             self.fundStyleSheet.cssRules.length
2495                         );
2496                         self.haveFundClass[cn] = true;
2497                     }
2498                 }
2499             );
2500         }
2501     };
2502
2503     this._ensureCSSFundClasses = function(store) {
2504         store.fetch({
2505             "query": {"id": "*"},
2506             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2507         });
2508     };
2509
2510     this._updateFundSelectorStyle = function(widget, fund_id) {
2511         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2512         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2513     };
2514
2515     this.updateLidState = function(copy, row) {
2516         var self = this;
2517
2518         if (typeof(row) == "undefined") {
2519             row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2520         }
2521
2522         // action links
2523         var recv_link = nodeByName("receive", row);
2524         var unrecv_link = nodeByName("unreceive", row);
2525         var del_link = nodeByName("delete", row);
2526         var cxl_link = nodeByName("cancel", row);
2527         var claim_link = nodeByName("claim", row);
2528         var cxl_reason_link = nodeByName("cancel_reason", row);
2529
2530         // by default, hide all the actions
2531         openils.Util.hide(del_link.parentNode);
2532         openils.Util.hide(recv_link);
2533         openils.Util.hide(unrecv_link);
2534         openils.Util.hide(cxl_link);
2535         openils.Util.hide(claim_link);
2536         openils.Util.hide(cxl_reason_link);
2537
2538         if (copy.id() > 0) { // real copies (LIDs)
2539
2540             if (copy.cancel_reason()) { 
2541
2542                 /* --------- cancelled -------------------------- */
2543
2544                 /* XXX the following may leak memory in a long lived table: 
2545                  * dijits may not get destroyed... not positive. revisit. */
2546                 var holds_reason = dojo.create(
2547                     "span", {
2548                         "style": "border-bottom: 1px dashed #000;",
2549                         "innerHTML": copy.cancel_reason().label()
2550                     }, cxl_reason_link, "only"
2551                 );
2552                 new dijit.Tooltip(
2553                     {
2554                         "label": "<em>" + copy.cancel_reason().label() +
2555                             "</em><br />" + copy.cancel_reason().description(),
2556                         "connectId": [holds_reason]
2557                     }, dojo.create("span", null, cxl_reason_link, "last")
2558                 );
2559                 openils.Util.show(cxl_reason_link, "inline");
2560
2561                 if (copy.cancel_reason().keep_debits() == 't' ) {
2562                     // allow further cancellation of "delayed" copies
2563                     
2564                     openils.Util.show(cxl_link, "inline");
2565                     cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2566                 }
2567
2568             } else if (copy.recv_time()) { 
2569
2570                 /* --------- received -------------------------- */
2571
2572                 openils.Util.show(unrecv_link, "inline");
2573                 unrecv_link.onclick = function() {
2574                     if (confirm(localeStrings.UNRECEIVE_LID))
2575                         self.issueReceive(copy, /* rollback */ true);
2576                 };
2577
2578             } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2579                 
2580                 /* --------- on order -------------------------- */
2581
2582                 openils.Util.show(recv_link, 'inline');
2583                 openils.Util.show(cxl_link, "inline");
2584
2585                 recv_link.onclick = function() {
2586                     if (self.checkLiAlerts(copy.lineitem()))
2587                         self.issueReceive(copy);
2588                 };
2589
2590                 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2591
2592             } else {
2593
2594                 /* --------- pre-order copies  -------------------------- */
2595
2596                 del_link.onclick = function() { self.deleteCopy(row) };
2597                 openils.Util.show(del_link.parentNode);
2598
2599             }
2600
2601         } else { 
2602
2603             /* --------- virtual copies  -------------------------- */
2604
2605             del_link.onclick = function() { self.deleteCopy(row) };
2606             openils.Util.show(del_link.parentNode);
2607         }
2608     };
2609
2610     this.cancelLid = function(lid_id) {
2611         lidCancelDialog._lid_id = lid_id;
2612         openils.Util.show(lidCancelDialog.domNode.parentNode);
2613         lidCancelDialog.show();
2614         if (!lidCancelDialog._prepared) {
2615             var widget = new openils.widget.AutoFieldWidget({
2616                 "fmField": "cancel_reason",
2617                 "fmClass": "acqlid",
2618                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2619                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2620                 "forceSync": true,
2621                 "searchOptions" : {order_by : {"acqcr":"label"}}
2622             });
2623             widget.build(
2624                 function(w, ww) {
2625                     acqLidCancelButton.onClick = function() {
2626                         if (w.attr("value")) {
2627                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2628                                 self._cancelLid(
2629                                     lidCancelDialog._lid_id,
2630                                     w.attr("value")
2631                                 );
2632                             }
2633                             lidCancelDialog.hide();
2634                         }
2635                     };
2636                     lidCancelDialog._prepared = true;
2637                 }
2638             );
2639         }
2640     };
2641
2642     this._cancelLid = function(lid_id, reason) {
2643         fieldmapper.standardRequest(
2644             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2645                 "params": [openils.User.authtoken, lid_id, reason],
2646                 "async": true,
2647                 "onresponse": function(r) {
2648                     if (r = openils.Util.readResponse(r)) {
2649                         if (r.lid) {
2650                             for (var id in r.lid) {
2651                                 /* actually this should only iterate once */
2652                                 self.copyCache[id].cancel_reason(
2653                                     r.lid[id].cancel_reason
2654                                 );
2655                                 self.updateLidState(self.copyCache[id]);
2656                             }
2657                         }
2658                     }
2659                 }
2660             }
2661         );
2662     };
2663
2664     this._confirmAlert = function(li, lin) {
2665         return confirm(
2666             dojo.string.substitute(
2667                 localeStrings.CONFIRM_LI_ALERT, [
2668                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2669                         "title", "lineitem_marc_attr_definition"
2670                     ), (
2671                         /* XXX it's really better add a parameter and to adjust
2672                          * the format string rather than do this concatenation
2673                          * here, but if someone wants this for 2.2 in a hurry,
2674                          * we can sidestep the problem of updating the strings
2675                          * while the translators are working. */
2676                         "[" +
2677                         aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2678                         "] " +
2679                         lin.alert_text().code()
2680                     ),
2681                     lin.alert_text().description() || "",
2682                     lin.value()
2683                 ]
2684             )
2685         );
2686     };
2687
2688     this.checkLiAlerts = function(li_id) {
2689         var li = this.liCache[li_id];
2690
2691         var alert_notes = li.lineitem_notes().filter(
2692             function(o) { return Boolean(o.alert_text()); }
2693         );
2694
2695         /* this is _intentionally_ not done in a call to forEach() ... */
2696         for (var i = 0; i < alert_notes.length; i++) {
2697             if (this.noteAcks[alert_notes[i].id()])
2698                 continue;
2699             else if (!this._confirmAlert(li, alert_notes[i]))
2700                 return false;
2701             else
2702                 this.noteAcks[alert_notes[i].id()] = true;
2703         }
2704
2705         return true;
2706     };
2707
2708     this.deleteCopy = function(row) {
2709         var copy = this.copyCache[row.getAttribute('copy_id')];
2710         copy.isdeleted(true);
2711         if(copy.isnew())
2712             delete this.copyCache[copy.id()];
2713         this.copyTbody.removeChild(row);
2714     }
2715
2716     this._virtDfaCountsAsList = function() {
2717         var L = [];
2718         for (var key in this.virtDfaCounts) {
2719             for (var i = 0; i < this.virtDfaCounts[key]; i++)
2720                 L.push(key);
2721         }
2722         return L;
2723     }
2724
2725     this.confirmBreachedCopyFunds = function(copies) {
2726         var stop = 0, warning = 0;
2727         copies.forEach(
2728             function(o) {
2729                 if (o.fund()) {
2730                     var state = self.fundBalanceState[o.fund()];
2731                     if (state[0] /* stop */)
2732                         stop++;
2733                     else if (state[1] /* warning */)
2734                         warning++;
2735                 }
2736             }
2737         );
2738
2739         if (stop) {
2740             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2741         } else if (warning) {
2742             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2743         }
2744         return true;
2745     };
2746
2747     this.saveCopyChanges = function(liId) {
2748         var self = this;
2749         var copies = [];
2750
2751
2752         var total = 0;
2753         for(var id in this.copyCache) {
2754             var c = this.copyCache[id];
2755             if(!c.isdeleted()) total++;
2756             if(c.isnew() || c.ischanged() || c.isdeleted()) {
2757                 if(c.id() < 0) c.id(null);
2758                 copies.push(c);
2759             }
2760         }
2761
2762
2763         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2764
2765
2766         if (copies.length > 0) {
2767             if (!this.confirmBreachedCopyFunds(copies))
2768                 return;
2769
2770             if (typeof(this._copy_count_cb) == "function")
2771                 this._copy_count_cb(liId, total);
2772
2773             openils.Util.show("acq-lit-update-copies-progress");
2774             fieldmapper.standardRequest(
2775                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2776                 {   async: true,
2777                     params: [openils.User.authtoken, copies],
2778                     onresponse: function(r) {
2779                         var res = openils.Util.readResponse(r);
2780                         litUpdateCopiesProgress.update(res);
2781                     },
2782                     oncomplete: function() {
2783                         self.drawCopies(liId, true /* force_fetch */);
2784                         openils.Util.hide("acq-lit-update-copies-progress");
2785                         refreshPOSummaryAmounts();
2786                     }
2787                 }
2788             );
2789         }
2790
2791         var dfa_list = this._virtDfaCountsAsList();
2792         if (dfa_list.length > 0) {
2793             fieldmapper.standardRequest(
2794                 ["open-ils.acq",
2795                 "open-ils.acq.distribution_formula.record_application"],
2796                 {
2797                     "async": true,
2798                     "params": [openils.User.authtoken, dfa_list, liId],
2799                     "onresponse": function(r) {
2800                         var res = openils.Util.readResponse(r);
2801                         if (res && res.length < dfa_list.length)
2802                             alert(localeStrings.DFA_NOT_ALL);
2803                     }
2804                 }
2805             );
2806             this.virtDfaCounts = {};
2807         }
2808
2809         if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2810             this.inlineCopiesNeedingRefresh.push(liId);
2811     };
2812
2813     this._updateCreatePoPrepayCheckbox = function(prepay) {
2814         var prepay = openils.Util.isTrue(prepay);
2815         this._prepayRequiredByVendor = prepay;
2816         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2817     };
2818
2819     this._confirmPoPrepaySituation = function() {
2820         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2821         if (want_prepay != this._prepayRequiredByVendor) {
2822             return confirm(
2823                 want_prepay ?
2824                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2825                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2826             );
2827         } else {
2828             return true;
2829         }
2830     };
2831
2832     this.applySelectedLiAction = function(action) {
2833         var self = this;
2834         switch(action) {
2835
2836             case 'delete_selected':
2837                 this._deleteLiList(self.getSelected());
2838                 break;
2839
2840             case 'add_to_order':
2841                 addToPoDialog._get_li = dojo.hitch(
2842                     this,
2843                     function() { 
2844                         return this.getSelected(
2845                             false, null, true, li_pre_po_states);
2846                     }
2847                 );
2848                 if (addToPoDialog._get_li().length == 0) {
2849                     alert(localeStrings.NO_LI_GENERAL);
2850                     return;
2851                 }
2852                 addToPoDialog.show();
2853                 break;
2854
2855             case 'create_order':
2856                 this._loadPOSelect();
2857                 acqLitPoCreateDialog.show();
2858                 break;
2859
2860             case 'save_picklist':
2861                 acqLitSavePlDialog.show();
2862                 break;
2863
2864             case 'selector_ready':
2865             case 'order_ready':
2866                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2867                 acqLitChangeLiStateDialog.show();
2868                 break;
2869
2870             case 'print_po':
2871                 this.printPO();
2872                 break;
2873
2874             case 'po_history':
2875                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2876                 break;
2877
2878             case 'batch_create_invoice':
2879                 this.batchCreateInvoice();
2880                 break;
2881
2882             case 'batch_link_invoice':
2883                 this.batchLinkInvoice();
2884                 break;
2885
2886             case 'receive_lineitems':
2887                 this.receiveSelectedLineitems();
2888                 break;
2889
2890             case 'rollback_receive_lineitems':
2891                 this.rollbackReceiveLineitems();
2892                 break;
2893
2894             case 'create_assets':
2895                 this.showAssetCreator();
2896                 break;
2897
2898             case 'export_attr_list':
2899                 this.chooseExportAttr();
2900                 break;
2901
2902             case 'batch_apply_funds':
2903                 this.applyBatchLiFunds();
2904                 break;
2905
2906             case 'add_brief_record':
2907                 if(this.isPO)
2908                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2909                 else
2910                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2911
2912                 break;
2913
2914             case "cancel_lineitems":
2915                 console.log('HERE');
2916                 this.maybeCancelLineitems();
2917                 break;
2918
2919             case "apply_claim_policy":
2920                 var li_list = this.getSelected();
2921                 this.claimPolicyPicker.attr("value", null);
2922                 liClaimPolicyDialog.show();
2923                 liClaimPolicySave.onClick = function() {
2924                     self.changeClaimPolicy(
2925                         li_list,
2926                         self.claimPolicyPicker.attr("value"),
2927                         function() {
2928                             li_list.forEach(
2929                                 function(li) {
2930                                     self.setClaimPolicyControl(li);
2931                                     self.reconsiderClaimControl(li);
2932                                 }
2933                             );
2934                             liClaimPolicyDialog.hide();
2935                         }
2936                     )
2937                 };
2938                 break;
2939         }
2940     };
2941
2942     this.changeClaimPolicy = function(li_list, value, callback) {
2943         li_list.forEach(
2944             function(li) { li.claim_policy(value); }
2945         );
2946         fieldmapper.standardRequest(
2947             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2948                 "params": [openils.User.authtoken, li_list],
2949                 "async": true,
2950                 "oncomplete": function(r) {
2951                     r = openils.Util.readResponse(r);
2952                     if (callback) callback(r);
2953                 }
2954             }
2955         );
2956     };
2957
2958     this.showAssetCreator = function(onAssetsCreated) {
2959         if(!this.isPO) return;
2960         var self = this;
2961     
2962         // first, let's see if this PO has any LI's that need to be merged/imported
2963         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2964             id_list : true,
2965             oncomplete : function(r) {
2966                 var resp = openils.Util.readResponse(r);
2967                 if (resp && resp.length) {
2968                     // PO has some non-linked jubs.  
2969                     
2970                     self.show('asset-creator');
2971                     if(!self.vlAgent.loaded)
2972                         self.vlAgent.init();
2973
2974                     dojo.connect(assetCreatorButton, 'onClick', 
2975                         function() { self.createAssets(onAssetsCreated) });
2976
2977                 } else {
2978
2979                     // all jubs linked, move on to asset creation
2980                     self.createAssets(onAssetsCreated, true); 
2981                 }
2982             }
2983         });
2984     }
2985
2986     this.createAssets = function(onAssetsCreated, noVl) {
2987         this.show('acq-lit-progress-numbers');
2988         var self = this;
2989         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2990         this.batchProgress = {};
2991         progressDialog.show(false);
2992         progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2993         fieldmapper.standardRequest(
2994             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
2995             {   async: true,
2996                 params: [this.authtoken, this.isPO, vlArgs],
2997                 onresponse: function(r) {
2998                     var resp = openils.Util.readResponse(r);
2999                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3000                 }
3001             }
3002         );
3003     }
3004
3005     this.maybeCancelLineitems = function() {
3006         openils.Util.show("acq-lit-cancel-reason", "inline");
3007         if (!acqLitCancelLineitemsButton._prepared) {
3008             var widget = new openils.widget.AutoFieldWidget({
3009                 "fmField": "cancel_reason",
3010                 "fmClass": "jub",
3011                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3012                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3013                 "forceSync": true,
3014                 "searchOptions" : {order_by : {"acqcr":"label"}}
3015             });
3016             widget.build(
3017                 function(w, ww) {
3018                     acqLitCancelLineitemsButton.onClick = function() {
3019                         if (w.attr("value")) {
3020                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3021                                 self._cancelLineitems(w.attr("value"));
3022                             }
3023                             openils.Util.hide("acq-lit-cancel-reason");
3024                         }
3025                     };
3026                     acqLitCancelLineitemsButton._prepared = true;
3027                 }
3028             );
3029         }
3030     };
3031
3032     this._cancelLineitems = function(reason) {
3033
3034         var li_list = this.getSelected();
3035
3036         // canceled lineitems may be canceled again if they were 
3037         // previously delayed (keep_debits = true).
3038         li_list = li_list.filter(
3039             function(li) {
3040                 return (
3041                     li.state() != 'cancelled' ||
3042                     li.cancel_reason().keep_debits() == 't'
3043                 );
3044             }
3045         );
3046
3047         id_list = li_list.map(function(l) {return l.id()});
3048
3049         if (!id_list.length) {
3050             alert(localeStrings.NO_LI_GENERAL);
3051             return;
3052         }
3053         fieldmapper.standardRequest(
3054             ["open-ils.acq", "open-ils.acq.lineitem.cancel.batch"], {
3055                 "params": [openils.User.authtoken, id_list, reason],
3056                 "async": true,
3057                 "onresponse": function(r) {
3058                     if (r = openils.Util.readResponse(r)) {
3059                         if (r.li) {
3060                             for (var id in r.li) {
3061                                 self.liCache[id].state(r.li[id].state);
3062                                 self.liCache[id].cancel_reason(
3063                                     r.li[id].cancel_reason
3064                                 );
3065                                 self.updateLiState(self.liCache[id]);
3066                             }
3067                         }
3068                         if (r.lid && self.copyCache) {
3069                             for (var id in r.lid) {
3070                                 if (self.copyCache[id]) {
3071                                     self.copyCache[id].cancel_reason(
3072                                         r.lid[id].cancel_reason
3073                                     );
3074                                     self.updateLidState(self.copyCache[id]);
3075                                 }
3076                             }
3077                         }
3078                     }
3079                 }
3080             }
3081         );
3082     };
3083
3084     this.chooseExportAttr = function() {
3085         if (!acqLitExportAttrSelector._li_setup) {
3086             var self = this;
3087             acqLitExportAttrSelector.store = new dojo.data.ItemFileReadStore(
3088                 {
3089                     "data": acqlimad.toStoreData(
3090                         this.pcrud.search(
3091                             "acqlimad", {"code": li_exportable_attrs}
3092                         )
3093                     )
3094                 }
3095             );
3096             acqLitExportAttrSelector.setValue();
3097             acqLitExportAttrButton.onClick = function(){self.exportAttrList();};
3098             acqLitExportAttrSelector._li_setup = true;
3099         }
3100         openils.Util.show("acq-lit-export-attr-holder", "inline");
3101     };
3102
3103     this.exportAttrList = function() {
3104         var attr_def = acqLitExportAttrSelector.item;
3105         var li_list = this.getSelected();
3106         var value_list = li_list.map(
3107             function(li) {
3108                 return (new openils.acq.Lineitem({"lineitem": li})).findAttr(
3109                     attr_def.code, "lineitem_marc_attr_definition"
3110                 );
3111             }
3112         ).filter(function(attr) { return Boolean(attr); });
3113
3114         if (value_list.length > 0) {
3115             if (value_list.length < li_list.length) {
3116                 if (!confirm(
3117                     dojo.string.substitute(
3118                         localeStrings.EXPORT_SHORT_LIST, [attr_def.description]
3119                     )
3120                 )) {
3121                     return;
3122                 }
3123             }
3124             try {
3125                 if (window.IAMBROWSER) {
3126                     var blob = new Blob(value_list, {type: "text/plain;charset=utf-8"});
3127                     saveAs(blob, "export_attr_list.txt");
3128                 } else {
3129                     openils.XUL.contentToFileSaveDialog(
3130                         value_list.join("\n"),
3131                         localeStrings.EXPORT_SAVE_DIALOG_TITLE
3132                     );
3133                 }
3134             } catch (E) {
3135                 alert(E);
3136             }
3137         } else {
3138             alert(dojo.string.substitute(
3139                 localeStrings.EXPORT_EMPTY_LIST, [attr_def.description]
3140             ));
3141         }
3142
3143         openils.Util.hide("acq-lit-export-attr-holder");
3144     };
3145
3146     this.printPO = function() {
3147         if(!this.isPO) return;
3148         progressDialog.show(true);
3149         fieldmapper.standardRequest(
3150             ['open-ils.acq', 'open-ils.acq.purchase_order.format'],
3151             {   async: true,
3152                 params: [this.authtoken, this.isPO, 'html'],
3153                 oncomplete: function(r) {
3154                     progressDialog.hide();
3155                     var evt = openils.Util.readResponse(r);
3156                     if(evt && evt.template_output()) {
3157                         openils.Util.printHtmlString(evt.template_output().data());
3158                     }
3159                 }
3160             }
3161         );
3162     };
3163
3164     this.batchCreateInvoice = function() {
3165         var liIds = this.getSelected(
3166             false, null, true /* id_list */, li_active_states)
3167         if (!liIds.length) {
3168             alert(localeStrings.NO_LI_GENERAL);
3169             return;
3170         }
3171         var path = oilsBasePath + '/acq/invoice/view?create=1';
3172         dojo.forEach(liIds, function(li, idx) { path += '&attach_li=' + li });
3173         if (openils.XUL.isXUL() && !window.IAMBROWSER)
3174             openils.XUL.newTabEasy(path, localeStrings.NEW_INVOICE, null, true);
3175         else
3176             location.href = path;
3177     };
3178
3179     this.batchLinkInvoice = function(create) {
3180         var liIds = this.getSelected(
3181             false, null, true /* id_list */, li_active_states)
3182         if (!liIds.length) {
3183             alert(localeStrings.NO_LI_GENERAL);
3184             return;
3185         }
3186         if (!self.invoiceLinkDialogManager) {
3187             self.invoiceLinkDialogManager =
3188                 new InvoiceLinkDialogManager("li");
3189         }
3190         self.invoiceLinkDialogManager.target = liIds;
3191         acqLitLinkInvoiceDialog.show();
3192     };
3193
3194     this.receiveSelectedLineitems = function() {
3195         var states = li_post_po_states.filter(
3196             function(s) { return s != 'received' });
3197         var li_list = this.getSelected(null, null, null, states);
3198
3199         if (!li_list.length) {
3200             alert(localeStrings.NO_LI_GENERAL);
3201             return;
3202         }
3203
3204         for (var i = 0; i < li_list.length; i++) {
3205             var li = li_list[i];
3206
3207             if (li.state() != "received" &&
3208                 !this.checkLiAlerts(li.id())) return;
3209         }
3210
3211         this.show('acq-lit-progress-numbers');
3212
3213         var self = this;
3214         fieldmapper.standardRequest(
3215             ['open-ils.acq', 'open-ils.acq.lineitem.receive.batch'],
3216             {   async: true,
3217                 params: [
3218                     this.authtoken,
3219                     li_list.map(function(li) { return li.id(); })
3220                 ],
3221                 onresponse : function(r) {
3222                     var resp = openils.Util.readResponse(r);
3223                     self._updateProgressNumbers(resp, true);
3224                 },
3225             }
3226         );
3227     };
3228
3229     this.issueReceive = function(obj, rollback) {
3230         var part =
3231             {"jub": "lineitem", "acqlid": "lineitem_detail"}[obj.classname];
3232         var method =
3233             "open-ils.acq." + part + ".receive" + (rollback ? ".rollback" : "");
3234
3235         progressDialog.show(true);
3236         fieldmapper.standardRequest(
3237             ["open-ils.acq", method], {
3238                 "async": true,
3239                 "params": [this.authtoken, obj.id()],
3240                 "onresponse": function(r) {
3241                     if (r = openils.Util.readResponse(r)) {
3242                         self.fetchClaimInfo(
3243                             part == "lineitem" ? obj.id() : obj.lineitem(),
3244                             /* force */ true,
3245                             function() { self.handleReceive(r); }
3246                         );
3247                         progressDialog.hide();
3248                     }
3249                 }
3250             }
3251         );
3252     };
3253
3254     /**
3255      * Handles the responses from receive and rollback ML calls.
3256      */
3257     this.handleReceive = function(resp) {
3258         if (resp) {
3259             if (resp.li) {
3260                 for (var li_id in resp.li) {
3261                     for (var key in resp.li[li_id])
3262                         self.liCache[li_id][key](resp.li[li_id][key]);
3263                     self.updateLiState(self.liCache[li_id]);
3264                 }
3265             }
3266             if (resp.po) {
3267                 if (typeof(self.poUpdateCallback) == "function")
3268                     self.poUpdateCallback(resp.po);
3269             }
3270             if (resp.lid) {
3271                 for (var lid_id in resp.lid) {
3272                     for (var key in resp.lid[lid_id])
3273                         self.copyCache[lid_id][key](resp.lid[lid_id][key]);
3274                     self.updateLidState(self.copyCache[lid_id]);
3275                 }
3276             }
3277         }
3278     };
3279
3280     this.rollbackReceiveLineitems = function() {
3281         var li_id_list = this.getSelected(false, null, true);
3282         if (!li_id_list.length) {
3283             alert(localeStrings.NO_LI_GENERAL);
3284             return;
3285         }
3286
3287         if (!confirm(localeStrings.ROLLBACK_LI_RECEIVE_CONFIRM)) return;
3288
3289         this.show('acq-lit-progress-numbers');
3290         var self = this;
3291
3292         fieldmapper.standardRequest(
3293             ['open-ils.acq', 'open-ils.acq.lineitem.receive.rollback.batch'],
3294             {   async: true,
3295                 params: [this.authtoken, li_id_list],
3296                 onresponse : function(r) {
3297                     var resp = openils.Util.readResponse(r);
3298                     self._updateProgressNumbers(resp, true);
3299                 },
3300             }
3301         );
3302     };
3303
3304     this._updateProgressNumbers = function(resp, reloadOnComplete, onComplete, clearProgressDialog) {
3305         this._updateProgressDialog(resp);
3306         this.vlAgent.handleResponse(resp,
3307             function(resp, res) {
3308                 if (clearProgressDialog) {
3309                     progressDialog.update({ "progress": 100});
3310                     progressDialog.update_message();
3311                     progressDialog.hide();
3312                     progressDialog.attr("title", "");
3313                 }
3314                 if(reloadOnComplete)
3315                      location.href = location.href;
3316                 if (onComplete)
3317                     onComplete(resp, res);
3318             }
3319         );
3320     }
3321
3322     this._updateProgressDialog = function(resp) {
3323         progressDialog.update({ "progress": (resp.progress / resp.total) * 100 });
3324         var keys = ['li', 'vqbr', 'bibs', 'lid', 'debits_accrued', 'copies'];
3325         for (var i = 0; i < keys.length; i++) {
3326             if (resp[keys[i]] > (this.batchProgress[keys[i]] || 0)) {
3327                 progressDialog.update_message(
3328                     dojo.string.substitute(
3329                         localeStrings["ACTIVATE_" + keys[i].toUpperCase() + "_PROCESSED"],
3330                         [ resp[keys[i]] ]
3331                     )
3332                 );
3333             }
3334         }
3335         this.batchProgress = resp;
3336     }
3337
3338     this._createPO = function(fields) {
3339         var wantall = (fields.create_from == "all");
3340
3341         /* If we're a picklist or purchase order already and the user wants
3342          * all lineitems, we might have pages' worth of lineitems haven't all
3343          * been loaded yet, so getSelected() won't find them.  The server,
3344          * however, should know about all our lineitems, so let's ask the
3345          * server for a complete list.
3346          */
3347
3348         if (wantall) {
3349             this.getSelected(
3350                 true, function(list) {
3351                     self._createPOFromLineitems(fields, list);
3352                 }, /* id_list */ true, li_pre_po_states
3353             );
3354         } else {
3355             this._createPOFromLineitems(
3356                 fields, this.getSelected(
3357                     false, null, true /* id_list */, li_pre_po_states)
3358             );
3359         }
3360     };
3361
3362     this._createPOFromLineitems = function(fields, selected) {
3363         if (selected.length == 0) {
3364             alert(localeStrings.NO_LI_GENERAL);
3365             return;
3366         }
3367         var self = this;
3368
3369         var po = new fieldmapper.acqpo();
3370         po.provider(this.createPoProviderSelector.attr("value"));
3371         po.ordering_agency(this.createPoAgencySelector.attr("value"));
3372         po.prepayment_required(fields.prepayment_required[0] ? true : false);
3373         var name = this.createPoNameInput.attr('value'); 
3374         if (name) po.name(name); // avoid name=""
3375
3376         // if we're creating assets, delay the asset creation 
3377         // until after the PO is created.  This will allow us to 
3378         // use showAssetCreator() directly.
3379
3380         fieldmapper.standardRequest(
3381             ["open-ils.acq", "open-ils.acq.purchase_order.create"],
3382             {   async: true,
3383                 params: [
3384                     openils.User.authtoken, 
3385                     po, {lineitems : selected}
3386                 ],
3387                 onresponse : function(r) {
3388                     var resp = openils.Util.readResponse(r);
3389                     if (resp.complete) {
3390                         // self.isPO is needed for showAssetCreator();
3391                         self.isPO = resp.purchase_order.id(); 
3392                         var redir = oilsBasePath + "/acq/po/view/" + self.isPO;
3393                         if (fields.create_assets[0]) {
3394                             self.showAssetCreator(
3395                                 function() {location.href = redir}
3396                             );
3397                         } else {
3398                            location.href = redir;
3399                         }
3400                     }
3401                 }
3402             }
3403         );
3404     };
3405
3406
3407     this.batchFundWidget = null;
3408
3409     this.applyBatchLiFunds = function() {
3410
3411         var liIds = this.getSelected().map(function(li) { return li.id(); });
3412         if(liIds.length == 0) return; // warn?
3413
3414         var self = this;
3415         batchFundUpdateDialog.show();
3416
3417         if(!this.batchFundWidget) {
3418             this.batchFundWidget = new openils.widget.AutoFieldWidget({
3419                 fmClass : 'acqf',
3420                 selfReference : true,
3421                 labelFormat : fundLabelFormat,
3422                 searchFormat : fundSearchFormat,
3423                 searchFilter : fundSearchFilter,
3424                 parentNode : dojo.byId('acq-lit-batch-fund-selector'),
3425                 orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
3426                 dijitArgs : { "required": true, "labelType": "html" },
3427                 forceSync : true
3428             });
3429             this.batchFundWidget.build();
3430         }
3431
3432         dojo.connect(batchFundUpdateCancel, 'onClick', function() { batchFundUpdateDialog.hide(); });
3433         dojo.connect(batchFundUpdateSubmit, 'onClick', 
3434             function() { 
3435
3436                 // TODO: call .dry_run first to test thresholds
3437                 fieldmapper.standardRequest(
3438                     ['open-ils.acq', 'open-ils.acq.lineitem.fund.update.batch'],
3439                     {
3440                         params : [
3441                             openils.User.authtoken, 
3442                             liIds,
3443                             self.batchFundWidget.widget.attr('value')
3444                         ],
3445                         oncomplete : function(r) {
3446                             var resp = openils.Util.readResponse(r);
3447                             if(resp) {
3448                                 location.href = location.href;
3449                             }
3450                         }
3451                     }
3452                 )
3453             }
3454         );
3455     }
3456
3457     this._deleteLiList = function(list, idx) {
3458         if(idx == null) idx = 0;
3459         if(idx >= list.length) return;
3460
3461         var li = list[idx];
3462         var liId = li.id();
3463
3464         if (this.isPO && (li.state() == "on-order" || li.state() == "received")) {
3465             /* It makes little sense to delete a lineitem from a PO that has
3466              * already been marked 'on-order'.  Especially if EDI is in use,
3467              * such a purchase order will probably have already been shipped
3468              * off to a vendor, and mucking with it at this point could leave
3469              * your data in a bad state that doesn't jive with reality.
3470              *
3471              * I could see making this restriction even firmer.
3472              *
3473              * I could also see adjusting the li state comparisons, extending
3474              * the comparison to the PO's state, and/or providing functions
3475              * that house the logic for comparing states in a single location.
3476              *
3477              * Yes, this will be really annoying if you have selected a lot
3478              * of lineitems to cancel that have been ordered. You'll get a
3479              * confirm dialog for each one.
3480              */
3481
3482             if (!confirm(localeStrings.DEL_LI_FROM_PO)) {
3483                 self._deleteLiList(list, ++idx); /* move on to next in list */
3484                 return;
3485             }
3486         }
3487
3488         fieldmapper.standardRequest(
3489             ['open-ils.acq',
3490              this.isPO ? 'open-ils.acq.purchase_order.lineitem.delete' : 'open-ils.acq.picklist.lineitem.delete'],