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