webstaff: rework line item sub-actions menu
[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     };
926
927     this.clearEligibility = function(li) {
928         this.claimEligibleLidByLi[li.id()] = [];
929
930         if (li.lineitem_details()) {
931             li.lineitem_details().forEach(
932                 function(lid) { delete self.claimEligibleLid[lid.id()]; }
933             );
934         }
935
936         if (this.copyCache) {
937             var to_del = [];
938             for (var k in this.copyCache) {
939                 if (this.copyCache[k].lineitem() == li.id())
940                     to_del.push(k);
941             }
942             to_del.forEach(
943                 function(k) { delete self.claimEligibleLid[k]; }
944             );
945         }
946     };
947
948     this.applyOrderIdentValues = function() {
949         this._identValuesInFlight = 
950             openils.Util.objectProperties(this.liCache).length;
951         for (var liId in this.liCache) {
952             this._applyOrderIdentValue(this.liCache[liId]);
953         }
954     };
955
956     // returns true if request was sent
957     this._applyOrderIdentValue = function(li, oncomplete) {
958         var self = this;
959
960         console.log('applying ident value for lineitem ' + li.id());
961
962         // main row
963         var row = dojo.query('[li=' + li.id() + ']')[0];
964
965         // find the selected ident value
966         var typeSel = dojo.query('[name=order_ident_type]', row)[0];
967         var valueSel = dojo.query('[name=order_ident_value]', row)[0];
968         var name = typeSel.options[typeSel.selectedIndex].value;
969         var val = typeSel._cbox.attr('value');
970
971         console.log("selected ident is " + val);
972
973         // it differs from the existing ident value, update it
974         var oldIdent = self.getLiOrderIdent(li);
975         if (oldIdent && 
976             oldIdent.attr_name() == name &&
977             oldIdent.attr_value() == val) {
978                 console.log('selected ident attr matches existing attr');
979                 if (--this._identValuesInFlight == 0) {
980                     if (oncomplete) oncomplete(li);
981                     else location.href = location.href;
982                 }
983                 return false;
984         }
985
986         // see if the selected ident value is represented
987         // by an existing lineitem attr
988
989         var args = {};
990         typeSel._cbox.store.fetch({
991             query : {attr_value : val},
992             onItem : function(item) {                                                       
993                 console.log('found existing attr for ident value');
994                 args.source_attr_id = li.attributes().filter(
995                     function(attr) { return attr.id() == item.id[0] }
996                 )[0];
997             }                                                                      
998         }); 
999
1000
1001         if (!args.source_attr_id) {
1002             // user entered new text in the combobox
1003             // so we need to create a new attr
1004             console.log('creating new ident attr');
1005             args.lineitem_id = li.id();
1006             args.attr_name = name;
1007             args.attr_value = val;
1008         }
1009
1010         fieldmapper.standardRequest(
1011             ['open-ils.acq', 'open-ils.acq.lineitem.order_identifier.set'],
1012             {   async : true,
1013                 params : [openils.User.authtoken, args],
1014                 oncomplete : function() {
1015                     console.log('order_ident oncomplete');
1016                     if (--self._identValuesInFlight == 0) {
1017                         if (oncomplete) oncomplete(li);
1018                         else location.href = location.href;
1019                     }
1020                     console.log(self._identValuesInFlight + ' still in flight');
1021                 }
1022             }
1023         );
1024
1025         return true;
1026     };
1027
1028     this.getLiOrderIdent = function(li) {
1029         var attrs = li.attributes();
1030         if (!attrs) return null;
1031         return attrs.filter(
1032             function(attr) {
1033                 return (
1034                     attr.attr_type() == 'lineitem_local_attr_definition' &&
1035                     openils.Util.isTrue(attr.order_ident())
1036                 );
1037             }
1038         )[0];
1039     };
1040
1041     this.drawOrderIdentSelector = function(li, row) {
1042         var self = this;
1043         var typeSel = dojo.query('[name=order_ident_type]', row)[0];
1044         var valueSel = dojo.query('[name=order_ident_value]', row)[0];
1045
1046         var attrs = li.attributes();
1047
1048         // limit to MARC attr defs
1049         attrs = attrs.filter(
1050             function(attr) {
1051                 return (attr.attr_type() == 'lineitem_marc_attr_definition');
1052             }
1053         );
1054
1055         var identAttr = this.getLiOrderIdent(li);
1056
1057
1058         // collect the values for each type of identifier
1059         // find a reasonable default identifier type to render
1060         
1061         var values = {};
1062         var typeSet = null;
1063         dojo.forEach(['isbn', 'upc', 'issn'],
1064             function(name) {
1065
1066                 // collect the values for this attr name
1067                 values[name] =  attrs.filter(
1068                     function(attr) {
1069                         return (attr.attr_name() == name)
1070                     }
1071                 );
1072
1073                 // select a reasonable default name in the type-selector
1074                 if (!typeSet) {
1075                     var useMe = false;
1076                     if (identAttr) {
1077                         if (identAttr.attr_name() == name)
1078                             useMe = true;
1079                     } else if (values[name].length) {
1080                         useMe = true;
1081                     }
1082
1083                     if (useMe) {
1084                         dojo.forEach(typeSel.options, function(opt) {
1085                             if (opt.value == name) {
1086                                 opt.selected = true;
1087                                 typeSet = name;
1088                             }
1089                         });
1090                     }
1091                 }
1092             }
1093         );
1094
1095         function updateOrderIdent(val) {
1096             self._identValuesInFlight = 1;
1097             self._applyOrderIdentValue(
1098                 this._lineitem,
1099                 function(li) {
1100                     self.refreshLineitem(li);
1101                 }
1102             );
1103         }
1104
1105         // replace the ident combobox with a new 
1106         // one for the selected ident type 
1107         function changeComboBox(sel) {
1108             var name = sel.options[sel.selectedIndex].value;
1109
1110             var td = dojo.query('[name=order_ident_value]', row)[0];
1111             if (td.childNodes[0]) 
1112                 dojo.destroy(td.childNodes[0]);
1113
1114             var store = new dojo.data.ItemFileWriteStore({
1115                 data : acqlia.toStoreData(values[name])
1116             });
1117
1118             var cbox = new dijit.form.ComboBox(
1119                 {   store : store,
1120                     labelAttr : 'attr_value',
1121                     searchAttr : 'attr_value'
1122                 }, 
1123                 dojo.create('div', {}, td)
1124             );
1125
1126             cbox.startup();
1127
1128             // set the value for the cbox
1129             if (values[name].length) {
1130                 var orderIdent = self.getLiOrderIdent(li);
1131
1132                 if (orderIdent && orderIdent.attr_name() == name) {
1133                     cbox.attr('value', orderIdent.attr_value());
1134                 } else  {
1135                     cbox.attr('value', values[name][0].attr_value());
1136                 }
1137             }
1138
1139             if (!self.orderIdentAllowed) 
1140                 cbox.attr('disabled', true);
1141
1142             sel._cbox = cbox;
1143             cbox._lineitem = li;
1144             dojo.connect(cbox, 'onChange', updateOrderIdent);
1145         }
1146
1147         changeComboBox(typeSel); // force the initial draw
1148         typeSel.onchange = function() {changeComboBox(typeSel)};
1149     };
1150
1151     this.testOrderIdentPerms = function(org, callback) {
1152         var self = this;
1153         new openils.User().getPermOrgList(
1154             'ACQ_SET_LINEITEM_IDENTIFIER',
1155             function(orgs) { 
1156                 console.log('found orgs = ' + orgs);
1157                 for (var i = 0; i < orgs.length; i++) {
1158                     if (Number(orgs[i]) == Number(org)) {
1159                         self.orderIdentAllowed = true;
1160                         if (callback) callback();
1161                         return;
1162                     }
1163                 }
1164                 if (callback) callback();
1165             }, 
1166             true, true
1167         );
1168     };
1169
1170     this.checkClaimEligibility = function(li, callback, row) {
1171         /* Assume always eligible, i.e. from this interface we don't care about
1172          * claim eligibility any more. this is where the user would force a
1173          * claime. */
1174         this.clearEligibility(li);
1175         this.claimEligibleLidByLi[li.id()] = li.lineitem_details().map(
1176             function(lid) { return lid.id(); }
1177         );
1178         li.lineitem_details().forEach(
1179             function(lid) { self.claimEligibleLid[lid.id()] = true; }
1180         );
1181         this.reconsiderClaimControl(li, row);
1182         if (callback) callback(li);
1183         /*
1184         this.clearEligibility(li);
1185         fieldmapper.standardRequest(
1186             ["open-ils.acq", "open-ils.acq.claim.eligible.lineitem_detail"], {
1187                 "params": [openils.User.authtoken, {"lineitem": li.id()}],
1188                 "async": true,
1189                 "onresponse": function(r) {
1190                     if (r = openils.Util.readResponse(r)) {
1191                         self.claimEligibleLidByLi[li.id()].push(
1192                             r.lineitem_detail()
1193                         );
1194                         self.claimEligibleLid[r.lineitem_detail()] = true;
1195                     }
1196                 },
1197                 "oncomplete": function() {
1198                     self.reconsiderClaimControl(li, row);
1199                     if (typeof(callback) == "function")
1200                         callback();
1201                 }
1202             }
1203         );
1204         */
1205     };
1206
1207     this.updateLiNotesCount = function(li, row) {
1208         if (!row) row = this._findLiRow(li);
1209
1210         var has_notes = (li.lineitem_notes().filter(
1211                 function(o) { return Boolean (o.alert_text()); }
1212             ).length > 0);
1213
1214         /* U+2691 is the code point for a filled-in flag character */
1215         nodeByName("notes_alert_flag", row).innerHTML =
1216              has_notes ? "&#x2691;" : "";
1217         nodeByName("noteslink", row).style.fontStyle =
1218             has_notes ? "italic" : "normal";
1219         nodeByName("notes_count", row).innerHTML = li.lineitem_notes().length;
1220     };
1221
1222     /* XXX NOT related to _updateLiState(). rethink */
1223     this.updateLiState = function(li, row) {
1224         if (!row) row = this._findLiRow(li);
1225
1226         nodeByName("actions", row).onchange = function() {
1227             switch(this.options[this.selectedIndex].value) {
1228                 case 'action_update_barcodes':
1229                     self.showRealCopyEditUI(li);
1230                     nodeByName("action_none", row).selected = true;
1231                     break;
1232                 case 'action_holdings_maint':
1233                     (self.generateMakeRecTab( li.eg_bib_id(), 'copy_browser', row ))();
1234                     break;
1235                 case 'action_manage_claims':
1236                     self.fetchClaimInfo(li.id(), true, function(full) { self.claimDialog.show(full) }, row);
1237                     break;
1238                 case 'action_view_history':
1239                     location.href = oilsBasePath + '/acq/lineitem/history/' + li.id();
1240                     break;
1241             }
1242         };
1243         var actUpdateBarcodes = nodeByName("action_update_barcodes", row);
1244         var actHoldingsMaint = nodeByName("action_holdings_maint", row);
1245
1246         /* handle row coloring for based on LI state */
1247         openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1248         openils.Util.addCSSClass(row, "oils-acq-li-state-" + li.state());
1249
1250         // Expose invoice actions for any lineitem that is linked to a PO 
1251         if (li.purchase_order()) {
1252             openils.Util.show(nodeByName("invoices_span", row), "inline");
1253             var link = nodeByName("invoices_link", row);
1254             link.onclick = function() {
1255                 var url = oilsBasePath + "/acq/search/unified?so=" +
1256                           base64Encode({"jub":[{"id": li.id()}]}) + "&rt=invoice"
1257                 if (window.IAMBROWSER) {
1258                     xulG.relay_url(url);
1259                 } else {
1260                     openils.XUL.newTabEasy(url);
1261                 }
1262                 return false;
1263             };
1264         }
1265                 
1266
1267         /*
1268          * If we haven't fleshed the lineitem_details, default to allowing access to the 
1269          * holdings maintenence actions.  The alternative is to flesh LIDs on every lineitem, 
1270          * but that will add to page render time.  Let's see if this will suffice...
1271          */
1272         var lids = li.lineitem_details();
1273         if( !lids || 
1274                 (lids && !lids.filter(function(lid) { return lid.eg_copy_id() })[0] )) {
1275
1276             actUpdateBarcodes.disabled = false;
1277             actHoldingsMaint.disabled = false;
1278         }
1279
1280         var state_cell = nodeByName("li_state_" + li.state(), row);
1281
1282         // re-hide any state label nodes which may have been un-hidden
1283         // through previous actions.
1284         dojo.query('[state-label]', row).forEach(function(node) {
1285             openils.Util.hide(node)
1286         });
1287
1288         if (li.state() == 'cancelled') {
1289             if(typeof li.cancel_reason() == "object") {
1290
1291                 // clear the stock "Canceled" label, since we have more
1292                 // information to replace it with.
1293                 state_cell.innerHTML = '';
1294
1295                 var holds_state = dojo.create(
1296                     "span", {
1297                         "style": "border-bottom: 1px dashed #000;",
1298                         "innerHTML": li.cancel_reason().label()
1299                     }, state_cell, "only"
1300                 );
1301                 new dijit.Tooltip(
1302                     {
1303                         "label": "<em>" + li.cancel_reason().label() +
1304                             "</em><br />" + li.cancel_reason().description(),
1305                         "connectId": [holds_state]
1306                     }, dojo.create("span", null, state_cell, "last")
1307                 );
1308
1309                 if (li.cancel_reason().keep_debits() == 't') {
1310                     openils.Util.removeCSSClass(row, /^oils-acq-li-state-/);
1311                     openils.Util.addCSSClass(row, "oils-acq-li-state-delayed");
1312                 }
1313             } else {
1314                 console.log('li cancel_reason is un-fleshed.  Please fix');
1315             }
1316         } 
1317
1318         openils.Util.show(state_cell);
1319     };
1320
1321
1322     this._setAlertStore = function() {
1323         acqLitAlertAlertText.store = new dojo.data.ItemFileReadStore(
1324             {
1325                 "data": acqliat.toStoreData(
1326                     this.pcrud.search(
1327                         "acqliat", {
1328                             "owning_lib": aou.orgNodeTrail(
1329                                 aou.findOrgUnit(openils.User.user.ws_ou())
1330                             ).map(function(o) { return o.id(); })
1331                         }
1332                     )
1333                 )
1334             }
1335         );
1336         acqLitAlertAlertText.setValue(); /* make the store "live" */
1337         acqLitAlertAlertText._store_ready = true;
1338     };
1339
1340     /**
1341      * Draws and shows the lineitem notes pane
1342      */
1343     this.drawLiNotes = function(li) {
1344         var self = this;
1345         this.focusLineitem = li.id();
1346
1347         if (!acqLitAlertAlertText._store_ready)
1348             this._setAlertStore();
1349
1350         li.lineitem_notes(
1351             li.lineitem_notes().sort(
1352                 function(a, b) { 
1353                     if(a.edit_time() < b.edit_time()) return 1;
1354                     return -1;
1355                 }
1356             )
1357         );
1358
1359         while(this.liNotesTbody.childNodes[0])
1360             this.liNotesTbody.removeChild(this.liNotesTbody.childNodes[0]);
1361         this.show('notes');
1362
1363         acqLitCreateNoteSubmit.onClick = function() {
1364             var value = acqLitCreateNoteText.attr('value');
1365             if(!value) return;
1366             var note = new fieldmapper.acqlin();
1367             note.isnew(true);
1368             note.vendor_public(
1369                 Boolean(acqLitCreateNoteVendorPublic.attr('checked'))
1370             );
1371             note.value(value);
1372             note.lineitem(li.id());
1373
1374             self.updateLiNotes(li, note);
1375             acqLitCreateNoteVendorPublic.attr("checked", false);
1376             acqLitCreateNoteText.attr("value", "");
1377         }
1378
1379         acqLitCreateAlertSubmit.onClick = function() {
1380             if (!acqLitAlertAlertText.item) {
1381                 alert(localeStrings.ALERT_UNSELECTED);
1382                 return;
1383             }
1384
1385             var alert_text = new fieldmapper.acqliat().fromStoreItem(
1386                 acqLitAlertAlertText.item
1387             );
1388             var value = acqLitAlertNoteValue.attr("value") || "";
1389
1390             var note = new fieldmapper.acqlin();
1391             note.isnew(true);
1392             note.lineitem(li.id());
1393             note.value(value);
1394             note.alert_text(alert_text);
1395
1396             self.updateLiNotes(li, note);
1397         }
1398
1399         dojo.forEach(li.lineitem_notes(), function(note) { self.addLiNote(li, note) });
1400     }
1401
1402     /**
1403      * Draws a single lineitem note in the notes pane
1404      */
1405     this.addLiNote = function(li, note) {
1406         if(note.isdeleted()) return;
1407         var self = this;
1408         var row = self.liNotesRow.cloneNode(true);
1409         nodeByName("value", row).innerHTML = note.value();
1410         var alert_node = nodeByName("alert_code", row);
1411         if (note.alert_text()) {
1412             alert_node.innerHTML = dojo.string.substitute(
1413                 "[${0}] ${1}", [
1414                     aou.findOrgUnit(note.alert_text().owning_lib()).shortname(),
1415                     note.alert_text().code()
1416                 ]
1417             );
1418             if (note.alert_text().description()) {
1419                 new dijit.Tooltip(
1420                     {
1421                         "connectId": [alert_node],
1422                         "label": note.alert_text().description()
1423                     }, dojo.create("span", null, alert_node, "after")
1424                 );
1425             }
1426         }
1427
1428         if (openils.Util.isTrue(note.vendor_public()))
1429             nodeByName("vendor_public", row).innerHTML =
1430                 localeStrings.VENDOR_PUBLIC;
1431
1432         nodeByName("delete", row).onclick = function() {
1433             note.isdeleted(true);
1434             self.liNotesTbody.removeChild(row);
1435             self.updateLiNotes(li);
1436         };
1437
1438         if(note.edit_time()) {
1439             nodeByName("edit_time", row).innerHTML =
1440                 dojo.date.locale.format(
1441                     dojo.date.stamp.fromISOString(note.edit_time()), 
1442                     {formatLength:'short'});
1443         }
1444
1445         self.liNotesTbody.appendChild(row);
1446     }
1447
1448     /**
1449      * Updates any new/changed/deleted notes on the server
1450      */
1451     this.updateLiNotes = function(li, newNote) {
1452
1453         var notes;
1454         if(newNote) {
1455             notes = [newNote];
1456         } else {
1457             notes = li.lineitem_notes().filter(
1458                 function(note) {
1459                     if(note.ischanged() || note.isnew() || note.isdeleted())
1460                         return note;
1461                 }
1462             );
1463         }
1464
1465         if(notes.length == 0) return;
1466         progressDialog.show();
1467
1468         fieldmapper.standardRequest(
1469             ['open-ils.acq', 'open-ils.acq.lineitem_note.cud.batch'],
1470             {   async : true,
1471                 params : [this.authtoken, notes],
1472                 onresponse : function(r) {
1473                     var resp = openils.Util.readResponse(r);
1474
1475                     if(resp.complete) {
1476
1477                         if(!newNote) {
1478                             // remove the old changed notes
1479                             var list = [];
1480                             dojo.forEach(li.lineitem_notes(), 
1481                                 function(note) {
1482                                     if(!(note.ischanged() || note.isnew() || note.isdeleted()))
1483                                         list.push(note);
1484                                 }
1485                             );
1486                             li.lineitem_notes(list);
1487                         }
1488
1489                         progressDialog.hide();
1490                         self.updateLiNotesCount(li);
1491                         self.drawLiNotes(li);
1492                         return;
1493                     }
1494
1495                     progressDialog.update(resp);
1496                     var newnote = resp.note;
1497
1498                     if(!newnote.isdeleted()) {
1499                         newnote.isnew(false);
1500                         newnote.ischanged(false);
1501                         li.lineitem_notes().push(newnote);
1502                     }
1503                 },
1504             }
1505         );
1506     }
1507
1508     this.updateLiPrice = function(input, li) {
1509         var self = this;
1510         var price = input.value;
1511         if(Number(price) == Number(li.estimated_unit_price())) return;
1512
1513         fieldmapper.standardRequest(
1514             ['open-ils.acq', 'open-ils.acq.lineitem.price.set'],
1515             {   async : false, // redundant w/ timeout
1516                 timeout : 10,
1517                 params : [this.authtoken, li.id(), price],
1518                 oncomplete : function(r) {
1519                     openils.Util.readResponse(r);
1520                     li.estimated_unit_price(price); // update local copy
1521
1522                     /*
1523                      * If this is a PO and every visible lineitem has a price,
1524                      * check again to see if this PO can be activated.  Note that 
1525                      * every visible lineitem having a price does not guarantee it can
1526                      * be activated, which is why we still make the call.  Having a price
1527                      * set for every visiable lineitem is just the lowest barrier to entry.
1528                      */
1529                     if (self.isPO) {
1530                         var priceNodes = dojo.query('[name=price]', dojo.byId('acq-lit-tbody'));
1531                         var allSet = true;
1532                         dojo.forEach(priceNodes, function(node) { if (node.value == '') allSet = false});
1533                         if (allSet) checkCouldActivatePo();
1534                         refreshPOSummaryAmounts();
1535                     }
1536                 }
1537             }
1538         );
1539     }
1540
1541     this.removeLineitem = function(liId) {
1542         this.tbody.removeChild(dojo.query('[li='+liId+']', this.tbody)[0]);
1543         delete this.liCache[liId];
1544         //selected.push(self.liCache[i.parentNode.parentNode.getAttribute('li')]);
1545     }
1546
1547     this.drawInfo = function(liId) {
1548         this.focusLineitem = liId;
1549         if (!this._isRelatedViewer) {
1550             var d = dojo.byId("acq-lit-info-related");
1551             if (!this.relCache[liId]) {
1552                 fieldmapper.standardRequest(
1553                     [
1554                         "open-ils.acq",
1555                         "open-ils.acq.lineitems_for_bib.by_lineitem_id.count"
1556                     ], {
1557                         "async": true,
1558                         "params": [openils.User.authtoken, liId],
1559                         "onresponse": function(r) {
1560                             self.relCache[liId] = openils.Util.readResponse(r);
1561                             nodeByName("related_number", d).innerHTML =
1562                                 self.relCache[liId];
1563                             openils.Util[
1564                                 self.relCache[liId] >1 ? "show" : "hide"
1565                             ](d);
1566                         }
1567                     }
1568                 );
1569             } else {
1570                 nodeByName("related_number", d).innerHTML = this.relCache[liId];
1571                 openils.Util[this.relCache[liId] > 1 ? "show" : "hide"](d);
1572             }
1573         }
1574
1575         this.show('info');
1576         openils.acq.Lineitem.fetchAttrDefs(
1577             function() { 
1578                 self._fetchLineitem(liId, function(li){self._drawInfo(li);}); 
1579             } 
1580         );
1581     };
1582
1583     this.toggleInlineCopies = function() {
1584         // if any inline copies are not displayed, 
1585         // display them all otherwise, hide them all.
1586
1587         var displayAll = false;
1588
1589         for (var liId in this.liCache) {
1590             if (!this.inlineCopiesVisible(liId)) {
1591                 displayAll = true;
1592                 break;
1593             }
1594         }
1595
1596         for (var liId in this.liCache) {
1597             var row = dojo.byId('acq-inline-copies-row-' + liId);
1598             if (displayAll) {
1599                 if (!row || row._hidden) {
1600                     this.drawInlineCopies(liId);
1601                 }
1602             } else { // hide all
1603                 if (row) {
1604                     // drawInlineCopies() on a visible row will hide it.
1605                     this.drawInlineCopies(liId);
1606                 }
1607             }
1608         }
1609
1610     };
1611
1612     this.inlineCopiesVisible = function(liId) {
1613         var row = dojo.byId('acq-inline-copies-row-' + liId); 
1614         return (row && !row._hidden);
1615     }
1616
1617     this.refreshInlineCopies = function(all, reFetch) {
1618         var self = this;
1619         var liIds = this.inlineCopiesNeedingRefresh;
1620         if (all) liIds = openils.Util.objectProperties(liCache);
1621         liIds.forEach(function(liId) {
1622             if (self.inlineCopiesVisible(liId)) {
1623                 self.drawInlineCopies(liId, reFetch); // hide
1624                 self.drawInlineCopies(liId, reFetch); // re-draw
1625             }
1626         });
1627     };
1628
1629     // draw inline copy table.  if the table is 
1630     // already visible, hide the table as-is
1631     // reFetch forces a retrieval of the lineitem and 
1632     // copies from the server.  otherwise the locally
1633     // cached version of each is used.
1634     this.drawInlineCopies = function(liId, reFetch) {
1635         var self = this;
1636             
1637         // find or create the row where the inline copies table will live
1638         var containerRow = dojo.byId('acq-inline-copies-row-' + liId);
1639         var liRow = dojo.query('[li=' + liId + ']')[0];
1640
1641         if (!containerRow) {
1642
1643             // build the inline copies container row and add it to 
1644             // the DOM directly after the primary lineitem row
1645
1646             containerRow = self.inlineCopyContainer.cloneNode(true);
1647             containerRow.id = 'acq-inline-copies-row-' + liId;
1648
1649             if (liRow.nextSibling) {
1650                 self.tbody.insertBefore(containerRow, liRow.nextSibling);
1651             } else {
1652                 self.tbody.appendChild(containerRow);
1653             }
1654
1655         } else {
1656
1657             // toggle the visible state
1658             containerRow._hidden = !containerRow._hidden;
1659             openils.Util.toggle(containerRow, 'table-row');
1660
1661             if (containerRow._hidden) return; // hide only
1662         }
1663
1664         var handler = function(li) {
1665
1666             var tbody = dojo.query(
1667                 '[name=acq-li-inline-copies-tbody]', 
1668                 containerRow)[0];
1669
1670             // reset the table before adding copy rows
1671             while (tbody.childNodes[0])
1672                 tbody.removeChild(tbody.childNodes[0]);
1673
1674             if(li.lineitem_details().length == 0) {
1675                 tbody.appendChild(
1676                     self.inlineNoCopies.cloneNode(true));
1677                 return; // no copies to show
1678             }
1679
1680             // add a row to the inline copy table for each copy
1681             dojo.forEach(li.lineitem_details(),
1682                 function(copy) {
1683                     var row = self.inlineCopyTemplate.cloneNode(true);
1684                     tbody.appendChild(row);
1685                     self.addInlineCopy(li, copy, row);
1686                 }
1687             );
1688         };
1689
1690         this._fetchLineitem(liId, handler, reFetch);
1691     };
1692
1693     /** Draw read-only copy widgets for inline copies */
1694     this.addInlineCopy = function(li, copy, row) {
1695
1696         var self = this;
1697         dojo.forEach(liDetailFields,
1698             function(field) {
1699
1700                 var widget = new openils.widget.AutoFieldWidget({
1701                     fmObject : copy,
1702                     fmField : field,
1703                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
1704                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
1705                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
1706                     fmClass : 'acqlid',
1707                     parentNode : dojo.query('[name=' + field + ']', row)[0],
1708                     readOnly : true,
1709                 });
1710
1711                 widget.build();
1712             }
1713         );
1714     };
1715
1716     /* For a given list of lineitem ids, build a list of full lineitems
1717      * re-using the fetching logic that is otherwise typical to use in this
1718      * module.
1719      *
1720      * If we've already got a lineitem in the cache, just use that.
1721      *
1722      * Once we've built a list of lineitems, call callback(thatlist).
1723      */
1724     this.fetchLineitemsById = function(id_list, callback) {
1725         var total = id_list.length;
1726         var result_list = [];
1727
1728         var inner = function(li) {
1729             result_list.push(li)
1730             if (--total <= 0)
1731                 callback(result_list);
1732         };
1733
1734         id_list.forEach(function(id) { self._fetchLineitem(id, inner); });
1735     };
1736
1737     this._fetchLineitem = function(liId, handler, force) {
1738
1739         var li = this.liCache[liId];
1740         if(li && li.marc() && li.lineitem_details() && !force)
1741             return handler(li);
1742         
1743         fieldmapper.standardRequest(
1744             ['open-ils.acq', 'open-ils.acq.lineitem.retrieve.authoritative'],
1745             {   async: true,
1746
1747                 params: [self.authtoken, liId, {
1748                     flesh_attrs: true,
1749                     flesh_cancel_reason: true,
1750                     flesh_li_details: true,
1751                     flesh_notes: true,
1752                     flesh_fund_debit: true }],
1753
1754                 oncomplete: function(r) {
1755                     var li = openils.Util.readResponse(r);
1756                     self.liCache[liId] = li;
1757                     handler(li)
1758                 }
1759             }
1760         );
1761     };
1762
1763     this._drawInfo = function(li) {
1764
1765         acqLitEditOrderMarc.onClick = function() { self.editOrderMarc(li); }
1766
1767         if(li.eg_bib_id()) {
1768             openils.Util.hide('acq-lit-marc-order-record-label');
1769             openils.Util.hide(acqLitEditOrderMarc.domNode);
1770             openils.Util.show('acq-lit-marc-real-record-label');
1771         } else {
1772             openils.Util.show('acq-lit-marc-order-record-label');
1773             openils.Util.show(acqLitEditOrderMarc.domNode);
1774             openils.Util.hide('acq-lit-marc-real-record-label');
1775         }
1776
1777         this.drawMarcHTML(li);
1778         this.infoTbody = dojo.byId('acq-lit-info-tbody');
1779
1780         if(!this.infoRow)
1781             this.infoRow = this.infoTbody.removeChild(dojo.byId('acq-lit-info-row'));
1782         while(this.infoTbody.childNodes[0])
1783             this.infoTbody.removeChild(this.infoTbody.childNodes[0]);
1784
1785         for(var i = 0; i < li.attributes().length; i++) {
1786             var attr = li.attributes()[i];
1787             var row = this.infoRow.cloneNode(true);
1788
1789             var type = attr.attr_type().replace(/lineitem_(.*)_attr_definition/, '$1');
1790             var name = openils.acq.Lineitem.attrDefs[type].filter(
1791                 function(a) {
1792                     return (a.code() == attr.attr_name());
1793                 }
1794             ).pop().description();
1795
1796             dojo.query('[name=label]', row)[0].appendChild(document.createTextNode(name));
1797             dojo.query('[name=value]', row)[0].appendChild(document.createTextNode(attr.attr_value()));
1798             this.infoTbody.appendChild(row);
1799         }
1800
1801         if (!this._isRelatedViewer) {
1802             nodeByName("rel_link", dojo.byId("acq-lit-info-related")).href =
1803                 oilsBasePath + "/acq/lineitem/related/" + li.id();
1804         }
1805
1806         // if a top scroll point is defined, jump up to it here
1807         var node = dojo.byId('oils-scroll-to-top');
1808         if (node) dijit.scrollIntoView(node);
1809     };
1810
1811     this.generateMakeRecTab = function(bib_id,default_view, row) {
1812         return function() {
1813             if(openils.XUL.isXUL() && !window.IAMBROWSER) {
1814                 xulG.new_tab(
1815                     XUL_OPAC_WRAPPER,
1816                     {tab_name: localeStrings.XUL_RECORD_DETAIL_PAGE, browser:false},
1817                     {
1818                         no_xulG : false, 
1819                         show_nav_buttons : true, 
1820                         show_print_button : true, 
1821                         opac_url : xulG.url_prefix('opac_rdetail|' + bib_id),
1822                         default_view : default_view
1823                     }
1824                 );
1825             } else {
1826                 var url = '/eg/staff/cat/catalog/record/' + bib_id;
1827                 if (default_view == 'copy_browser') {
1828                     url += '/holdings';
1829                 }
1830                 window.open(url);
1831             }
1832
1833             if(row) nodeByName("action_none", row).selected = true;
1834         }
1835     };
1836
1837     this.drawMarcHTML = function(li) {
1838         var params = [null, true, li.marc()];
1839         if(li.eg_bib_id()) 
1840             params = [li.eg_bib_id(), true];
1841
1842         fieldmapper.standardRequest(
1843             ['open-ils.search', 'open-ils.search.biblio.record.html'],
1844             {   async: true,
1845                 params: params,
1846                 oncomplete: function(r) {
1847                     dojo.byId('acq-lit-marc-div').innerHTML = 
1848                         openils.Util.readResponse(r);
1849                 }
1850             }
1851         );
1852     }
1853
1854     this.drawCopies = function(liId, force_fetch) {
1855         this.focusLineitem = liId;
1856         if (typeof force_fetch == "undefined")
1857             force_fetch = false;
1858
1859         var cgi = new openils.CGI();
1860         var source = cgi.param('source');
1861         if (source && source.match(/invoice/)) {
1862             // got here from the invoice page, show the 'return-to-invoice' button
1863             var cgi = new openils.CGI({url : source});
1864             cgi.param('focus_li', liId);
1865             openils.Util.show(dojo.byId('acq-lit-copies-back-to-invoice-button-wrapper'), 'inline');
1866             var button = dojo.byId('acq-lit-copies-back-to-invoice-button');
1867             button.onclick = function() { location.href = cgi.url() };
1868         }
1869
1870         openils.acq.Lineitem.fetchAndRender(liId, {}, 
1871             function(li, html) {
1872                 dojo.byId('acq-lit-copies-li-summary').innerHTML = html;
1873             }
1874         );
1875
1876         this.show('copies');
1877         var self = this;
1878         this.copyCache = {};
1879         this.copyWidgetCache = {};
1880         this.oldCopyWidgetCache = {};
1881         this.virtDfaCounts = {};
1882         this.realDfaCache = {};
1883         this.dfeOffset = 0;
1884
1885         acqLitSaveCopies.onClick = function() { self.saveCopyChanges(liId) };
1886         acqLitBatchUpdateCopies.onClick = function() { self.batchCopyUpdate() };
1887         acqLitCopyCountInput.attr('value', '0');
1888
1889         if (this.isPO && PO && PO.order_date()) {
1890             // prevent adding copies to activated POs
1891             acqLitCopyCountInput.attr('disabled', true);
1892             acqLitAddCopyCount.attr('disabled', true);
1893         }
1894
1895         while(this.copyTbody.childNodes[0])
1896             this.copyTbody.removeChild(this.copyTbody.childNodes[0]);
1897
1898         this._drawBatchCopyWidgets();
1899
1900         this._drawDistribApplied(liId);
1901
1902         this._fetchDistribFormulas(
1903             function() {
1904                 openils.acq.Lineitem.fetchAttrDefs(
1905                     function() { 
1906                         self._fetchLineitem(liId, function(li){self._drawCopies(li);}, force_fetch); 
1907                     } 
1908                 );
1909             }
1910         );
1911     };
1912
1913     this._saveDistribAppliedTemplates = function() {
1914         if (!this._appliedDistribTemplate) {
1915             this._appliedDistribTemplate =
1916                 dojo.byId("acq-lit-distrib-applied-tbody").
1917                     removeChild(dojo.byId("acq-lit-distrib-applied-row"));
1918             dojo.attr(this._appliedDistribTemplate, "id");
1919         }
1920     };
1921
1922     this._drawDistribApplied = function(liId) {
1923         /* Build this table while hidden to prevent rendering artifacts */
1924         openils.Util.hide("acq-lit-distrib-applied-tbody");
1925
1926         this._saveDistribAppliedTemplates();
1927
1928         /* Remove any rows in the table from previous populations */
1929         dojo.query("tr[formula]", "acq-lit-distrib-applied-tbody").
1930             forEach(dojo.destroy);
1931
1932         /* Unregister all dijits previously created (for some reason this isn't
1933          * covered by the above destroy calls). */
1934         dijit.registry.forEach(
1935             function(w) { if (/^dfa-/.test(w.id)) w.destroyRecursive(); }
1936         );
1937
1938         /* Populate the table with our liId */
1939         var total = 0;
1940         fieldmapper.standardRequest(
1941             ["open-ils.acq",
1942             "open-ils.acq.distribution_formula_application.ranged.retrieve"],
1943             {
1944                 "async": true,
1945                 "params": [self.authtoken, liId],
1946                 "onresponse": function(r) {
1947                     var dfa = openils.Util.readResponse(r);
1948                     if (dfa) {
1949                         total++;
1950                         self.realDfaCache[dfa.id()] = dfa;
1951                         self._drawDistribAppliedUnit(dfa);
1952                     }
1953                 },
1954                 "oncomplete": function() {
1955                     /* Reveal built table */
1956                     if (total) {
1957                         openils.Util.show(
1958                             "acq-lit-distrib-applied-tbody", "table-row-group"
1959                         );
1960                     }
1961                 }
1962             }
1963         );
1964     };
1965
1966     this._drawDistribAppliedUnit = function(dfa) {
1967         var new_row = false;
1968         var row = dojo.query(
1969             'tr[formula="' + dfa.formula().id() + '"]',
1970             "acq-lit-distrib-applied-tbody"
1971         )[0];
1972
1973         if (!row) {
1974             new_row = true;
1975             row = dojo.clone(this._appliedDistribTemplate);
1976             dojo.attr(row, "formula", dfa.formula().id());
1977             dojo.query("th", row)[0].innerHTML = dfa.formula().name();
1978         }
1979
1980         var td = dojo.query("td", row)[0];
1981
1982         dojo.create("span", {"id": "dfa-button-" + dfa.id()}, td, "last");
1983         dojo.create("span", {"id": "dfa-tip-" + dfa.id()}, td, "last");
1984
1985         if (new_row)
1986             dojo.place(row, "acq-lit-distrib-applied-tbody", "last");
1987
1988         new dijit.form.Button(
1989             {
1990                 "onClick": function() {
1991                     if (confirm(localeStrings.EXPLAIN_DFA_MGMT))
1992                         self.deleteDfa(dfa);
1993                 },
1994                 "label": "X",
1995                 /* XXX I /cannot/ make the following work in as a CSS class
1996                  * for some reason. So frustrating... */
1997                 "style": function(id) {
1998                      return (id > 0 ?
1999                         "font-weight: bold; color: #c00;" :
2000                         "color: #666;");
2001                      }(dfa.id()) + "margin: 0 6px;display: inline;"
2002             }, "dfa-button-" + dfa.id()
2003         );
2004         new dijit.Tooltip(
2005             {
2006                 "connectId": ["dfa-button-" + dfa.id()],
2007                 "label": dojo.string.substitute(
2008                     localeStrings.DFA_TIP, dfa.id() > 0 ? [
2009                         openils.User.formalName(dfa.creator()),
2010                         dojo.date.locale.format(
2011                             dojo.date.stamp.fromISOString(dfa.create_time()),
2012                             {"formatLength":"short"}
2013                         )
2014                     ] : [localeStrings.ITS_YOU, localeStrings.JUST_NOW]
2015                 )
2016             }, "dfa-tip-" + dfa.id()
2017         );
2018     }
2019
2020     this.deleteDfa = function(dfa) {
2021         if (dfa.id() > 0) { /* real */
2022             this.pcrud.eliminate(
2023                 dfa, {
2024                     "async": true,
2025                     "oncomplete": function() {
2026                         self._removeDistribApplied(dfa.id());
2027                         delete self.realDfaCache[dfa.id()];
2028                     }
2029                 }
2030             );
2031         } else { /* virtual */
2032             if (--(this.virtDfaCounts[dfa.formula().id()]) < 0)
2033             this.virtDfaCounts[dfa.formula().id()] = 0;
2034             /* hasn't been saved yet, so no need to do anything server side */
2035             this._removeDistribApplied(dfa.id());
2036         }
2037
2038     };
2039
2040     this._removeDistribApplied = function(dfaId) {
2041         var re = new RegExp("^dfa-\\w+-" + String(dfaId));
2042         dijit.registry.forEach(
2043             function(w) { if (re.test(w.id)) w.destroyRecursive(); }
2044         );
2045         this._removeDistribAppliedEmptyRows();
2046     };
2047
2048     this._removeAllDistribAppliedVirtual = function() {
2049         /* Unregister dijits */
2050         dijit.registry.forEach(
2051             function(w) { if (/^dfa-\w+--/.test(w.id)) w.destroyRecursive(); }
2052         );
2053         this._removeDistribAppliedEmptyRows();
2054     };
2055
2056     this._removeDistribAppliedEmptyRows = function() {
2057         /* Remove any rows with no DFA at all */
2058         dojo.query("tr[formula] td", "acq-lit-distrib-applied-tbody").forEach(
2059             function(o) {
2060                 if (o.childNodes.length < 1) dojo.destroy(o.parentNode);
2061             }
2062         );
2063     };
2064
2065     /**
2066      * Insert a new row into the distribution formula selection form
2067      */
2068     this._addDistribFormulaRow = function() {
2069         var self = this;
2070
2071         if (!self.distribForms) {
2072             // no formulas, hide the form
2073             openils.Util.hide('acq-lit-distrib-formula-table');
2074             return;
2075         }
2076
2077         if(!this.distribFormulaTemplate) 
2078             this.distribFormulaTemplate = 
2079                 dojo.byId('acq-lit-distrib-formula-tbody').removeChild(dojo.byId('acq-lit-distrib-form-row'));
2080
2081         var row = this.distribFormulaTemplate.cloneNode(true);
2082         dojo.place(row, "acq-lit-distrib-formula-tbody", "only");
2083
2084         this.dfSelector = new dijit.form.FilteringSelect(
2085             {"labelAttr": "dynLabel", "labelType": "html"},
2086             nodeByName("selector", row)
2087         );
2088         this._updateFormulaStore();
2089         this.dfSelector.fetchProperties =
2090             {"sort": [{"attribute": "use_count", "descending": true}]};
2091
2092         var apply = new dijit.form.Button(
2093             {"label": localeStrings.APPLY},
2094             nodeByName('set_button', row)
2095         ); 
2096
2097         var reset = new dijit.form.Button(
2098             {"label": localeStrings.RESET_FORMULAE, "disabled": true},
2099             nodeByName("reset_button", row)  
2100         );
2101
2102         dojo.connect(apply, 'onClick', 
2103             function() {
2104                 var form_id = self.dfSelector.attr("value");
2105                 if(!form_id) return;
2106                 self._applyDistribFormula(form_id);
2107                 reset.attr("disabled", false);
2108             }
2109         );
2110
2111         dojo.connect(reset, 'onClick', 
2112             function() {
2113                 self.restoreCopyFieldsBeforeDF();
2114                 self.virtDfaCounts = {};
2115                 self.virtDfaId = -1;
2116                 self.dfeOffset = 0;
2117                 self._updateFormulaStore();
2118                 self._removeAllDistribAppliedVirtual();
2119                 reset.attr("disabled", "true");
2120             }
2121         );
2122
2123     };
2124
2125     /**
2126      * Applies a distrib formula to the current set of copies
2127      */
2128     this._applyDistribFormula = function(formula) {
2129         if(!formula) return;
2130
2131         formula = this.distribForms.filter(
2132             function(form) { return form.id() == formula; }
2133         )[0];
2134
2135         var copyRows = dojo.query('tr', self.copyTbody);
2136
2137         if (this.dfeOffset >= copyRows.length) {
2138             alert(localeStrings.OUT_OF_COPIES);
2139             return;
2140         }
2141
2142         var entries_applied = 0;
2143         for(
2144             var rowIndex = this.dfeOffset;
2145             rowIndex < copyRows.length;
2146             rowIndex++
2147         ) {
2148             
2149             var row = copyRows[rowIndex];
2150             var copy_id = row.getAttribute('copy_id');
2151             var copyWidgets = this.copyWidgetCache[copy_id];
2152             var entryIndex = this.dfeOffset;
2153             var entry = null;
2154
2155             // find the correct entry for the current row
2156             dojo.forEach(formula.entries(), 
2157                 function(e) {
2158                     if(!entry) {
2159                         entryIndex += e.item_count();
2160                         if(entryIndex > rowIndex)
2161                             entry = e;
2162                     }
2163                 }
2164             );
2165
2166             if(entry) {
2167                 
2168                 //console.log("rowIndex = " + rowIndex + ", entry = " + entry.id() + ", entryIndex=" + 
2169                 //  entryIndex + ", owning_lib = " + entry.owning_lib() + ", location = " + entry.location());
2170     
2171                 entries_applied++;
2172                 this.saveCopyFieldsBeforeDF(copy_id);
2173                 this._copy_fields_for_acqdf.forEach(
2174                     function(field) {
2175                         if(entry[field]()) {
2176                             copyWidgets[field].attr('value', (entry[field]()));
2177                         }
2178                     }
2179                 );
2180             }
2181         }
2182
2183         if (entries_applied) {
2184             this.virtDfaCounts[formula.id()] =
2185                 ++(this.virtDfaCounts[formula.id()]) || 1;
2186             this._updateFormulaStore();
2187             this._drawDistribAppliedUnit(
2188                 function(df) {
2189                     var dfa = new acqdfa();
2190                     dfa.formula(df); dfa.id(self.virtDfaId--); return dfa;
2191                 }(formula)
2192             );
2193             this.dfeOffset += entries_applied;
2194         };
2195     };
2196
2197     /**
2198      * This function updates the DF store for the dropdown so that use_counts
2199      * can reflect DF applications from this session before they're saved
2200      * server-side.
2201      */
2202     this._updateFormulaStore = function() {
2203         this.dfSelector.store = new dojo.data.ItemFileReadStore(
2204             {
2205                 "data": self._labelFormulasWithCounts(
2206                     acqdf.toStoreData(self.distribForms)
2207                 )
2208             }
2209         );
2210     };
2211
2212     this.saveCopyFieldsBeforeDF = function(copy_id) {
2213         var self = this;
2214         if (!this.oldCopyWidgetCache[copy_id]) {
2215             var copyWidgets = this.copyWidgetCache[copy_id];
2216
2217             this.oldCopyWidgetCache[copy_id] = {};
2218             this._copy_fields_for_acqdf.forEach(
2219                 function(f) {
2220                     self.oldCopyWidgetCache[copy_id][f] =
2221                         copyWidgets[f].attr("value");
2222                 }
2223             );
2224         }
2225     };
2226
2227     this.restoreCopyFieldsBeforeDF = function() {
2228         var self = this;
2229         for (var copy_id in this.oldCopyWidgetCache) {
2230             this._copy_fields_for_acqdf.forEach(
2231                 function(f) {
2232                     self.copyWidgetCache[copy_id][f].attr(
2233                         "value", self.oldCopyWidgetCache[copy_id][f]
2234                     );
2235                 }
2236             );
2237         }
2238     };
2239
2240     this._labelFormulasWithCounts = function(store_data) {
2241         for (var key in store_data.items) {
2242             var obj = store_data.items[key];
2243             obj.use_count = Number(obj.use_count); /* needed for sorting */
2244
2245             if (this.virtDfaCounts[obj.id])
2246                 obj.use_count = obj.use_count + Number(this.virtDfaCounts[obj.id]);
2247
2248             obj.dynLabel = "<span class='acq-lit-distrib-form-use-count'>[" +
2249                 obj.use_count + "]</span>&nbsp; " + obj.name;
2250         }
2251         return store_data;
2252     };
2253
2254     /**
2255      * This method formerly would not refetch the DF formulas if they'd been
2256      * loaded already, but now it always re-fetches, since use_count changes.
2257      */
2258     /** TODO: port distrib-formula selector to autofieldwidget+pcrud/dojo store */
2259     this._fetchDistribFormulas = function(onload) {
2260         fieldmapper.standardRequest(
2261             ["open-ils.acq",
2262                 "open-ils.acq.distribution_formula.ranged.retrieve.atomic"],
2263             {
2264                 "async": true,
2265                 "params": [openils.User.authtoken, 0, 500],
2266                 "oncomplete": function(r) {
2267                     self.distribForms = openils.Util.readResponse(r);
2268                     if(!self.distribForms || self.distribForms.length == 0) {
2269                         self.distribForms = [];
2270                     }
2271                     self._addDistribFormulaRow();
2272                     onload();
2273                 }
2274             }
2275         );
2276     }
2277
2278     this._drawBatchCopyWidgets = function() {
2279         var row = this.copyBatchRow;
2280         dojo.forEach(liDetailBatchFields, 
2281             function(field) {
2282                 if(self.copyBatchRowDrawn) {
2283                     self.copyBatchWidgets[field].attr('value', null);
2284                 } else {
2285                     var args = self.afwCopyFieldArgs(field, "CREATE_PICKLIST");
2286                     args.parentNode = dojo.query('[name='+field+']', row)[0];
2287
2288                     var widget = new openils.widget.AutoFieldWidget(args);
2289                     widget.build(
2290                         function(w, ww) {
2291                             if (field == "fund" && w.store)
2292                                 self._ensureCSSFundClasses(w.store);
2293                             self.copyBatchWidgets[field] = w;
2294                         }
2295                     );
2296                     if (field == "fund") {
2297                         dojo.connect(
2298                             widget.widget, "onChange", function(val) {
2299                                 self._updateFundSelectorStyle(widget, val);
2300                             }
2301                         );
2302                     }
2303                 }
2304             }
2305         );
2306         this.copyBatchRowDrawn = true;
2307     };
2308
2309     this.batchCopyUpdate = function() {
2310         var self = this;
2311         for(var k in this.copyWidgetCache) {
2312             var cache = this.copyWidgetCache[k];
2313             dojo.forEach(liDetailBatchFields, function(f) {
2314                 var newval = self.copyBatchWidgets[f].attr('value');
2315                 if(newval) cache[f].attr('value', newval);
2316             });
2317         }
2318     };
2319
2320     this._drawCopies = function(li) {
2321         var self = this;
2322
2323         // this button sets the total number of copies for a given lineitem
2324         acqLitAddCopyCount.onClick = function() { 
2325             var count = acqLitCopyCountInput.attr('value');
2326
2327             // add new rows
2328             while(self.copyCount() < count)
2329                 self.addCopy(li); 
2330             
2331             // delete rows if necessary
2332             var diff = self.copyCount() - count;
2333             if(diff > 0) {
2334                 var rows = dojo.query('tr', self.copyTbody).reverse().slice(0, diff);
2335                 if(confirm(dojo.string.substitute(localeStrings.DELETE_LI_COPIES_CONFIRM, [diff]))) {
2336                     dojo.forEach(rows, function(row) {self.deleteCopy(row); });
2337                 } else {
2338                     acqLitCopyCountInput.attr('value', self.copyCount()+'');
2339                 }
2340             }
2341         }
2342
2343
2344         if(li.lineitem_details().length > 0) {
2345             dojo.forEach(li.lineitem_details(),
2346                 function(copy) {
2347                     self.addCopy(li, copy);
2348                 }
2349             );
2350         } else {
2351             self.addCopy(li);
2352         }
2353     };
2354
2355     this.copyCount = function() {
2356         var count = 0;
2357         for(var id in this.copyCache) {
2358             if(!this.copyCache[id].isdeleted())
2359                 count++;
2360         }
2361         return count;
2362     }
2363
2364     this.virtCopyId = -1;
2365     this.addCopy = function(li, copy) {
2366         var row = this.copyRow.cloneNode(true);
2367         this.copyTbody.appendChild(row);
2368         var self = this;
2369
2370         if(!copy) {
2371             copy = new fieldmapper.acqlid();
2372             copy.isnew(true);
2373             copy.id(this.virtCopyId--);
2374             copy.lineitem(li.id());
2375         }
2376
2377         this.copyCache[copy.id()] = copy;
2378         row.setAttribute('copy_id', copy.id());
2379         self.copyWidgetCache[copy.id()] = {};
2380
2381         acqLitCopyCountInput.attr('value', self.copyCount()+'');
2382
2383         var rcvr = copy.receiver();
2384         if (rcvr) {
2385             if (!userCache[rcvr]) {
2386                 if(rcvr == openils.User.user.id()) {
2387                     userCache[rcvr] = openils.User.user;
2388                 } else {
2389                     userCache[rcvr] = fieldmapper.standardRequest(
2390                         ['open-ils.actor', 'open-ils.actor.user.retrieve'],
2391                         {params: [openils.User.authtoken, rcvr]}
2392                     );
2393                 }
2394             }
2395             dojo.query('[name=receiver]', row)[0].innerHTML =  userCache[rcvr].usrname();
2396         }
2397
2398         dojo.forEach(liDetailFields,
2399             function(field) {
2400                 var searchFilter;
2401                 if (field == "fund") {
2402                     searchFilter = (copy.fund() ?
2403                         {"-or": {"active": "t", "id": copy.fund()}} :
2404                         {"active" : "t"});
2405                     searchFilter.org = fundSearchFilter.org;
2406                 } else {
2407                     searchFilter = null;
2408                 }
2409
2410                 var readOnly = false;
2411                 
2412                 // TODO: Add support for changing the owning_lib after real copies have been made.  
2413                 // owning_lib is order data as much as its item data
2414                 if(copy.eg_copy_id() && ['owning_lib', 'location', 'circ_modifier', 'cn_label', 'barcode'].indexOf(field) >= 0) {
2415                     readOnly = true;
2416                 }
2417
2418                 // TODO: add support for changing the fund after debits have been created
2419                 // Note: invoicing allows the change
2420                 if(copy.fund_debit() && field == 'fund') {
2421                     readOnly = true;
2422                 }
2423
2424
2425                 var widget = new openils.widget.AutoFieldWidget({
2426                     fmObject : copy,
2427                     fmField : field,
2428                     labelFormat : (field == 'fund') ? fundLabelFormat : null,
2429                     searchFormat : (field == 'fund') ? fundSearchFormat : null,
2430                     dijitArgs: {"labelType": (field == 'fund') ? "html" : null},
2431                     searchFilter : searchFilter,
2432                     noCache: (field == "fund"),
2433                     fmClass : 'acqlid',
2434                     parentNode : dojo.query('[name='+field+']', row)[0],
2435                     orgLimitPerms : ['CREATE_PICKLIST', 'CREATE_PURCHASE_ORDER'],
2436                     readOnly : readOnly,
2437                     orgDefaultsToWs : true
2438                 });
2439
2440                 widget.build(
2441                     // make sure we capture the value from any async widgets
2442                     function(w, ww) { 
2443
2444                         if (field == "fund" && w.store)
2445                             self._ensureCSSFundClasses(w.store);
2446
2447                         if(!readOnly) 
2448                             copy[field](ww.getFormattedValue()) 
2449
2450                         self.copyWidgetCache[copy.id()][field] = w;
2451
2452                         dojo.connect(w, 'onChange', 
2453                             function(val) { 
2454                                 if (field == "fund")
2455                                     self._updateFundSelectorStyle(widget, val);
2456
2457                                 if (!readOnly && (copy.isnew() || val != copy[field]())) {
2458                                     // prevent setting ischanged() automatically on widget load for existing copies
2459                                     copy[field](widget.getFormattedValue()) 
2460                                     copy.ischanged(true);
2461                                 }
2462                             }
2463                         );
2464                     }
2465                 );
2466             }
2467         );
2468
2469         this.updateLidState(copy, row);
2470     };
2471
2472     this._ensureCSSFundClass = function(id) {
2473         if (!this.fundStyleSheet) {
2474             dojo.create(
2475                 "style", {"type": "text/css"},
2476                 document.getElementsByTagName("head")[0], "last"
2477             );
2478             this.fundStyleSheet = document.styleSheets[
2479                 document.styleSheets.length - 1
2480             ];
2481         }
2482
2483         var cn = "fund_" + id;
2484         if (!this.haveFundClass[cn]) {
2485             fieldmapper.standardRequest(
2486                 ["open-ils.acq", "open-ils.acq.fund.check_balance_percentages"],
2487                 {
2488                     "params": [openils.User.authtoken, id],
2489                     "async": true,
2490                     "oncomplete": function(r) {
2491                         r = openils.Util.readResponse(r);
2492                         self.fundBalanceState[id] = r;
2493                         var style = "";
2494                         if (r[0] /* stop */)
2495                             style = fundStyles.stop;
2496                         else if (r[1] /* warning */)
2497                             style = fundStyles.warning;
2498                         self.fundStyleSheet.insertRule(
2499                             "." + cn + " { " + style + " }",
2500                             self.fundStyleSheet.cssRules.length
2501                         );
2502                         self.haveFundClass[cn] = true;
2503                     }
2504                 }
2505             );
2506         }
2507     };
2508
2509     this._ensureCSSFundClasses = function(store) {
2510         store.fetch({
2511             "query": {"id": "*"},
2512             "onItem": function(o) { self._ensureCSSFundClass(o.id[0]); }
2513         });
2514     };
2515
2516     this._updateFundSelectorStyle = function(widget, fund_id) {
2517         openils.Util.removeCSSClass(widget.widget.domNode, /fund_\d+/);
2518         openils.Util.addCSSClass(widget.widget.domNode, "fund_" + fund_id);
2519     };
2520
2521     this.updateLidState = function(copy, row) {
2522         var self = this;
2523
2524         if (typeof(row) == "undefined") {
2525             row = dojo.query('tr[copy_id="' + copy.id() + '"]', this.copyTbody)[0];
2526         }
2527
2528         // action links
2529         var recv_link = nodeByName("receive", row);
2530         var unrecv_link = nodeByName("unreceive", row);
2531         var del_link = nodeByName("delete", row);
2532         var cxl_link = nodeByName("cancel", row);
2533         var claim_link = nodeByName("claim", row);
2534         var cxl_reason_link = nodeByName("cancel_reason", row);
2535
2536         // by default, hide all the actions
2537         openils.Util.hide(del_link.parentNode);
2538         openils.Util.hide(recv_link);
2539         openils.Util.hide(unrecv_link);
2540         openils.Util.hide(cxl_link);
2541         openils.Util.hide(claim_link);
2542         openils.Util.hide(cxl_reason_link);
2543
2544         if (copy.id() > 0) { // real copies (LIDs)
2545
2546             if (copy.cancel_reason()) { 
2547
2548                 /* --------- cancelled -------------------------- */
2549
2550                 /* XXX the following may leak memory in a long lived table: 
2551                  * dijits may not get destroyed... not positive. revisit. */
2552                 var holds_reason = dojo.create(
2553                     "span", {
2554                         "style": "border-bottom: 1px dashed #000;",
2555                         "innerHTML": copy.cancel_reason().label()
2556                     }, cxl_reason_link, "only"
2557                 );
2558                 new dijit.Tooltip(
2559                     {
2560                         "label": "<em>" + copy.cancel_reason().label() +
2561                             "</em><br />" + copy.cancel_reason().description(),
2562                         "connectId": [holds_reason]
2563                     }, dojo.create("span", null, cxl_reason_link, "last")
2564                 );
2565                 openils.Util.show(cxl_reason_link, "inline");
2566
2567                 if (copy.cancel_reason().keep_debits() == 't' ) {
2568                     // allow further cancellation of "delayed" copies
2569                     
2570                     openils.Util.show(cxl_link, "inline");
2571                     cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2572                 }
2573
2574             } else if (copy.recv_time()) { 
2575
2576                 /* --------- received -------------------------- */
2577
2578                 openils.Util.show(unrecv_link, "inline");
2579                 unrecv_link.onclick = function() {
2580                     if (confirm(localeStrings.UNRECEIVE_LID))
2581                         self.issueReceive(copy, /* rollback */ true);
2582                 };
2583
2584             } else if (this.liCache[copy.lineitem()].state() == 'on-order') {
2585                 
2586                 /* --------- on order -------------------------- */
2587
2588                 openils.Util.show(recv_link, 'inline');
2589                 openils.Util.show(cxl_link, "inline");
2590
2591                 recv_link.onclick = function() {
2592                     if (self.checkLiAlerts(copy.lineitem()))
2593                         self.issueReceive(copy);
2594                 };
2595
2596                 cxl_link.onclick = function() { self.cancelLid(copy.id()) };
2597
2598             } else {
2599
2600                 /* --------- pre-order copies  -------------------------- */
2601
2602                 del_link.onclick = function() { self.deleteCopy(row) };
2603                 openils.Util.show(del_link.parentNode);
2604
2605             }
2606
2607         } else { 
2608
2609             /* --------- virtual copies  -------------------------- */
2610
2611             del_link.onclick = function() { self.deleteCopy(row) };
2612             openils.Util.show(del_link.parentNode);
2613         }
2614     };
2615
2616     this.cancelLid = function(lid_id) {
2617         lidCancelDialog._lid_id = lid_id;
2618         openils.Util.show(lidCancelDialog.domNode.parentNode);
2619         lidCancelDialog.show();
2620         if (!lidCancelDialog._prepared) {
2621             var widget = new openils.widget.AutoFieldWidget({
2622                 "fmField": "cancel_reason",
2623                 "fmClass": "acqlid",
2624                 "parentNode": dojo.byId("acq-lit-lid-cancel-reason"),
2625                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
2626                 "forceSync": true,
2627                 "searchOptions" : {order_by : {"acqcr":"label"}}
2628             });
2629             widget.build(
2630                 function(w, ww) {
2631                     acqLidCancelButton.onClick = function() {
2632                         if (w.attr("value")) {
2633                             if (confirm(localeStrings.LID_CANCEL_CONFIRM)) {
2634                                 self._cancelLid(
2635                                     lidCancelDialog._lid_id,
2636                                     w.attr("value")
2637                                 );
2638                             }
2639                             lidCancelDialog.hide();
2640                         }
2641                     };
2642                     lidCancelDialog._prepared = true;
2643                 }
2644             );
2645         }
2646     };
2647
2648     this._cancelLid = function(lid_id, reason) {
2649         fieldmapper.standardRequest(
2650             ["open-ils.acq", "open-ils.acq.lineitem_detail.cancel"], {
2651                 "params": [openils.User.authtoken, lid_id, reason],
2652                 "async": true,
2653                 "onresponse": function(r) {
2654                     if (r = openils.Util.readResponse(r)) {
2655                         if (r.lid) {
2656                             for (var id in r.lid) {
2657                                 /* actually this should only iterate once */
2658                                 self.copyCache[id].cancel_reason(
2659                                     r.lid[id].cancel_reason
2660                                 );
2661                                 self.updateLidState(self.copyCache[id]);
2662                             }
2663                         }
2664                     }
2665                 }
2666             }
2667         );
2668     };
2669
2670     this._confirmAlert = function(li, lin) {
2671         return confirm(
2672             dojo.string.substitute(
2673                 localeStrings.CONFIRM_LI_ALERT, [
2674                     (new openils.acq.Lineitem({"lineitem": li})).findAttr(
2675                         "title", "lineitem_marc_attr_definition"
2676                     ), (
2677                         /* XXX it's really better add a parameter and to adjust
2678                          * the format string rather than do this concatenation
2679                          * here, but if someone wants this for 2.2 in a hurry,
2680                          * we can sidestep the problem of updating the strings
2681                          * while the translators are working. */
2682                         "[" +
2683                         aou.findOrgUnit(lin.alert_text().owning_lib()).shortname() +
2684                         "] " +
2685                         lin.alert_text().code()
2686                     ),
2687                     lin.alert_text().description() || "",
2688                     lin.value()
2689                 ]
2690             )
2691         );
2692     };
2693
2694     this.checkLiAlerts = function(li_id) {
2695         var li = this.liCache[li_id];
2696
2697         var alert_notes = li.lineitem_notes().filter(
2698             function(o) { return Boolean(o.alert_text()); }
2699         );
2700
2701         /* this is _intentionally_ not done in a call to forEach() ... */
2702         for (var i = 0; i < alert_notes.length; i++) {
2703             if (this.noteAcks[alert_notes[i].id()])
2704                 continue;
2705             else if (!this._confirmAlert(li, alert_notes[i]))
2706                 return false;
2707             else
2708                 this.noteAcks[alert_notes[i].id()] = true;
2709         }
2710
2711         return true;
2712     };
2713
2714     this.deleteCopy = function(row) {
2715         var copy = this.copyCache[row.getAttribute('copy_id')];
2716         copy.isdeleted(true);
2717         if(copy.isnew())
2718             delete this.copyCache[copy.id()];
2719         this.copyTbody.removeChild(row);
2720     }
2721
2722     this._virtDfaCountsAsList = function() {
2723         var L = [];
2724         for (var key in this.virtDfaCounts) {
2725             for (var i = 0; i < this.virtDfaCounts[key]; i++)
2726                 L.push(key);
2727         }
2728         return L;
2729     }
2730
2731     this.confirmBreachedCopyFunds = function(copies) {
2732         var stop = 0, warning = 0;
2733         copies.forEach(
2734             function(o) {
2735                 if (o.fund()) {
2736                     var state = self.fundBalanceState[o.fund()];
2737                     if (state[0] /* stop */)
2738                         stop++;
2739                     else if (state[1] /* warning */)
2740                         warning++;
2741                 }
2742             }
2743         );
2744
2745         if (stop) {
2746             return confirm(localeStrings.CONFIRM_FUNDS_AT_STOP);
2747         } else if (warning) {
2748             return confirm(localeStrings.CONFIRM_FUNDS_AT_WARNING);
2749         }
2750         return true;
2751     };
2752
2753     this.saveCopyChanges = function(liId) {
2754         var self = this;
2755         var copies = [];
2756
2757
2758         var total = 0;
2759         for(var id in this.copyCache) {
2760             var c = this.copyCache[id];
2761             if(!c.isdeleted()) total++;
2762             if(c.isnew() || c.ischanged() || c.isdeleted()) {
2763                 if(c.id() < 0) c.id(null);
2764                 copies.push(c);
2765             }
2766         }
2767
2768
2769         dojo.byId('acq-lit-copy-count-label-' + liId).innerHTML = total;
2770
2771
2772         if (copies.length > 0) {
2773             if (!this.confirmBreachedCopyFunds(copies))
2774                 return;
2775
2776             if (typeof(this._copy_count_cb) == "function")
2777                 this._copy_count_cb(liId, total);
2778
2779             openils.Util.show("acq-lit-update-copies-progress");
2780             fieldmapper.standardRequest(
2781                 ['open-ils.acq', 'open-ils.acq.lineitem_detail.cud.batch'],
2782                 {   async: true,
2783                     params: [openils.User.authtoken, copies],
2784                     onresponse: function(r) {
2785                         var res = openils.Util.readResponse(r);
2786                         litUpdateCopiesProgress.update(res);
2787                     },
2788                     oncomplete: function() {
2789                         self.drawCopies(liId, true /* force_fetch */);
2790                         openils.Util.hide("acq-lit-update-copies-progress");
2791                         refreshPOSummaryAmounts();
2792                     }
2793                 }
2794             );
2795         }
2796
2797         var dfa_list = this._virtDfaCountsAsList();
2798         if (dfa_list.length > 0) {
2799             fieldmapper.standardRequest(
2800                 ["open-ils.acq",
2801                 "open-ils.acq.distribution_formula.record_application"],
2802                 {
2803                     "async": true,
2804                     "params": [openils.User.authtoken, dfa_list, liId],
2805                     "onresponse": function(r) {
2806                         var res = openils.Util.readResponse(r);
2807                         if (res && res.length < dfa_list.length)
2808                             alert(localeStrings.DFA_NOT_ALL);
2809                     }
2810                 }
2811             );
2812             this.virtDfaCounts = {};
2813         }
2814
2815         if (this.inlineCopiesNeedingRefresh.indexOf(liId) < 0)
2816             this.inlineCopiesNeedingRefresh.push(liId);
2817     };
2818
2819     this._updateCreatePoPrepayCheckbox = function(prepay) {
2820         var prepay = openils.Util.isTrue(prepay);
2821         this._prepayRequiredByVendor = prepay;
2822         dijit.byId("acq-lit-po-prepay").attr("checked", prepay);
2823     };
2824
2825     this._confirmPoPrepaySituation = function() {
2826         var want_prepay = dijit.byId("acq-lit-po-prepay").attr("checked");
2827         if (want_prepay != this._prepayRequiredByVendor) {
2828             return confirm(
2829                 want_prepay ?
2830                     localeStrings.VENDOR_SAYS_PREPAY_NOT_NEEDED :
2831                     localeStrings.VENDOR_SAYS_PREPAY_NEEDED
2832             );
2833         } else {
2834             return true;
2835         }
2836     };
2837
2838     this.applySelectedLiAction = function(action) {
2839         var self = this;
2840         switch(action) {
2841
2842             case 'delete_selected':
2843                 this._deleteLiList(self.getSelected());
2844                 break;
2845
2846             case 'add_to_order':
2847                 addToPoDialog._get_li = dojo.hitch(
2848                     this,
2849                     function() { 
2850                         return this.getSelected(
2851                             false, null, true, li_pre_po_states);
2852                     }
2853                 );
2854                 if (addToPoDialog._get_li().length == 0) {
2855                     alert(localeStrings.NO_LI_GENERAL);
2856                     return;
2857                 }
2858                 addToPoDialog.show();
2859                 break;
2860
2861             case 'create_order':
2862                 this._loadPOSelect();
2863                 acqLitPoCreateDialog.show();
2864                 break;
2865
2866             case 'save_picklist':
2867                 acqLitSavePlDialog.show();
2868                 break;
2869
2870             case 'selector_ready':
2871             case 'order_ready':
2872                 acqLitChangeLiStateDialog.attr('state', action.replace('_', '-'));
2873                 acqLitChangeLiStateDialog.show();
2874                 break;
2875
2876             case 'print_po':
2877                 this.printPO();
2878                 break;
2879
2880             case 'po_history':
2881                 location.href = oilsBasePath + '/acq/po/history/' + this.isPO;
2882                 break;
2883
2884             case 'batch_create_invoice':
2885                 this.batchCreateInvoice();
2886                 break;
2887
2888             case 'batch_link_invoice':
2889                 this.batchLinkInvoice();
2890                 break;
2891
2892             case 'receive_lineitems':
2893                 this.receiveSelectedLineitems();
2894                 break;
2895
2896             case 'rollback_receive_lineitems':
2897                 this.rollbackReceiveLineitems();
2898                 break;
2899
2900             case 'create_assets':
2901                 this.showAssetCreator();
2902                 break;
2903
2904             case 'export_attr_list':
2905                 this.chooseExportAttr();
2906                 break;
2907
2908             case 'batch_apply_funds':
2909                 this.applyBatchLiFunds();
2910                 break;
2911
2912             case 'add_brief_record':
2913                 if(this.isPO)
2914                     location.href = oilsBasePath + '/acq/picklist/brief_record?po=' + this.isPO;
2915                 else
2916                     location.href = oilsBasePath + '/acq/picklist/brief_record?pl=' + this.isPL;
2917
2918                 break;
2919
2920             case "cancel_lineitems":
2921                 console.log('HERE');
2922                 this.maybeCancelLineitems();
2923                 break;
2924
2925             case "apply_claim_policy":
2926                 var li_list = this.getSelected();
2927                 this.claimPolicyPicker.attr("value", null);
2928                 liClaimPolicyDialog.show();
2929                 liClaimPolicySave.onClick = function() {
2930                     self.changeClaimPolicy(
2931                         li_list,
2932                         self.claimPolicyPicker.attr("value"),
2933                         function() {
2934                             li_list.forEach(
2935                                 function(li) {
2936                                     self.setClaimPolicyControl(li);
2937                                     self.reconsiderClaimControl(li);
2938                                 }
2939                             );
2940                             liClaimPolicyDialog.hide();
2941                         }
2942                     )
2943                 };
2944                 break;
2945         }
2946     };
2947
2948     this.changeClaimPolicy = function(li_list, value, callback) {
2949         li_list.forEach(
2950             function(li) { li.claim_policy(value); }
2951         );
2952         fieldmapper.standardRequest(
2953             ["open-ils.acq", "open-ils.acq.lineitem.update"], {
2954                 "params": [openils.User.authtoken, li_list],
2955                 "async": true,
2956                 "oncomplete": function(r) {
2957                     r = openils.Util.readResponse(r);
2958                     if (callback) callback(r);
2959                 }
2960             }
2961         );
2962     };
2963
2964     this.showAssetCreator = function(onAssetsCreated) {
2965         if(!this.isPO) return;
2966         var self = this;
2967     
2968         // first, let's see if this PO has any LI's that need to be merged/imported
2969         self.pcrud.search('jub', {purchase_order : this.isPO, eg_bib_id : null}, {
2970             id_list : true,
2971             oncomplete : function(r) {
2972                 var resp = openils.Util.readResponse(r);
2973                 if (resp && resp.length) {
2974                     // PO has some non-linked jubs.  
2975                     
2976                     self.show('asset-creator');
2977                     if(!self.vlAgent.loaded)
2978                         self.vlAgent.init();
2979
2980                     dojo.connect(assetCreatorButton, 'onClick', 
2981                         function() { self.createAssets(onAssetsCreated) });
2982
2983                 } else {
2984
2985                     // all jubs linked, move on to asset creation
2986                     self.createAssets(onAssetsCreated, true); 
2987                 }
2988             }
2989         });
2990     }
2991
2992     this.createAssets = function(onAssetsCreated, noVl) {
2993         this.show('acq-lit-progress-numbers');
2994         var self = this;
2995         var vlArgs = (noVl) ? {} : {vandelay : this.vlAgent.values()};
2996         this.batchProgress = {};
2997         progressDialog.show(false);
2998         progressDialog.attr("title", localeStrings.LI_CREATING_ASSETS);
2999         fieldmapper.standardRequest(
3000             ['open-ils.acq', 'open-ils.acq.purchase_order.assets.create'],
3001             {   async: true,
3002                 params: [this.authtoken, this.isPO, vlArgs],
3003                 onresponse: function(r) {
3004                     var resp = openils.Util.readResponse(r);
3005                     self._updateProgressNumbers(resp, !Boolean(onAssetsCreated), onAssetsCreated, true);
3006                 }
3007             }
3008         );
3009     }
3010
3011     this.maybeCancelLineitems = function() {
3012         openils.Util.show("acq-lit-cancel-reason", "inline");
3013         if (!acqLitCancelLineitemsButton._prepared) {
3014             var widget = new openils.widget.AutoFieldWidget({
3015                 "fmField": "cancel_reason",
3016                 "fmClass": "jub",
3017                 "parentNode": dojo.byId("acq-lit-cancel-reason-selector"),
3018                 "orgLimitPerms": ["CREATE_PURCHASE_ORDER"],
3019                 "forceSync": true,
3020                 "searchOptions" : {order_by : {"acqcr":"label"}}
3021             });
3022             widget.build(
3023                 function(w, ww) {
3024                     acqLitCancelLineitemsButton.onClick = function() {
3025                         if (w.attr("value")) {
3026                             if (confirm(localeStrings.LI_CANCEL_CONFIRM)) {
3027                                 self._cancelLineitems(w.attr("value"));
3028                             }
3029                             openils.Util.hide("acq-lit-cancel-reason");
3030                         }
3031                     };
3032                     acqLitCancelLineitemsButton._prepared = true;
3033                 }
3034             );
3035         }
3036     };
3037
3038     this._cancelLineitems = function(reason) {
3039
3040         var li_list = this.getSelected();
3041
3042         // canceled lineitems may be canceled again if they were 
3043         // previously delayed (keep_debits = true).
3044         li_list = li_list.filter(
3045             function(li) {
3046                 return (